Implement target independent TLS compatible with glibc's emutls.c.
[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 X86TargetLowering::X86TargetLowering(const X86TargetMachine &TM,
71                                      const X86Subtarget &STI)
72     : TargetLowering(TM), Subtarget(&STI) {
73   X86ScalarSSEf64 = Subtarget->hasSSE2();
74   X86ScalarSSEf32 = Subtarget->hasSSE1();
75   MVT PtrVT = MVT::getIntegerVT(8 * TM.getPointerSize());
76
77   // Set up the TargetLowering object.
78   static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
79
80   // X86 is weird. It always uses i8 for shift amounts and setcc results.
81   setBooleanContents(ZeroOrOneBooleanContent);
82   // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
83   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
84
85   // For 64-bit, since we have so many registers, use the ILP scheduler.
86   // For 32-bit, use the register pressure specific scheduling.
87   // For Atom, always use ILP scheduling.
88   if (Subtarget->isAtom())
89     setSchedulingPreference(Sched::ILP);
90   else if (Subtarget->is64Bit())
91     setSchedulingPreference(Sched::ILP);
92   else
93     setSchedulingPreference(Sched::RegPressure);
94   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
95   setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
96
97   // Bypass expensive divides on Atom when compiling with O2.
98   if (TM.getOptLevel() >= CodeGenOpt::Default) {
99     if (Subtarget->hasSlowDivide32())
100       addBypassSlowDiv(32, 8);
101     if (Subtarget->hasSlowDivide64() && Subtarget->is64Bit())
102       addBypassSlowDiv(64, 16);
103   }
104
105   if (Subtarget->isTargetKnownWindowsMSVC()) {
106     // Setup Windows compiler runtime calls.
107     setLibcallName(RTLIB::SDIV_I64, "_alldiv");
108     setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
109     setLibcallName(RTLIB::SREM_I64, "_allrem");
110     setLibcallName(RTLIB::UREM_I64, "_aullrem");
111     setLibcallName(RTLIB::MUL_I64, "_allmul");
112     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
113     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
114     setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
115     setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
116     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
117
118     // The _ftol2 runtime function has an unusual calling conv, which
119     // is modeled by a special pseudo-instruction.
120     setLibcallName(RTLIB::FPTOUINT_F64_I64, nullptr);
121     setLibcallName(RTLIB::FPTOUINT_F32_I64, nullptr);
122     setLibcallName(RTLIB::FPTOUINT_F64_I32, nullptr);
123     setLibcallName(RTLIB::FPTOUINT_F32_I32, nullptr);
124   }
125
126   if (Subtarget->isTargetDarwin()) {
127     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
128     setUseUnderscoreSetJmp(false);
129     setUseUnderscoreLongJmp(false);
130   } else if (Subtarget->isTargetWindowsGNU()) {
131     // MS runtime is weird: it exports _setjmp, but longjmp!
132     setUseUnderscoreSetJmp(true);
133     setUseUnderscoreLongJmp(false);
134   } else {
135     setUseUnderscoreSetJmp(true);
136     setUseUnderscoreLongJmp(true);
137   }
138
139   // Set up the register classes.
140   addRegisterClass(MVT::i8, &X86::GR8RegClass);
141   addRegisterClass(MVT::i16, &X86::GR16RegClass);
142   addRegisterClass(MVT::i32, &X86::GR32RegClass);
143   if (Subtarget->is64Bit())
144     addRegisterClass(MVT::i64, &X86::GR64RegClass);
145
146   for (MVT VT : MVT::integer_valuetypes())
147     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
148
149   // We don't accept any truncstore of integer registers.
150   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
151   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
152   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
153   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
154   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
155   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
156
157   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
158
159   // SETOEQ and SETUNE require checking two conditions.
160   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
161   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
162   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
163   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
164   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
165   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
166
167   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
168   // operation.
169   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
170   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
171   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
172
173   if (Subtarget->is64Bit()) {
174     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
175     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
176   } else if (!Subtarget->useSoftFloat()) {
177     // We have an algorithm for SSE2->double, and we turn this into a
178     // 64-bit FILD followed by conditional FADD for other targets.
179     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
180     // We have an algorithm for SSE2, and we turn this into a 64-bit
181     // FILD for other targets.
182     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
183   }
184
185   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
186   // this operation.
187   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
188   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
189
190   if (!Subtarget->useSoftFloat()) {
191     // SSE has no i16 to fp conversion, only i32
192     if (X86ScalarSSEf32) {
193       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
194       // f32 and f64 cases are Legal, f80 case is not
195       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
196     } else {
197       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
198       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
199     }
200   } else {
201     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
202     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
203   }
204
205   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
206   // are Legal, f80 is custom lowered.
207   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
208   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
209
210   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
211   // this operation.
212   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
213   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
214
215   if (X86ScalarSSEf32) {
216     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
217     // f32 and f64 cases are Legal, f80 case is not
218     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
219   } else {
220     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
221     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
222   }
223
224   // Handle FP_TO_UINT by promoting the destination to a larger signed
225   // conversion.
226   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
227   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
228   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
229
230   if (Subtarget->is64Bit()) {
231     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
232     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
233   } else if (!Subtarget->useSoftFloat()) {
234     // Since AVX is a superset of SSE3, only check for SSE here.
235     if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
236       // Expand FP_TO_UINT into a select.
237       // FIXME: We would like to use a Custom expander here eventually to do
238       // the optimal thing for SSE vs. the default expansion in the legalizer.
239       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
240     else
241       // With SSE3 we can use fisttpll to convert to a signed i64; without
242       // SSE, we're stuck with a fistpll.
243       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
244   }
245
246   if (isTargetFTOL()) {
247     // Use the _ftol2 runtime function, which has a pseudo-instruction
248     // to handle its weird calling convention.
249     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Custom);
250   }
251
252   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
253   if (!X86ScalarSSEf64) {
254     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
255     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
256     if (Subtarget->is64Bit()) {
257       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
258       // Without SSE, i64->f64 goes through memory.
259       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
260     }
261   }
262
263   // Scalar integer divide and remainder are lowered to use operations that
264   // produce two results, to match the available instructions. This exposes
265   // the two-result form to trivial CSE, which is able to combine x/y and x%y
266   // into a single instruction.
267   //
268   // Scalar integer multiply-high is also lowered to use two-result
269   // operations, to match the available instructions. However, plain multiply
270   // (low) operations are left as Legal, as there are single-result
271   // instructions for this in x86. Using the two-result multiply instructions
272   // when both high and low results are needed must be arranged by dagcombine.
273   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
274     MVT VT = IntVTs[i];
275     setOperationAction(ISD::MULHS, VT, Expand);
276     setOperationAction(ISD::MULHU, VT, Expand);
277     setOperationAction(ISD::SDIV, VT, Expand);
278     setOperationAction(ISD::UDIV, VT, Expand);
279     setOperationAction(ISD::SREM, VT, Expand);
280     setOperationAction(ISD::UREM, VT, Expand);
281
282     // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
283     setOperationAction(ISD::ADDC, VT, Custom);
284     setOperationAction(ISD::ADDE, VT, Custom);
285     setOperationAction(ISD::SUBC, VT, Custom);
286     setOperationAction(ISD::SUBE, VT, Custom);
287   }
288
289   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
290   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
291   setOperationAction(ISD::BR_CC            , MVT::f32,   Expand);
292   setOperationAction(ISD::BR_CC            , MVT::f64,   Expand);
293   setOperationAction(ISD::BR_CC            , MVT::f80,   Expand);
294   setOperationAction(ISD::BR_CC            , MVT::i8,    Expand);
295   setOperationAction(ISD::BR_CC            , MVT::i16,   Expand);
296   setOperationAction(ISD::BR_CC            , MVT::i32,   Expand);
297   setOperationAction(ISD::BR_CC            , MVT::i64,   Expand);
298   setOperationAction(ISD::SELECT_CC        , MVT::f32,   Expand);
299   setOperationAction(ISD::SELECT_CC        , MVT::f64,   Expand);
300   setOperationAction(ISD::SELECT_CC        , MVT::f80,   Expand);
301   setOperationAction(ISD::SELECT_CC        , MVT::i8,    Expand);
302   setOperationAction(ISD::SELECT_CC        , MVT::i16,   Expand);
303   setOperationAction(ISD::SELECT_CC        , MVT::i32,   Expand);
304   setOperationAction(ISD::SELECT_CC        , MVT::i64,   Expand);
305   if (Subtarget->is64Bit())
306     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
307   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
308   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
309   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
310   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
311   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
312   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
313   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
314   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
315
316   // Promote the i8 variants and force them on up to i32 which has a shorter
317   // encoding.
318   setOperationAction(ISD::CTTZ             , MVT::i8   , Promote);
319   AddPromotedToType (ISD::CTTZ             , MVT::i8   , MVT::i32);
320   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , Promote);
321   AddPromotedToType (ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , MVT::i32);
322   if (Subtarget->hasBMI()) {
323     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16  , Expand);
324     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32  , Expand);
325     if (Subtarget->is64Bit())
326       setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
327   } else {
328     setOperationAction(ISD::CTTZ           , MVT::i16  , Custom);
329     setOperationAction(ISD::CTTZ           , MVT::i32  , Custom);
330     if (Subtarget->is64Bit())
331       setOperationAction(ISD::CTTZ         , MVT::i64  , Custom);
332   }
333
334   if (Subtarget->hasLZCNT()) {
335     // When promoting the i8 variants, force them to i32 for a shorter
336     // encoding.
337     setOperationAction(ISD::CTLZ           , MVT::i8   , Promote);
338     AddPromotedToType (ISD::CTLZ           , MVT::i8   , MVT::i32);
339     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Promote);
340     AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8   , MVT::i32);
341     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Expand);
342     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Expand);
343     if (Subtarget->is64Bit())
344       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
345   } else {
346     setOperationAction(ISD::CTLZ           , MVT::i8   , Custom);
347     setOperationAction(ISD::CTLZ           , MVT::i16  , Custom);
348     setOperationAction(ISD::CTLZ           , MVT::i32  , Custom);
349     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Custom);
350     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Custom);
351     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Custom);
352     if (Subtarget->is64Bit()) {
353       setOperationAction(ISD::CTLZ         , MVT::i64  , Custom);
354       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
355     }
356   }
357
358   // Special handling for half-precision floating point conversions.
359   // If we don't have F16C support, then lower half float conversions
360   // into library calls.
361   if (Subtarget->useSoftFloat() || !Subtarget->hasF16C()) {
362     setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
363     setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
364   }
365
366   // There's never any support for operations beyond MVT::f32.
367   setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
368   setOperationAction(ISD::FP16_TO_FP, MVT::f80, Expand);
369   setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
370   setOperationAction(ISD::FP_TO_FP16, MVT::f80, Expand);
371
372   setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
373   setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
374   setLoadExtAction(ISD::EXTLOAD, MVT::f80, MVT::f16, Expand);
375   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
376   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
377   setTruncStoreAction(MVT::f80, MVT::f16, Expand);
378
379   if (Subtarget->hasPOPCNT()) {
380     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
381   } else {
382     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
383     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
384     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
385     if (Subtarget->is64Bit())
386       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
387   }
388
389   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
390
391   if (!Subtarget->hasMOVBE())
392     setOperationAction(ISD::BSWAP          , MVT::i16  , Expand);
393
394   // These should be promoted to a larger select which is supported.
395   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
396   // X86 wants to expand cmov itself.
397   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
398   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
399   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
400   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
401   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
402   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
403   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
404   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
405   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
406   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
407   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
408   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
409   if (Subtarget->is64Bit()) {
410     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
411     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
412   }
413   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
414   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
415   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
416   // support continuation, user-level threading, and etc.. As a result, no
417   // other SjLj exception interfaces are implemented and please don't build
418   // your own exception handling based on them.
419   // LLVM/Clang supports zero-cost DWARF exception handling.
420   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
421   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
422
423   // Darwin ABI issue.
424   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
425   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
426   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
427   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
428   if (Subtarget->is64Bit())
429     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
430   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
431   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
432   if (Subtarget->is64Bit()) {
433     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
434     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
435     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
436     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
437     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
438   }
439   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
440   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
441   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
442   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
443   if (Subtarget->is64Bit()) {
444     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
445     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
446     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
447   }
448
449   if (Subtarget->hasSSE1())
450     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
451
452   setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
453
454   // Expand certain atomics
455   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
456     MVT VT = IntVTs[i];
457     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, VT, Custom);
458     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
459     setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
460   }
461
462   if (Subtarget->hasCmpxchg16b()) {
463     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i128, Custom);
464   }
465
466   // FIXME - use subtarget debug flags
467   if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetELF() &&
468       !Subtarget->isTargetCygMing() && !Subtarget->isTargetWin64()) {
469     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
470   }
471
472   if (Subtarget->is64Bit()) {
473     setExceptionPointerRegister(X86::RAX);
474     setExceptionSelectorRegister(X86::RDX);
475   } else {
476     setExceptionPointerRegister(X86::EAX);
477     setExceptionSelectorRegister(X86::EDX);
478   }
479   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
480   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
481
482   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
483   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
484
485   setOperationAction(ISD::TRAP, MVT::Other, Legal);
486   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
487
488   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
489   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
490   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
491   if (Subtarget->is64Bit() && !Subtarget->isTargetWin64()) {
492     // TargetInfo::X86_64ABIBuiltinVaList
493     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
494     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
495   } else {
496     // TargetInfo::CharPtrBuiltinVaList
497     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
498     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
499   }
500
501   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
502   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
503
504   setOperationAction(ISD::DYNAMIC_STACKALLOC, PtrVT, Custom);
505
506   // GC_TRANSITION_START and GC_TRANSITION_END need custom lowering.
507   setOperationAction(ISD::GC_TRANSITION_START, MVT::Other, Custom);
508   setOperationAction(ISD::GC_TRANSITION_END, MVT::Other, Custom);
509
510   if (!Subtarget->useSoftFloat() && X86ScalarSSEf64) {
511     // f32 and f64 use SSE.
512     // Set up the FP register classes.
513     addRegisterClass(MVT::f32, &X86::FR32RegClass);
514     addRegisterClass(MVT::f64, &X86::FR64RegClass);
515
516     // Use ANDPD to simulate FABS.
517     setOperationAction(ISD::FABS , MVT::f64, Custom);
518     setOperationAction(ISD::FABS , MVT::f32, Custom);
519
520     // Use XORP to simulate FNEG.
521     setOperationAction(ISD::FNEG , MVT::f64, Custom);
522     setOperationAction(ISD::FNEG , MVT::f32, Custom);
523
524     // Use ANDPD and ORPD to simulate FCOPYSIGN.
525     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
526     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
527
528     // Lower this to FGETSIGNx86 plus an AND.
529     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
530     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
531
532     // We don't support sin/cos/fmod
533     setOperationAction(ISD::FSIN   , MVT::f64, Expand);
534     setOperationAction(ISD::FCOS   , MVT::f64, Expand);
535     setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
536     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
537     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
538     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
539
540     // Expand FP immediates into loads from the stack, except for the special
541     // cases we handle.
542     addLegalFPImmediate(APFloat(+0.0)); // xorpd
543     addLegalFPImmediate(APFloat(+0.0f)); // xorps
544   } else if (!Subtarget->useSoftFloat() && X86ScalarSSEf32) {
545     // Use SSE for f32, x87 for f64.
546     // Set up the FP register classes.
547     addRegisterClass(MVT::f32, &X86::FR32RegClass);
548     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
549
550     // Use ANDPS to simulate FABS.
551     setOperationAction(ISD::FABS , MVT::f32, Custom);
552
553     // Use XORP to simulate FNEG.
554     setOperationAction(ISD::FNEG , MVT::f32, Custom);
555
556     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
557
558     // Use ANDPS and ORPS to simulate FCOPYSIGN.
559     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
560     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
561
562     // We don't support sin/cos/fmod
563     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
564     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
565     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
566
567     // Special cases we handle for FP constants.
568     addLegalFPImmediate(APFloat(+0.0f)); // xorps
569     addLegalFPImmediate(APFloat(+0.0)); // FLD0
570     addLegalFPImmediate(APFloat(+1.0)); // FLD1
571     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
572     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
573
574     if (!TM.Options.UnsafeFPMath) {
575       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
576       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
577       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
578     }
579   } else if (!Subtarget->useSoftFloat()) {
580     // f32 and f64 in x87.
581     // Set up the FP register classes.
582     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
583     addRegisterClass(MVT::f32, &X86::RFP32RegClass);
584
585     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
586     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
587     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
588     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
589
590     if (!TM.Options.UnsafeFPMath) {
591       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
592       setOperationAction(ISD::FSIN   , MVT::f32, Expand);
593       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
594       setOperationAction(ISD::FCOS   , MVT::f32, Expand);
595       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
596       setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
597     }
598     addLegalFPImmediate(APFloat(+0.0)); // FLD0
599     addLegalFPImmediate(APFloat(+1.0)); // FLD1
600     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
601     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
602     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
603     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
604     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
605     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
606   }
607
608   // We don't support FMA.
609   setOperationAction(ISD::FMA, MVT::f64, Expand);
610   setOperationAction(ISD::FMA, MVT::f32, Expand);
611
612   // Long double always uses X87.
613   if (!Subtarget->useSoftFloat()) {
614     addRegisterClass(MVT::f80, &X86::RFP80RegClass);
615     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
616     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
617     {
618       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
619       addLegalFPImmediate(TmpFlt);  // FLD0
620       TmpFlt.changeSign();
621       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
622
623       bool ignored;
624       APFloat TmpFlt2(+1.0);
625       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
626                       &ignored);
627       addLegalFPImmediate(TmpFlt2);  // FLD1
628       TmpFlt2.changeSign();
629       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
630     }
631
632     if (!TM.Options.UnsafeFPMath) {
633       setOperationAction(ISD::FSIN   , MVT::f80, Expand);
634       setOperationAction(ISD::FCOS   , MVT::f80, Expand);
635       setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
636     }
637
638     setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
639     setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
640     setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
641     setOperationAction(ISD::FRINT,  MVT::f80, Expand);
642     setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
643     setOperationAction(ISD::FMA, MVT::f80, Expand);
644   }
645
646   // Always use a library call for pow.
647   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
648   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
649   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
650
651   setOperationAction(ISD::FLOG, MVT::f80, Expand);
652   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
653   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
654   setOperationAction(ISD::FEXP, MVT::f80, Expand);
655   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
656   setOperationAction(ISD::FMINNUM, MVT::f80, Expand);
657   setOperationAction(ISD::FMAXNUM, MVT::f80, Expand);
658
659   // First set operation action for all vector types to either promote
660   // (for widening) or expand (for scalarization). Then we will selectively
661   // turn on ones that can be effectively codegen'd.
662   for (MVT VT : MVT::vector_valuetypes()) {
663     setOperationAction(ISD::ADD , VT, Expand);
664     setOperationAction(ISD::SUB , VT, Expand);
665     setOperationAction(ISD::FADD, VT, Expand);
666     setOperationAction(ISD::FNEG, VT, Expand);
667     setOperationAction(ISD::FSUB, VT, Expand);
668     setOperationAction(ISD::MUL , VT, Expand);
669     setOperationAction(ISD::FMUL, VT, Expand);
670     setOperationAction(ISD::SDIV, VT, Expand);
671     setOperationAction(ISD::UDIV, VT, Expand);
672     setOperationAction(ISD::FDIV, VT, Expand);
673     setOperationAction(ISD::SREM, VT, Expand);
674     setOperationAction(ISD::UREM, VT, Expand);
675     setOperationAction(ISD::LOAD, VT, Expand);
676     setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
677     setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
678     setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
679     setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
680     setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
681     setOperationAction(ISD::FABS, VT, Expand);
682     setOperationAction(ISD::FSIN, VT, Expand);
683     setOperationAction(ISD::FSINCOS, VT, Expand);
684     setOperationAction(ISD::FCOS, VT, Expand);
685     setOperationAction(ISD::FSINCOS, VT, Expand);
686     setOperationAction(ISD::FREM, VT, Expand);
687     setOperationAction(ISD::FMA,  VT, Expand);
688     setOperationAction(ISD::FPOWI, VT, Expand);
689     setOperationAction(ISD::FSQRT, VT, Expand);
690     setOperationAction(ISD::FCOPYSIGN, VT, Expand);
691     setOperationAction(ISD::FFLOOR, VT, Expand);
692     setOperationAction(ISD::FCEIL, VT, Expand);
693     setOperationAction(ISD::FTRUNC, VT, Expand);
694     setOperationAction(ISD::FRINT, VT, Expand);
695     setOperationAction(ISD::FNEARBYINT, VT, Expand);
696     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
697     setOperationAction(ISD::MULHS, VT, Expand);
698     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
699     setOperationAction(ISD::MULHU, VT, Expand);
700     setOperationAction(ISD::SDIVREM, VT, Expand);
701     setOperationAction(ISD::UDIVREM, VT, Expand);
702     setOperationAction(ISD::FPOW, VT, Expand);
703     setOperationAction(ISD::CTPOP, VT, Expand);
704     setOperationAction(ISD::CTTZ, VT, Expand);
705     setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
706     setOperationAction(ISD::CTLZ, VT, Expand);
707     setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
708     setOperationAction(ISD::SHL, VT, Expand);
709     setOperationAction(ISD::SRA, VT, Expand);
710     setOperationAction(ISD::SRL, VT, Expand);
711     setOperationAction(ISD::ROTL, VT, Expand);
712     setOperationAction(ISD::ROTR, VT, Expand);
713     setOperationAction(ISD::BSWAP, VT, Expand);
714     setOperationAction(ISD::SETCC, VT, Expand);
715     setOperationAction(ISD::FLOG, VT, Expand);
716     setOperationAction(ISD::FLOG2, VT, Expand);
717     setOperationAction(ISD::FLOG10, VT, Expand);
718     setOperationAction(ISD::FEXP, VT, Expand);
719     setOperationAction(ISD::FEXP2, VT, Expand);
720     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
721     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
722     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
723     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
724     setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
725     setOperationAction(ISD::TRUNCATE, VT, Expand);
726     setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
727     setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
728     setOperationAction(ISD::ANY_EXTEND, VT, Expand);
729     setOperationAction(ISD::VSELECT, VT, Expand);
730     setOperationAction(ISD::SELECT_CC, VT, Expand);
731     for (MVT InnerVT : MVT::vector_valuetypes()) {
732       setTruncStoreAction(InnerVT, VT, Expand);
733
734       setLoadExtAction(ISD::SEXTLOAD, InnerVT, VT, Expand);
735       setLoadExtAction(ISD::ZEXTLOAD, InnerVT, VT, Expand);
736
737       // N.b. ISD::EXTLOAD legality is basically ignored except for i1-like
738       // types, we have to deal with them whether we ask for Expansion or not.
739       // Setting Expand causes its own optimisation problems though, so leave
740       // them legal.
741       if (VT.getVectorElementType() == MVT::i1)
742         setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
743
744       // EXTLOAD for MVT::f16 vectors is not legal because f16 vectors are
745       // split/scalarized right now.
746       if (VT.getVectorElementType() == MVT::f16)
747         setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
748     }
749   }
750
751   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
752   // with -msoft-float, disable use of MMX as well.
753   if (!Subtarget->useSoftFloat() && Subtarget->hasMMX()) {
754     addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
755     // No operations on x86mmx supported, everything uses intrinsics.
756   }
757
758   // MMX-sized vectors (other than x86mmx) are expected to be expanded
759   // into smaller operations.
760   for (MVT MMXTy : {MVT::v8i8, MVT::v4i16, MVT::v2i32, MVT::v1i64}) {
761     setOperationAction(ISD::MULHS,              MMXTy,      Expand);
762     setOperationAction(ISD::AND,                MMXTy,      Expand);
763     setOperationAction(ISD::OR,                 MMXTy,      Expand);
764     setOperationAction(ISD::XOR,                MMXTy,      Expand);
765     setOperationAction(ISD::SCALAR_TO_VECTOR,   MMXTy,      Expand);
766     setOperationAction(ISD::SELECT,             MMXTy,      Expand);
767     setOperationAction(ISD::BITCAST,            MMXTy,      Expand);
768   }
769   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
770
771   if (!Subtarget->useSoftFloat() && Subtarget->hasSSE1()) {
772     addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
773
774     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
775     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
776     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
777     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
778     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
779     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
780     setOperationAction(ISD::FABS,               MVT::v4f32, Custom);
781     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
782     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
783     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
784     setOperationAction(ISD::VSELECT,            MVT::v4f32, Custom);
785     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
786     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
787     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Custom);
788   }
789
790   if (!Subtarget->useSoftFloat() && Subtarget->hasSSE2()) {
791     addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
792
793     // FIXME: Unfortunately, -soft-float and -no-implicit-float mean XMM
794     // registers cannot be used even for integer operations.
795     addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
796     addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
797     addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
798     addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
799
800     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
801     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
802     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
803     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
804     setOperationAction(ISD::MUL,                MVT::v16i8, Custom);
805     setOperationAction(ISD::MUL,                MVT::v4i32, Custom);
806     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
807     setOperationAction(ISD::UMUL_LOHI,          MVT::v4i32, Custom);
808     setOperationAction(ISD::SMUL_LOHI,          MVT::v4i32, Custom);
809     setOperationAction(ISD::MULHU,              MVT::v8i16, Legal);
810     setOperationAction(ISD::MULHS,              MVT::v8i16, Legal);
811     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
812     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
813     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
814     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
815     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
816     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
817     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
818     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
819     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
820     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
821     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
822     setOperationAction(ISD::FABS,               MVT::v2f64, Custom);
823
824     setOperationAction(ISD::SMAX,               MVT::v8i16, Legal);
825     setOperationAction(ISD::UMAX,               MVT::v16i8, Legal);
826     setOperationAction(ISD::SMIN,               MVT::v8i16, Legal);
827     setOperationAction(ISD::UMIN,               MVT::v16i8, Legal);
828
829     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
830     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
831     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
832     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
833
834     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
835     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
836     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
837     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
838     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
839
840     setOperationAction(ISD::CTPOP,              MVT::v16i8, Custom);
841     setOperationAction(ISD::CTPOP,              MVT::v8i16, Custom);
842     setOperationAction(ISD::CTPOP,              MVT::v4i32, Custom);
843     setOperationAction(ISD::CTPOP,              MVT::v2i64, Custom);
844
845     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
846     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
847       MVT VT = (MVT::SimpleValueType)i;
848       // Do not attempt to custom lower non-power-of-2 vectors
849       if (!isPowerOf2_32(VT.getVectorNumElements()))
850         continue;
851       // Do not attempt to custom lower non-128-bit vectors
852       if (!VT.is128BitVector())
853         continue;
854       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
855       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
856       setOperationAction(ISD::VSELECT,            VT, Custom);
857       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
858     }
859
860     // We support custom legalizing of sext and anyext loads for specific
861     // memory vector types which we can load as a scalar (or sequence of
862     // scalars) and extend in-register to a legal 128-bit vector type. For sext
863     // loads these must work with a single scalar load.
864     for (MVT VT : MVT::integer_vector_valuetypes()) {
865       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i8, Custom);
866       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i16, Custom);
867       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v8i8, Custom);
868       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i8, Custom);
869       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i16, Custom);
870       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i32, Custom);
871       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i8, Custom);
872       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i16, Custom);
873       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8i8, Custom);
874     }
875
876     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
877     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
878     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
879     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
880     setOperationAction(ISD::VSELECT,            MVT::v2f64, Custom);
881     setOperationAction(ISD::VSELECT,            MVT::v2i64, Custom);
882     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
883     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
884
885     if (Subtarget->is64Bit()) {
886       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
887       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
888     }
889
890     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
891     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
892       MVT VT = (MVT::SimpleValueType)i;
893
894       // Do not attempt to promote non-128-bit vectors
895       if (!VT.is128BitVector())
896         continue;
897
898       setOperationAction(ISD::AND,    VT, Promote);
899       AddPromotedToType (ISD::AND,    VT, MVT::v2i64);
900       setOperationAction(ISD::OR,     VT, Promote);
901       AddPromotedToType (ISD::OR,     VT, MVT::v2i64);
902       setOperationAction(ISD::XOR,    VT, Promote);
903       AddPromotedToType (ISD::XOR,    VT, MVT::v2i64);
904       setOperationAction(ISD::LOAD,   VT, Promote);
905       AddPromotedToType (ISD::LOAD,   VT, MVT::v2i64);
906       setOperationAction(ISD::SELECT, VT, Promote);
907       AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
908     }
909
910     // Custom lower v2i64 and v2f64 selects.
911     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
912     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
913     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
914     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
915
916     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
917     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
918
919     setOperationAction(ISD::SINT_TO_FP,         MVT::v2i32, Custom);
920
921     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i8,  Custom);
922     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i16, Custom);
923     // As there is no 64-bit GPR available, we need build a special custom
924     // sequence to convert from v2i32 to v2f32.
925     if (!Subtarget->is64Bit())
926       setOperationAction(ISD::UINT_TO_FP,       MVT::v2f32, Custom);
927
928     setOperationAction(ISD::FP_EXTEND,          MVT::v2f32, Custom);
929     setOperationAction(ISD::FP_ROUND,           MVT::v2f32, Custom);
930
931     for (MVT VT : MVT::fp_vector_valuetypes())
932       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2f32, Legal);
933
934     setOperationAction(ISD::BITCAST,            MVT::v2i32, Custom);
935     setOperationAction(ISD::BITCAST,            MVT::v4i16, Custom);
936     setOperationAction(ISD::BITCAST,            MVT::v8i8,  Custom);
937   }
938
939   if (!Subtarget->useSoftFloat() && Subtarget->hasSSE41()) {
940     for (MVT RoundedTy : {MVT::f32, MVT::f64, MVT::v4f32, MVT::v2f64}) {
941       setOperationAction(ISD::FFLOOR,           RoundedTy,  Legal);
942       setOperationAction(ISD::FCEIL,            RoundedTy,  Legal);
943       setOperationAction(ISD::FTRUNC,           RoundedTy,  Legal);
944       setOperationAction(ISD::FRINT,            RoundedTy,  Legal);
945       setOperationAction(ISD::FNEARBYINT,       RoundedTy,  Legal);
946     }
947
948     setOperationAction(ISD::SMAX,               MVT::v16i8, Legal);
949     setOperationAction(ISD::SMAX,               MVT::v4i32, Legal);
950     setOperationAction(ISD::UMAX,               MVT::v8i16, Legal);
951     setOperationAction(ISD::UMAX,               MVT::v4i32, Legal);
952     setOperationAction(ISD::SMIN,               MVT::v16i8, Legal);
953     setOperationAction(ISD::SMIN,               MVT::v4i32, Legal);
954     setOperationAction(ISD::UMIN,               MVT::v8i16, Legal);
955     setOperationAction(ISD::UMIN,               MVT::v4i32, Legal);
956
957     // FIXME: Do we need to handle scalar-to-vector here?
958     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
959
960     // We directly match byte blends in the backend as they match the VSELECT
961     // condition form.
962     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
963
964     // SSE41 brings specific instructions for doing vector sign extend even in
965     // cases where we don't have SRA.
966     for (MVT VT : MVT::integer_vector_valuetypes()) {
967       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i8, Custom);
968       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i16, Custom);
969       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i32, Custom);
970     }
971
972     // SSE41 also has vector sign/zero extending loads, PMOV[SZ]X
973     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i16, MVT::v8i8,  Legal);
974     setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i8,  Legal);
975     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i8,  Legal);
976     setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
977     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
978     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
979
980     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i16, MVT::v8i8,  Legal);
981     setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i8,  Legal);
982     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i8,  Legal);
983     setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
984     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
985     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
986
987     // i8 and i16 vectors are custom because the source register and source
988     // source memory operand types are not the same width.  f32 vectors are
989     // custom since the immediate controlling the insert encodes additional
990     // information.
991     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
992     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
993     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
994     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
995
996     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
997     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
998     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
999     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1000
1001     // FIXME: these should be Legal, but that's only for the case where
1002     // the index is constant.  For now custom expand to deal with that.
1003     if (Subtarget->is64Bit()) {
1004       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1005       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1006     }
1007   }
1008
1009   if (Subtarget->hasSSE2()) {
1010     setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v2i64, Custom);
1011     setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v4i32, Custom);
1012     setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v8i16, Custom);
1013
1014     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
1015     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
1016
1017     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
1018     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
1019
1020     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
1021     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
1022
1023     // In the customized shift lowering, the legal cases in AVX2 will be
1024     // recognized.
1025     setOperationAction(ISD::SRL,               MVT::v2i64, Custom);
1026     setOperationAction(ISD::SRL,               MVT::v4i32, Custom);
1027
1028     setOperationAction(ISD::SHL,               MVT::v2i64, Custom);
1029     setOperationAction(ISD::SHL,               MVT::v4i32, Custom);
1030
1031     setOperationAction(ISD::SRA,               MVT::v2i64, Custom);
1032     setOperationAction(ISD::SRA,               MVT::v4i32, Custom);
1033   }
1034
1035   if (!Subtarget->useSoftFloat() && Subtarget->hasFp256()) {
1036     addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1037     addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1038     addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1039     addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1040     addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1041     addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1042
1043     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1044     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1045     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1046
1047     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1048     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1049     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1050     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1051     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1052     setOperationAction(ISD::FFLOOR,             MVT::v8f32, Legal);
1053     setOperationAction(ISD::FCEIL,              MVT::v8f32, Legal);
1054     setOperationAction(ISD::FTRUNC,             MVT::v8f32, Legal);
1055     setOperationAction(ISD::FRINT,              MVT::v8f32, Legal);
1056     setOperationAction(ISD::FNEARBYINT,         MVT::v8f32, Legal);
1057     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1058     setOperationAction(ISD::FABS,               MVT::v8f32, Custom);
1059
1060     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1061     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1062     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1063     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1064     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1065     setOperationAction(ISD::FFLOOR,             MVT::v4f64, Legal);
1066     setOperationAction(ISD::FCEIL,              MVT::v4f64, Legal);
1067     setOperationAction(ISD::FTRUNC,             MVT::v4f64, Legal);
1068     setOperationAction(ISD::FRINT,              MVT::v4f64, Legal);
1069     setOperationAction(ISD::FNEARBYINT,         MVT::v4f64, Legal);
1070     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1071     setOperationAction(ISD::FABS,               MVT::v4f64, Custom);
1072
1073     // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1074     // even though v8i16 is a legal type.
1075     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i16, Promote);
1076     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i16, Promote);
1077     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1078
1079     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i16, Promote);
1080     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1081     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1082
1083     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i8,  Custom);
1084     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i16, Custom);
1085
1086     for (MVT VT : MVT::fp_vector_valuetypes())
1087       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4f32, Legal);
1088
1089     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1090     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1091
1092     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1093     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1094
1095     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1096     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1097
1098     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1099     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1100     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1101     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1102
1103     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1104     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1105     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1106
1107     setOperationAction(ISD::SIGN_EXTEND,       MVT::v4i64, Custom);
1108     setOperationAction(ISD::SIGN_EXTEND,       MVT::v8i32, Custom);
1109     setOperationAction(ISD::SIGN_EXTEND,       MVT::v16i16, Custom);
1110     setOperationAction(ISD::ZERO_EXTEND,       MVT::v4i64, Custom);
1111     setOperationAction(ISD::ZERO_EXTEND,       MVT::v8i32, Custom);
1112     setOperationAction(ISD::ZERO_EXTEND,       MVT::v16i16, Custom);
1113     setOperationAction(ISD::ANY_EXTEND,        MVT::v4i64, Custom);
1114     setOperationAction(ISD::ANY_EXTEND,        MVT::v8i32, Custom);
1115     setOperationAction(ISD::ANY_EXTEND,        MVT::v16i16, Custom);
1116     setOperationAction(ISD::TRUNCATE,          MVT::v16i8, Custom);
1117     setOperationAction(ISD::TRUNCATE,          MVT::v8i16, Custom);
1118     setOperationAction(ISD::TRUNCATE,          MVT::v4i32, Custom);
1119
1120     setOperationAction(ISD::CTPOP,             MVT::v32i8, Custom);
1121     setOperationAction(ISD::CTPOP,             MVT::v16i16, Custom);
1122     setOperationAction(ISD::CTPOP,             MVT::v8i32, Custom);
1123     setOperationAction(ISD::CTPOP,             MVT::v4i64, Custom);
1124
1125     if (Subtarget->hasFMA() || Subtarget->hasFMA4() || Subtarget->hasAVX512()) {
1126       setOperationAction(ISD::FMA,             MVT::v8f32, Legal);
1127       setOperationAction(ISD::FMA,             MVT::v4f64, Legal);
1128       setOperationAction(ISD::FMA,             MVT::v4f32, Legal);
1129       setOperationAction(ISD::FMA,             MVT::v2f64, Legal);
1130       setOperationAction(ISD::FMA,             MVT::f32, Legal);
1131       setOperationAction(ISD::FMA,             MVT::f64, Legal);
1132     }
1133
1134     if (Subtarget->hasInt256()) {
1135       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1136       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1137       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1138       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1139
1140       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1141       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1142       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1143       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1144
1145       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1146       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1147       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1148       setOperationAction(ISD::MUL,             MVT::v32i8, Custom);
1149
1150       setOperationAction(ISD::UMUL_LOHI,       MVT::v8i32, Custom);
1151       setOperationAction(ISD::SMUL_LOHI,       MVT::v8i32, Custom);
1152       setOperationAction(ISD::MULHU,           MVT::v16i16, Legal);
1153       setOperationAction(ISD::MULHS,           MVT::v16i16, Legal);
1154
1155       setOperationAction(ISD::SMAX,            MVT::v32i8,  Legal);
1156       setOperationAction(ISD::SMAX,            MVT::v16i16, Legal);
1157       setOperationAction(ISD::SMAX,            MVT::v8i32,  Legal);
1158       setOperationAction(ISD::UMAX,            MVT::v32i8,  Legal);
1159       setOperationAction(ISD::UMAX,            MVT::v16i16, Legal);
1160       setOperationAction(ISD::UMAX,            MVT::v8i32,  Legal);
1161       setOperationAction(ISD::SMIN,            MVT::v32i8,  Legal);
1162       setOperationAction(ISD::SMIN,            MVT::v16i16, Legal);
1163       setOperationAction(ISD::SMIN,            MVT::v8i32,  Legal);
1164       setOperationAction(ISD::UMIN,            MVT::v32i8,  Legal);
1165       setOperationAction(ISD::UMIN,            MVT::v16i16, Legal);
1166       setOperationAction(ISD::UMIN,            MVT::v8i32,  Legal);
1167
1168       // The custom lowering for UINT_TO_FP for v8i32 becomes interesting
1169       // when we have a 256bit-wide blend with immediate.
1170       setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Custom);
1171
1172       // AVX2 also has wider vector sign/zero extending loads, VPMOV[SZ]X
1173       setLoadExtAction(ISD::SEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1174       setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32,  MVT::v8i8,  Legal);
1175       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i8,  Legal);
1176       setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32,  MVT::v8i16, Legal);
1177       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i16, Legal);
1178       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i32, Legal);
1179
1180       setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1181       setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32,  MVT::v8i8,  Legal);
1182       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i8,  Legal);
1183       setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32,  MVT::v8i16, Legal);
1184       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i16, Legal);
1185       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i32, Legal);
1186     } else {
1187       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1188       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1189       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1190       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1191
1192       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1193       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1194       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1195       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1196
1197       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1198       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1199       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1200       setOperationAction(ISD::MUL,             MVT::v32i8, Custom);
1201     }
1202
1203     // In the customized shift lowering, the legal cases in AVX2 will be
1204     // recognized.
1205     setOperationAction(ISD::SRL,               MVT::v4i64, Custom);
1206     setOperationAction(ISD::SRL,               MVT::v8i32, Custom);
1207
1208     setOperationAction(ISD::SHL,               MVT::v4i64, Custom);
1209     setOperationAction(ISD::SHL,               MVT::v8i32, Custom);
1210
1211     setOperationAction(ISD::SRA,               MVT::v4i64, Custom);
1212     setOperationAction(ISD::SRA,               MVT::v8i32, Custom);
1213
1214     // Custom lower several nodes for 256-bit types.
1215     for (MVT VT : MVT::vector_valuetypes()) {
1216       if (VT.getScalarSizeInBits() >= 32) {
1217         setOperationAction(ISD::MLOAD,  VT, Legal);
1218         setOperationAction(ISD::MSTORE, VT, Legal);
1219       }
1220       // Extract subvector is special because the value type
1221       // (result) is 128-bit but the source is 256-bit wide.
1222       if (VT.is128BitVector()) {
1223         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1224       }
1225       // Do not attempt to custom lower other non-256-bit vectors
1226       if (!VT.is256BitVector())
1227         continue;
1228
1229       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1230       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1231       setOperationAction(ISD::VSELECT,            VT, Custom);
1232       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1233       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1234       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1235       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1236       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1237     }
1238
1239     if (Subtarget->hasInt256())
1240       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1241
1242
1243     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1244     for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1245       MVT VT = (MVT::SimpleValueType)i;
1246
1247       // Do not attempt to promote non-256-bit vectors
1248       if (!VT.is256BitVector())
1249         continue;
1250
1251       setOperationAction(ISD::AND,    VT, Promote);
1252       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1253       setOperationAction(ISD::OR,     VT, Promote);
1254       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1255       setOperationAction(ISD::XOR,    VT, Promote);
1256       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1257       setOperationAction(ISD::LOAD,   VT, Promote);
1258       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1259       setOperationAction(ISD::SELECT, VT, Promote);
1260       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1261     }
1262   }
1263
1264   if (!Subtarget->useSoftFloat() && Subtarget->hasAVX512()) {
1265     addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1266     addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1267     addRegisterClass(MVT::v8i64,  &X86::VR512RegClass);
1268     addRegisterClass(MVT::v8f64,  &X86::VR512RegClass);
1269
1270     addRegisterClass(MVT::i1,     &X86::VK1RegClass);
1271     addRegisterClass(MVT::v8i1,   &X86::VK8RegClass);
1272     addRegisterClass(MVT::v16i1,  &X86::VK16RegClass);
1273
1274     for (MVT VT : MVT::fp_vector_valuetypes())
1275       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8f32, Legal);
1276
1277     setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i32, MVT::v16i8, Legal);
1278     setLoadExtAction(ISD::SEXTLOAD, MVT::v16i32, MVT::v16i8, Legal);
1279     setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i32, MVT::v16i16, Legal);
1280     setLoadExtAction(ISD::SEXTLOAD, MVT::v16i32, MVT::v16i16, Legal);
1281     setLoadExtAction(ISD::ZEXTLOAD, MVT::v32i16, MVT::v32i8, Legal);
1282     setLoadExtAction(ISD::SEXTLOAD, MVT::v32i16, MVT::v32i8, Legal);
1283     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64,  MVT::v8i8,  Legal);
1284     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64,  MVT::v8i8,  Legal);
1285     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64,  MVT::v8i16,  Legal);
1286     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64,  MVT::v8i16,  Legal);
1287     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64,  MVT::v8i32,  Legal);
1288     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64,  MVT::v8i32,  Legal);
1289
1290     setOperationAction(ISD::BR_CC,              MVT::i1,    Expand);
1291     setOperationAction(ISD::SETCC,              MVT::i1,    Custom);
1292     setOperationAction(ISD::XOR,                MVT::i1,    Legal);
1293     setOperationAction(ISD::OR,                 MVT::i1,    Legal);
1294     setOperationAction(ISD::AND,                MVT::i1,    Legal);
1295     setOperationAction(ISD::SUB,                MVT::i1,    Custom);
1296     setOperationAction(ISD::ADD,                MVT::i1,    Custom);
1297     setOperationAction(ISD::MUL,                MVT::i1,    Custom);
1298     setOperationAction(ISD::LOAD,               MVT::v16f32, Legal);
1299     setOperationAction(ISD::LOAD,               MVT::v8f64, Legal);
1300     setOperationAction(ISD::LOAD,               MVT::v8i64, Legal);
1301     setOperationAction(ISD::LOAD,               MVT::v16i32, Legal);
1302     setOperationAction(ISD::LOAD,               MVT::v16i1, Legal);
1303
1304     setOperationAction(ISD::FADD,               MVT::v16f32, Legal);
1305     setOperationAction(ISD::FSUB,               MVT::v16f32, Legal);
1306     setOperationAction(ISD::FMUL,               MVT::v16f32, Legal);
1307     setOperationAction(ISD::FDIV,               MVT::v16f32, Legal);
1308     setOperationAction(ISD::FSQRT,              MVT::v16f32, Legal);
1309     setOperationAction(ISD::FNEG,               MVT::v16f32, Custom);
1310
1311     setOperationAction(ISD::FADD,               MVT::v8f64, Legal);
1312     setOperationAction(ISD::FSUB,               MVT::v8f64, Legal);
1313     setOperationAction(ISD::FMUL,               MVT::v8f64, Legal);
1314     setOperationAction(ISD::FDIV,               MVT::v8f64, Legal);
1315     setOperationAction(ISD::FSQRT,              MVT::v8f64, Legal);
1316     setOperationAction(ISD::FNEG,               MVT::v8f64, Custom);
1317     setOperationAction(ISD::FMA,                MVT::v8f64, Legal);
1318     setOperationAction(ISD::FMA,                MVT::v16f32, Legal);
1319
1320     setOperationAction(ISD::FP_TO_SINT,         MVT::i32, Legal);
1321     setOperationAction(ISD::FP_TO_UINT,         MVT::i32, Legal);
1322     setOperationAction(ISD::SINT_TO_FP,         MVT::i32, Legal);
1323     setOperationAction(ISD::UINT_TO_FP,         MVT::i32, Legal);
1324     if (Subtarget->is64Bit()) {
1325       setOperationAction(ISD::FP_TO_UINT,       MVT::i64, Legal);
1326       setOperationAction(ISD::FP_TO_SINT,       MVT::i64, Legal);
1327       setOperationAction(ISD::SINT_TO_FP,       MVT::i64, Legal);
1328       setOperationAction(ISD::UINT_TO_FP,       MVT::i64, Legal);
1329     }
1330     setOperationAction(ISD::FP_TO_SINT,         MVT::v16i32, Legal);
1331     setOperationAction(ISD::FP_TO_UINT,         MVT::v16i32, Legal);
1332     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i32, Legal);
1333     setOperationAction(ISD::FP_TO_UINT,         MVT::v4i32, Legal);
1334     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i32, Legal);
1335     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i1,   Custom);
1336     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i1,  Custom);
1337     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i8,  Promote);
1338     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i16, Promote);
1339     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i32, Legal);
1340     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i32, Legal);
1341     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Legal);
1342     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i8, Custom);
1343     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i16, Custom);
1344     setOperationAction(ISD::FP_ROUND,           MVT::v8f32, Legal);
1345     setOperationAction(ISD::FP_EXTEND,          MVT::v8f32, Legal);
1346
1347     setTruncStoreAction(MVT::v8i64,   MVT::v8i8,   Legal);
1348     setTruncStoreAction(MVT::v8i64,   MVT::v8i16,  Legal);
1349     setTruncStoreAction(MVT::v8i64,   MVT::v8i32,  Legal);
1350     setTruncStoreAction(MVT::v16i32,  MVT::v16i8,  Legal);
1351     setTruncStoreAction(MVT::v16i32,  MVT::v16i16, Legal);
1352     if (Subtarget->hasVLX()){
1353       setTruncStoreAction(MVT::v4i64, MVT::v4i8,  Legal);
1354       setTruncStoreAction(MVT::v4i64, MVT::v4i16, Legal);
1355       setTruncStoreAction(MVT::v4i64, MVT::v4i32, Legal);
1356       setTruncStoreAction(MVT::v8i32, MVT::v8i8,  Legal);
1357       setTruncStoreAction(MVT::v8i32, MVT::v8i16, Legal);
1358
1359       setTruncStoreAction(MVT::v2i64, MVT::v2i8,  Legal);
1360       setTruncStoreAction(MVT::v2i64, MVT::v2i16, Legal);
1361       setTruncStoreAction(MVT::v2i64, MVT::v2i32, Legal);
1362       setTruncStoreAction(MVT::v4i32, MVT::v4i8,  Legal);
1363       setTruncStoreAction(MVT::v4i32, MVT::v4i16, Legal);
1364     }
1365     setOperationAction(ISD::TRUNCATE,           MVT::i1, Custom);
1366     setOperationAction(ISD::TRUNCATE,           MVT::v16i8, Custom);
1367     setOperationAction(ISD::TRUNCATE,           MVT::v8i32, Custom);
1368     if (Subtarget->hasDQI()) {
1369       setOperationAction(ISD::TRUNCATE,         MVT::v2i1, Custom);
1370       setOperationAction(ISD::TRUNCATE,         MVT::v4i1, Custom);
1371
1372       setOperationAction(ISD::SINT_TO_FP,       MVT::v8i64, Legal);
1373       setOperationAction(ISD::UINT_TO_FP,       MVT::v8i64, Legal);
1374       setOperationAction(ISD::FP_TO_SINT,       MVT::v8i64, Legal);
1375       setOperationAction(ISD::FP_TO_UINT,       MVT::v8i64, Legal);
1376       if (Subtarget->hasVLX()) {
1377         setOperationAction(ISD::SINT_TO_FP,    MVT::v4i64, Legal);
1378         setOperationAction(ISD::SINT_TO_FP,    MVT::v2i64, Legal);
1379         setOperationAction(ISD::UINT_TO_FP,    MVT::v4i64, Legal);
1380         setOperationAction(ISD::UINT_TO_FP,    MVT::v2i64, Legal);
1381         setOperationAction(ISD::FP_TO_SINT,    MVT::v4i64, Legal);
1382         setOperationAction(ISD::FP_TO_SINT,    MVT::v2i64, Legal);
1383         setOperationAction(ISD::FP_TO_UINT,    MVT::v4i64, Legal);
1384         setOperationAction(ISD::FP_TO_UINT,    MVT::v2i64, Legal);
1385       }
1386     }
1387     if (Subtarget->hasVLX()) {
1388       setOperationAction(ISD::SINT_TO_FP,       MVT::v8i32, Legal);
1389       setOperationAction(ISD::UINT_TO_FP,       MVT::v8i32, Legal);
1390       setOperationAction(ISD::FP_TO_SINT,       MVT::v8i32, Legal);
1391       setOperationAction(ISD::FP_TO_UINT,       MVT::v8i32, Legal);
1392       setOperationAction(ISD::SINT_TO_FP,       MVT::v4i32, Legal);
1393       setOperationAction(ISD::UINT_TO_FP,       MVT::v4i32, Legal);
1394       setOperationAction(ISD::FP_TO_SINT,       MVT::v4i32, Legal);
1395       setOperationAction(ISD::FP_TO_UINT,       MVT::v4i32, Legal);
1396     }
1397     setOperationAction(ISD::TRUNCATE,           MVT::v8i1, Custom);
1398     setOperationAction(ISD::TRUNCATE,           MVT::v16i1, Custom);
1399     setOperationAction(ISD::TRUNCATE,           MVT::v16i16, Custom);
1400     setOperationAction(ISD::ZERO_EXTEND,        MVT::v16i32, Custom);
1401     setOperationAction(ISD::ZERO_EXTEND,        MVT::v8i64, Custom);
1402     setOperationAction(ISD::ANY_EXTEND,         MVT::v16i32, Custom);
1403     setOperationAction(ISD::ANY_EXTEND,         MVT::v8i64, Custom);
1404     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i32, Custom);
1405     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i64, Custom);
1406     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i8, Custom);
1407     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i16, Custom);
1408     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i16, Custom);
1409     if (Subtarget->hasDQI()) {
1410       setOperationAction(ISD::SIGN_EXTEND,        MVT::v4i32, Custom);
1411       setOperationAction(ISD::SIGN_EXTEND,        MVT::v2i64, Custom);
1412     }
1413     setOperationAction(ISD::FFLOOR,             MVT::v16f32, Legal);
1414     setOperationAction(ISD::FFLOOR,             MVT::v8f64, Legal);
1415     setOperationAction(ISD::FCEIL,              MVT::v16f32, Legal);
1416     setOperationAction(ISD::FCEIL,              MVT::v8f64, Legal);
1417     setOperationAction(ISD::FTRUNC,             MVT::v16f32, Legal);
1418     setOperationAction(ISD::FTRUNC,             MVT::v8f64, Legal);
1419     setOperationAction(ISD::FRINT,              MVT::v16f32, Legal);
1420     setOperationAction(ISD::FRINT,              MVT::v8f64, Legal);
1421     setOperationAction(ISD::FNEARBYINT,         MVT::v16f32, Legal);
1422     setOperationAction(ISD::FNEARBYINT,         MVT::v8f64, Legal);
1423
1424     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8f64,  Custom);
1425     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i64,  Custom);
1426     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16f32,  Custom);
1427     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i32,  Custom);
1428     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i1, Legal);
1429
1430     setOperationAction(ISD::SETCC,              MVT::v16i1, Custom);
1431     setOperationAction(ISD::SETCC,              MVT::v8i1, Custom);
1432
1433     setOperationAction(ISD::MUL,              MVT::v8i64, Custom);
1434
1435     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1,  Custom);
1436     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1437     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i1, Custom);
1438     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i1, Custom);
1439     setOperationAction(ISD::BUILD_VECTOR,       MVT::v8i1, Custom);
1440     setOperationAction(ISD::BUILD_VECTOR,       MVT::v16i1, Custom);
1441     setOperationAction(ISD::SELECT,             MVT::v8f64, Custom);
1442     setOperationAction(ISD::SELECT,             MVT::v8i64, Custom);
1443     setOperationAction(ISD::SELECT,             MVT::v16f32, Custom);
1444     setOperationAction(ISD::SELECT,             MVT::v16i1, Custom);
1445     setOperationAction(ISD::SELECT,             MVT::v8i1,  Custom);
1446
1447     setOperationAction(ISD::SMAX,               MVT::v16i32, Legal);
1448     setOperationAction(ISD::SMAX,               MVT::v8i64, Legal);
1449     setOperationAction(ISD::UMAX,               MVT::v16i32, Legal);
1450     setOperationAction(ISD::UMAX,               MVT::v8i64, Legal);
1451     setOperationAction(ISD::SMIN,               MVT::v16i32, Legal);
1452     setOperationAction(ISD::SMIN,               MVT::v8i64, Legal);
1453     setOperationAction(ISD::UMIN,               MVT::v16i32, Legal);
1454     setOperationAction(ISD::UMIN,               MVT::v8i64, Legal);
1455
1456     setOperationAction(ISD::ADD,                MVT::v8i64, Legal);
1457     setOperationAction(ISD::ADD,                MVT::v16i32, Legal);
1458
1459     setOperationAction(ISD::SUB,                MVT::v8i64, Legal);
1460     setOperationAction(ISD::SUB,                MVT::v16i32, Legal);
1461
1462     setOperationAction(ISD::MUL,                MVT::v16i32, Legal);
1463
1464     setOperationAction(ISD::SRL,                MVT::v8i64, Custom);
1465     setOperationAction(ISD::SRL,                MVT::v16i32, Custom);
1466
1467     setOperationAction(ISD::SHL,                MVT::v8i64, Custom);
1468     setOperationAction(ISD::SHL,                MVT::v16i32, Custom);
1469
1470     setOperationAction(ISD::SRA,                MVT::v8i64, Custom);
1471     setOperationAction(ISD::SRA,                MVT::v16i32, Custom);
1472
1473     setOperationAction(ISD::AND,                MVT::v8i64, Legal);
1474     setOperationAction(ISD::OR,                 MVT::v8i64, Legal);
1475     setOperationAction(ISD::XOR,                MVT::v8i64, Legal);
1476     setOperationAction(ISD::AND,                MVT::v16i32, Legal);
1477     setOperationAction(ISD::OR,                 MVT::v16i32, Legal);
1478     setOperationAction(ISD::XOR,                MVT::v16i32, Legal);
1479
1480     if (Subtarget->hasCDI()) {
1481       setOperationAction(ISD::CTLZ,             MVT::v8i64, Legal);
1482       setOperationAction(ISD::CTLZ,             MVT::v16i32, Legal);
1483     }
1484     if (Subtarget->hasDQI()) {
1485       setOperationAction(ISD::MUL,             MVT::v2i64, Legal);
1486       setOperationAction(ISD::MUL,             MVT::v4i64, Legal);
1487       setOperationAction(ISD::MUL,             MVT::v8i64, Legal);
1488     }
1489     // Custom lower several nodes.
1490     for (MVT VT : MVT::vector_valuetypes()) {
1491       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1492       if (EltSize == 1) {
1493         setOperationAction(ISD::AND, VT, Legal);
1494         setOperationAction(ISD::OR,  VT, Legal);
1495         setOperationAction(ISD::XOR,  VT, Legal);
1496       }
1497       if (EltSize >= 32 && VT.getSizeInBits() <= 512) {
1498         setOperationAction(ISD::MGATHER,  VT, Custom);
1499         setOperationAction(ISD::MSCATTER, VT, Custom);
1500       }
1501       // Extract subvector is special because the value type
1502       // (result) is 256/128-bit but the source is 512-bit wide.
1503       if (VT.is128BitVector() || VT.is256BitVector()) {
1504         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1505       }
1506       if (VT.getVectorElementType() == MVT::i1)
1507         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1508
1509       // Do not attempt to custom lower other non-512-bit vectors
1510       if (!VT.is512BitVector())
1511         continue;
1512
1513       if (EltSize >= 32) {
1514         setOperationAction(ISD::VECTOR_SHUFFLE,      VT, Custom);
1515         setOperationAction(ISD::INSERT_VECTOR_ELT,   VT, Custom);
1516         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1517         setOperationAction(ISD::VSELECT,             VT, Legal);
1518         setOperationAction(ISD::EXTRACT_VECTOR_ELT,  VT, Custom);
1519         setOperationAction(ISD::SCALAR_TO_VECTOR,    VT, Custom);
1520         setOperationAction(ISD::INSERT_SUBVECTOR,    VT, Custom);
1521         setOperationAction(ISD::MLOAD,               VT, Legal);
1522         setOperationAction(ISD::MSTORE,              VT, Legal);
1523       }
1524     }
1525     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1526       MVT VT = (MVT::SimpleValueType)i;
1527
1528       // Do not attempt to promote non-512-bit vectors.
1529       if (!VT.is512BitVector())
1530         continue;
1531
1532       setOperationAction(ISD::SELECT, VT, Promote);
1533       AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1534     }
1535   }// has  AVX-512
1536
1537   if (!Subtarget->useSoftFloat() && Subtarget->hasBWI()) {
1538     addRegisterClass(MVT::v32i16, &X86::VR512RegClass);
1539     addRegisterClass(MVT::v64i8,  &X86::VR512RegClass);
1540
1541     addRegisterClass(MVT::v32i1,  &X86::VK32RegClass);
1542     addRegisterClass(MVT::v64i1,  &X86::VK64RegClass);
1543
1544     setOperationAction(ISD::LOAD,               MVT::v32i16, Legal);
1545     setOperationAction(ISD::LOAD,               MVT::v64i8, Legal);
1546     setOperationAction(ISD::SETCC,              MVT::v32i1, Custom);
1547     setOperationAction(ISD::SETCC,              MVT::v64i1, Custom);
1548     setOperationAction(ISD::ADD,                MVT::v32i16, Legal);
1549     setOperationAction(ISD::ADD,                MVT::v64i8, Legal);
1550     setOperationAction(ISD::SUB,                MVT::v32i16, Legal);
1551     setOperationAction(ISD::SUB,                MVT::v64i8, Legal);
1552     setOperationAction(ISD::MUL,                MVT::v32i16, Legal);
1553     setOperationAction(ISD::MULHS,              MVT::v32i16, Legal);
1554     setOperationAction(ISD::MULHU,              MVT::v32i16, Legal);
1555     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v32i1, Custom);
1556     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v64i1, Custom);
1557     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v32i1, Custom);
1558     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v64i1, Custom);
1559     setOperationAction(ISD::SELECT,             MVT::v32i1, Custom);
1560     setOperationAction(ISD::SELECT,             MVT::v64i1, Custom);
1561     setOperationAction(ISD::SIGN_EXTEND,        MVT::v32i8, Custom);
1562     setOperationAction(ISD::ZERO_EXTEND,        MVT::v32i8, Custom);
1563     setOperationAction(ISD::SIGN_EXTEND,        MVT::v32i16, Custom);
1564     setOperationAction(ISD::ZERO_EXTEND,        MVT::v32i16, Custom);
1565     setOperationAction(ISD::SIGN_EXTEND,        MVT::v64i8, Custom);
1566     setOperationAction(ISD::ZERO_EXTEND,        MVT::v64i8, Custom);
1567     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v32i1, Custom);
1568     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v64i1, Custom);
1569     setOperationAction(ISD::VSELECT,            MVT::v32i16, Legal);
1570     setOperationAction(ISD::VSELECT,            MVT::v64i8, Legal);
1571     setOperationAction(ISD::TRUNCATE,           MVT::v32i1, Custom);
1572     setOperationAction(ISD::TRUNCATE,           MVT::v64i1, Custom);
1573     setOperationAction(ISD::TRUNCATE,           MVT::v32i8, Custom);
1574
1575     setOperationAction(ISD::SMAX,               MVT::v64i8, Legal);
1576     setOperationAction(ISD::SMAX,               MVT::v32i16, Legal);
1577     setOperationAction(ISD::UMAX,               MVT::v64i8, Legal);
1578     setOperationAction(ISD::UMAX,               MVT::v32i16, Legal);
1579     setOperationAction(ISD::SMIN,               MVT::v64i8, Legal);
1580     setOperationAction(ISD::SMIN,               MVT::v32i16, Legal);
1581     setOperationAction(ISD::UMIN,               MVT::v64i8, Legal);
1582     setOperationAction(ISD::UMIN,               MVT::v32i16, Legal);
1583
1584     setTruncStoreAction(MVT::v32i16,  MVT::v32i8, Legal);
1585     setTruncStoreAction(MVT::v16i16,  MVT::v16i8, Legal);
1586     if (Subtarget->hasVLX())
1587       setTruncStoreAction(MVT::v8i16,   MVT::v8i8,  Legal);
1588
1589     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1590       const MVT VT = (MVT::SimpleValueType)i;
1591
1592       const unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1593
1594       // Do not attempt to promote non-512-bit vectors.
1595       if (!VT.is512BitVector())
1596         continue;
1597
1598       if (EltSize < 32) {
1599         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1600         setOperationAction(ISD::VSELECT,             VT, Legal);
1601       }
1602     }
1603   }
1604
1605   if (!Subtarget->useSoftFloat() && Subtarget->hasVLX()) {
1606     addRegisterClass(MVT::v4i1,   &X86::VK4RegClass);
1607     addRegisterClass(MVT::v2i1,   &X86::VK2RegClass);
1608
1609     setOperationAction(ISD::SETCC,              MVT::v4i1, Custom);
1610     setOperationAction(ISD::SETCC,              MVT::v2i1, Custom);
1611     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4i1, Custom);
1612     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i1, Custom);
1613     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v8i1, Custom);
1614     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v4i1, Custom);
1615     setOperationAction(ISD::SELECT,             MVT::v4i1, Custom);
1616     setOperationAction(ISD::SELECT,             MVT::v2i1, Custom);
1617     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4i1, Custom);
1618     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i1, Custom);
1619
1620     setOperationAction(ISD::AND,                MVT::v8i32, Legal);
1621     setOperationAction(ISD::OR,                 MVT::v8i32, Legal);
1622     setOperationAction(ISD::XOR,                MVT::v8i32, Legal);
1623     setOperationAction(ISD::AND,                MVT::v4i32, Legal);
1624     setOperationAction(ISD::OR,                 MVT::v4i32, Legal);
1625     setOperationAction(ISD::XOR,                MVT::v4i32, Legal);
1626     setOperationAction(ISD::SRA,                MVT::v2i64, Custom);
1627     setOperationAction(ISD::SRA,                MVT::v4i64, Custom);
1628
1629     setOperationAction(ISD::SMAX,               MVT::v2i64, Legal);
1630     setOperationAction(ISD::SMAX,               MVT::v4i64, Legal);
1631     setOperationAction(ISD::UMAX,               MVT::v2i64, Legal);
1632     setOperationAction(ISD::UMAX,               MVT::v4i64, Legal);
1633     setOperationAction(ISD::SMIN,               MVT::v2i64, Legal);
1634     setOperationAction(ISD::SMIN,               MVT::v4i64, Legal);
1635     setOperationAction(ISD::UMIN,               MVT::v2i64, Legal);
1636     setOperationAction(ISD::UMIN,               MVT::v4i64, Legal);
1637   }
1638
1639   // We want to custom lower some of our intrinsics.
1640   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1641   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1642   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1643   if (!Subtarget->is64Bit())
1644     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1645
1646   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1647   // handle type legalization for these operations here.
1648   //
1649   // FIXME: We really should do custom legalization for addition and
1650   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1651   // than generic legalization for 64-bit multiplication-with-overflow, though.
1652   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1653     // Add/Sub/Mul with overflow operations are custom lowered.
1654     MVT VT = IntVTs[i];
1655     setOperationAction(ISD::SADDO, VT, Custom);
1656     setOperationAction(ISD::UADDO, VT, Custom);
1657     setOperationAction(ISD::SSUBO, VT, Custom);
1658     setOperationAction(ISD::USUBO, VT, Custom);
1659     setOperationAction(ISD::SMULO, VT, Custom);
1660     setOperationAction(ISD::UMULO, VT, Custom);
1661   }
1662
1663
1664   if (!Subtarget->is64Bit()) {
1665     // These libcalls are not available in 32-bit.
1666     setLibcallName(RTLIB::SHL_I128, nullptr);
1667     setLibcallName(RTLIB::SRL_I128, nullptr);
1668     setLibcallName(RTLIB::SRA_I128, nullptr);
1669   }
1670
1671   // Combine sin / cos into one node or libcall if possible.
1672   if (Subtarget->hasSinCos()) {
1673     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1674     setLibcallName(RTLIB::SINCOS_F64, "sincos");
1675     if (Subtarget->isTargetDarwin()) {
1676       // For MacOSX, we don't want the normal expansion of a libcall to sincos.
1677       // We want to issue a libcall to __sincos_stret to avoid memory traffic.
1678       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1679       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1680     }
1681   }
1682
1683   if (Subtarget->isTargetWin64()) {
1684     setOperationAction(ISD::SDIV, MVT::i128, Custom);
1685     setOperationAction(ISD::UDIV, MVT::i128, Custom);
1686     setOperationAction(ISD::SREM, MVT::i128, Custom);
1687     setOperationAction(ISD::UREM, MVT::i128, Custom);
1688     setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1689     setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1690   }
1691
1692   // We have target-specific dag combine patterns for the following nodes:
1693   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1694   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1695   setTargetDAGCombine(ISD::BITCAST);
1696   setTargetDAGCombine(ISD::VSELECT);
1697   setTargetDAGCombine(ISD::SELECT);
1698   setTargetDAGCombine(ISD::SHL);
1699   setTargetDAGCombine(ISD::SRA);
1700   setTargetDAGCombine(ISD::SRL);
1701   setTargetDAGCombine(ISD::OR);
1702   setTargetDAGCombine(ISD::AND);
1703   setTargetDAGCombine(ISD::ADD);
1704   setTargetDAGCombine(ISD::FADD);
1705   setTargetDAGCombine(ISD::FSUB);
1706   setTargetDAGCombine(ISD::FMA);
1707   setTargetDAGCombine(ISD::SUB);
1708   setTargetDAGCombine(ISD::LOAD);
1709   setTargetDAGCombine(ISD::MLOAD);
1710   setTargetDAGCombine(ISD::STORE);
1711   setTargetDAGCombine(ISD::MSTORE);
1712   setTargetDAGCombine(ISD::ZERO_EXTEND);
1713   setTargetDAGCombine(ISD::ANY_EXTEND);
1714   setTargetDAGCombine(ISD::SIGN_EXTEND);
1715   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1716   setTargetDAGCombine(ISD::SINT_TO_FP);
1717   setTargetDAGCombine(ISD::UINT_TO_FP);
1718   setTargetDAGCombine(ISD::SETCC);
1719   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1720   setTargetDAGCombine(ISD::BUILD_VECTOR);
1721   setTargetDAGCombine(ISD::MUL);
1722   setTargetDAGCombine(ISD::XOR);
1723
1724   computeRegisterProperties(Subtarget->getRegisterInfo());
1725
1726   // On Darwin, -Os means optimize for size without hurting performance,
1727   // do not reduce the limit.
1728   MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1729   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1730   MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1731   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1732   MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1733   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1734   setPrefLoopAlignment(4); // 2^4 bytes.
1735
1736   // Predictable cmov don't hurt on atom because it's in-order.
1737   PredictableSelectIsExpensive = !Subtarget->isAtom();
1738   EnableExtLdPromotion = true;
1739   setPrefFunctionAlignment(4); // 2^4 bytes.
1740
1741   verifyIntrinsicTables();
1742 }
1743
1744 // This has so far only been implemented for 64-bit MachO.
1745 bool X86TargetLowering::useLoadStackGuardNode() const {
1746   return Subtarget->isTargetMachO() && Subtarget->is64Bit();
1747 }
1748
1749 TargetLoweringBase::LegalizeTypeAction
1750 X86TargetLowering::getPreferredVectorAction(EVT VT) const {
1751   if (ExperimentalVectorWideningLegalization &&
1752       VT.getVectorNumElements() != 1 &&
1753       VT.getVectorElementType().getSimpleVT() != MVT::i1)
1754     return TypeWidenVector;
1755
1756   return TargetLoweringBase::getPreferredVectorAction(VT);
1757 }
1758
1759 EVT X86TargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &,
1760                                           EVT VT) const {
1761   if (!VT.isVector())
1762     return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1763
1764   const unsigned NumElts = VT.getVectorNumElements();
1765   const EVT EltVT = VT.getVectorElementType();
1766   if (VT.is512BitVector()) {
1767     if (Subtarget->hasAVX512())
1768       if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1769           EltVT == MVT::f32 || EltVT == MVT::f64)
1770         switch(NumElts) {
1771         case  8: return MVT::v8i1;
1772         case 16: return MVT::v16i1;
1773       }
1774     if (Subtarget->hasBWI())
1775       if (EltVT == MVT::i8 || EltVT == MVT::i16)
1776         switch(NumElts) {
1777         case 32: return MVT::v32i1;
1778         case 64: return MVT::v64i1;
1779       }
1780   }
1781
1782   if (VT.is256BitVector() || VT.is128BitVector()) {
1783     if (Subtarget->hasVLX())
1784       if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1785           EltVT == MVT::f32 || EltVT == MVT::f64)
1786         switch(NumElts) {
1787         case 2: return MVT::v2i1;
1788         case 4: return MVT::v4i1;
1789         case 8: return MVT::v8i1;
1790       }
1791     if (Subtarget->hasBWI() && Subtarget->hasVLX())
1792       if (EltVT == MVT::i8 || EltVT == MVT::i16)
1793         switch(NumElts) {
1794         case  8: return MVT::v8i1;
1795         case 16: return MVT::v16i1;
1796         case 32: return MVT::v32i1;
1797       }
1798   }
1799
1800   return VT.changeVectorElementTypeToInteger();
1801 }
1802
1803 /// Helper for getByValTypeAlignment to determine
1804 /// the desired ByVal argument alignment.
1805 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1806   if (MaxAlign == 16)
1807     return;
1808   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1809     if (VTy->getBitWidth() == 128)
1810       MaxAlign = 16;
1811   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1812     unsigned EltAlign = 0;
1813     getMaxByValAlign(ATy->getElementType(), EltAlign);
1814     if (EltAlign > MaxAlign)
1815       MaxAlign = EltAlign;
1816   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1817     for (auto *EltTy : STy->elements()) {
1818       unsigned EltAlign = 0;
1819       getMaxByValAlign(EltTy, EltAlign);
1820       if (EltAlign > MaxAlign)
1821         MaxAlign = EltAlign;
1822       if (MaxAlign == 16)
1823         break;
1824     }
1825   }
1826 }
1827
1828 /// Return the desired alignment for ByVal aggregate
1829 /// function arguments in the caller parameter area. For X86, aggregates
1830 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1831 /// are at 4-byte boundaries.
1832 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty,
1833                                                   const DataLayout &DL) const {
1834   if (Subtarget->is64Bit()) {
1835     // Max of 8 and alignment of type.
1836     unsigned TyAlign = DL.getABITypeAlignment(Ty);
1837     if (TyAlign > 8)
1838       return TyAlign;
1839     return 8;
1840   }
1841
1842   unsigned Align = 4;
1843   if (Subtarget->hasSSE1())
1844     getMaxByValAlign(Ty, Align);
1845   return Align;
1846 }
1847
1848 /// Returns the target specific optimal type for load
1849 /// and store operations as a result of memset, memcpy, and memmove
1850 /// lowering. If DstAlign is zero that means it's safe to destination
1851 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1852 /// means there isn't a need to check it against alignment requirement,
1853 /// probably because the source does not need to be loaded. If 'IsMemset' is
1854 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1855 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1856 /// source is constant so it does not need to be loaded.
1857 /// It returns EVT::Other if the type should be determined using generic
1858 /// target-independent logic.
1859 EVT
1860 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1861                                        unsigned DstAlign, unsigned SrcAlign,
1862                                        bool IsMemset, bool ZeroMemset,
1863                                        bool MemcpyStrSrc,
1864                                        MachineFunction &MF) const {
1865   const Function *F = MF.getFunction();
1866   if ((!IsMemset || ZeroMemset) &&
1867       !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
1868     if (Size >= 16 &&
1869         (Subtarget->isUnalignedMemAccessFast() ||
1870          ((DstAlign == 0 || DstAlign >= 16) &&
1871           (SrcAlign == 0 || SrcAlign >= 16)))) {
1872       if (Size >= 32) {
1873         if (Subtarget->hasInt256())
1874           return MVT::v8i32;
1875         if (Subtarget->hasFp256())
1876           return MVT::v8f32;
1877       }
1878       if (Subtarget->hasSSE2())
1879         return MVT::v4i32;
1880       if (Subtarget->hasSSE1())
1881         return MVT::v4f32;
1882     } else if (!MemcpyStrSrc && Size >= 8 &&
1883                !Subtarget->is64Bit() &&
1884                Subtarget->hasSSE2()) {
1885       // Do not use f64 to lower memcpy if source is string constant. It's
1886       // better to use i32 to avoid the loads.
1887       return MVT::f64;
1888     }
1889   }
1890   if (Subtarget->is64Bit() && Size >= 8)
1891     return MVT::i64;
1892   return MVT::i32;
1893 }
1894
1895 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1896   if (VT == MVT::f32)
1897     return X86ScalarSSEf32;
1898   else if (VT == MVT::f64)
1899     return X86ScalarSSEf64;
1900   return true;
1901 }
1902
1903 bool
1904 X86TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
1905                                                   unsigned,
1906                                                   unsigned,
1907                                                   bool *Fast) const {
1908   if (Fast)
1909     *Fast = Subtarget->isUnalignedMemAccessFast();
1910   return true;
1911 }
1912
1913 /// Return the entry encoding for a jump table in the
1914 /// current function.  The returned value is a member of the
1915 /// MachineJumpTableInfo::JTEntryKind enum.
1916 unsigned X86TargetLowering::getJumpTableEncoding() const {
1917   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1918   // symbol.
1919   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1920       Subtarget->isPICStyleGOT())
1921     return MachineJumpTableInfo::EK_Custom32;
1922
1923   // Otherwise, use the normal jump table encoding heuristics.
1924   return TargetLowering::getJumpTableEncoding();
1925 }
1926
1927 bool X86TargetLowering::useSoftFloat() const {
1928   return Subtarget->useSoftFloat();
1929 }
1930
1931 const MCExpr *
1932 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1933                                              const MachineBasicBlock *MBB,
1934                                              unsigned uid,MCContext &Ctx) const{
1935   assert(MBB->getParent()->getTarget().getRelocationModel() == Reloc::PIC_ &&
1936          Subtarget->isPICStyleGOT());
1937   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1938   // entries.
1939   return MCSymbolRefExpr::create(MBB->getSymbol(),
1940                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1941 }
1942
1943 /// Returns relocation base for the given PIC jumptable.
1944 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1945                                                     SelectionDAG &DAG) const {
1946   if (!Subtarget->is64Bit())
1947     // This doesn't have SDLoc associated with it, but is not really the
1948     // same as a Register.
1949     return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(),
1950                        getPointerTy(DAG.getDataLayout()));
1951   return Table;
1952 }
1953
1954 /// This returns the relocation base for the given PIC jumptable,
1955 /// the same as getPICJumpTableRelocBase, but as an MCExpr.
1956 const MCExpr *X86TargetLowering::
1957 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1958                              MCContext &Ctx) const {
1959   // X86-64 uses RIP relative addressing based on the jump table label.
1960   if (Subtarget->isPICStyleRIPRel())
1961     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1962
1963   // Otherwise, the reference is relative to the PIC base.
1964   return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx);
1965 }
1966
1967 std::pair<const TargetRegisterClass *, uint8_t>
1968 X86TargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
1969                                            MVT VT) const {
1970   const TargetRegisterClass *RRC = nullptr;
1971   uint8_t Cost = 1;
1972   switch (VT.SimpleTy) {
1973   default:
1974     return TargetLowering::findRepresentativeClass(TRI, VT);
1975   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1976     RRC = Subtarget->is64Bit() ? &X86::GR64RegClass : &X86::GR32RegClass;
1977     break;
1978   case MVT::x86mmx:
1979     RRC = &X86::VR64RegClass;
1980     break;
1981   case MVT::f32: case MVT::f64:
1982   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1983   case MVT::v4f32: case MVT::v2f64:
1984   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1985   case MVT::v4f64:
1986     RRC = &X86::VR128RegClass;
1987     break;
1988   }
1989   return std::make_pair(RRC, Cost);
1990 }
1991
1992 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1993                                                unsigned &Offset) const {
1994   if (!Subtarget->isTargetLinux())
1995     return false;
1996
1997   if (Subtarget->is64Bit()) {
1998     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1999     Offset = 0x28;
2000     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
2001       AddressSpace = 256;
2002     else
2003       AddressSpace = 257;
2004   } else {
2005     // %gs:0x14 on i386
2006     Offset = 0x14;
2007     AddressSpace = 256;
2008   }
2009   return true;
2010 }
2011
2012 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
2013                                             unsigned DestAS) const {
2014   assert(SrcAS != DestAS && "Expected different address spaces!");
2015
2016   return SrcAS < 256 && DestAS < 256;
2017 }
2018
2019 //===----------------------------------------------------------------------===//
2020 //               Return Value Calling Convention Implementation
2021 //===----------------------------------------------------------------------===//
2022
2023 #include "X86GenCallingConv.inc"
2024
2025 bool
2026 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2027                                   MachineFunction &MF, bool isVarArg,
2028                         const SmallVectorImpl<ISD::OutputArg> &Outs,
2029                         LLVMContext &Context) const {
2030   SmallVector<CCValAssign, 16> RVLocs;
2031   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2032   return CCInfo.CheckReturn(Outs, RetCC_X86);
2033 }
2034
2035 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
2036   static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
2037   return ScratchRegs;
2038 }
2039
2040 SDValue
2041 X86TargetLowering::LowerReturn(SDValue Chain,
2042                                CallingConv::ID CallConv, bool isVarArg,
2043                                const SmallVectorImpl<ISD::OutputArg> &Outs,
2044                                const SmallVectorImpl<SDValue> &OutVals,
2045                                SDLoc dl, SelectionDAG &DAG) const {
2046   MachineFunction &MF = DAG.getMachineFunction();
2047   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2048
2049   SmallVector<CCValAssign, 16> RVLocs;
2050   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, *DAG.getContext());
2051   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
2052
2053   SDValue Flag;
2054   SmallVector<SDValue, 6> RetOps;
2055   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2056   // Operand #1 = Bytes To Pop
2057   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(), dl,
2058                    MVT::i16));
2059
2060   // Copy the result values into the output registers.
2061   for (unsigned i = 0; i != RVLocs.size(); ++i) {
2062     CCValAssign &VA = RVLocs[i];
2063     assert(VA.isRegLoc() && "Can only return in registers!");
2064     SDValue ValToCopy = OutVals[i];
2065     EVT ValVT = ValToCopy.getValueType();
2066
2067     // Promote values to the appropriate types.
2068     if (VA.getLocInfo() == CCValAssign::SExt)
2069       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2070     else if (VA.getLocInfo() == CCValAssign::ZExt)
2071       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
2072     else if (VA.getLocInfo() == CCValAssign::AExt) {
2073       if (ValVT.isVector() && ValVT.getScalarType() == MVT::i1)
2074         ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2075       else
2076         ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
2077     }
2078     else if (VA.getLocInfo() == CCValAssign::BCvt)
2079       ValToCopy = DAG.getBitcast(VA.getLocVT(), ValToCopy);
2080
2081     assert(VA.getLocInfo() != CCValAssign::FPExt &&
2082            "Unexpected FP-extend for return value.");
2083
2084     // If this is x86-64, and we disabled SSE, we can't return FP values,
2085     // or SSE or MMX vectors.
2086     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
2087          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
2088           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
2089       report_fatal_error("SSE register return with SSE disabled");
2090     }
2091     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
2092     // llvm-gcc has never done it right and no one has noticed, so this
2093     // should be OK for now.
2094     if (ValVT == MVT::f64 &&
2095         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
2096       report_fatal_error("SSE2 register return with SSE2 disabled");
2097
2098     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
2099     // the RET instruction and handled by the FP Stackifier.
2100     if (VA.getLocReg() == X86::FP0 ||
2101         VA.getLocReg() == X86::FP1) {
2102       // If this is a copy from an xmm register to ST(0), use an FPExtend to
2103       // change the value to the FP stack register class.
2104       if (isScalarFPTypeInSSEReg(VA.getValVT()))
2105         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
2106       RetOps.push_back(ValToCopy);
2107       // Don't emit a copytoreg.
2108       continue;
2109     }
2110
2111     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
2112     // which is returned in RAX / RDX.
2113     if (Subtarget->is64Bit()) {
2114       if (ValVT == MVT::x86mmx) {
2115         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
2116           ValToCopy = DAG.getBitcast(MVT::i64, ValToCopy);
2117           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
2118                                   ValToCopy);
2119           // If we don't have SSE2 available, convert to v4f32 so the generated
2120           // register is legal.
2121           if (!Subtarget->hasSSE2())
2122             ValToCopy = DAG.getBitcast(MVT::v4f32, ValToCopy);
2123         }
2124       }
2125     }
2126
2127     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
2128     Flag = Chain.getValue(1);
2129     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2130   }
2131
2132   // All x86 ABIs require that for returning structs by value we copy
2133   // the sret argument into %rax/%eax (depending on ABI) for the return.
2134   // We saved the argument into a virtual register in the entry block,
2135   // so now we copy the value out and into %rax/%eax.
2136   //
2137   // Checking Function.hasStructRetAttr() here is insufficient because the IR
2138   // may not have an explicit sret argument. If FuncInfo.CanLowerReturn is
2139   // false, then an sret argument may be implicitly inserted in the SelDAG. In
2140   // either case FuncInfo->setSRetReturnReg() will have been called.
2141   if (unsigned SRetReg = FuncInfo->getSRetReturnReg()) {
2142     SDValue Val = DAG.getCopyFromReg(Chain, dl, SRetReg,
2143                                      getPointerTy(MF.getDataLayout()));
2144
2145     unsigned RetValReg
2146         = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
2147           X86::RAX : X86::EAX;
2148     Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
2149     Flag = Chain.getValue(1);
2150
2151     // RAX/EAX now acts like a return value.
2152     RetOps.push_back(
2153         DAG.getRegister(RetValReg, getPointerTy(DAG.getDataLayout())));
2154   }
2155
2156   RetOps[0] = Chain;  // Update chain.
2157
2158   // Add the flag if we have it.
2159   if (Flag.getNode())
2160     RetOps.push_back(Flag);
2161
2162   return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
2163 }
2164
2165 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2166   if (N->getNumValues() != 1)
2167     return false;
2168   if (!N->hasNUsesOfValue(1, 0))
2169     return false;
2170
2171   SDValue TCChain = Chain;
2172   SDNode *Copy = *N->use_begin();
2173   if (Copy->getOpcode() == ISD::CopyToReg) {
2174     // If the copy has a glue operand, we conservatively assume it isn't safe to
2175     // perform a tail call.
2176     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2177       return false;
2178     TCChain = Copy->getOperand(0);
2179   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
2180     return false;
2181
2182   bool HasRet = false;
2183   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2184        UI != UE; ++UI) {
2185     if (UI->getOpcode() != X86ISD::RET_FLAG)
2186       return false;
2187     // If we are returning more than one value, we can definitely
2188     // not make a tail call see PR19530
2189     if (UI->getNumOperands() > 4)
2190       return false;
2191     if (UI->getNumOperands() == 4 &&
2192         UI->getOperand(UI->getNumOperands()-1).getValueType() != MVT::Glue)
2193       return false;
2194     HasRet = true;
2195   }
2196
2197   if (!HasRet)
2198     return false;
2199
2200   Chain = TCChain;
2201   return true;
2202 }
2203
2204 EVT
2205 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
2206                                             ISD::NodeType ExtendKind) const {
2207   MVT ReturnMVT;
2208   // TODO: Is this also valid on 32-bit?
2209   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
2210     ReturnMVT = MVT::i8;
2211   else
2212     ReturnMVT = MVT::i32;
2213
2214   EVT MinVT = getRegisterType(Context, ReturnMVT);
2215   return VT.bitsLT(MinVT) ? MinVT : VT;
2216 }
2217
2218 /// Lower the result values of a call into the
2219 /// appropriate copies out of appropriate physical registers.
2220 ///
2221 SDValue
2222 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2223                                    CallingConv::ID CallConv, bool isVarArg,
2224                                    const SmallVectorImpl<ISD::InputArg> &Ins,
2225                                    SDLoc dl, SelectionDAG &DAG,
2226                                    SmallVectorImpl<SDValue> &InVals) const {
2227
2228   // Assign locations to each value returned by this call.
2229   SmallVector<CCValAssign, 16> RVLocs;
2230   bool Is64Bit = Subtarget->is64Bit();
2231   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2232                  *DAG.getContext());
2233   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2234
2235   // Copy all of the result registers out of their specified physreg.
2236   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2237     CCValAssign &VA = RVLocs[i];
2238     EVT CopyVT = VA.getLocVT();
2239
2240     // If this is x86-64, and we disabled SSE, we can't return FP values
2241     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2242         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2243       report_fatal_error("SSE register return with SSE disabled");
2244     }
2245
2246     // If we prefer to use the value in xmm registers, copy it out as f80 and
2247     // use a truncate to move it from fp stack reg to xmm reg.
2248     bool RoundAfterCopy = false;
2249     if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
2250         isScalarFPTypeInSSEReg(VA.getValVT())) {
2251       CopyVT = MVT::f80;
2252       RoundAfterCopy = (CopyVT != VA.getLocVT());
2253     }
2254
2255     Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2256                                CopyVT, InFlag).getValue(1);
2257     SDValue Val = Chain.getValue(0);
2258
2259     if (RoundAfterCopy)
2260       Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2261                         // This truncation won't change the value.
2262                         DAG.getIntPtrConstant(1, dl));
2263
2264     if (VA.isExtInLoc() && VA.getValVT().getScalarType() == MVT::i1)
2265       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
2266
2267     InFlag = Chain.getValue(2);
2268     InVals.push_back(Val);
2269   }
2270
2271   return Chain;
2272 }
2273
2274 //===----------------------------------------------------------------------===//
2275 //                C & StdCall & Fast Calling Convention implementation
2276 //===----------------------------------------------------------------------===//
2277 //  StdCall calling convention seems to be standard for many Windows' API
2278 //  routines and around. It differs from C calling convention just a little:
2279 //  callee should clean up the stack, not caller. Symbols should be also
2280 //  decorated in some fancy way :) It doesn't support any vector arguments.
2281 //  For info on fast calling convention see Fast Calling Convention (tail call)
2282 //  implementation LowerX86_32FastCCCallTo.
2283
2284 /// CallIsStructReturn - Determines whether a call uses struct return
2285 /// semantics.
2286 enum StructReturnType {
2287   NotStructReturn,
2288   RegStructReturn,
2289   StackStructReturn
2290 };
2291 static StructReturnType
2292 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2293   if (Outs.empty())
2294     return NotStructReturn;
2295
2296   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2297   if (!Flags.isSRet())
2298     return NotStructReturn;
2299   if (Flags.isInReg())
2300     return RegStructReturn;
2301   return StackStructReturn;
2302 }
2303
2304 /// Determines whether a function uses struct return semantics.
2305 static StructReturnType
2306 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2307   if (Ins.empty())
2308     return NotStructReturn;
2309
2310   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2311   if (!Flags.isSRet())
2312     return NotStructReturn;
2313   if (Flags.isInReg())
2314     return RegStructReturn;
2315   return StackStructReturn;
2316 }
2317
2318 /// Make a copy of an aggregate at address specified by "Src" to address
2319 /// "Dst" with size and alignment information specified by the specific
2320 /// parameter attribute. The copy will be passed as a byval function parameter.
2321 static SDValue
2322 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2323                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2324                           SDLoc dl) {
2325   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
2326
2327   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2328                        /*isVolatile*/false, /*AlwaysInline=*/true,
2329                        /*isTailCall*/false,
2330                        MachinePointerInfo(), MachinePointerInfo());
2331 }
2332
2333 /// Return true if the calling convention is one that
2334 /// supports tail call optimization.
2335 static bool IsTailCallConvention(CallingConv::ID CC) {
2336   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2337           CC == CallingConv::HiPE);
2338 }
2339
2340 /// \brief Return true if the calling convention is a C calling convention.
2341 static bool IsCCallConvention(CallingConv::ID CC) {
2342   return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2343           CC == CallingConv::X86_64_SysV);
2344 }
2345
2346 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2347   auto Attr =
2348       CI->getParent()->getParent()->getFnAttribute("disable-tail-calls");
2349   if (!CI->isTailCall() || Attr.getValueAsString() == "true")
2350     return false;
2351
2352   CallSite CS(CI);
2353   CallingConv::ID CalleeCC = CS.getCallingConv();
2354   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2355     return false;
2356
2357   return true;
2358 }
2359
2360 /// Return true if the function is being made into
2361 /// a tailcall target by changing its ABI.
2362 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2363                                    bool GuaranteedTailCallOpt) {
2364   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2365 }
2366
2367 SDValue
2368 X86TargetLowering::LowerMemArgument(SDValue Chain,
2369                                     CallingConv::ID CallConv,
2370                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2371                                     SDLoc dl, SelectionDAG &DAG,
2372                                     const CCValAssign &VA,
2373                                     MachineFrameInfo *MFI,
2374                                     unsigned i) const {
2375   // Create the nodes corresponding to a load from this parameter slot.
2376   ISD::ArgFlagsTy Flags = Ins[i].Flags;
2377   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(
2378       CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2379   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2380   EVT ValVT;
2381
2382   // If value is passed by pointer we have address passed instead of the value
2383   // itself.
2384   bool ExtendedInMem = VA.isExtInLoc() &&
2385     VA.getValVT().getScalarType() == MVT::i1;
2386
2387   if (VA.getLocInfo() == CCValAssign::Indirect || ExtendedInMem)
2388     ValVT = VA.getLocVT();
2389   else
2390     ValVT = VA.getValVT();
2391
2392   // FIXME: For now, all byval parameter objects are marked mutable. This can be
2393   // changed with more analysis.
2394   // In case of tail call optimization mark all arguments mutable. Since they
2395   // could be overwritten by lowering of arguments in case of a tail call.
2396   if (Flags.isByVal()) {
2397     unsigned Bytes = Flags.getByValSize();
2398     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2399     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2400     return DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2401   } else {
2402     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2403                                     VA.getLocMemOffset(), isImmutable);
2404     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2405     SDValue Val =  DAG.getLoad(ValVT, dl, Chain, FIN,
2406                                MachinePointerInfo::getFixedStack(FI),
2407                                false, false, false, 0);
2408     return ExtendedInMem ?
2409       DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val) : Val;
2410   }
2411 }
2412
2413 // FIXME: Get this from tablegen.
2414 static ArrayRef<MCPhysReg> get64BitArgumentGPRs(CallingConv::ID CallConv,
2415                                                 const X86Subtarget *Subtarget) {
2416   assert(Subtarget->is64Bit());
2417
2418   if (Subtarget->isCallingConvWin64(CallConv)) {
2419     static const MCPhysReg GPR64ArgRegsWin64[] = {
2420       X86::RCX, X86::RDX, X86::R8,  X86::R9
2421     };
2422     return makeArrayRef(std::begin(GPR64ArgRegsWin64), std::end(GPR64ArgRegsWin64));
2423   }
2424
2425   static const MCPhysReg GPR64ArgRegs64Bit[] = {
2426     X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2427   };
2428   return makeArrayRef(std::begin(GPR64ArgRegs64Bit), std::end(GPR64ArgRegs64Bit));
2429 }
2430
2431 // FIXME: Get this from tablegen.
2432 static ArrayRef<MCPhysReg> get64BitArgumentXMMs(MachineFunction &MF,
2433                                                 CallingConv::ID CallConv,
2434                                                 const X86Subtarget *Subtarget) {
2435   assert(Subtarget->is64Bit());
2436   if (Subtarget->isCallingConvWin64(CallConv)) {
2437     // The XMM registers which might contain var arg parameters are shadowed
2438     // in their paired GPR.  So we only need to save the GPR to their home
2439     // slots.
2440     // TODO: __vectorcall will change this.
2441     return None;
2442   }
2443
2444   const Function *Fn = MF.getFunction();
2445   bool NoImplicitFloatOps = Fn->hasFnAttribute(Attribute::NoImplicitFloat);
2446   bool isSoftFloat = Subtarget->useSoftFloat();
2447   assert(!(isSoftFloat && NoImplicitFloatOps) &&
2448          "SSE register cannot be used when SSE is disabled!");
2449   if (isSoftFloat || NoImplicitFloatOps || !Subtarget->hasSSE1())
2450     // Kernel mode asks for SSE to be disabled, so there are no XMM argument
2451     // registers.
2452     return None;
2453
2454   static const MCPhysReg XMMArgRegs64Bit[] = {
2455     X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2456     X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2457   };
2458   return makeArrayRef(std::begin(XMMArgRegs64Bit), std::end(XMMArgRegs64Bit));
2459 }
2460
2461 SDValue
2462 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2463                                         CallingConv::ID CallConv,
2464                                         bool isVarArg,
2465                                       const SmallVectorImpl<ISD::InputArg> &Ins,
2466                                         SDLoc dl,
2467                                         SelectionDAG &DAG,
2468                                         SmallVectorImpl<SDValue> &InVals)
2469                                           const {
2470   MachineFunction &MF = DAG.getMachineFunction();
2471   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2472   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
2473
2474   const Function* Fn = MF.getFunction();
2475   if (Fn->hasExternalLinkage() &&
2476       Subtarget->isTargetCygMing() &&
2477       Fn->getName() == "main")
2478     FuncInfo->setForceFramePointer(true);
2479
2480   MachineFrameInfo *MFI = MF.getFrameInfo();
2481   bool Is64Bit = Subtarget->is64Bit();
2482   bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2483
2484   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2485          "Var args not supported with calling convention fastcc, ghc or hipe");
2486
2487   // Assign locations to all of the incoming arguments.
2488   SmallVector<CCValAssign, 16> ArgLocs;
2489   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2490
2491   // Allocate shadow area for Win64
2492   if (IsWin64)
2493     CCInfo.AllocateStack(32, 8);
2494
2495   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2496
2497   unsigned LastVal = ~0U;
2498   SDValue ArgValue;
2499   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2500     CCValAssign &VA = ArgLocs[i];
2501     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2502     // places.
2503     assert(VA.getValNo() != LastVal &&
2504            "Don't support value assigned to multiple locs yet");
2505     (void)LastVal;
2506     LastVal = VA.getValNo();
2507
2508     if (VA.isRegLoc()) {
2509       EVT RegVT = VA.getLocVT();
2510       const TargetRegisterClass *RC;
2511       if (RegVT == MVT::i32)
2512         RC = &X86::GR32RegClass;
2513       else if (Is64Bit && RegVT == MVT::i64)
2514         RC = &X86::GR64RegClass;
2515       else if (RegVT == MVT::f32)
2516         RC = &X86::FR32RegClass;
2517       else if (RegVT == MVT::f64)
2518         RC = &X86::FR64RegClass;
2519       else if (RegVT.is512BitVector())
2520         RC = &X86::VR512RegClass;
2521       else if (RegVT.is256BitVector())
2522         RC = &X86::VR256RegClass;
2523       else if (RegVT.is128BitVector())
2524         RC = &X86::VR128RegClass;
2525       else if (RegVT == MVT::x86mmx)
2526         RC = &X86::VR64RegClass;
2527       else if (RegVT == MVT::i1)
2528         RC = &X86::VK1RegClass;
2529       else if (RegVT == MVT::v8i1)
2530         RC = &X86::VK8RegClass;
2531       else if (RegVT == MVT::v16i1)
2532         RC = &X86::VK16RegClass;
2533       else if (RegVT == MVT::v32i1)
2534         RC = &X86::VK32RegClass;
2535       else if (RegVT == MVT::v64i1)
2536         RC = &X86::VK64RegClass;
2537       else
2538         llvm_unreachable("Unknown argument type!");
2539
2540       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2541       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2542
2543       // If this is an 8 or 16-bit value, it is really passed promoted to 32
2544       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
2545       // right size.
2546       if (VA.getLocInfo() == CCValAssign::SExt)
2547         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2548                                DAG.getValueType(VA.getValVT()));
2549       else if (VA.getLocInfo() == CCValAssign::ZExt)
2550         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2551                                DAG.getValueType(VA.getValVT()));
2552       else if (VA.getLocInfo() == CCValAssign::BCvt)
2553         ArgValue = DAG.getBitcast(VA.getValVT(), ArgValue);
2554
2555       if (VA.isExtInLoc()) {
2556         // Handle MMX values passed in XMM regs.
2557         if (RegVT.isVector() && VA.getValVT().getScalarType() != MVT::i1)
2558           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2559         else
2560           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2561       }
2562     } else {
2563       assert(VA.isMemLoc());
2564       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2565     }
2566
2567     // If value is passed via pointer - do a load.
2568     if (VA.getLocInfo() == CCValAssign::Indirect)
2569       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2570                              MachinePointerInfo(), false, false, false, 0);
2571
2572     InVals.push_back(ArgValue);
2573   }
2574
2575   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2576     // All x86 ABIs require that for returning structs by value we copy the
2577     // sret argument into %rax/%eax (depending on ABI) for the return. Save
2578     // the argument into a virtual register so that we can access it from the
2579     // return points.
2580     if (Ins[i].Flags.isSRet()) {
2581       unsigned Reg = FuncInfo->getSRetReturnReg();
2582       if (!Reg) {
2583         MVT PtrTy = getPointerTy(DAG.getDataLayout());
2584         Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2585         FuncInfo->setSRetReturnReg(Reg);
2586       }
2587       SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2588       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2589       break;
2590     }
2591   }
2592
2593   unsigned StackSize = CCInfo.getNextStackOffset();
2594   // Align stack specially for tail calls.
2595   if (FuncIsMadeTailCallSafe(CallConv,
2596                              MF.getTarget().Options.GuaranteedTailCallOpt))
2597     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2598
2599   // If the function takes variable number of arguments, make a frame index for
2600   // the start of the first vararg value... for expansion of llvm.va_start. We
2601   // can skip this if there are no va_start calls.
2602   if (MFI->hasVAStart() &&
2603       (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2604                    CallConv != CallingConv::X86_ThisCall))) {
2605     FuncInfo->setVarArgsFrameIndex(
2606         MFI->CreateFixedObject(1, StackSize, true));
2607   }
2608
2609   MachineModuleInfo &MMI = MF.getMMI();
2610   const Function *WinEHParent = nullptr;
2611   if (MMI.hasWinEHFuncInfo(Fn))
2612     WinEHParent = MMI.getWinEHParent(Fn);
2613   bool IsWinEHOutlined = WinEHParent && WinEHParent != Fn;
2614   bool IsWinEHParent = WinEHParent && WinEHParent == Fn;
2615
2616   // Figure out if XMM registers are in use.
2617   assert(!(Subtarget->useSoftFloat() &&
2618            Fn->hasFnAttribute(Attribute::NoImplicitFloat)) &&
2619          "SSE register cannot be used when SSE is disabled!");
2620
2621   // 64-bit calling conventions support varargs and register parameters, so we
2622   // have to do extra work to spill them in the prologue.
2623   if (Is64Bit && isVarArg && MFI->hasVAStart()) {
2624     // Find the first unallocated argument registers.
2625     ArrayRef<MCPhysReg> ArgGPRs = get64BitArgumentGPRs(CallConv, Subtarget);
2626     ArrayRef<MCPhysReg> ArgXMMs = get64BitArgumentXMMs(MF, CallConv, Subtarget);
2627     unsigned NumIntRegs = CCInfo.getFirstUnallocated(ArgGPRs);
2628     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(ArgXMMs);
2629     assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2630            "SSE register cannot be used when SSE is disabled!");
2631
2632     // Gather all the live in physical registers.
2633     SmallVector<SDValue, 6> LiveGPRs;
2634     SmallVector<SDValue, 8> LiveXMMRegs;
2635     SDValue ALVal;
2636     for (MCPhysReg Reg : ArgGPRs.slice(NumIntRegs)) {
2637       unsigned GPR = MF.addLiveIn(Reg, &X86::GR64RegClass);
2638       LiveGPRs.push_back(
2639           DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64));
2640     }
2641     if (!ArgXMMs.empty()) {
2642       unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2643       ALVal = DAG.getCopyFromReg(Chain, dl, AL, MVT::i8);
2644       for (MCPhysReg Reg : ArgXMMs.slice(NumXMMRegs)) {
2645         unsigned XMMReg = MF.addLiveIn(Reg, &X86::VR128RegClass);
2646         LiveXMMRegs.push_back(
2647             DAG.getCopyFromReg(Chain, dl, XMMReg, MVT::v4f32));
2648       }
2649     }
2650
2651     if (IsWin64) {
2652       // Get to the caller-allocated home save location.  Add 8 to account
2653       // for the return address.
2654       int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2655       FuncInfo->setRegSaveFrameIndex(
2656           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2657       // Fixup to set vararg frame on shadow area (4 x i64).
2658       if (NumIntRegs < 4)
2659         FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2660     } else {
2661       // For X86-64, if there are vararg parameters that are passed via
2662       // registers, then we must store them to their spots on the stack so
2663       // they may be loaded by deferencing the result of va_next.
2664       FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2665       FuncInfo->setVarArgsFPOffset(ArgGPRs.size() * 8 + NumXMMRegs * 16);
2666       FuncInfo->setRegSaveFrameIndex(MFI->CreateStackObject(
2667           ArgGPRs.size() * 8 + ArgXMMs.size() * 16, 16, false));
2668     }
2669
2670     // Store the integer parameter registers.
2671     SmallVector<SDValue, 8> MemOps;
2672     SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2673                                       getPointerTy(DAG.getDataLayout()));
2674     unsigned Offset = FuncInfo->getVarArgsGPOffset();
2675     for (SDValue Val : LiveGPRs) {
2676       SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
2677                                 RSFIN, DAG.getIntPtrConstant(Offset, dl));
2678       SDValue Store =
2679         DAG.getStore(Val.getValue(1), dl, Val, FIN,
2680                      MachinePointerInfo::getFixedStack(
2681                        FuncInfo->getRegSaveFrameIndex(), Offset),
2682                      false, false, 0);
2683       MemOps.push_back(Store);
2684       Offset += 8;
2685     }
2686
2687     if (!ArgXMMs.empty() && NumXMMRegs != ArgXMMs.size()) {
2688       // Now store the XMM (fp + vector) parameter registers.
2689       SmallVector<SDValue, 12> SaveXMMOps;
2690       SaveXMMOps.push_back(Chain);
2691       SaveXMMOps.push_back(ALVal);
2692       SaveXMMOps.push_back(DAG.getIntPtrConstant(
2693                              FuncInfo->getRegSaveFrameIndex(), dl));
2694       SaveXMMOps.push_back(DAG.getIntPtrConstant(
2695                              FuncInfo->getVarArgsFPOffset(), dl));
2696       SaveXMMOps.insert(SaveXMMOps.end(), LiveXMMRegs.begin(),
2697                         LiveXMMRegs.end());
2698       MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2699                                    MVT::Other, SaveXMMOps));
2700     }
2701
2702     if (!MemOps.empty())
2703       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2704   } else if (IsWin64 && IsWinEHOutlined) {
2705     // Get to the caller-allocated home save location.  Add 8 to account
2706     // for the return address.
2707     int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2708     FuncInfo->setRegSaveFrameIndex(MFI->CreateFixedObject(
2709         /*Size=*/1, /*SPOffset=*/HomeOffset + 8, /*Immutable=*/false));
2710
2711     MMI.getWinEHFuncInfo(Fn)
2712         .CatchHandlerParentFrameObjIdx[const_cast<Function *>(Fn)] =
2713         FuncInfo->getRegSaveFrameIndex();
2714
2715     // Store the second integer parameter (rdx) into rsp+16 relative to the
2716     // stack pointer at the entry of the function.
2717     SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2718                                       getPointerTy(DAG.getDataLayout()));
2719     unsigned GPR = MF.addLiveIn(X86::RDX, &X86::GR64RegClass);
2720     SDValue Val = DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64);
2721     Chain = DAG.getStore(
2722         Val.getValue(1), dl, Val, RSFIN,
2723         MachinePointerInfo::getFixedStack(FuncInfo->getRegSaveFrameIndex()),
2724         /*isVolatile=*/true, /*isNonTemporal=*/false, /*Alignment=*/0);
2725   }
2726
2727   if (isVarArg && MFI->hasMustTailInVarArgFunc()) {
2728     // Find the largest legal vector type.
2729     MVT VecVT = MVT::Other;
2730     // FIXME: Only some x86_32 calling conventions support AVX512.
2731     if (Subtarget->hasAVX512() &&
2732         (Is64Bit || (CallConv == CallingConv::X86_VectorCall ||
2733                      CallConv == CallingConv::Intel_OCL_BI)))
2734       VecVT = MVT::v16f32;
2735     else if (Subtarget->hasAVX())
2736       VecVT = MVT::v8f32;
2737     else if (Subtarget->hasSSE2())
2738       VecVT = MVT::v4f32;
2739
2740     // We forward some GPRs and some vector types.
2741     SmallVector<MVT, 2> RegParmTypes;
2742     MVT IntVT = Is64Bit ? MVT::i64 : MVT::i32;
2743     RegParmTypes.push_back(IntVT);
2744     if (VecVT != MVT::Other)
2745       RegParmTypes.push_back(VecVT);
2746
2747     // Compute the set of forwarded registers. The rest are scratch.
2748     SmallVectorImpl<ForwardedRegister> &Forwards =
2749         FuncInfo->getForwardedMustTailRegParms();
2750     CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes, CC_X86);
2751
2752     // Conservatively forward AL on x86_64, since it might be used for varargs.
2753     if (Is64Bit && !CCInfo.isAllocated(X86::AL)) {
2754       unsigned ALVReg = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2755       Forwards.push_back(ForwardedRegister(ALVReg, X86::AL, MVT::i8));
2756     }
2757
2758     // Copy all forwards from physical to virtual registers.
2759     for (ForwardedRegister &F : Forwards) {
2760       // FIXME: Can we use a less constrained schedule?
2761       SDValue RegVal = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
2762       F.VReg = MF.getRegInfo().createVirtualRegister(getRegClassFor(F.VT));
2763       Chain = DAG.getCopyToReg(Chain, dl, F.VReg, RegVal);
2764     }
2765   }
2766
2767   // Some CCs need callee pop.
2768   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2769                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2770     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2771   } else {
2772     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2773     // If this is an sret function, the return should pop the hidden pointer.
2774     if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2775         !Subtarget->getTargetTriple().isOSMSVCRT() &&
2776         argsAreStructReturn(Ins) == StackStructReturn)
2777       FuncInfo->setBytesToPopOnReturn(4);
2778   }
2779
2780   if (!Is64Bit) {
2781     // RegSaveFrameIndex is X86-64 only.
2782     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2783     if (CallConv == CallingConv::X86_FastCall ||
2784         CallConv == CallingConv::X86_ThisCall)
2785       // fastcc functions can't have varargs.
2786       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2787   }
2788
2789   FuncInfo->setArgumentStackSize(StackSize);
2790
2791   if (IsWinEHParent) {
2792     if (Is64Bit) {
2793       int UnwindHelpFI = MFI->CreateStackObject(8, 8, /*isSS=*/false);
2794       SDValue StackSlot = DAG.getFrameIndex(UnwindHelpFI, MVT::i64);
2795       MMI.getWinEHFuncInfo(MF.getFunction()).UnwindHelpFrameIdx = UnwindHelpFI;
2796       SDValue Neg2 = DAG.getConstant(-2, dl, MVT::i64);
2797       Chain = DAG.getStore(Chain, dl, Neg2, StackSlot,
2798                            MachinePointerInfo::getFixedStack(UnwindHelpFI),
2799                            /*isVolatile=*/true,
2800                            /*isNonTemporal=*/false, /*Alignment=*/0);
2801     } else {
2802       // Functions using Win32 EH are considered to have opaque SP adjustments
2803       // to force local variables to be addressed from the frame or base
2804       // pointers.
2805       MFI->setHasOpaqueSPAdjustment(true);
2806     }
2807   }
2808
2809   return Chain;
2810 }
2811
2812 SDValue
2813 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2814                                     SDValue StackPtr, SDValue Arg,
2815                                     SDLoc dl, SelectionDAG &DAG,
2816                                     const CCValAssign &VA,
2817                                     ISD::ArgFlagsTy Flags) const {
2818   unsigned LocMemOffset = VA.getLocMemOffset();
2819   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
2820   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
2821                        StackPtr, PtrOff);
2822   if (Flags.isByVal())
2823     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2824
2825   return DAG.getStore(Chain, dl, Arg, PtrOff,
2826                       MachinePointerInfo::getStack(LocMemOffset),
2827                       false, false, 0);
2828 }
2829
2830 /// Emit a load of return address if tail call
2831 /// optimization is performed and it is required.
2832 SDValue
2833 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2834                                            SDValue &OutRetAddr, SDValue Chain,
2835                                            bool IsTailCall, bool Is64Bit,
2836                                            int FPDiff, SDLoc dl) const {
2837   // Adjust the Return address stack slot.
2838   EVT VT = getPointerTy(DAG.getDataLayout());
2839   OutRetAddr = getReturnAddressFrameIndex(DAG);
2840
2841   // Load the "old" Return address.
2842   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2843                            false, false, false, 0);
2844   return SDValue(OutRetAddr.getNode(), 1);
2845 }
2846
2847 /// Emit a store of the return address if tail call
2848 /// optimization is performed and it is required (FPDiff!=0).
2849 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2850                                         SDValue Chain, SDValue RetAddrFrIdx,
2851                                         EVT PtrVT, unsigned SlotSize,
2852                                         int FPDiff, SDLoc dl) {
2853   // Store the return address to the appropriate stack slot.
2854   if (!FPDiff) return Chain;
2855   // Calculate the new stack slot for the return address.
2856   int NewReturnAddrFI =
2857     MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2858                                          false);
2859   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2860   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2861                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2862                        false, false, 0);
2863   return Chain;
2864 }
2865
2866 /// Returns a vector_shuffle mask for an movs{s|d}, movd
2867 /// operation of specified width.
2868 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
2869                        SDValue V2) {
2870   unsigned NumElems = VT.getVectorNumElements();
2871   SmallVector<int, 8> Mask;
2872   Mask.push_back(NumElems);
2873   for (unsigned i = 1; i != NumElems; ++i)
2874     Mask.push_back(i);
2875   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
2876 }
2877
2878 SDValue
2879 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2880                              SmallVectorImpl<SDValue> &InVals) const {
2881   SelectionDAG &DAG                     = CLI.DAG;
2882   SDLoc &dl                             = CLI.DL;
2883   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2884   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
2885   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
2886   SDValue Chain                         = CLI.Chain;
2887   SDValue Callee                        = CLI.Callee;
2888   CallingConv::ID CallConv              = CLI.CallConv;
2889   bool &isTailCall                      = CLI.IsTailCall;
2890   bool isVarArg                         = CLI.IsVarArg;
2891
2892   MachineFunction &MF = DAG.getMachineFunction();
2893   bool Is64Bit        = Subtarget->is64Bit();
2894   bool IsWin64        = Subtarget->isCallingConvWin64(CallConv);
2895   StructReturnType SR = callIsStructReturn(Outs);
2896   bool IsSibcall      = false;
2897   X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2898   auto Attr = MF.getFunction()->getFnAttribute("disable-tail-calls");
2899
2900   if (Attr.getValueAsString() == "true")
2901     isTailCall = false;
2902
2903   if (Subtarget->isPICStyleGOT() &&
2904       !MF.getTarget().Options.GuaranteedTailCallOpt) {
2905     // If we are using a GOT, disable tail calls to external symbols with
2906     // default visibility. Tail calling such a symbol requires using a GOT
2907     // relocation, which forces early binding of the symbol. This breaks code
2908     // that require lazy function symbol resolution. Using musttail or
2909     // GuaranteedTailCallOpt will override this.
2910     GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2911     if (!G || (!G->getGlobal()->hasLocalLinkage() &&
2912                G->getGlobal()->hasDefaultVisibility()))
2913       isTailCall = false;
2914   }
2915
2916   bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
2917   if (IsMustTail) {
2918     // Force this to be a tail call.  The verifier rules are enough to ensure
2919     // that we can lower this successfully without moving the return address
2920     // around.
2921     isTailCall = true;
2922   } else if (isTailCall) {
2923     // Check if it's really possible to do a tail call.
2924     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2925                     isVarArg, SR != NotStructReturn,
2926                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2927                     Outs, OutVals, Ins, DAG);
2928
2929     // Sibcalls are automatically detected tailcalls which do not require
2930     // ABI changes.
2931     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2932       IsSibcall = true;
2933
2934     if (isTailCall)
2935       ++NumTailCalls;
2936   }
2937
2938   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2939          "Var args not supported with calling convention fastcc, ghc or hipe");
2940
2941   // Analyze operands of the call, assigning locations to each operand.
2942   SmallVector<CCValAssign, 16> ArgLocs;
2943   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2944
2945   // Allocate shadow area for Win64
2946   if (IsWin64)
2947     CCInfo.AllocateStack(32, 8);
2948
2949   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2950
2951   // Get a count of how many bytes are to be pushed on the stack.
2952   unsigned NumBytes = CCInfo.getNextStackOffset();
2953   if (IsSibcall)
2954     // This is a sibcall. The memory operands are available in caller's
2955     // own caller's stack.
2956     NumBytes = 0;
2957   else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
2958            IsTailCallConvention(CallConv))
2959     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2960
2961   int FPDiff = 0;
2962   if (isTailCall && !IsSibcall && !IsMustTail) {
2963     // Lower arguments at fp - stackoffset + fpdiff.
2964     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2965
2966     FPDiff = NumBytesCallerPushed - NumBytes;
2967
2968     // Set the delta of movement of the returnaddr stackslot.
2969     // But only set if delta is greater than previous delta.
2970     if (FPDiff < X86Info->getTCReturnAddrDelta())
2971       X86Info->setTCReturnAddrDelta(FPDiff);
2972   }
2973
2974   unsigned NumBytesToPush = NumBytes;
2975   unsigned NumBytesToPop = NumBytes;
2976
2977   // If we have an inalloca argument, all stack space has already been allocated
2978   // for us and be right at the top of the stack.  We don't support multiple
2979   // arguments passed in memory when using inalloca.
2980   if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
2981     NumBytesToPush = 0;
2982     if (!ArgLocs.back().isMemLoc())
2983       report_fatal_error("cannot use inalloca attribute on a register "
2984                          "parameter");
2985     if (ArgLocs.back().getLocMemOffset() != 0)
2986       report_fatal_error("any parameter with the inalloca attribute must be "
2987                          "the only memory argument");
2988   }
2989
2990   if (!IsSibcall)
2991     Chain = DAG.getCALLSEQ_START(
2992         Chain, DAG.getIntPtrConstant(NumBytesToPush, dl, true), dl);
2993
2994   SDValue RetAddrFrIdx;
2995   // Load return address for tail calls.
2996   if (isTailCall && FPDiff)
2997     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2998                                     Is64Bit, FPDiff, dl);
2999
3000   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3001   SmallVector<SDValue, 8> MemOpChains;
3002   SDValue StackPtr;
3003
3004   // Walk the register/memloc assignments, inserting copies/loads.  In the case
3005   // of tail call optimization arguments are handle later.
3006   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3007   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3008     // Skip inalloca arguments, they have already been written.
3009     ISD::ArgFlagsTy Flags = Outs[i].Flags;
3010     if (Flags.isInAlloca())
3011       continue;
3012
3013     CCValAssign &VA = ArgLocs[i];
3014     EVT RegVT = VA.getLocVT();
3015     SDValue Arg = OutVals[i];
3016     bool isByVal = Flags.isByVal();
3017
3018     // Promote the value if needed.
3019     switch (VA.getLocInfo()) {
3020     default: llvm_unreachable("Unknown loc info!");
3021     case CCValAssign::Full: break;
3022     case CCValAssign::SExt:
3023       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
3024       break;
3025     case CCValAssign::ZExt:
3026       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
3027       break;
3028     case CCValAssign::AExt:
3029       if (Arg.getValueType().isVector() &&
3030           Arg.getValueType().getScalarType() == MVT::i1)
3031         Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
3032       else if (RegVT.is128BitVector()) {
3033         // Special case: passing MMX values in XMM registers.
3034         Arg = DAG.getBitcast(MVT::i64, Arg);
3035         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
3036         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
3037       } else
3038         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
3039       break;
3040     case CCValAssign::BCvt:
3041       Arg = DAG.getBitcast(RegVT, Arg);
3042       break;
3043     case CCValAssign::Indirect: {
3044       // Store the argument.
3045       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
3046       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
3047       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
3048                            MachinePointerInfo::getFixedStack(FI),
3049                            false, false, 0);
3050       Arg = SpillSlot;
3051       break;
3052     }
3053     }
3054
3055     if (VA.isRegLoc()) {
3056       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3057       if (isVarArg && IsWin64) {
3058         // Win64 ABI requires argument XMM reg to be copied to the corresponding
3059         // shadow reg if callee is a varargs function.
3060         unsigned ShadowReg = 0;
3061         switch (VA.getLocReg()) {
3062         case X86::XMM0: ShadowReg = X86::RCX; break;
3063         case X86::XMM1: ShadowReg = X86::RDX; break;
3064         case X86::XMM2: ShadowReg = X86::R8; break;
3065         case X86::XMM3: ShadowReg = X86::R9; break;
3066         }
3067         if (ShadowReg)
3068           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
3069       }
3070     } else if (!IsSibcall && (!isTailCall || isByVal)) {
3071       assert(VA.isMemLoc());
3072       if (!StackPtr.getNode())
3073         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
3074                                       getPointerTy(DAG.getDataLayout()));
3075       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
3076                                              dl, DAG, VA, Flags));
3077     }
3078   }
3079
3080   if (!MemOpChains.empty())
3081     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
3082
3083   if (Subtarget->isPICStyleGOT()) {
3084     // ELF / PIC requires GOT in the EBX register before function calls via PLT
3085     // GOT pointer.
3086     if (!isTailCall) {
3087       RegsToPass.push_back(std::make_pair(
3088           unsigned(X86::EBX), DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(),
3089                                           getPointerTy(DAG.getDataLayout()))));
3090     } else {
3091       // If we are tail calling and generating PIC/GOT style code load the
3092       // address of the callee into ECX. The value in ecx is used as target of
3093       // the tail jump. This is done to circumvent the ebx/callee-saved problem
3094       // for tail calls on PIC/GOT architectures. Normally we would just put the
3095       // address of GOT into ebx and then call target@PLT. But for tail calls
3096       // ebx would be restored (since ebx is callee saved) before jumping to the
3097       // target@PLT.
3098
3099       // Note: The actual moving to ECX is done further down.
3100       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
3101       if (G && !G->getGlobal()->hasLocalLinkage() &&
3102           G->getGlobal()->hasDefaultVisibility())
3103         Callee = LowerGlobalAddress(Callee, DAG);
3104       else if (isa<ExternalSymbolSDNode>(Callee))
3105         Callee = LowerExternalSymbol(Callee, DAG);
3106     }
3107   }
3108
3109   if (Is64Bit && isVarArg && !IsWin64 && !IsMustTail) {
3110     // From AMD64 ABI document:
3111     // For calls that may call functions that use varargs or stdargs
3112     // (prototype-less calls or calls to functions containing ellipsis (...) in
3113     // the declaration) %al is used as hidden argument to specify the number
3114     // of SSE registers used. The contents of %al do not need to match exactly
3115     // the number of registers, but must be an ubound on the number of SSE
3116     // registers used and is in the range 0 - 8 inclusive.
3117
3118     // Count the number of XMM registers allocated.
3119     static const MCPhysReg XMMArgRegs[] = {
3120       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
3121       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
3122     };
3123     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs);
3124     assert((Subtarget->hasSSE1() || !NumXMMRegs)
3125            && "SSE registers cannot be used when SSE is disabled");
3126
3127     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
3128                                         DAG.getConstant(NumXMMRegs, dl,
3129                                                         MVT::i8)));
3130   }
3131
3132   if (isVarArg && IsMustTail) {
3133     const auto &Forwards = X86Info->getForwardedMustTailRegParms();
3134     for (const auto &F : Forwards) {
3135       SDValue Val = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
3136       RegsToPass.push_back(std::make_pair(unsigned(F.PReg), Val));
3137     }
3138   }
3139
3140   // For tail calls lower the arguments to the 'real' stack slots.  Sibcalls
3141   // don't need this because the eligibility check rejects calls that require
3142   // shuffling arguments passed in memory.
3143   if (!IsSibcall && isTailCall) {
3144     // Force all the incoming stack arguments to be loaded from the stack
3145     // before any new outgoing arguments are stored to the stack, because the
3146     // outgoing stack slots may alias the incoming argument stack slots, and
3147     // the alias isn't otherwise explicit. This is slightly more conservative
3148     // than necessary, because it means that each store effectively depends
3149     // on every argument instead of just those arguments it would clobber.
3150     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
3151
3152     SmallVector<SDValue, 8> MemOpChains2;
3153     SDValue FIN;
3154     int FI = 0;
3155     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3156       CCValAssign &VA = ArgLocs[i];
3157       if (VA.isRegLoc())
3158         continue;
3159       assert(VA.isMemLoc());
3160       SDValue Arg = OutVals[i];
3161       ISD::ArgFlagsTy Flags = Outs[i].Flags;
3162       // Skip inalloca arguments.  They don't require any work.
3163       if (Flags.isInAlloca())
3164         continue;
3165       // Create frame index.
3166       int32_t Offset = VA.getLocMemOffset()+FPDiff;
3167       uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
3168       FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3169       FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
3170
3171       if (Flags.isByVal()) {
3172         // Copy relative to framepointer.
3173         SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset(), dl);
3174         if (!StackPtr.getNode())
3175           StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
3176                                         getPointerTy(DAG.getDataLayout()));
3177         Source = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
3178                              StackPtr, Source);
3179
3180         MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
3181                                                          ArgChain,
3182                                                          Flags, DAG, dl));
3183       } else {
3184         // Store relative to framepointer.
3185         MemOpChains2.push_back(
3186           DAG.getStore(ArgChain, dl, Arg, FIN,
3187                        MachinePointerInfo::getFixedStack(FI),
3188                        false, false, 0));
3189       }
3190     }
3191
3192     if (!MemOpChains2.empty())
3193       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
3194
3195     // Store the return address to the appropriate stack slot.
3196     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
3197                                      getPointerTy(DAG.getDataLayout()),
3198                                      RegInfo->getSlotSize(), FPDiff, dl);
3199   }
3200
3201   // Build a sequence of copy-to-reg nodes chained together with token chain
3202   // and flag operands which copy the outgoing args into registers.
3203   SDValue InFlag;
3204   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
3205     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
3206                              RegsToPass[i].second, InFlag);
3207     InFlag = Chain.getValue(1);
3208   }
3209
3210   if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
3211     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
3212     // In the 64-bit large code model, we have to make all calls
3213     // through a register, since the call instruction's 32-bit
3214     // pc-relative offset may not be large enough to hold the whole
3215     // address.
3216   } else if (Callee->getOpcode() == ISD::GlobalAddress) {
3217     // If the callee is a GlobalAddress node (quite common, every direct call
3218     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
3219     // it.
3220     GlobalAddressSDNode* G = cast<GlobalAddressSDNode>(Callee);
3221
3222     // We should use extra load for direct calls to dllimported functions in
3223     // non-JIT mode.
3224     const GlobalValue *GV = G->getGlobal();
3225     if (!GV->hasDLLImportStorageClass()) {
3226       unsigned char OpFlags = 0;
3227       bool ExtraLoad = false;
3228       unsigned WrapperKind = ISD::DELETED_NODE;
3229
3230       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
3231       // external symbols most go through the PLT in PIC mode.  If the symbol
3232       // has hidden or protected visibility, or if it is static or local, then
3233       // we don't need to use the PLT - we can directly call it.
3234       if (Subtarget->isTargetELF() &&
3235           DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
3236           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
3237         OpFlags = X86II::MO_PLT;
3238       } else if (Subtarget->isPICStyleStubAny() &&
3239                  !GV->isStrongDefinitionForLinker() &&
3240                  (!Subtarget->getTargetTriple().isMacOSX() ||
3241                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3242         // PC-relative references to external symbols should go through $stub,
3243         // unless we're building with the leopard linker or later, which
3244         // automatically synthesizes these stubs.
3245         OpFlags = X86II::MO_DARWIN_STUB;
3246       } else if (Subtarget->isPICStyleRIPRel() && isa<Function>(GV) &&
3247                  cast<Function>(GV)->hasFnAttribute(Attribute::NonLazyBind)) {
3248         // If the function is marked as non-lazy, generate an indirect call
3249         // which loads from the GOT directly. This avoids runtime overhead
3250         // at the cost of eager binding (and one extra byte of encoding).
3251         OpFlags = X86II::MO_GOTPCREL;
3252         WrapperKind = X86ISD::WrapperRIP;
3253         ExtraLoad = true;
3254       }
3255
3256       Callee = DAG.getTargetGlobalAddress(
3257           GV, dl, getPointerTy(DAG.getDataLayout()), G->getOffset(), OpFlags);
3258
3259       // Add a wrapper if needed.
3260       if (WrapperKind != ISD::DELETED_NODE)
3261         Callee = DAG.getNode(X86ISD::WrapperRIP, dl,
3262                              getPointerTy(DAG.getDataLayout()), Callee);
3263       // Add extra indirection if needed.
3264       if (ExtraLoad)
3265         Callee = DAG.getLoad(
3266             getPointerTy(DAG.getDataLayout()), dl, DAG.getEntryNode(), Callee,
3267             MachinePointerInfo::getGOT(), false, false, false, 0);
3268     }
3269   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3270     unsigned char OpFlags = 0;
3271
3272     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
3273     // external symbols should go through the PLT.
3274     if (Subtarget->isTargetELF() &&
3275         DAG.getTarget().getRelocationModel() == Reloc::PIC_) {
3276       OpFlags = X86II::MO_PLT;
3277     } else if (Subtarget->isPICStyleStubAny() &&
3278                (!Subtarget->getTargetTriple().isMacOSX() ||
3279                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3280       // PC-relative references to external symbols should go through $stub,
3281       // unless we're building with the leopard linker or later, which
3282       // automatically synthesizes these stubs.
3283       OpFlags = X86II::MO_DARWIN_STUB;
3284     }
3285
3286     Callee = DAG.getTargetExternalSymbol(
3287         S->getSymbol(), getPointerTy(DAG.getDataLayout()), OpFlags);
3288   } else if (Subtarget->isTarget64BitILP32() &&
3289              Callee->getValueType(0) == MVT::i32) {
3290     // Zero-extend the 32-bit Callee address into a 64-bit according to x32 ABI
3291     Callee = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, Callee);
3292   }
3293
3294   // Returns a chain & a flag for retval copy to use.
3295   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3296   SmallVector<SDValue, 8> Ops;
3297
3298   if (!IsSibcall && isTailCall) {
3299     Chain = DAG.getCALLSEQ_END(Chain,
3300                                DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3301                                DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
3302     InFlag = Chain.getValue(1);
3303   }
3304
3305   Ops.push_back(Chain);
3306   Ops.push_back(Callee);
3307
3308   if (isTailCall)
3309     Ops.push_back(DAG.getConstant(FPDiff, dl, MVT::i32));
3310
3311   // Add argument registers to the end of the list so that they are known live
3312   // into the call.
3313   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3314     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3315                                   RegsToPass[i].second.getValueType()));
3316
3317   // Add a register mask operand representing the call-preserved registers.
3318   const uint32_t *Mask = RegInfo->getCallPreservedMask(MF, CallConv);
3319   assert(Mask && "Missing call preserved mask for calling convention");
3320
3321   // If this is an invoke in a 32-bit function using an MSVC personality, assume
3322   // the function clobbers all registers. If an exception is thrown, the runtime
3323   // will not restore CSRs.
3324   // FIXME: Model this more precisely so that we can register allocate across
3325   // the normal edge and spill and fill across the exceptional edge.
3326   if (!Is64Bit && CLI.CS && CLI.CS->isInvoke()) {
3327     const Function *CallerFn = MF.getFunction();
3328     EHPersonality Pers =
3329         CallerFn->hasPersonalityFn()
3330             ? classifyEHPersonality(CallerFn->getPersonalityFn())
3331             : EHPersonality::Unknown;
3332     if (isMSVCEHPersonality(Pers))
3333       Mask = RegInfo->getNoPreservedMask();
3334   }
3335
3336   Ops.push_back(DAG.getRegisterMask(Mask));
3337
3338   if (InFlag.getNode())
3339     Ops.push_back(InFlag);
3340
3341   if (isTailCall) {
3342     // We used to do:
3343     //// If this is the first return lowered for this function, add the regs
3344     //// to the liveout set for the function.
3345     // This isn't right, although it's probably harmless on x86; liveouts
3346     // should be computed from returns not tail calls.  Consider a void
3347     // function making a tail call to a function returning int.
3348     MF.getFrameInfo()->setHasTailCall();
3349     return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
3350   }
3351
3352   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
3353   InFlag = Chain.getValue(1);
3354
3355   // Create the CALLSEQ_END node.
3356   unsigned NumBytesForCalleeToPop;
3357   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
3358                        DAG.getTarget().Options.GuaranteedTailCallOpt))
3359     NumBytesForCalleeToPop = NumBytes;    // Callee pops everything
3360   else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
3361            !Subtarget->getTargetTriple().isOSMSVCRT() &&
3362            SR == StackStructReturn)
3363     // If this is a call to a struct-return function, the callee
3364     // pops the hidden struct pointer, so we have to push it back.
3365     // This is common for Darwin/X86, Linux & Mingw32 targets.
3366     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
3367     NumBytesForCalleeToPop = 4;
3368   else
3369     NumBytesForCalleeToPop = 0;  // Callee pops nothing.
3370
3371   // Returns a flag for retval copy to use.
3372   if (!IsSibcall) {
3373     Chain = DAG.getCALLSEQ_END(Chain,
3374                                DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3375                                DAG.getIntPtrConstant(NumBytesForCalleeToPop, dl,
3376                                                      true),
3377                                InFlag, dl);
3378     InFlag = Chain.getValue(1);
3379   }
3380
3381   // Handle result values, copying them out of physregs into vregs that we
3382   // return.
3383   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3384                          Ins, dl, DAG, InVals);
3385 }
3386
3387 //===----------------------------------------------------------------------===//
3388 //                Fast Calling Convention (tail call) implementation
3389 //===----------------------------------------------------------------------===//
3390
3391 //  Like std call, callee cleans arguments, convention except that ECX is
3392 //  reserved for storing the tail called function address. Only 2 registers are
3393 //  free for argument passing (inreg). Tail call optimization is performed
3394 //  provided:
3395 //                * tailcallopt is enabled
3396 //                * caller/callee are fastcc
3397 //  On X86_64 architecture with GOT-style position independent code only local
3398 //  (within module) calls are supported at the moment.
3399 //  To keep the stack aligned according to platform abi the function
3400 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
3401 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3402 //  If a tail called function callee has more arguments than the caller the
3403 //  caller needs to make sure that there is room to move the RETADDR to. This is
3404 //  achieved by reserving an area the size of the argument delta right after the
3405 //  original RETADDR, but before the saved framepointer or the spilled registers
3406 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3407 //  stack layout:
3408 //    arg1
3409 //    arg2
3410 //    RETADDR
3411 //    [ new RETADDR
3412 //      move area ]
3413 //    (possible EBP)
3414 //    ESI
3415 //    EDI
3416 //    local1 ..
3417
3418 /// Make the stack size align e.g 16n + 12 aligned for a 16-byte align
3419 /// requirement.
3420 unsigned
3421 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3422                                                SelectionDAG& DAG) const {
3423   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3424   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
3425   unsigned StackAlignment = TFI.getStackAlignment();
3426   uint64_t AlignMask = StackAlignment - 1;
3427   int64_t Offset = StackSize;
3428   unsigned SlotSize = RegInfo->getSlotSize();
3429   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3430     // Number smaller than 12 so just add the difference.
3431     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3432   } else {
3433     // Mask out lower bits, add stackalignment once plus the 12 bytes.
3434     Offset = ((~AlignMask) & Offset) + StackAlignment +
3435       (StackAlignment-SlotSize);
3436   }
3437   return Offset;
3438 }
3439
3440 /// Return true if the given stack call argument is already available in the
3441 /// same position (relatively) of the caller's incoming argument stack.
3442 static
3443 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3444                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3445                          const X86InstrInfo *TII) {
3446   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3447   int FI = INT_MAX;
3448   if (Arg.getOpcode() == ISD::CopyFromReg) {
3449     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3450     if (!TargetRegisterInfo::isVirtualRegister(VR))
3451       return false;
3452     MachineInstr *Def = MRI->getVRegDef(VR);
3453     if (!Def)
3454       return false;
3455     if (!Flags.isByVal()) {
3456       if (!TII->isLoadFromStackSlot(Def, FI))
3457         return false;
3458     } else {
3459       unsigned Opcode = Def->getOpcode();
3460       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r ||
3461            Opcode == X86::LEA64_32r) &&
3462           Def->getOperand(1).isFI()) {
3463         FI = Def->getOperand(1).getIndex();
3464         Bytes = Flags.getByValSize();
3465       } else
3466         return false;
3467     }
3468   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3469     if (Flags.isByVal())
3470       // ByVal argument is passed in as a pointer but it's now being
3471       // dereferenced. e.g.
3472       // define @foo(%struct.X* %A) {
3473       //   tail call @bar(%struct.X* byval %A)
3474       // }
3475       return false;
3476     SDValue Ptr = Ld->getBasePtr();
3477     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3478     if (!FINode)
3479       return false;
3480     FI = FINode->getIndex();
3481   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3482     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3483     FI = FINode->getIndex();
3484     Bytes = Flags.getByValSize();
3485   } else
3486     return false;
3487
3488   assert(FI != INT_MAX);
3489   if (!MFI->isFixedObjectIndex(FI))
3490     return false;
3491   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3492 }
3493
3494 /// Check whether the call is eligible for tail call optimization. Targets
3495 /// that want to do tail call optimization should implement this function.
3496 bool
3497 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3498                                                      CallingConv::ID CalleeCC,
3499                                                      bool isVarArg,
3500                                                      bool isCalleeStructRet,
3501                                                      bool isCallerStructRet,
3502                                                      Type *RetTy,
3503                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
3504                                     const SmallVectorImpl<SDValue> &OutVals,
3505                                     const SmallVectorImpl<ISD::InputArg> &Ins,
3506                                                      SelectionDAG &DAG) const {
3507   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3508     return false;
3509
3510   // If -tailcallopt is specified, make fastcc functions tail-callable.
3511   const MachineFunction &MF = DAG.getMachineFunction();
3512   const Function *CallerF = MF.getFunction();
3513
3514   // If the function return type is x86_fp80 and the callee return type is not,
3515   // then the FP_EXTEND of the call result is not a nop. It's not safe to
3516   // perform a tailcall optimization here.
3517   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3518     return false;
3519
3520   CallingConv::ID CallerCC = CallerF->getCallingConv();
3521   bool CCMatch = CallerCC == CalleeCC;
3522   bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3523   bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3524
3525   // Win64 functions have extra shadow space for argument homing. Don't do the
3526   // sibcall if the caller and callee have mismatched expectations for this
3527   // space.
3528   if (IsCalleeWin64 != IsCallerWin64)
3529     return false;
3530
3531   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3532     if (IsTailCallConvention(CalleeCC) && CCMatch)
3533       return true;
3534     return false;
3535   }
3536
3537   // Look for obvious safe cases to perform tail call optimization that do not
3538   // require ABI changes. This is what gcc calls sibcall.
3539
3540   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3541   // emit a special epilogue.
3542   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3543   if (RegInfo->needsStackRealignment(MF))
3544     return false;
3545
3546   // Also avoid sibcall optimization if either caller or callee uses struct
3547   // return semantics.
3548   if (isCalleeStructRet || isCallerStructRet)
3549     return false;
3550
3551   // An stdcall/thiscall caller is expected to clean up its arguments; the
3552   // callee isn't going to do that.
3553   // FIXME: this is more restrictive than needed. We could produce a tailcall
3554   // when the stack adjustment matches. For example, with a thiscall that takes
3555   // only one argument.
3556   if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3557                    CallerCC == CallingConv::X86_ThisCall))
3558     return false;
3559
3560   // Do not sibcall optimize vararg calls unless all arguments are passed via
3561   // registers.
3562   if (isVarArg && !Outs.empty()) {
3563
3564     // Optimizing for varargs on Win64 is unlikely to be safe without
3565     // additional testing.
3566     if (IsCalleeWin64 || IsCallerWin64)
3567       return false;
3568
3569     SmallVector<CCValAssign, 16> ArgLocs;
3570     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3571                    *DAG.getContext());
3572
3573     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3574     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3575       if (!ArgLocs[i].isRegLoc())
3576         return false;
3577   }
3578
3579   // If the call result is in ST0 / ST1, it needs to be popped off the x87
3580   // stack.  Therefore, if it's not used by the call it is not safe to optimize
3581   // this into a sibcall.
3582   bool Unused = false;
3583   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3584     if (!Ins[i].Used) {
3585       Unused = true;
3586       break;
3587     }
3588   }
3589   if (Unused) {
3590     SmallVector<CCValAssign, 16> RVLocs;
3591     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(), RVLocs,
3592                    *DAG.getContext());
3593     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3594     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3595       CCValAssign &VA = RVLocs[i];
3596       if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
3597         return false;
3598     }
3599   }
3600
3601   // If the calling conventions do not match, then we'd better make sure the
3602   // results are returned in the same way as what the caller expects.
3603   if (!CCMatch) {
3604     SmallVector<CCValAssign, 16> RVLocs1;
3605     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
3606                     *DAG.getContext());
3607     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3608
3609     SmallVector<CCValAssign, 16> RVLocs2;
3610     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
3611                     *DAG.getContext());
3612     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3613
3614     if (RVLocs1.size() != RVLocs2.size())
3615       return false;
3616     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3617       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3618         return false;
3619       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3620         return false;
3621       if (RVLocs1[i].isRegLoc()) {
3622         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3623           return false;
3624       } else {
3625         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3626           return false;
3627       }
3628     }
3629   }
3630
3631   // If the callee takes no arguments then go on to check the results of the
3632   // call.
3633   if (!Outs.empty()) {
3634     // Check if stack adjustment is needed. For now, do not do this if any
3635     // argument is passed on the stack.
3636     SmallVector<CCValAssign, 16> ArgLocs;
3637     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3638                    *DAG.getContext());
3639
3640     // Allocate shadow area for Win64
3641     if (IsCalleeWin64)
3642       CCInfo.AllocateStack(32, 8);
3643
3644     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3645     if (CCInfo.getNextStackOffset()) {
3646       MachineFunction &MF = DAG.getMachineFunction();
3647       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3648         return false;
3649
3650       // Check if the arguments are already laid out in the right way as
3651       // the caller's fixed stack objects.
3652       MachineFrameInfo *MFI = MF.getFrameInfo();
3653       const MachineRegisterInfo *MRI = &MF.getRegInfo();
3654       const X86InstrInfo *TII = Subtarget->getInstrInfo();
3655       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3656         CCValAssign &VA = ArgLocs[i];
3657         SDValue Arg = OutVals[i];
3658         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3659         if (VA.getLocInfo() == CCValAssign::Indirect)
3660           return false;
3661         if (!VA.isRegLoc()) {
3662           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3663                                    MFI, MRI, TII))
3664             return false;
3665         }
3666       }
3667     }
3668
3669     // If the tailcall address may be in a register, then make sure it's
3670     // possible to register allocate for it. In 32-bit, the call address can
3671     // only target EAX, EDX, or ECX since the tail call must be scheduled after
3672     // callee-saved registers are restored. These happen to be the same
3673     // registers used to pass 'inreg' arguments so watch out for those.
3674     if (!Subtarget->is64Bit() &&
3675         ((!isa<GlobalAddressSDNode>(Callee) &&
3676           !isa<ExternalSymbolSDNode>(Callee)) ||
3677          DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3678       unsigned NumInRegs = 0;
3679       // In PIC we need an extra register to formulate the address computation
3680       // for the callee.
3681       unsigned MaxInRegs =
3682         (DAG.getTarget().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3683
3684       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3685         CCValAssign &VA = ArgLocs[i];
3686         if (!VA.isRegLoc())
3687           continue;
3688         unsigned Reg = VA.getLocReg();
3689         switch (Reg) {
3690         default: break;
3691         case X86::EAX: case X86::EDX: case X86::ECX:
3692           if (++NumInRegs == MaxInRegs)
3693             return false;
3694           break;
3695         }
3696       }
3697     }
3698   }
3699
3700   return true;
3701 }
3702
3703 FastISel *
3704 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3705                                   const TargetLibraryInfo *libInfo) const {
3706   return X86::createFastISel(funcInfo, libInfo);
3707 }
3708
3709 //===----------------------------------------------------------------------===//
3710 //                           Other Lowering Hooks
3711 //===----------------------------------------------------------------------===//
3712
3713 static bool MayFoldLoad(SDValue Op) {
3714   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3715 }
3716
3717 static bool MayFoldIntoStore(SDValue Op) {
3718   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3719 }
3720
3721 static bool isTargetShuffle(unsigned Opcode) {
3722   switch(Opcode) {
3723   default: return false;
3724   case X86ISD::BLENDI:
3725   case X86ISD::PSHUFB:
3726   case X86ISD::PSHUFD:
3727   case X86ISD::PSHUFHW:
3728   case X86ISD::PSHUFLW:
3729   case X86ISD::SHUFP:
3730   case X86ISD::PALIGNR:
3731   case X86ISD::MOVLHPS:
3732   case X86ISD::MOVLHPD:
3733   case X86ISD::MOVHLPS:
3734   case X86ISD::MOVLPS:
3735   case X86ISD::MOVLPD:
3736   case X86ISD::MOVSHDUP:
3737   case X86ISD::MOVSLDUP:
3738   case X86ISD::MOVDDUP:
3739   case X86ISD::MOVSS:
3740   case X86ISD::MOVSD:
3741   case X86ISD::UNPCKL:
3742   case X86ISD::UNPCKH:
3743   case X86ISD::VPERMILPI:
3744   case X86ISD::VPERM2X128:
3745   case X86ISD::VPERMI:
3746     return true;
3747   }
3748 }
3749
3750 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3751                                     SDValue V1, unsigned TargetMask,
3752                                     SelectionDAG &DAG) {
3753   switch(Opc) {
3754   default: llvm_unreachable("Unknown x86 shuffle node");
3755   case X86ISD::PSHUFD:
3756   case X86ISD::PSHUFHW:
3757   case X86ISD::PSHUFLW:
3758   case X86ISD::VPERMILPI:
3759   case X86ISD::VPERMI:
3760     return DAG.getNode(Opc, dl, VT, V1,
3761                        DAG.getConstant(TargetMask, dl, MVT::i8));
3762   }
3763 }
3764
3765 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3766                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
3767   switch(Opc) {
3768   default: llvm_unreachable("Unknown x86 shuffle node");
3769   case X86ISD::MOVLHPS:
3770   case X86ISD::MOVLHPD:
3771   case X86ISD::MOVHLPS:
3772   case X86ISD::MOVLPS:
3773   case X86ISD::MOVLPD:
3774   case X86ISD::MOVSS:
3775   case X86ISD::MOVSD:
3776   case X86ISD::UNPCKL:
3777   case X86ISD::UNPCKH:
3778     return DAG.getNode(Opc, dl, VT, V1, V2);
3779   }
3780 }
3781
3782 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3783   MachineFunction &MF = DAG.getMachineFunction();
3784   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3785   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3786   int ReturnAddrIndex = FuncInfo->getRAIndex();
3787
3788   if (ReturnAddrIndex == 0) {
3789     // Set up a frame object for the return address.
3790     unsigned SlotSize = RegInfo->getSlotSize();
3791     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3792                                                            -(int64_t)SlotSize,
3793                                                            false);
3794     FuncInfo->setRAIndex(ReturnAddrIndex);
3795   }
3796
3797   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy(DAG.getDataLayout()));
3798 }
3799
3800 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3801                                        bool hasSymbolicDisplacement) {
3802   // Offset should fit into 32 bit immediate field.
3803   if (!isInt<32>(Offset))
3804     return false;
3805
3806   // If we don't have a symbolic displacement - we don't have any extra
3807   // restrictions.
3808   if (!hasSymbolicDisplacement)
3809     return true;
3810
3811   // FIXME: Some tweaks might be needed for medium code model.
3812   if (M != CodeModel::Small && M != CodeModel::Kernel)
3813     return false;
3814
3815   // For small code model we assume that latest object is 16MB before end of 31
3816   // bits boundary. We may also accept pretty large negative constants knowing
3817   // that all objects are in the positive half of address space.
3818   if (M == CodeModel::Small && Offset < 16*1024*1024)
3819     return true;
3820
3821   // For kernel code model we know that all object resist in the negative half
3822   // of 32bits address space. We may not accept negative offsets, since they may
3823   // be just off and we may accept pretty large positive ones.
3824   if (M == CodeModel::Kernel && Offset >= 0)
3825     return true;
3826
3827   return false;
3828 }
3829
3830 /// Determines whether the callee is required to pop its own arguments.
3831 /// Callee pop is necessary to support tail calls.
3832 bool X86::isCalleePop(CallingConv::ID CallingConv,
3833                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3834   switch (CallingConv) {
3835   default:
3836     return false;
3837   case CallingConv::X86_StdCall:
3838   case CallingConv::X86_FastCall:
3839   case CallingConv::X86_ThisCall:
3840     return !is64Bit;
3841   case CallingConv::Fast:
3842   case CallingConv::GHC:
3843   case CallingConv::HiPE:
3844     if (IsVarArg)
3845       return false;
3846     return TailCallOpt;
3847   }
3848 }
3849
3850 /// \brief Return true if the condition is an unsigned comparison operation.
3851 static bool isX86CCUnsigned(unsigned X86CC) {
3852   switch (X86CC) {
3853   default: llvm_unreachable("Invalid integer condition!");
3854   case X86::COND_E:     return true;
3855   case X86::COND_G:     return false;
3856   case X86::COND_GE:    return false;
3857   case X86::COND_L:     return false;
3858   case X86::COND_LE:    return false;
3859   case X86::COND_NE:    return true;
3860   case X86::COND_B:     return true;
3861   case X86::COND_A:     return true;
3862   case X86::COND_BE:    return true;
3863   case X86::COND_AE:    return true;
3864   }
3865   llvm_unreachable("covered switch fell through?!");
3866 }
3867
3868 /// Do a one-to-one translation of a ISD::CondCode to the X86-specific
3869 /// condition code, returning the condition code and the LHS/RHS of the
3870 /// comparison to make.
3871 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, SDLoc DL, bool isFP,
3872                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3873   if (!isFP) {
3874     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3875       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3876         // X > -1   -> X == 0, jump !sign.
3877         RHS = DAG.getConstant(0, DL, RHS.getValueType());
3878         return X86::COND_NS;
3879       }
3880       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3881         // X < 0   -> X == 0, jump on sign.
3882         return X86::COND_S;
3883       }
3884       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3885         // X < 1   -> X <= 0
3886         RHS = DAG.getConstant(0, DL, RHS.getValueType());
3887         return X86::COND_LE;
3888       }
3889     }
3890
3891     switch (SetCCOpcode) {
3892     default: llvm_unreachable("Invalid integer condition!");
3893     case ISD::SETEQ:  return X86::COND_E;
3894     case ISD::SETGT:  return X86::COND_G;
3895     case ISD::SETGE:  return X86::COND_GE;
3896     case ISD::SETLT:  return X86::COND_L;
3897     case ISD::SETLE:  return X86::COND_LE;
3898     case ISD::SETNE:  return X86::COND_NE;
3899     case ISD::SETULT: return X86::COND_B;
3900     case ISD::SETUGT: return X86::COND_A;
3901     case ISD::SETULE: return X86::COND_BE;
3902     case ISD::SETUGE: return X86::COND_AE;
3903     }
3904   }
3905
3906   // First determine if it is required or is profitable to flip the operands.
3907
3908   // If LHS is a foldable load, but RHS is not, flip the condition.
3909   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3910       !ISD::isNON_EXTLoad(RHS.getNode())) {
3911     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3912     std::swap(LHS, RHS);
3913   }
3914
3915   switch (SetCCOpcode) {
3916   default: break;
3917   case ISD::SETOLT:
3918   case ISD::SETOLE:
3919   case ISD::SETUGT:
3920   case ISD::SETUGE:
3921     std::swap(LHS, RHS);
3922     break;
3923   }
3924
3925   // On a floating point condition, the flags are set as follows:
3926   // ZF  PF  CF   op
3927   //  0 | 0 | 0 | X > Y
3928   //  0 | 0 | 1 | X < Y
3929   //  1 | 0 | 0 | X == Y
3930   //  1 | 1 | 1 | unordered
3931   switch (SetCCOpcode) {
3932   default: llvm_unreachable("Condcode should be pre-legalized away");
3933   case ISD::SETUEQ:
3934   case ISD::SETEQ:   return X86::COND_E;
3935   case ISD::SETOLT:              // flipped
3936   case ISD::SETOGT:
3937   case ISD::SETGT:   return X86::COND_A;
3938   case ISD::SETOLE:              // flipped
3939   case ISD::SETOGE:
3940   case ISD::SETGE:   return X86::COND_AE;
3941   case ISD::SETUGT:              // flipped
3942   case ISD::SETULT:
3943   case ISD::SETLT:   return X86::COND_B;
3944   case ISD::SETUGE:              // flipped
3945   case ISD::SETULE:
3946   case ISD::SETLE:   return X86::COND_BE;
3947   case ISD::SETONE:
3948   case ISD::SETNE:   return X86::COND_NE;
3949   case ISD::SETUO:   return X86::COND_P;
3950   case ISD::SETO:    return X86::COND_NP;
3951   case ISD::SETOEQ:
3952   case ISD::SETUNE:  return X86::COND_INVALID;
3953   }
3954 }
3955
3956 /// Is there a floating point cmov for the specific X86 condition code?
3957 /// Current x86 isa includes the following FP cmov instructions:
3958 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3959 static bool hasFPCMov(unsigned X86CC) {
3960   switch (X86CC) {
3961   default:
3962     return false;
3963   case X86::COND_B:
3964   case X86::COND_BE:
3965   case X86::COND_E:
3966   case X86::COND_P:
3967   case X86::COND_A:
3968   case X86::COND_AE:
3969   case X86::COND_NE:
3970   case X86::COND_NP:
3971     return true;
3972   }
3973 }
3974
3975 /// Returns true if the target can instruction select the
3976 /// specified FP immediate natively. If false, the legalizer will
3977 /// materialize the FP immediate as a load from a constant pool.
3978 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3979   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3980     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3981       return true;
3982   }
3983   return false;
3984 }
3985
3986 bool X86TargetLowering::shouldReduceLoadWidth(SDNode *Load,
3987                                               ISD::LoadExtType ExtTy,
3988                                               EVT NewVT) const {
3989   // "ELF Handling for Thread-Local Storage" specifies that R_X86_64_GOTTPOFF
3990   // relocation target a movq or addq instruction: don't let the load shrink.
3991   SDValue BasePtr = cast<LoadSDNode>(Load)->getBasePtr();
3992   if (BasePtr.getOpcode() == X86ISD::WrapperRIP)
3993     if (const auto *GA = dyn_cast<GlobalAddressSDNode>(BasePtr.getOperand(0)))
3994       return GA->getTargetFlags() != X86II::MO_GOTTPOFF;
3995   return true;
3996 }
3997
3998 /// \brief Returns true if it is beneficial to convert a load of a constant
3999 /// to just the constant itself.
4000 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
4001                                                           Type *Ty) const {
4002   assert(Ty->isIntegerTy());
4003
4004   unsigned BitSize = Ty->getPrimitiveSizeInBits();
4005   if (BitSize == 0 || BitSize > 64)
4006     return false;
4007   return true;
4008 }
4009
4010 bool X86TargetLowering::isExtractSubvectorCheap(EVT ResVT,
4011                                                 unsigned Index) const {
4012   if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
4013     return false;
4014
4015   return (Index == 0 || Index == ResVT.getVectorNumElements());
4016 }
4017
4018 bool X86TargetLowering::isCheapToSpeculateCttz() const {
4019   // Speculate cttz only if we can directly use TZCNT.
4020   return Subtarget->hasBMI();
4021 }
4022
4023 bool X86TargetLowering::isCheapToSpeculateCtlz() const {
4024   // Speculate ctlz only if we can directly use LZCNT.
4025   return Subtarget->hasLZCNT();
4026 }
4027
4028 /// Return true if every element in Mask, beginning
4029 /// from position Pos and ending in Pos+Size is undef.
4030 static bool isUndefInRange(ArrayRef<int> Mask, unsigned Pos, unsigned Size) {
4031   for (unsigned i = Pos, e = Pos + Size; i != e; ++i)
4032     if (0 <= Mask[i])
4033       return false;
4034   return true;
4035 }
4036
4037 /// Return true if Val is undef or if its value falls within the
4038 /// specified range (L, H].
4039 static bool isUndefOrInRange(int Val, int Low, int Hi) {
4040   return (Val < 0) || (Val >= Low && Val < Hi);
4041 }
4042
4043 /// Val is either less than zero (undef) or equal to the specified value.
4044 static bool isUndefOrEqual(int Val, int CmpVal) {
4045   return (Val < 0 || Val == CmpVal);
4046 }
4047
4048 /// Return true if every element in Mask, beginning
4049 /// from position Pos and ending in Pos+Size, falls within the specified
4050 /// sequential range (Low, Low+Size]. or is undef.
4051 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
4052                                        unsigned Pos, unsigned Size, int Low) {
4053   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
4054     if (!isUndefOrEqual(Mask[i], Low))
4055       return false;
4056   return true;
4057 }
4058
4059 /// Return true if the specified EXTRACT_SUBVECTOR operand specifies a vector
4060 /// extract that is suitable for instruction that extract 128 or 256 bit vectors
4061 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4062   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4063   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4064     return false;
4065
4066   // The index should be aligned on a vecWidth-bit boundary.
4067   uint64_t Index =
4068     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4069
4070   MVT VT = N->getSimpleValueType(0);
4071   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4072   bool Result = (Index * ElSize) % vecWidth == 0;
4073
4074   return Result;
4075 }
4076
4077 /// Return true if the specified INSERT_SUBVECTOR
4078 /// operand specifies a subvector insert that is suitable for input to
4079 /// insertion of 128 or 256-bit subvectors
4080 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4081   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4082   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4083     return false;
4084   // The index should be aligned on a vecWidth-bit boundary.
4085   uint64_t Index =
4086     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4087
4088   MVT VT = N->getSimpleValueType(0);
4089   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4090   bool Result = (Index * ElSize) % vecWidth == 0;
4091
4092   return Result;
4093 }
4094
4095 bool X86::isVINSERT128Index(SDNode *N) {
4096   return isVINSERTIndex(N, 128);
4097 }
4098
4099 bool X86::isVINSERT256Index(SDNode *N) {
4100   return isVINSERTIndex(N, 256);
4101 }
4102
4103 bool X86::isVEXTRACT128Index(SDNode *N) {
4104   return isVEXTRACTIndex(N, 128);
4105 }
4106
4107 bool X86::isVEXTRACT256Index(SDNode *N) {
4108   return isVEXTRACTIndex(N, 256);
4109 }
4110
4111 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4112   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4113   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4114     llvm_unreachable("Illegal extract subvector for VEXTRACT");
4115
4116   uint64_t Index =
4117     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4118
4119   MVT VecVT = N->getOperand(0).getSimpleValueType();
4120   MVT ElVT = VecVT.getVectorElementType();
4121
4122   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4123   return Index / NumElemsPerChunk;
4124 }
4125
4126 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4127   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4128   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4129     llvm_unreachable("Illegal insert subvector for VINSERT");
4130
4131   uint64_t Index =
4132     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4133
4134   MVT VecVT = N->getSimpleValueType(0);
4135   MVT ElVT = VecVT.getVectorElementType();
4136
4137   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4138   return Index / NumElemsPerChunk;
4139 }
4140
4141 /// Return the appropriate immediate to extract the specified
4142 /// EXTRACT_SUBVECTOR index with VEXTRACTF128 and VINSERTI128 instructions.
4143 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4144   return getExtractVEXTRACTImmediate(N, 128);
4145 }
4146
4147 /// Return the appropriate immediate to extract the specified
4148 /// EXTRACT_SUBVECTOR index with VEXTRACTF64x4 and VINSERTI64x4 instructions.
4149 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4150   return getExtractVEXTRACTImmediate(N, 256);
4151 }
4152
4153 /// Return the appropriate immediate to insert at the specified
4154 /// INSERT_SUBVECTOR index with VINSERTF128 and VINSERTI128 instructions.
4155 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4156   return getInsertVINSERTImmediate(N, 128);
4157 }
4158
4159 /// Return the appropriate immediate to insert at the specified
4160 /// INSERT_SUBVECTOR index with VINSERTF46x4 and VINSERTI64x4 instructions.
4161 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4162   return getInsertVINSERTImmediate(N, 256);
4163 }
4164
4165 /// Returns true if Elt is a constant integer zero
4166 static bool isZero(SDValue V) {
4167   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
4168   return C && C->isNullValue();
4169 }
4170
4171 /// Returns true if Elt is a constant zero or a floating point constant +0.0.
4172 bool X86::isZeroNode(SDValue Elt) {
4173   if (isZero(Elt))
4174     return true;
4175   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4176     return CFP->getValueAPF().isPosZero();
4177   return false;
4178 }
4179
4180 /// Returns a vector of specified type with all zero elements.
4181 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4182                              SelectionDAG &DAG, SDLoc dl) {
4183   assert(VT.isVector() && "Expected a vector type");
4184
4185   // Always build SSE zero vectors as <4 x i32> bitcasted
4186   // to their dest type. This ensures they get CSE'd.
4187   SDValue Vec;
4188   if (VT.is128BitVector()) {  // SSE
4189     if (Subtarget->hasSSE2()) {  // SSE2
4190       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4191       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4192     } else { // SSE1
4193       SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4194       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4195     }
4196   } else if (VT.is256BitVector()) { // AVX
4197     if (Subtarget->hasInt256()) { // AVX2
4198       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4199       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4200       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4201     } else {
4202       // 256-bit logic and arithmetic instructions in AVX are all
4203       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4204       SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4205       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4206       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
4207     }
4208   } else if (VT.is512BitVector()) { // AVX-512
4209       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4210       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4211                         Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4212       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4213   } else if (VT.getScalarType() == MVT::i1) {
4214
4215     assert((Subtarget->hasBWI() || VT.getVectorNumElements() <= 16)
4216             && "Unexpected vector type");
4217     assert((Subtarget->hasVLX() || VT.getVectorNumElements() >= 8)
4218             && "Unexpected vector type");
4219     SDValue Cst = DAG.getConstant(0, dl, MVT::i1);
4220     SmallVector<SDValue, 64> Ops(VT.getVectorNumElements(), Cst);
4221     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
4222   } else
4223     llvm_unreachable("Unexpected vector type");
4224
4225   return DAG.getBitcast(VT, Vec);
4226 }
4227
4228 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
4229                                 SelectionDAG &DAG, SDLoc dl,
4230                                 unsigned vectorWidth) {
4231   assert((vectorWidth == 128 || vectorWidth == 256) &&
4232          "Unsupported vector width");
4233   EVT VT = Vec.getValueType();
4234   EVT ElVT = VT.getVectorElementType();
4235   unsigned Factor = VT.getSizeInBits()/vectorWidth;
4236   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
4237                                   VT.getVectorNumElements()/Factor);
4238
4239   // Extract from UNDEF is UNDEF.
4240   if (Vec.getOpcode() == ISD::UNDEF)
4241     return DAG.getUNDEF(ResultVT);
4242
4243   // Extract the relevant vectorWidth bits.  Generate an EXTRACT_SUBVECTOR
4244   unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
4245
4246   // This is the index of the first element of the vectorWidth-bit chunk
4247   // we want.
4248   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / vectorWidth)
4249                                * ElemsPerChunk);
4250
4251   // If the input is a buildvector just emit a smaller one.
4252   if (Vec.getOpcode() == ISD::BUILD_VECTOR)
4253     return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
4254                        makeArrayRef(Vec->op_begin() + NormalizedIdxVal,
4255                                     ElemsPerChunk));
4256
4257   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal, dl);
4258   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec, VecIdx);
4259 }
4260
4261 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
4262 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
4263 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
4264 /// instructions or a simple subregister reference. Idx is an index in the
4265 /// 128 bits we want.  It need not be aligned to a 128-bit boundary.  That makes
4266 /// lowering EXTRACT_VECTOR_ELT operations easier.
4267 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
4268                                    SelectionDAG &DAG, SDLoc dl) {
4269   assert((Vec.getValueType().is256BitVector() ||
4270           Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
4271   return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
4272 }
4273
4274 /// Generate a DAG to grab 256-bits from a 512-bit vector.
4275 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
4276                                    SelectionDAG &DAG, SDLoc dl) {
4277   assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
4278   return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
4279 }
4280
4281 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
4282                                unsigned IdxVal, SelectionDAG &DAG,
4283                                SDLoc dl, unsigned vectorWidth) {
4284   assert((vectorWidth == 128 || vectorWidth == 256) &&
4285          "Unsupported vector width");
4286   // Inserting UNDEF is Result
4287   if (Vec.getOpcode() == ISD::UNDEF)
4288     return Result;
4289   EVT VT = Vec.getValueType();
4290   EVT ElVT = VT.getVectorElementType();
4291   EVT ResultVT = Result.getValueType();
4292
4293   // Insert the relevant vectorWidth bits.
4294   unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
4295
4296   // This is the index of the first element of the vectorWidth-bit chunk
4297   // we want.
4298   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/vectorWidth)
4299                                * ElemsPerChunk);
4300
4301   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal, dl);
4302   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec, VecIdx);
4303 }
4304
4305 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
4306 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
4307 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
4308 /// simple superregister reference.  Idx is an index in the 128 bits
4309 /// we want.  It need not be aligned to a 128-bit boundary.  That makes
4310 /// lowering INSERT_VECTOR_ELT operations easier.
4311 static SDValue Insert128BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4312                                   SelectionDAG &DAG, SDLoc dl) {
4313   assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
4314
4315   // For insertion into the zero index (low half) of a 256-bit vector, it is
4316   // more efficient to generate a blend with immediate instead of an insert*128.
4317   // We are still creating an INSERT_SUBVECTOR below with an undef node to
4318   // extend the subvector to the size of the result vector. Make sure that
4319   // we are not recursing on that node by checking for undef here.
4320   if (IdxVal == 0 && Result.getValueType().is256BitVector() &&
4321       Result.getOpcode() != ISD::UNDEF) {
4322     EVT ResultVT = Result.getValueType();
4323     SDValue ZeroIndex = DAG.getIntPtrConstant(0, dl);
4324     SDValue Undef = DAG.getUNDEF(ResultVT);
4325     SDValue Vec256 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Undef,
4326                                  Vec, ZeroIndex);
4327
4328     // The blend instruction, and therefore its mask, depend on the data type.
4329     MVT ScalarType = ResultVT.getScalarType().getSimpleVT();
4330     if (ScalarType.isFloatingPoint()) {
4331       // Choose either vblendps (float) or vblendpd (double).
4332       unsigned ScalarSize = ScalarType.getSizeInBits();
4333       assert((ScalarSize == 64 || ScalarSize == 32) && "Unknown float type");
4334       unsigned MaskVal = (ScalarSize == 64) ? 0x03 : 0x0f;
4335       SDValue Mask = DAG.getConstant(MaskVal, dl, MVT::i8);
4336       return DAG.getNode(X86ISD::BLENDI, dl, ResultVT, Result, Vec256, Mask);
4337     }
4338
4339     const X86Subtarget &Subtarget =
4340     static_cast<const X86Subtarget &>(DAG.getSubtarget());
4341
4342     // AVX2 is needed for 256-bit integer blend support.
4343     // Integers must be cast to 32-bit because there is only vpblendd;
4344     // vpblendw can't be used for this because it has a handicapped mask.
4345
4346     // If we don't have AVX2, then cast to float. Using a wrong domain blend
4347     // is still more efficient than using the wrong domain vinsertf128 that
4348     // will be created by InsertSubVector().
4349     MVT CastVT = Subtarget.hasAVX2() ? MVT::v8i32 : MVT::v8f32;
4350
4351     SDValue Mask = DAG.getConstant(0x0f, dl, MVT::i8);
4352     Vec256 = DAG.getBitcast(CastVT, Vec256);
4353     Vec256 = DAG.getNode(X86ISD::BLENDI, dl, CastVT, Result, Vec256, Mask);
4354     return DAG.getBitcast(ResultVT, Vec256);
4355   }
4356
4357   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
4358 }
4359
4360 static SDValue Insert256BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4361                                   SelectionDAG &DAG, SDLoc dl) {
4362   assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
4363   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
4364 }
4365
4366 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
4367 /// instructions. This is used because creating CONCAT_VECTOR nodes of
4368 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
4369 /// large BUILD_VECTORS.
4370 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
4371                                    unsigned NumElems, SelectionDAG &DAG,
4372                                    SDLoc dl) {
4373   SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4374   return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
4375 }
4376
4377 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
4378                                    unsigned NumElems, SelectionDAG &DAG,
4379                                    SDLoc dl) {
4380   SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4381   return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
4382 }
4383
4384 /// Returns a vector of specified type with all bits set.
4385 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4386 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4387 /// Then bitcast to their original type, ensuring they get CSE'd.
4388 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4389                              SDLoc dl) {
4390   assert(VT.isVector() && "Expected a vector type");
4391
4392   SDValue Cst = DAG.getConstant(~0U, dl, MVT::i32);
4393   SDValue Vec;
4394   if (VT.is256BitVector()) {
4395     if (HasInt256) { // AVX2
4396       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4397       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4398     } else { // AVX
4399       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4400       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4401     }
4402   } else if (VT.is128BitVector()) {
4403     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4404   } else
4405     llvm_unreachable("Unexpected vector type");
4406
4407   return DAG.getBitcast(VT, Vec);
4408 }
4409
4410 /// Returns a vector_shuffle node for an unpackl operation.
4411 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4412                           SDValue V2) {
4413   unsigned NumElems = VT.getVectorNumElements();
4414   SmallVector<int, 8> Mask;
4415   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4416     Mask.push_back(i);
4417     Mask.push_back(i + NumElems);
4418   }
4419   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4420 }
4421
4422 /// Returns a vector_shuffle node for an unpackh operation.
4423 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4424                           SDValue V2) {
4425   unsigned NumElems = VT.getVectorNumElements();
4426   SmallVector<int, 8> Mask;
4427   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4428     Mask.push_back(i + Half);
4429     Mask.push_back(i + NumElems + Half);
4430   }
4431   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4432 }
4433
4434 /// Return a vector_shuffle of the specified vector of zero or undef vector.
4435 /// This produces a shuffle where the low element of V2 is swizzled into the
4436 /// zero/undef vector, landing at element Idx.
4437 /// This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
4438 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4439                                            bool IsZero,
4440                                            const X86Subtarget *Subtarget,
4441                                            SelectionDAG &DAG) {
4442   MVT VT = V2.getSimpleValueType();
4443   SDValue V1 = IsZero
4444     ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
4445   unsigned NumElems = VT.getVectorNumElements();
4446   SmallVector<int, 16> MaskVec;
4447   for (unsigned i = 0; i != NumElems; ++i)
4448     // If this is the insertion idx, put the low elt of V2 here.
4449     MaskVec.push_back(i == Idx ? NumElems : i);
4450   return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
4451 }
4452
4453 /// Calculates the shuffle mask corresponding to the target-specific opcode.
4454 /// Returns true if the Mask could be calculated. Sets IsUnary to true if only
4455 /// uses one source. Note that this will set IsUnary for shuffles which use a
4456 /// single input multiple times, and in those cases it will
4457 /// adjust the mask to only have indices within that single input.
4458 /// FIXME: Add support for Decode*Mask functions that return SM_SentinelZero.
4459 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4460                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
4461   unsigned NumElems = VT.getVectorNumElements();
4462   SDValue ImmN;
4463
4464   IsUnary = false;
4465   bool IsFakeUnary = false;
4466   switch(N->getOpcode()) {
4467   case X86ISD::BLENDI:
4468     ImmN = N->getOperand(N->getNumOperands()-1);
4469     DecodeBLENDMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4470     break;
4471   case X86ISD::SHUFP:
4472     ImmN = N->getOperand(N->getNumOperands()-1);
4473     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4474     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4475     break;
4476   case X86ISD::UNPCKH:
4477     DecodeUNPCKHMask(VT, Mask);
4478     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4479     break;
4480   case X86ISD::UNPCKL:
4481     DecodeUNPCKLMask(VT, Mask);
4482     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4483     break;
4484   case X86ISD::MOVHLPS:
4485     DecodeMOVHLPSMask(NumElems, Mask);
4486     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4487     break;
4488   case X86ISD::MOVLHPS:
4489     DecodeMOVLHPSMask(NumElems, Mask);
4490     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4491     break;
4492   case X86ISD::PALIGNR:
4493     ImmN = N->getOperand(N->getNumOperands()-1);
4494     DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4495     break;
4496   case X86ISD::PSHUFD:
4497   case X86ISD::VPERMILPI:
4498     ImmN = N->getOperand(N->getNumOperands()-1);
4499     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4500     IsUnary = true;
4501     break;
4502   case X86ISD::PSHUFHW:
4503     ImmN = N->getOperand(N->getNumOperands()-1);
4504     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4505     IsUnary = true;
4506     break;
4507   case X86ISD::PSHUFLW:
4508     ImmN = N->getOperand(N->getNumOperands()-1);
4509     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4510     IsUnary = true;
4511     break;
4512   case X86ISD::PSHUFB: {
4513     IsUnary = true;
4514     SDValue MaskNode = N->getOperand(1);
4515     while (MaskNode->getOpcode() == ISD::BITCAST)
4516       MaskNode = MaskNode->getOperand(0);
4517
4518     if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
4519       // If we have a build-vector, then things are easy.
4520       EVT VT = MaskNode.getValueType();
4521       assert(VT.isVector() &&
4522              "Can't produce a non-vector with a build_vector!");
4523       if (!VT.isInteger())
4524         return false;
4525
4526       int NumBytesPerElement = VT.getVectorElementType().getSizeInBits() / 8;
4527
4528       SmallVector<uint64_t, 32> RawMask;
4529       for (int i = 0, e = MaskNode->getNumOperands(); i < e; ++i) {
4530         SDValue Op = MaskNode->getOperand(i);
4531         if (Op->getOpcode() == ISD::UNDEF) {
4532           RawMask.push_back((uint64_t)SM_SentinelUndef);
4533           continue;
4534         }
4535         auto *CN = dyn_cast<ConstantSDNode>(Op.getNode());
4536         if (!CN)
4537           return false;
4538         APInt MaskElement = CN->getAPIntValue();
4539
4540         // We now have to decode the element which could be any integer size and
4541         // extract each byte of it.
4542         for (int j = 0; j < NumBytesPerElement; ++j) {
4543           // Note that this is x86 and so always little endian: the low byte is
4544           // the first byte of the mask.
4545           RawMask.push_back(MaskElement.getLoBits(8).getZExtValue());
4546           MaskElement = MaskElement.lshr(8);
4547         }
4548       }
4549       DecodePSHUFBMask(RawMask, Mask);
4550       break;
4551     }
4552
4553     auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
4554     if (!MaskLoad)
4555       return false;
4556
4557     SDValue Ptr = MaskLoad->getBasePtr();
4558     if (Ptr->getOpcode() == X86ISD::Wrapper ||
4559         Ptr->getOpcode() == X86ISD::WrapperRIP)
4560       Ptr = Ptr->getOperand(0);
4561
4562     auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
4563     if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
4564       return false;
4565
4566     if (auto *C = dyn_cast<Constant>(MaskCP->getConstVal())) {
4567       DecodePSHUFBMask(C, Mask);
4568       if (Mask.empty())
4569         return false;
4570       break;
4571     }
4572
4573     return false;
4574   }
4575   case X86ISD::VPERMI:
4576     ImmN = N->getOperand(N->getNumOperands()-1);
4577     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4578     IsUnary = true;
4579     break;
4580   case X86ISD::MOVSS:
4581   case X86ISD::MOVSD:
4582     DecodeScalarMoveMask(VT, /* IsLoad */ false, Mask);
4583     break;
4584   case X86ISD::VPERM2X128:
4585     ImmN = N->getOperand(N->getNumOperands()-1);
4586     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4587     if (Mask.empty()) return false;
4588     // Mask only contains negative index if an element is zero.
4589     if (std::any_of(Mask.begin(), Mask.end(),
4590                     [](int M){ return M == SM_SentinelZero; }))
4591       return false;
4592     break;
4593   case X86ISD::MOVSLDUP:
4594     DecodeMOVSLDUPMask(VT, Mask);
4595     IsUnary = true;
4596     break;
4597   case X86ISD::MOVSHDUP:
4598     DecodeMOVSHDUPMask(VT, Mask);
4599     IsUnary = true;
4600     break;
4601   case X86ISD::MOVDDUP:
4602     DecodeMOVDDUPMask(VT, Mask);
4603     IsUnary = true;
4604     break;
4605   case X86ISD::MOVLHPD:
4606   case X86ISD::MOVLPD:
4607   case X86ISD::MOVLPS:
4608     // Not yet implemented
4609     return false;
4610   default: llvm_unreachable("unknown target shuffle node");
4611   }
4612
4613   // If we have a fake unary shuffle, the shuffle mask is spread across two
4614   // inputs that are actually the same node. Re-map the mask to always point
4615   // into the first input.
4616   if (IsFakeUnary)
4617     for (int &M : Mask)
4618       if (M >= (int)Mask.size())
4619         M -= Mask.size();
4620
4621   return true;
4622 }
4623
4624 /// Returns the scalar element that will make up the ith
4625 /// element of the result of the vector shuffle.
4626 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4627                                    unsigned Depth) {
4628   if (Depth == 6)
4629     return SDValue();  // Limit search depth.
4630
4631   SDValue V = SDValue(N, 0);
4632   EVT VT = V.getValueType();
4633   unsigned Opcode = V.getOpcode();
4634
4635   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4636   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4637     int Elt = SV->getMaskElt(Index);
4638
4639     if (Elt < 0)
4640       return DAG.getUNDEF(VT.getVectorElementType());
4641
4642     unsigned NumElems = VT.getVectorNumElements();
4643     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4644                                          : SV->getOperand(1);
4645     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4646   }
4647
4648   // Recurse into target specific vector shuffles to find scalars.
4649   if (isTargetShuffle(Opcode)) {
4650     MVT ShufVT = V.getSimpleValueType();
4651     unsigned NumElems = ShufVT.getVectorNumElements();
4652     SmallVector<int, 16> ShuffleMask;
4653     bool IsUnary;
4654
4655     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4656       return SDValue();
4657
4658     int Elt = ShuffleMask[Index];
4659     if (Elt < 0)
4660       return DAG.getUNDEF(ShufVT.getVectorElementType());
4661
4662     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4663                                          : N->getOperand(1);
4664     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4665                                Depth+1);
4666   }
4667
4668   // Actual nodes that may contain scalar elements
4669   if (Opcode == ISD::BITCAST) {
4670     V = V.getOperand(0);
4671     EVT SrcVT = V.getValueType();
4672     unsigned NumElems = VT.getVectorNumElements();
4673
4674     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4675       return SDValue();
4676   }
4677
4678   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4679     return (Index == 0) ? V.getOperand(0)
4680                         : DAG.getUNDEF(VT.getVectorElementType());
4681
4682   if (V.getOpcode() == ISD::BUILD_VECTOR)
4683     return V.getOperand(Index);
4684
4685   return SDValue();
4686 }
4687
4688 /// Custom lower build_vector of v16i8.
4689 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4690                                        unsigned NumNonZero, unsigned NumZero,
4691                                        SelectionDAG &DAG,
4692                                        const X86Subtarget* Subtarget,
4693                                        const TargetLowering &TLI) {
4694   if (NumNonZero > 8)
4695     return SDValue();
4696
4697   SDLoc dl(Op);
4698   SDValue V;
4699   bool First = true;
4700
4701   // SSE4.1 - use PINSRB to insert each byte directly.
4702   if (Subtarget->hasSSE41()) {
4703     for (unsigned i = 0; i < 16; ++i) {
4704       bool isNonZero = (NonZeros & (1 << i)) != 0;
4705       if (isNonZero) {
4706         if (First) {
4707           if (NumZero)
4708             V = getZeroVector(MVT::v16i8, Subtarget, DAG, dl);
4709           else
4710             V = DAG.getUNDEF(MVT::v16i8);
4711           First = false;
4712         }
4713         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4714                         MVT::v16i8, V, Op.getOperand(i),
4715                         DAG.getIntPtrConstant(i, dl));
4716       }
4717     }
4718
4719     return V;
4720   }
4721
4722   // Pre-SSE4.1 - merge byte pairs and insert with PINSRW.
4723   for (unsigned i = 0; i < 16; ++i) {
4724     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4725     if (ThisIsNonZero && First) {
4726       if (NumZero)
4727         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4728       else
4729         V = DAG.getUNDEF(MVT::v8i16);
4730       First = false;
4731     }
4732
4733     if ((i & 1) != 0) {
4734       SDValue ThisElt, LastElt;
4735       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4736       if (LastIsNonZero) {
4737         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4738                               MVT::i16, Op.getOperand(i-1));
4739       }
4740       if (ThisIsNonZero) {
4741         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4742         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4743                               ThisElt, DAG.getConstant(8, dl, MVT::i8));
4744         if (LastIsNonZero)
4745           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4746       } else
4747         ThisElt = LastElt;
4748
4749       if (ThisElt.getNode())
4750         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4751                         DAG.getIntPtrConstant(i/2, dl));
4752     }
4753   }
4754
4755   return DAG.getBitcast(MVT::v16i8, V);
4756 }
4757
4758 /// Custom lower build_vector of v8i16.
4759 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4760                                      unsigned NumNonZero, unsigned NumZero,
4761                                      SelectionDAG &DAG,
4762                                      const X86Subtarget* Subtarget,
4763                                      const TargetLowering &TLI) {
4764   if (NumNonZero > 4)
4765     return SDValue();
4766
4767   SDLoc dl(Op);
4768   SDValue V;
4769   bool First = true;
4770   for (unsigned i = 0; i < 8; ++i) {
4771     bool isNonZero = (NonZeros & (1 << i)) != 0;
4772     if (isNonZero) {
4773       if (First) {
4774         if (NumZero)
4775           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4776         else
4777           V = DAG.getUNDEF(MVT::v8i16);
4778         First = false;
4779       }
4780       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4781                       MVT::v8i16, V, Op.getOperand(i),
4782                       DAG.getIntPtrConstant(i, dl));
4783     }
4784   }
4785
4786   return V;
4787 }
4788
4789 /// Custom lower build_vector of v4i32 or v4f32.
4790 static SDValue LowerBuildVectorv4x32(SDValue Op, SelectionDAG &DAG,
4791                                      const X86Subtarget *Subtarget,
4792                                      const TargetLowering &TLI) {
4793   // Find all zeroable elements.
4794   std::bitset<4> Zeroable;
4795   for (int i=0; i < 4; ++i) {
4796     SDValue Elt = Op->getOperand(i);
4797     Zeroable[i] = (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt));
4798   }
4799   assert(Zeroable.size() - Zeroable.count() > 1 &&
4800          "We expect at least two non-zero elements!");
4801
4802   // We only know how to deal with build_vector nodes where elements are either
4803   // zeroable or extract_vector_elt with constant index.
4804   SDValue FirstNonZero;
4805   unsigned FirstNonZeroIdx;
4806   for (unsigned i=0; i < 4; ++i) {
4807     if (Zeroable[i])
4808       continue;
4809     SDValue Elt = Op->getOperand(i);
4810     if (Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4811         !isa<ConstantSDNode>(Elt.getOperand(1)))
4812       return SDValue();
4813     // Make sure that this node is extracting from a 128-bit vector.
4814     MVT VT = Elt.getOperand(0).getSimpleValueType();
4815     if (!VT.is128BitVector())
4816       return SDValue();
4817     if (!FirstNonZero.getNode()) {
4818       FirstNonZero = Elt;
4819       FirstNonZeroIdx = i;
4820     }
4821   }
4822
4823   assert(FirstNonZero.getNode() && "Unexpected build vector of all zeros!");
4824   SDValue V1 = FirstNonZero.getOperand(0);
4825   MVT VT = V1.getSimpleValueType();
4826
4827   // See if this build_vector can be lowered as a blend with zero.
4828   SDValue Elt;
4829   unsigned EltMaskIdx, EltIdx;
4830   int Mask[4];
4831   for (EltIdx = 0; EltIdx < 4; ++EltIdx) {
4832     if (Zeroable[EltIdx]) {
4833       // The zero vector will be on the right hand side.
4834       Mask[EltIdx] = EltIdx+4;
4835       continue;
4836     }
4837
4838     Elt = Op->getOperand(EltIdx);
4839     // By construction, Elt is a EXTRACT_VECTOR_ELT with constant index.
4840     EltMaskIdx = cast<ConstantSDNode>(Elt.getOperand(1))->getZExtValue();
4841     if (Elt.getOperand(0) != V1 || EltMaskIdx != EltIdx)
4842       break;
4843     Mask[EltIdx] = EltIdx;
4844   }
4845
4846   if (EltIdx == 4) {
4847     // Let the shuffle legalizer deal with blend operations.
4848     SDValue VZero = getZeroVector(VT, Subtarget, DAG, SDLoc(Op));
4849     if (V1.getSimpleValueType() != VT)
4850       V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), VT, V1);
4851     return DAG.getVectorShuffle(VT, SDLoc(V1), V1, VZero, &Mask[0]);
4852   }
4853
4854   // See if we can lower this build_vector to a INSERTPS.
4855   if (!Subtarget->hasSSE41())
4856     return SDValue();
4857
4858   SDValue V2 = Elt.getOperand(0);
4859   if (Elt == FirstNonZero && EltIdx == FirstNonZeroIdx)
4860     V1 = SDValue();
4861
4862   bool CanFold = true;
4863   for (unsigned i = EltIdx + 1; i < 4 && CanFold; ++i) {
4864     if (Zeroable[i])
4865       continue;
4866
4867     SDValue Current = Op->getOperand(i);
4868     SDValue SrcVector = Current->getOperand(0);
4869     if (!V1.getNode())
4870       V1 = SrcVector;
4871     CanFold = SrcVector == V1 &&
4872       cast<ConstantSDNode>(Current.getOperand(1))->getZExtValue() == i;
4873   }
4874
4875   if (!CanFold)
4876     return SDValue();
4877
4878   assert(V1.getNode() && "Expected at least two non-zero elements!");
4879   if (V1.getSimpleValueType() != MVT::v4f32)
4880     V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), MVT::v4f32, V1);
4881   if (V2.getSimpleValueType() != MVT::v4f32)
4882     V2 = DAG.getNode(ISD::BITCAST, SDLoc(V2), MVT::v4f32, V2);
4883
4884   // Ok, we can emit an INSERTPS instruction.
4885   unsigned ZMask = Zeroable.to_ulong();
4886
4887   unsigned InsertPSMask = EltMaskIdx << 6 | EltIdx << 4 | ZMask;
4888   assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
4889   SDLoc DL(Op);
4890   SDValue Result = DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
4891                                DAG.getIntPtrConstant(InsertPSMask, DL));
4892   return DAG.getBitcast(VT, Result);
4893 }
4894
4895 /// Return a vector logical shift node.
4896 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4897                          unsigned NumBits, SelectionDAG &DAG,
4898                          const TargetLowering &TLI, SDLoc dl) {
4899   assert(VT.is128BitVector() && "Unknown type for VShift");
4900   MVT ShVT = MVT::v2i64;
4901   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
4902   SrcOp = DAG.getBitcast(ShVT, SrcOp);
4903   MVT ScalarShiftTy = TLI.getScalarShiftAmountTy(DAG.getDataLayout(), VT);
4904   assert(NumBits % 8 == 0 && "Only support byte sized shifts");
4905   SDValue ShiftVal = DAG.getConstant(NumBits/8, dl, ScalarShiftTy);
4906   return DAG.getBitcast(VT, DAG.getNode(Opc, dl, ShVT, SrcOp, ShiftVal));
4907 }
4908
4909 static SDValue
4910 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
4911
4912   // Check if the scalar load can be widened into a vector load. And if
4913   // the address is "base + cst" see if the cst can be "absorbed" into
4914   // the shuffle mask.
4915   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4916     SDValue Ptr = LD->getBasePtr();
4917     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4918       return SDValue();
4919     EVT PVT = LD->getValueType(0);
4920     if (PVT != MVT::i32 && PVT != MVT::f32)
4921       return SDValue();
4922
4923     int FI = -1;
4924     int64_t Offset = 0;
4925     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4926       FI = FINode->getIndex();
4927       Offset = 0;
4928     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4929                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4930       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4931       Offset = Ptr.getConstantOperandVal(1);
4932       Ptr = Ptr.getOperand(0);
4933     } else {
4934       return SDValue();
4935     }
4936
4937     // FIXME: 256-bit vector instructions don't require a strict alignment,
4938     // improve this code to support it better.
4939     unsigned RequiredAlign = VT.getSizeInBits()/8;
4940     SDValue Chain = LD->getChain();
4941     // Make sure the stack object alignment is at least 16 or 32.
4942     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4943     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
4944       if (MFI->isFixedObjectIndex(FI)) {
4945         // Can't change the alignment. FIXME: It's possible to compute
4946         // the exact stack offset and reference FI + adjust offset instead.
4947         // If someone *really* cares about this. That's the way to implement it.
4948         return SDValue();
4949       } else {
4950         MFI->setObjectAlignment(FI, RequiredAlign);
4951       }
4952     }
4953
4954     // (Offset % 16 or 32) must be multiple of 4. Then address is then
4955     // Ptr + (Offset & ~15).
4956     if (Offset < 0)
4957       return SDValue();
4958     if ((Offset % RequiredAlign) & 3)
4959       return SDValue();
4960     int64_t StartOffset = Offset & ~(RequiredAlign-1);
4961     if (StartOffset) {
4962       SDLoc DL(Ptr);
4963       Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
4964                         DAG.getConstant(StartOffset, DL, Ptr.getValueType()));
4965     }
4966
4967     int EltNo = (Offset - StartOffset) >> 2;
4968     unsigned NumElems = VT.getVectorNumElements();
4969
4970     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
4971     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
4972                              LD->getPointerInfo().getWithOffset(StartOffset),
4973                              false, false, false, 0);
4974
4975     SmallVector<int, 8> Mask(NumElems, EltNo);
4976
4977     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
4978   }
4979
4980   return SDValue();
4981 }
4982
4983 /// Given the initializing elements 'Elts' of a vector of type 'VT', see if the
4984 /// elements can be replaced by a single large load which has the same value as
4985 /// a build_vector or insert_subvector whose loaded operands are 'Elts'.
4986 ///
4987 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4988 ///
4989 /// FIXME: we'd also like to handle the case where the last elements are zero
4990 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4991 /// There's even a handy isZeroNode for that purpose.
4992 static SDValue EltsFromConsecutiveLoads(EVT VT, ArrayRef<SDValue> Elts,
4993                                         SDLoc &DL, SelectionDAG &DAG,
4994                                         bool isAfterLegalize) {
4995   unsigned NumElems = Elts.size();
4996
4997   LoadSDNode *LDBase = nullptr;
4998   unsigned LastLoadedElt = -1U;
4999
5000   // For each element in the initializer, see if we've found a load or an undef.
5001   // If we don't find an initial load element, or later load elements are
5002   // non-consecutive, bail out.
5003   for (unsigned i = 0; i < NumElems; ++i) {
5004     SDValue Elt = Elts[i];
5005     // Look through a bitcast.
5006     if (Elt.getNode() && Elt.getOpcode() == ISD::BITCAST)
5007       Elt = Elt.getOperand(0);
5008     if (!Elt.getNode() ||
5009         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5010       return SDValue();
5011     if (!LDBase) {
5012       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5013         return SDValue();
5014       LDBase = cast<LoadSDNode>(Elt.getNode());
5015       LastLoadedElt = i;
5016       continue;
5017     }
5018     if (Elt.getOpcode() == ISD::UNDEF)
5019       continue;
5020
5021     LoadSDNode *LD = cast<LoadSDNode>(Elt);
5022     EVT LdVT = Elt.getValueType();
5023     // Each loaded element must be the correct fractional portion of the
5024     // requested vector load.
5025     if (LdVT.getSizeInBits() != VT.getSizeInBits() / NumElems)
5026       return SDValue();
5027     if (!DAG.isConsecutiveLoad(LD, LDBase, LdVT.getSizeInBits() / 8, i))
5028       return SDValue();
5029     LastLoadedElt = i;
5030   }
5031
5032   // If we have found an entire vector of loads and undefs, then return a large
5033   // load of the entire vector width starting at the base pointer.  If we found
5034   // consecutive loads for the low half, generate a vzext_load node.
5035   if (LastLoadedElt == NumElems - 1) {
5036     assert(LDBase && "Did not find base load for merging consecutive loads");
5037     EVT EltVT = LDBase->getValueType(0);
5038     // Ensure that the input vector size for the merged loads matches the
5039     // cumulative size of the input elements.
5040     if (VT.getSizeInBits() != EltVT.getSizeInBits() * NumElems)
5041       return SDValue();
5042
5043     if (isAfterLegalize &&
5044         !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
5045       return SDValue();
5046
5047     SDValue NewLd = SDValue();
5048
5049     NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5050                         LDBase->getPointerInfo(), LDBase->isVolatile(),
5051                         LDBase->isNonTemporal(), LDBase->isInvariant(),
5052                         LDBase->getAlignment());
5053
5054     if (LDBase->hasAnyUseOfValue(1)) {
5055       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5056                                      SDValue(LDBase, 1),
5057                                      SDValue(NewLd.getNode(), 1));
5058       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5059       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5060                              SDValue(NewLd.getNode(), 1));
5061     }
5062
5063     return NewLd;
5064   }
5065
5066   //TODO: The code below fires only for for loading the low v2i32 / v2f32
5067   //of a v4i32 / v4f32. It's probably worth generalizing.
5068   EVT EltVT = VT.getVectorElementType();
5069   if (NumElems == 4 && LastLoadedElt == 1 && (EltVT.getSizeInBits() == 32) &&
5070       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5071     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5072     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5073     SDValue ResNode =
5074         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
5075                                 LDBase->getPointerInfo(),
5076                                 LDBase->getAlignment(),
5077                                 false/*isVolatile*/, true/*ReadMem*/,
5078                                 false/*WriteMem*/);
5079
5080     // Make sure the newly-created LOAD is in the same position as LDBase in
5081     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5082     // update uses of LDBase's output chain to use the TokenFactor.
5083     if (LDBase->hasAnyUseOfValue(1)) {
5084       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5085                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5086       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5087       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5088                              SDValue(ResNode.getNode(), 1));
5089     }
5090
5091     return DAG.getBitcast(VT, ResNode);
5092   }
5093   return SDValue();
5094 }
5095
5096 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5097 /// to generate a splat value for the following cases:
5098 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5099 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5100 /// a scalar load, or a constant.
5101 /// The VBROADCAST node is returned when a pattern is found,
5102 /// or SDValue() otherwise.
5103 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5104                                     SelectionDAG &DAG) {
5105   // VBROADCAST requires AVX.
5106   // TODO: Splats could be generated for non-AVX CPUs using SSE
5107   // instructions, but there's less potential gain for only 128-bit vectors.
5108   if (!Subtarget->hasAVX())
5109     return SDValue();
5110
5111   MVT VT = Op.getSimpleValueType();
5112   SDLoc dl(Op);
5113
5114   assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5115          "Unsupported vector type for broadcast.");
5116
5117   SDValue Ld;
5118   bool ConstSplatVal;
5119
5120   switch (Op.getOpcode()) {
5121     default:
5122       // Unknown pattern found.
5123       return SDValue();
5124
5125     case ISD::BUILD_VECTOR: {
5126       auto *BVOp = cast<BuildVectorSDNode>(Op.getNode());
5127       BitVector UndefElements;
5128       SDValue Splat = BVOp->getSplatValue(&UndefElements);
5129
5130       // We need a splat of a single value to use broadcast, and it doesn't
5131       // make any sense if the value is only in one element of the vector.
5132       if (!Splat || (VT.getVectorNumElements() - UndefElements.count()) <= 1)
5133         return SDValue();
5134
5135       Ld = Splat;
5136       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5137                        Ld.getOpcode() == ISD::ConstantFP);
5138
5139       // Make sure that all of the users of a non-constant load are from the
5140       // BUILD_VECTOR node.
5141       if (!ConstSplatVal && !BVOp->isOnlyUserOf(Ld.getNode()))
5142         return SDValue();
5143       break;
5144     }
5145
5146     case ISD::VECTOR_SHUFFLE: {
5147       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5148
5149       // Shuffles must have a splat mask where the first element is
5150       // broadcasted.
5151       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5152         return SDValue();
5153
5154       SDValue Sc = Op.getOperand(0);
5155       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5156           Sc.getOpcode() != ISD::BUILD_VECTOR) {
5157
5158         if (!Subtarget->hasInt256())
5159           return SDValue();
5160
5161         // Use the register form of the broadcast instruction available on AVX2.
5162         if (VT.getSizeInBits() >= 256)
5163           Sc = Extract128BitVector(Sc, 0, DAG, dl);
5164         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5165       }
5166
5167       Ld = Sc.getOperand(0);
5168       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5169                        Ld.getOpcode() == ISD::ConstantFP);
5170
5171       // The scalar_to_vector node and the suspected
5172       // load node must have exactly one user.
5173       // Constants may have multiple users.
5174
5175       // AVX-512 has register version of the broadcast
5176       bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5177         Ld.getValueType().getSizeInBits() >= 32;
5178       if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5179           !hasRegVer))
5180         return SDValue();
5181       break;
5182     }
5183   }
5184
5185   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5186   bool IsGE256 = (VT.getSizeInBits() >= 256);
5187
5188   // When optimizing for size, generate up to 5 extra bytes for a broadcast
5189   // instruction to save 8 or more bytes of constant pool data.
5190   // TODO: If multiple splats are generated to load the same constant,
5191   // it may be detrimental to overall size. There needs to be a way to detect
5192   // that condition to know if this is truly a size win.
5193   const Function *F = DAG.getMachineFunction().getFunction();
5194   bool OptForSize = F->hasFnAttribute(Attribute::OptimizeForSize);
5195
5196   // Handle broadcasting a single constant scalar from the constant pool
5197   // into a vector.
5198   // On Sandybridge (no AVX2), it is still better to load a constant vector
5199   // from the constant pool and not to broadcast it from a scalar.
5200   // But override that restriction when optimizing for size.
5201   // TODO: Check if splatting is recommended for other AVX-capable CPUs.
5202   if (ConstSplatVal && (Subtarget->hasAVX2() || OptForSize)) {
5203     EVT CVT = Ld.getValueType();
5204     assert(!CVT.isVector() && "Must not broadcast a vector type");
5205
5206     // Splat f32, i32, v4f64, v4i64 in all cases with AVX2.
5207     // For size optimization, also splat v2f64 and v2i64, and for size opt
5208     // with AVX2, also splat i8 and i16.
5209     // With pattern matching, the VBROADCAST node may become a VMOVDDUP.
5210     if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5211         (OptForSize && (ScalarSize == 64 || Subtarget->hasAVX2()))) {
5212       const Constant *C = nullptr;
5213       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5214         C = CI->getConstantIntValue();
5215       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5216         C = CF->getConstantFPValue();
5217
5218       assert(C && "Invalid constant type");
5219
5220       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5221       SDValue CP =
5222           DAG.getConstantPool(C, TLI.getPointerTy(DAG.getDataLayout()));
5223       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5224       Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5225                        MachinePointerInfo::getConstantPool(),
5226                        false, false, false, Alignment);
5227
5228       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5229     }
5230   }
5231
5232   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5233
5234   // Handle AVX2 in-register broadcasts.
5235   if (!IsLoad && Subtarget->hasInt256() &&
5236       (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5237     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5238
5239   // The scalar source must be a normal load.
5240   if (!IsLoad)
5241     return SDValue();
5242
5243   if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5244       (Subtarget->hasVLX() && ScalarSize == 64))
5245     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5246
5247   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5248   // double since there is no vbroadcastsd xmm
5249   if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5250     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5251       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5252   }
5253
5254   // Unsupported broadcast.
5255   return SDValue();
5256 }
5257
5258 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
5259 /// underlying vector and index.
5260 ///
5261 /// Modifies \p ExtractedFromVec to the real vector and returns the real
5262 /// index.
5263 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
5264                                          SDValue ExtIdx) {
5265   int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5266   if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
5267     return Idx;
5268
5269   // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
5270   // lowered this:
5271   //   (extract_vector_elt (v8f32 %vreg1), Constant<6>)
5272   // to:
5273   //   (extract_vector_elt (vector_shuffle<2,u,u,u>
5274   //                           (extract_subvector (v8f32 %vreg0), Constant<4>),
5275   //                           undef)
5276   //                       Constant<0>)
5277   // In this case the vector is the extract_subvector expression and the index
5278   // is 2, as specified by the shuffle.
5279   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
5280   SDValue ShuffleVec = SVOp->getOperand(0);
5281   MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
5282   assert(ShuffleVecVT.getVectorElementType() ==
5283          ExtractedFromVec.getSimpleValueType().getVectorElementType());
5284
5285   int ShuffleIdx = SVOp->getMaskElt(Idx);
5286   if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
5287     ExtractedFromVec = ShuffleVec;
5288     return ShuffleIdx;
5289   }
5290   return Idx;
5291 }
5292
5293 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5294   MVT VT = Op.getSimpleValueType();
5295
5296   // Skip if insert_vec_elt is not supported.
5297   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5298   if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5299     return SDValue();
5300
5301   SDLoc DL(Op);
5302   unsigned NumElems = Op.getNumOperands();
5303
5304   SDValue VecIn1;
5305   SDValue VecIn2;
5306   SmallVector<unsigned, 4> InsertIndices;
5307   SmallVector<int, 8> Mask(NumElems, -1);
5308
5309   for (unsigned i = 0; i != NumElems; ++i) {
5310     unsigned Opc = Op.getOperand(i).getOpcode();
5311
5312     if (Opc == ISD::UNDEF)
5313       continue;
5314
5315     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5316       // Quit if more than 1 elements need inserting.
5317       if (InsertIndices.size() > 1)
5318         return SDValue();
5319
5320       InsertIndices.push_back(i);
5321       continue;
5322     }
5323
5324     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5325     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5326     // Quit if non-constant index.
5327     if (!isa<ConstantSDNode>(ExtIdx))
5328       return SDValue();
5329     int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5330
5331     // Quit if extracted from vector of different type.
5332     if (ExtractedFromVec.getValueType() != VT)
5333       return SDValue();
5334
5335     if (!VecIn1.getNode())
5336       VecIn1 = ExtractedFromVec;
5337     else if (VecIn1 != ExtractedFromVec) {
5338       if (!VecIn2.getNode())
5339         VecIn2 = ExtractedFromVec;
5340       else if (VecIn2 != ExtractedFromVec)
5341         // Quit if more than 2 vectors to shuffle
5342         return SDValue();
5343     }
5344
5345     if (ExtractedFromVec == VecIn1)
5346       Mask[i] = Idx;
5347     else if (ExtractedFromVec == VecIn2)
5348       Mask[i] = Idx + NumElems;
5349   }
5350
5351   if (!VecIn1.getNode())
5352     return SDValue();
5353
5354   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5355   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5356   for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5357     unsigned Idx = InsertIndices[i];
5358     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5359                      DAG.getIntPtrConstant(Idx, DL));
5360   }
5361
5362   return NV;
5363 }
5364
5365 static SDValue ConvertI1VectorToInteger(SDValue Op, SelectionDAG &DAG) {
5366   assert(ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) &&
5367          Op.getScalarValueSizeInBits() == 1 &&
5368          "Can not convert non-constant vector");
5369   uint64_t Immediate = 0;
5370   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5371     SDValue In = Op.getOperand(idx);
5372     if (In.getOpcode() != ISD::UNDEF)
5373       Immediate |= cast<ConstantSDNode>(In)->getZExtValue() << idx;
5374   }
5375   SDLoc dl(Op);
5376   MVT VT =
5377    MVT::getIntegerVT(std::max((int)Op.getValueType().getSizeInBits(), 8));
5378   return DAG.getConstant(Immediate, dl, VT);
5379 }
5380 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5381 SDValue
5382 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5383
5384   MVT VT = Op.getSimpleValueType();
5385   assert((VT.getVectorElementType() == MVT::i1) &&
5386          "Unexpected type in LowerBUILD_VECTORvXi1!");
5387
5388   SDLoc dl(Op);
5389   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5390     SDValue Cst = DAG.getTargetConstant(0, dl, MVT::i1);
5391     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5392     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5393   }
5394
5395   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5396     SDValue Cst = DAG.getTargetConstant(1, dl, MVT::i1);
5397     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5398     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5399   }
5400
5401   if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) {
5402     SDValue Imm = ConvertI1VectorToInteger(Op, DAG);
5403     if (Imm.getValueSizeInBits() == VT.getSizeInBits())
5404       return DAG.getBitcast(VT, Imm);
5405     SDValue ExtVec = DAG.getBitcast(MVT::v8i1, Imm);
5406     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, ExtVec,
5407                         DAG.getIntPtrConstant(0, dl));
5408   }
5409
5410   // Vector has one or more non-const elements
5411   uint64_t Immediate = 0;
5412   SmallVector<unsigned, 16> NonConstIdx;
5413   bool IsSplat = true;
5414   bool HasConstElts = false;
5415   int SplatIdx = -1;
5416   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5417     SDValue In = Op.getOperand(idx);
5418     if (In.getOpcode() == ISD::UNDEF)
5419       continue;
5420     if (!isa<ConstantSDNode>(In))
5421       NonConstIdx.push_back(idx);
5422     else {
5423       Immediate |= cast<ConstantSDNode>(In)->getZExtValue() << idx;
5424       HasConstElts = true;
5425     }
5426     if (SplatIdx == -1)
5427       SplatIdx = idx;
5428     else if (In != Op.getOperand(SplatIdx))
5429       IsSplat = false;
5430   }
5431
5432   // for splat use " (select i1 splat_elt, all-ones, all-zeroes)"
5433   if (IsSplat)
5434     return DAG.getNode(ISD::SELECT, dl, VT, Op.getOperand(SplatIdx),
5435                        DAG.getConstant(1, dl, VT),
5436                        DAG.getConstant(0, dl, VT));
5437
5438   // insert elements one by one
5439   SDValue DstVec;
5440   SDValue Imm;
5441   if (Immediate) {
5442     MVT ImmVT = MVT::getIntegerVT(std::max((int)VT.getSizeInBits(), 8));
5443     Imm = DAG.getConstant(Immediate, dl, ImmVT);
5444   }
5445   else if (HasConstElts)
5446     Imm = DAG.getConstant(0, dl, VT);
5447   else
5448     Imm = DAG.getUNDEF(VT);
5449   if (Imm.getValueSizeInBits() == VT.getSizeInBits())
5450     DstVec = DAG.getBitcast(VT, Imm);
5451   else {
5452     SDValue ExtVec = DAG.getBitcast(MVT::v8i1, Imm);
5453     DstVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, ExtVec,
5454                          DAG.getIntPtrConstant(0, dl));
5455   }
5456
5457   for (unsigned i = 0; i < NonConstIdx.size(); ++i) {
5458     unsigned InsertIdx = NonConstIdx[i];
5459     DstVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5460                          Op.getOperand(InsertIdx),
5461                          DAG.getIntPtrConstant(InsertIdx, dl));
5462   }
5463   return DstVec;
5464 }
5465
5466 /// \brief Return true if \p N implements a horizontal binop and return the
5467 /// operands for the horizontal binop into V0 and V1.
5468 ///
5469 /// This is a helper function of LowerToHorizontalOp().
5470 /// This function checks that the build_vector \p N in input implements a
5471 /// horizontal operation. Parameter \p Opcode defines the kind of horizontal
5472 /// operation to match.
5473 /// For example, if \p Opcode is equal to ISD::ADD, then this function
5474 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
5475 /// is equal to ISD::SUB, then this function checks if this is a horizontal
5476 /// arithmetic sub.
5477 ///
5478 /// This function only analyzes elements of \p N whose indices are
5479 /// in range [BaseIdx, LastIdx).
5480 static bool isHorizontalBinOp(const BuildVectorSDNode *N, unsigned Opcode,
5481                               SelectionDAG &DAG,
5482                               unsigned BaseIdx, unsigned LastIdx,
5483                               SDValue &V0, SDValue &V1) {
5484   EVT VT = N->getValueType(0);
5485
5486   assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
5487   assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
5488          "Invalid Vector in input!");
5489
5490   bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
5491   bool CanFold = true;
5492   unsigned ExpectedVExtractIdx = BaseIdx;
5493   unsigned NumElts = LastIdx - BaseIdx;
5494   V0 = DAG.getUNDEF(VT);
5495   V1 = DAG.getUNDEF(VT);
5496
5497   // Check if N implements a horizontal binop.
5498   for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
5499     SDValue Op = N->getOperand(i + BaseIdx);
5500
5501     // Skip UNDEFs.
5502     if (Op->getOpcode() == ISD::UNDEF) {
5503       // Update the expected vector extract index.
5504       if (i * 2 == NumElts)
5505         ExpectedVExtractIdx = BaseIdx;
5506       ExpectedVExtractIdx += 2;
5507       continue;
5508     }
5509
5510     CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
5511
5512     if (!CanFold)
5513       break;
5514
5515     SDValue Op0 = Op.getOperand(0);
5516     SDValue Op1 = Op.getOperand(1);
5517
5518     // Try to match the following pattern:
5519     // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
5520     CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5521         Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5522         Op0.getOperand(0) == Op1.getOperand(0) &&
5523         isa<ConstantSDNode>(Op0.getOperand(1)) &&
5524         isa<ConstantSDNode>(Op1.getOperand(1)));
5525     if (!CanFold)
5526       break;
5527
5528     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5529     unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
5530
5531     if (i * 2 < NumElts) {
5532       if (V0.getOpcode() == ISD::UNDEF) {
5533         V0 = Op0.getOperand(0);
5534         if (V0.getValueType() != VT)
5535           return false;
5536       }
5537     } else {
5538       if (V1.getOpcode() == ISD::UNDEF) {
5539         V1 = Op0.getOperand(0);
5540         if (V1.getValueType() != VT)
5541           return false;
5542       }
5543       if (i * 2 == NumElts)
5544         ExpectedVExtractIdx = BaseIdx;
5545     }
5546
5547     SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
5548     if (I0 == ExpectedVExtractIdx)
5549       CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
5550     else if (IsCommutable && I1 == ExpectedVExtractIdx) {
5551       // Try to match the following dag sequence:
5552       // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
5553       CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
5554     } else
5555       CanFold = false;
5556
5557     ExpectedVExtractIdx += 2;
5558   }
5559
5560   return CanFold;
5561 }
5562
5563 /// \brief Emit a sequence of two 128-bit horizontal add/sub followed by
5564 /// a concat_vector.
5565 ///
5566 /// This is a helper function of LowerToHorizontalOp().
5567 /// This function expects two 256-bit vectors called V0 and V1.
5568 /// At first, each vector is split into two separate 128-bit vectors.
5569 /// Then, the resulting 128-bit vectors are used to implement two
5570 /// horizontal binary operations.
5571 ///
5572 /// The kind of horizontal binary operation is defined by \p X86Opcode.
5573 ///
5574 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
5575 /// the two new horizontal binop.
5576 /// When Mode is set, the first horizontal binop dag node would take as input
5577 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
5578 /// horizontal binop dag node would take as input the lower 128-bit of V1
5579 /// and the upper 128-bit of V1.
5580 ///   Example:
5581 ///     HADD V0_LO, V0_HI
5582 ///     HADD V1_LO, V1_HI
5583 ///
5584 /// Otherwise, the first horizontal binop dag node takes as input the lower
5585 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
5586 /// dag node takes the upper 128-bit of V0 and the upper 128-bit of V1.
5587 ///   Example:
5588 ///     HADD V0_LO, V1_LO
5589 ///     HADD V0_HI, V1_HI
5590 ///
5591 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
5592 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
5593 /// the upper 128-bits of the result.
5594 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
5595                                      SDLoc DL, SelectionDAG &DAG,
5596                                      unsigned X86Opcode, bool Mode,
5597                                      bool isUndefLO, bool isUndefHI) {
5598   EVT VT = V0.getValueType();
5599   assert(VT.is256BitVector() && VT == V1.getValueType() &&
5600          "Invalid nodes in input!");
5601
5602   unsigned NumElts = VT.getVectorNumElements();
5603   SDValue V0_LO = Extract128BitVector(V0, 0, DAG, DL);
5604   SDValue V0_HI = Extract128BitVector(V0, NumElts/2, DAG, DL);
5605   SDValue V1_LO = Extract128BitVector(V1, 0, DAG, DL);
5606   SDValue V1_HI = Extract128BitVector(V1, NumElts/2, DAG, DL);
5607   EVT NewVT = V0_LO.getValueType();
5608
5609   SDValue LO = DAG.getUNDEF(NewVT);
5610   SDValue HI = DAG.getUNDEF(NewVT);
5611
5612   if (Mode) {
5613     // Don't emit a horizontal binop if the result is expected to be UNDEF.
5614     if (!isUndefLO && V0->getOpcode() != ISD::UNDEF)
5615       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
5616     if (!isUndefHI && V1->getOpcode() != ISD::UNDEF)
5617       HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
5618   } else {
5619     // Don't emit a horizontal binop if the result is expected to be UNDEF.
5620     if (!isUndefLO && (V0_LO->getOpcode() != ISD::UNDEF ||
5621                        V1_LO->getOpcode() != ISD::UNDEF))
5622       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
5623
5624     if (!isUndefHI && (V0_HI->getOpcode() != ISD::UNDEF ||
5625                        V1_HI->getOpcode() != ISD::UNDEF))
5626       HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
5627   }
5628
5629   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
5630 }
5631
5632 /// Try to fold a build_vector that performs an 'addsub' to an X86ISD::ADDSUB
5633 /// node.
5634 static SDValue LowerToAddSub(const BuildVectorSDNode *BV,
5635                              const X86Subtarget *Subtarget, SelectionDAG &DAG) {
5636   EVT VT = BV->getValueType(0);
5637   if ((!Subtarget->hasSSE3() || (VT != MVT::v4f32 && VT != MVT::v2f64)) &&
5638       (!Subtarget->hasAVX() || (VT != MVT::v8f32 && VT != MVT::v4f64)))
5639     return SDValue();
5640
5641   SDLoc DL(BV);
5642   unsigned NumElts = VT.getVectorNumElements();
5643   SDValue InVec0 = DAG.getUNDEF(VT);
5644   SDValue InVec1 = DAG.getUNDEF(VT);
5645
5646   assert((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v4f32 ||
5647           VT == MVT::v2f64) && "build_vector with an invalid type found!");
5648
5649   // Odd-numbered elements in the input build vector are obtained from
5650   // adding two integer/float elements.
5651   // Even-numbered elements in the input build vector are obtained from
5652   // subtracting two integer/float elements.
5653   unsigned ExpectedOpcode = ISD::FSUB;
5654   unsigned NextExpectedOpcode = ISD::FADD;
5655   bool AddFound = false;
5656   bool SubFound = false;
5657
5658   for (unsigned i = 0, e = NumElts; i != e; ++i) {
5659     SDValue Op = BV->getOperand(i);
5660
5661     // Skip 'undef' values.
5662     unsigned Opcode = Op.getOpcode();
5663     if (Opcode == ISD::UNDEF) {
5664       std::swap(ExpectedOpcode, NextExpectedOpcode);
5665       continue;
5666     }
5667
5668     // Early exit if we found an unexpected opcode.
5669     if (Opcode != ExpectedOpcode)
5670       return SDValue();
5671
5672     SDValue Op0 = Op.getOperand(0);
5673     SDValue Op1 = Op.getOperand(1);
5674
5675     // Try to match the following pattern:
5676     // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
5677     // Early exit if we cannot match that sequence.
5678     if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5679         Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5680         !isa<ConstantSDNode>(Op0.getOperand(1)) ||
5681         !isa<ConstantSDNode>(Op1.getOperand(1)) ||
5682         Op0.getOperand(1) != Op1.getOperand(1))
5683       return SDValue();
5684
5685     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5686     if (I0 != i)
5687       return SDValue();
5688
5689     // We found a valid add/sub node. Update the information accordingly.
5690     if (i & 1)
5691       AddFound = true;
5692     else
5693       SubFound = true;
5694
5695     // Update InVec0 and InVec1.
5696     if (InVec0.getOpcode() == ISD::UNDEF) {
5697       InVec0 = Op0.getOperand(0);
5698       if (InVec0.getValueType() != VT)
5699         return SDValue();
5700     }
5701     if (InVec1.getOpcode() == ISD::UNDEF) {
5702       InVec1 = Op1.getOperand(0);
5703       if (InVec1.getValueType() != VT)
5704         return SDValue();
5705     }
5706
5707     // Make sure that operands in input to each add/sub node always
5708     // come from a same pair of vectors.
5709     if (InVec0 != Op0.getOperand(0)) {
5710       if (ExpectedOpcode == ISD::FSUB)
5711         return SDValue();
5712
5713       // FADD is commutable. Try to commute the operands
5714       // and then test again.
5715       std::swap(Op0, Op1);
5716       if (InVec0 != Op0.getOperand(0))
5717         return SDValue();
5718     }
5719
5720     if (InVec1 != Op1.getOperand(0))
5721       return SDValue();
5722
5723     // Update the pair of expected opcodes.
5724     std::swap(ExpectedOpcode, NextExpectedOpcode);
5725   }
5726
5727   // Don't try to fold this build_vector into an ADDSUB if the inputs are undef.
5728   if (AddFound && SubFound && InVec0.getOpcode() != ISD::UNDEF &&
5729       InVec1.getOpcode() != ISD::UNDEF)
5730     return DAG.getNode(X86ISD::ADDSUB, DL, VT, InVec0, InVec1);
5731
5732   return SDValue();
5733 }
5734
5735 /// Lower BUILD_VECTOR to a horizontal add/sub operation if possible.
5736 static SDValue LowerToHorizontalOp(const BuildVectorSDNode *BV,
5737                                    const X86Subtarget *Subtarget,
5738                                    SelectionDAG &DAG) {
5739   EVT VT = BV->getValueType(0);
5740   unsigned NumElts = VT.getVectorNumElements();
5741   unsigned NumUndefsLO = 0;
5742   unsigned NumUndefsHI = 0;
5743   unsigned Half = NumElts/2;
5744
5745   // Count the number of UNDEF operands in the build_vector in input.
5746   for (unsigned i = 0, e = Half; i != e; ++i)
5747     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
5748       NumUndefsLO++;
5749
5750   for (unsigned i = Half, e = NumElts; i != e; ++i)
5751     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
5752       NumUndefsHI++;
5753
5754   // Early exit if this is either a build_vector of all UNDEFs or all the
5755   // operands but one are UNDEF.
5756   if (NumUndefsLO + NumUndefsHI + 1 >= NumElts)
5757     return SDValue();
5758
5759   SDLoc DL(BV);
5760   SDValue InVec0, InVec1;
5761   if ((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) {
5762     // Try to match an SSE3 float HADD/HSUB.
5763     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
5764       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
5765
5766     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
5767       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
5768   } else if ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) {
5769     // Try to match an SSSE3 integer HADD/HSUB.
5770     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
5771       return DAG.getNode(X86ISD::HADD, DL, VT, InVec0, InVec1);
5772
5773     if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
5774       return DAG.getNode(X86ISD::HSUB, DL, VT, InVec0, InVec1);
5775   }
5776
5777   if (!Subtarget->hasAVX())
5778     return SDValue();
5779
5780   if ((VT == MVT::v8f32 || VT == MVT::v4f64)) {
5781     // Try to match an AVX horizontal add/sub of packed single/double
5782     // precision floating point values from 256-bit vectors.
5783     SDValue InVec2, InVec3;
5784     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, Half, InVec0, InVec1) &&
5785         isHorizontalBinOp(BV, ISD::FADD, 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::FHADD, DL, VT, InVec0, InVec1);
5791
5792     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, Half, InVec0, InVec1) &&
5793         isHorizontalBinOp(BV, ISD::FSUB, DAG, Half, NumElts, InVec2, InVec3) &&
5794         ((InVec0.getOpcode() == ISD::UNDEF ||
5795           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5796         ((InVec1.getOpcode() == ISD::UNDEF ||
5797           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5798       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
5799   } else if (VT == MVT::v8i32 || VT == MVT::v16i16) {
5800     // Try to match an AVX2 horizontal add/sub of signed integers.
5801     SDValue InVec2, InVec3;
5802     unsigned X86Opcode;
5803     bool CanFold = true;
5804
5805     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
5806         isHorizontalBinOp(BV, ISD::ADD, DAG, Half, NumElts, InVec2, InVec3) &&
5807         ((InVec0.getOpcode() == ISD::UNDEF ||
5808           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5809         ((InVec1.getOpcode() == ISD::UNDEF ||
5810           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5811       X86Opcode = X86ISD::HADD;
5812     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, Half, InVec0, InVec1) &&
5813         isHorizontalBinOp(BV, ISD::SUB, DAG, Half, NumElts, InVec2, InVec3) &&
5814         ((InVec0.getOpcode() == ISD::UNDEF ||
5815           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5816         ((InVec1.getOpcode() == ISD::UNDEF ||
5817           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5818       X86Opcode = X86ISD::HSUB;
5819     else
5820       CanFold = false;
5821
5822     if (CanFold) {
5823       // Fold this build_vector into a single horizontal add/sub.
5824       // Do this only if the target has AVX2.
5825       if (Subtarget->hasAVX2())
5826         return DAG.getNode(X86Opcode, DL, VT, InVec0, InVec1);
5827
5828       // Do not try to expand this build_vector into a pair of horizontal
5829       // add/sub if we can emit a pair of scalar add/sub.
5830       if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
5831         return SDValue();
5832
5833       // Convert this build_vector into a pair of horizontal binop followed by
5834       // a concat vector.
5835       bool isUndefLO = NumUndefsLO == Half;
5836       bool isUndefHI = NumUndefsHI == Half;
5837       return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, false,
5838                                    isUndefLO, isUndefHI);
5839     }
5840   }
5841
5842   if ((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
5843        VT == MVT::v16i16) && Subtarget->hasAVX()) {
5844     unsigned X86Opcode;
5845     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
5846       X86Opcode = X86ISD::HADD;
5847     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
5848       X86Opcode = X86ISD::HSUB;
5849     else if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
5850       X86Opcode = X86ISD::FHADD;
5851     else if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
5852       X86Opcode = X86ISD::FHSUB;
5853     else
5854       return SDValue();
5855
5856     // Don't try to expand this build_vector into a pair of horizontal add/sub
5857     // if we can simply emit a pair of scalar add/sub.
5858     if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
5859       return SDValue();
5860
5861     // Convert this build_vector into two horizontal add/sub followed by
5862     // a concat vector.
5863     bool isUndefLO = NumUndefsLO == Half;
5864     bool isUndefHI = NumUndefsHI == Half;
5865     return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
5866                                  isUndefLO, isUndefHI);
5867   }
5868
5869   return SDValue();
5870 }
5871
5872 SDValue
5873 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5874   SDLoc dl(Op);
5875
5876   MVT VT = Op.getSimpleValueType();
5877   MVT ExtVT = VT.getVectorElementType();
5878   unsigned NumElems = Op.getNumOperands();
5879
5880   // Generate vectors for predicate vectors.
5881   if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
5882     return LowerBUILD_VECTORvXi1(Op, DAG);
5883
5884   // Vectors containing all zeros can be matched by pxor and xorps later
5885   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5886     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5887     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5888     if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
5889       return Op;
5890
5891     return getZeroVector(VT, Subtarget, DAG, dl);
5892   }
5893
5894   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5895   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5896   // vpcmpeqd on 256-bit vectors.
5897   if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
5898     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
5899       return Op;
5900
5901     if (!VT.is512BitVector())
5902       return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
5903   }
5904
5905   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(Op.getNode());
5906   if (SDValue AddSub = LowerToAddSub(BV, Subtarget, DAG))
5907     return AddSub;
5908   if (SDValue HorizontalOp = LowerToHorizontalOp(BV, Subtarget, DAG))
5909     return HorizontalOp;
5910   if (SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG))
5911     return Broadcast;
5912
5913   unsigned EVTBits = ExtVT.getSizeInBits();
5914
5915   unsigned NumZero  = 0;
5916   unsigned NumNonZero = 0;
5917   unsigned NonZeros = 0;
5918   bool IsAllConstants = true;
5919   SmallSet<SDValue, 8> Values;
5920   for (unsigned i = 0; i < NumElems; ++i) {
5921     SDValue Elt = Op.getOperand(i);
5922     if (Elt.getOpcode() == ISD::UNDEF)
5923       continue;
5924     Values.insert(Elt);
5925     if (Elt.getOpcode() != ISD::Constant &&
5926         Elt.getOpcode() != ISD::ConstantFP)
5927       IsAllConstants = false;
5928     if (X86::isZeroNode(Elt))
5929       NumZero++;
5930     else {
5931       NonZeros |= (1 << i);
5932       NumNonZero++;
5933     }
5934   }
5935
5936   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
5937   if (NumNonZero == 0)
5938     return DAG.getUNDEF(VT);
5939
5940   // Special case for single non-zero, non-undef, element.
5941   if (NumNonZero == 1) {
5942     unsigned Idx = countTrailingZeros(NonZeros);
5943     SDValue Item = Op.getOperand(Idx);
5944
5945     // If this is an insertion of an i64 value on x86-32, and if the top bits of
5946     // the value are obviously zero, truncate the value to i32 and do the
5947     // insertion that way.  Only do this if the value is non-constant or if the
5948     // value is a constant being inserted into element 0.  It is cheaper to do
5949     // a constant pool load than it is to do a movd + shuffle.
5950     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5951         (!IsAllConstants || Idx == 0)) {
5952       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5953         // Handle SSE only.
5954         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5955         EVT VecVT = MVT::v4i32;
5956
5957         // Truncate the value (which may itself be a constant) to i32, and
5958         // convert it to a vector with movd (S2V+shuffle to zero extend).
5959         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5960         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5961         return DAG.getBitcast(VT, getShuffleVectorZeroOrUndef(
5962                                       Item, Idx * 2, true, Subtarget, DAG));
5963       }
5964     }
5965
5966     // If we have a constant or non-constant insertion into the low element of
5967     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5968     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
5969     // depending on what the source datatype is.
5970     if (Idx == 0) {
5971       if (NumZero == 0)
5972         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5973
5974       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5975           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5976         if (VT.is512BitVector()) {
5977           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
5978           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
5979                              Item, DAG.getIntPtrConstant(0, dl));
5980         }
5981         assert((VT.is128BitVector() || VT.is256BitVector()) &&
5982                "Expected an SSE value type!");
5983         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5984         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5985         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5986       }
5987
5988       // We can't directly insert an i8 or i16 into a vector, so zero extend
5989       // it to i32 first.
5990       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5991         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5992         if (VT.is256BitVector()) {
5993           if (Subtarget->hasAVX()) {
5994             Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v8i32, Item);
5995             Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5996           } else {
5997             // Without AVX, we need to extend to a 128-bit vector and then
5998             // insert into the 256-bit vector.
5999             Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6000             SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
6001             Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
6002           }
6003         } else {
6004           assert(VT.is128BitVector() && "Expected an SSE value type!");
6005           Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6006           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6007         }
6008         return DAG.getBitcast(VT, Item);
6009       }
6010     }
6011
6012     // Is it a vector logical left shift?
6013     if (NumElems == 2 && Idx == 1 &&
6014         X86::isZeroNode(Op.getOperand(0)) &&
6015         !X86::isZeroNode(Op.getOperand(1))) {
6016       unsigned NumBits = VT.getSizeInBits();
6017       return getVShift(true, VT,
6018                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6019                                    VT, Op.getOperand(1)),
6020                        NumBits/2, DAG, *this, dl);
6021     }
6022
6023     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
6024       return SDValue();
6025
6026     // Otherwise, if this is a vector with i32 or f32 elements, and the element
6027     // is a non-constant being inserted into an element other than the low one,
6028     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
6029     // movd/movss) to move this into the low element, then shuffle it into
6030     // place.
6031     if (EVTBits == 32) {
6032       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6033       return getShuffleVectorZeroOrUndef(Item, Idx, NumZero > 0, Subtarget, DAG);
6034     }
6035   }
6036
6037   // Splat is obviously ok. Let legalizer expand it to a shuffle.
6038   if (Values.size() == 1) {
6039     if (EVTBits == 32) {
6040       // Instead of a shuffle like this:
6041       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6042       // Check if it's possible to issue this instead.
6043       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6044       unsigned Idx = countTrailingZeros(NonZeros);
6045       SDValue Item = Op.getOperand(Idx);
6046       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6047         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6048     }
6049     return SDValue();
6050   }
6051
6052   // A vector full of immediates; various special cases are already
6053   // handled, so this is best done with a single constant-pool load.
6054   if (IsAllConstants)
6055     return SDValue();
6056
6057   // For AVX-length vectors, see if we can use a vector load to get all of the
6058   // elements, otherwise build the individual 128-bit pieces and use
6059   // shuffles to put them in place.
6060   if (VT.is256BitVector() || VT.is512BitVector()) {
6061     SmallVector<SDValue, 64> V(Op->op_begin(), Op->op_begin() + NumElems);
6062
6063     // Check for a build vector of consecutive loads.
6064     if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
6065       return LD;
6066
6067     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6068
6069     // Build both the lower and upper subvector.
6070     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6071                                 makeArrayRef(&V[0], NumElems/2));
6072     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6073                                 makeArrayRef(&V[NumElems / 2], NumElems/2));
6074
6075     // Recreate the wider vector with the lower and upper part.
6076     if (VT.is256BitVector())
6077       return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6078     return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6079   }
6080
6081   // Let legalizer expand 2-wide build_vectors.
6082   if (EVTBits == 64) {
6083     if (NumNonZero == 1) {
6084       // One half is zero or undef.
6085       unsigned Idx = countTrailingZeros(NonZeros);
6086       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6087                                  Op.getOperand(Idx));
6088       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6089     }
6090     return SDValue();
6091   }
6092
6093   // If element VT is < 32 bits, convert it to inserts into a zero vector.
6094   if (EVTBits == 8 && NumElems == 16)
6095     if (SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
6096                                         Subtarget, *this))
6097       return V;
6098
6099   if (EVTBits == 16 && NumElems == 8)
6100     if (SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
6101                                       Subtarget, *this))
6102       return V;
6103
6104   // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
6105   if (EVTBits == 32 && NumElems == 4)
6106     if (SDValue V = LowerBuildVectorv4x32(Op, DAG, Subtarget, *this))
6107       return V;
6108
6109   // If element VT is == 32 bits, turn it into a number of shuffles.
6110   SmallVector<SDValue, 8> V(NumElems);
6111   if (NumElems == 4 && NumZero > 0) {
6112     for (unsigned i = 0; i < 4; ++i) {
6113       bool isZero = !(NonZeros & (1 << i));
6114       if (isZero)
6115         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6116       else
6117         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6118     }
6119
6120     for (unsigned i = 0; i < 2; ++i) {
6121       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6122         default: break;
6123         case 0:
6124           V[i] = V[i*2];  // Must be a zero vector.
6125           break;
6126         case 1:
6127           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6128           break;
6129         case 2:
6130           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6131           break;
6132         case 3:
6133           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6134           break;
6135       }
6136     }
6137
6138     bool Reverse1 = (NonZeros & 0x3) == 2;
6139     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6140     int MaskVec[] = {
6141       Reverse1 ? 1 : 0,
6142       Reverse1 ? 0 : 1,
6143       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6144       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
6145     };
6146     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6147   }
6148
6149   if (Values.size() > 1 && VT.is128BitVector()) {
6150     // Check for a build vector of consecutive loads.
6151     for (unsigned i = 0; i < NumElems; ++i)
6152       V[i] = Op.getOperand(i);
6153
6154     // Check for elements which are consecutive loads.
6155     if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
6156       return LD;
6157
6158     // Check for a build vector from mostly shuffle plus few inserting.
6159     if (SDValue Sh = buildFromShuffleMostly(Op, DAG))
6160       return Sh;
6161
6162     // For SSE 4.1, use insertps to put the high elements into the low element.
6163     if (Subtarget->hasSSE41()) {
6164       SDValue Result;
6165       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6166         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6167       else
6168         Result = DAG.getUNDEF(VT);
6169
6170       for (unsigned i = 1; i < NumElems; ++i) {
6171         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6172         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6173                              Op.getOperand(i), DAG.getIntPtrConstant(i, dl));
6174       }
6175       return Result;
6176     }
6177
6178     // Otherwise, expand into a number of unpckl*, start by extending each of
6179     // our (non-undef) elements to the full vector width with the element in the
6180     // bottom slot of the vector (which generates no code for SSE).
6181     for (unsigned i = 0; i < NumElems; ++i) {
6182       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6183         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6184       else
6185         V[i] = DAG.getUNDEF(VT);
6186     }
6187
6188     // Next, we iteratively mix elements, e.g. for v4f32:
6189     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6190     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6191     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
6192     unsigned EltStride = NumElems >> 1;
6193     while (EltStride != 0) {
6194       for (unsigned i = 0; i < EltStride; ++i) {
6195         // If V[i+EltStride] is undef and this is the first round of mixing,
6196         // then it is safe to just drop this shuffle: V[i] is already in the
6197         // right place, the one element (since it's the first round) being
6198         // inserted as undef can be dropped.  This isn't safe for successive
6199         // rounds because they will permute elements within both vectors.
6200         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6201             EltStride == NumElems/2)
6202           continue;
6203
6204         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6205       }
6206       EltStride >>= 1;
6207     }
6208     return V[0];
6209   }
6210   return SDValue();
6211 }
6212
6213 // 256-bit AVX can use the vinsertf128 instruction
6214 // to create 256-bit vectors from two other 128-bit ones.
6215 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6216   SDLoc dl(Op);
6217   MVT ResVT = Op.getSimpleValueType();
6218
6219   assert((ResVT.is256BitVector() ||
6220           ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6221
6222   SDValue V1 = Op.getOperand(0);
6223   SDValue V2 = Op.getOperand(1);
6224   unsigned NumElems = ResVT.getVectorNumElements();
6225   if (ResVT.is256BitVector())
6226     return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6227
6228   if (Op.getNumOperands() == 4) {
6229     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6230                                 ResVT.getVectorNumElements()/2);
6231     SDValue V3 = Op.getOperand(2);
6232     SDValue V4 = Op.getOperand(3);
6233     return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6234       Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6235   }
6236   return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6237 }
6238
6239 static SDValue LowerCONCAT_VECTORSvXi1(SDValue Op,
6240                                        const X86Subtarget *Subtarget,
6241                                        SelectionDAG & DAG) {
6242   SDLoc dl(Op);
6243   MVT ResVT = Op.getSimpleValueType();
6244   unsigned NumOfOperands = Op.getNumOperands();
6245
6246   assert(isPowerOf2_32(NumOfOperands) &&
6247          "Unexpected number of operands in CONCAT_VECTORS");
6248
6249   if (NumOfOperands > 2) {
6250     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6251                                   ResVT.getVectorNumElements()/2);
6252     SmallVector<SDValue, 2> Ops;
6253     for (unsigned i = 0; i < NumOfOperands/2; i++)
6254       Ops.push_back(Op.getOperand(i));
6255     SDValue Lo = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6256     Ops.clear();
6257     for (unsigned i = NumOfOperands/2; i < NumOfOperands; i++)
6258       Ops.push_back(Op.getOperand(i));
6259     SDValue Hi = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6260     return DAG.getNode(ISD::CONCAT_VECTORS, dl, ResVT, Lo, Hi);
6261   }
6262
6263   SDValue V1 = Op.getOperand(0);
6264   SDValue V2 = Op.getOperand(1);
6265   bool IsZeroV1 = ISD::isBuildVectorAllZeros(V1.getNode());
6266   bool IsZeroV2 = ISD::isBuildVectorAllZeros(V2.getNode());
6267
6268   if (IsZeroV1 && IsZeroV2)
6269     return getZeroVector(ResVT, Subtarget, DAG, dl);
6270
6271   SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
6272   SDValue Undef = DAG.getUNDEF(ResVT);
6273   unsigned NumElems = ResVT.getVectorNumElements();
6274   SDValue ShiftBits = DAG.getConstant(NumElems/2, dl, MVT::i8);
6275
6276   V2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V2, ZeroIdx);
6277   V2 = DAG.getNode(X86ISD::VSHLI, dl, ResVT, V2, ShiftBits);
6278   if (IsZeroV1)
6279     return V2;
6280
6281   V1 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V1, ZeroIdx);
6282   // Zero the upper bits of V1
6283   V1 = DAG.getNode(X86ISD::VSHLI, dl, ResVT, V1, ShiftBits);
6284   V1 = DAG.getNode(X86ISD::VSRLI, dl, ResVT, V1, ShiftBits);
6285   if (IsZeroV2)
6286     return V1;
6287   return DAG.getNode(ISD::OR, dl, ResVT, V1, V2);
6288 }
6289
6290 static SDValue LowerCONCAT_VECTORS(SDValue Op,
6291                                    const X86Subtarget *Subtarget,
6292                                    SelectionDAG &DAG) {
6293   MVT VT = Op.getSimpleValueType();
6294   if (VT.getVectorElementType() == MVT::i1)
6295     return LowerCONCAT_VECTORSvXi1(Op, Subtarget, DAG);
6296
6297   assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6298          (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6299           Op.getNumOperands() == 4)));
6300
6301   // AVX can use the vinsertf128 instruction to create 256-bit vectors
6302   // from two other 128-bit ones.
6303
6304   // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6305   return LowerAVXCONCAT_VECTORS(Op, DAG);
6306 }
6307
6308
6309 //===----------------------------------------------------------------------===//
6310 // Vector shuffle lowering
6311 //
6312 // This is an experimental code path for lowering vector shuffles on x86. It is
6313 // designed to handle arbitrary vector shuffles and blends, gracefully
6314 // degrading performance as necessary. It works hard to recognize idiomatic
6315 // shuffles and lower them to optimal instruction patterns without leaving
6316 // a framework that allows reasonably efficient handling of all vector shuffle
6317 // patterns.
6318 //===----------------------------------------------------------------------===//
6319
6320 /// \brief Tiny helper function to identify a no-op mask.
6321 ///
6322 /// This is a somewhat boring predicate function. It checks whether the mask
6323 /// array input, which is assumed to be a single-input shuffle mask of the kind
6324 /// used by the X86 shuffle instructions (not a fully general
6325 /// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
6326 /// in-place shuffle are 'no-op's.
6327 static bool isNoopShuffleMask(ArrayRef<int> Mask) {
6328   for (int i = 0, Size = Mask.size(); i < Size; ++i)
6329     if (Mask[i] != -1 && Mask[i] != i)
6330       return false;
6331   return true;
6332 }
6333
6334 /// \brief Helper function to classify a mask as a single-input mask.
6335 ///
6336 /// This isn't a generic single-input test because in the vector shuffle
6337 /// lowering we canonicalize single inputs to be the first input operand. This
6338 /// means we can more quickly test for a single input by only checking whether
6339 /// an input from the second operand exists. We also assume that the size of
6340 /// mask corresponds to the size of the input vectors which isn't true in the
6341 /// fully general case.
6342 static bool isSingleInputShuffleMask(ArrayRef<int> Mask) {
6343   for (int M : Mask)
6344     if (M >= (int)Mask.size())
6345       return false;
6346   return true;
6347 }
6348
6349 /// \brief Test whether there are elements crossing 128-bit lanes in this
6350 /// shuffle mask.
6351 ///
6352 /// X86 divides up its shuffles into in-lane and cross-lane shuffle operations
6353 /// and we routinely test for these.
6354 static bool is128BitLaneCrossingShuffleMask(MVT VT, ArrayRef<int> Mask) {
6355   int LaneSize = 128 / VT.getScalarSizeInBits();
6356   int Size = Mask.size();
6357   for (int i = 0; i < Size; ++i)
6358     if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
6359       return true;
6360   return false;
6361 }
6362
6363 /// \brief Test whether a shuffle mask is equivalent within each 128-bit lane.
6364 ///
6365 /// This checks a shuffle mask to see if it is performing the same
6366 /// 128-bit lane-relative shuffle in each 128-bit lane. This trivially implies
6367 /// that it is also not lane-crossing. It may however involve a blend from the
6368 /// same lane of a second vector.
6369 ///
6370 /// The specific repeated shuffle mask is populated in \p RepeatedMask, as it is
6371 /// non-trivial to compute in the face of undef lanes. The representation is
6372 /// *not* suitable for use with existing 128-bit shuffles as it will contain
6373 /// entries from both V1 and V2 inputs to the wider mask.
6374 static bool
6375 is128BitLaneRepeatedShuffleMask(MVT VT, ArrayRef<int> Mask,
6376                                 SmallVectorImpl<int> &RepeatedMask) {
6377   int LaneSize = 128 / VT.getScalarSizeInBits();
6378   RepeatedMask.resize(LaneSize, -1);
6379   int Size = Mask.size();
6380   for (int i = 0; i < Size; ++i) {
6381     if (Mask[i] < 0)
6382       continue;
6383     if ((Mask[i] % Size) / LaneSize != i / LaneSize)
6384       // This entry crosses lanes, so there is no way to model this shuffle.
6385       return false;
6386
6387     // Ok, handle the in-lane shuffles by detecting if and when they repeat.
6388     if (RepeatedMask[i % LaneSize] == -1)
6389       // This is the first non-undef entry in this slot of a 128-bit lane.
6390       RepeatedMask[i % LaneSize] =
6391           Mask[i] < Size ? Mask[i] % LaneSize : Mask[i] % LaneSize + Size;
6392     else if (RepeatedMask[i % LaneSize] + (i / LaneSize) * LaneSize != Mask[i])
6393       // Found a mismatch with the repeated mask.
6394       return false;
6395   }
6396   return true;
6397 }
6398
6399 /// \brief Checks whether a shuffle mask is equivalent to an explicit list of
6400 /// arguments.
6401 ///
6402 /// This is a fast way to test a shuffle mask against a fixed pattern:
6403 ///
6404 ///   if (isShuffleEquivalent(Mask, 3, 2, {1, 0})) { ... }
6405 ///
6406 /// It returns true if the mask is exactly as wide as the argument list, and
6407 /// each element of the mask is either -1 (signifying undef) or the value given
6408 /// in the argument.
6409 static bool isShuffleEquivalent(SDValue V1, SDValue V2, ArrayRef<int> Mask,
6410                                 ArrayRef<int> ExpectedMask) {
6411   if (Mask.size() != ExpectedMask.size())
6412     return false;
6413
6414   int Size = Mask.size();
6415
6416   // If the values are build vectors, we can look through them to find
6417   // equivalent inputs that make the shuffles equivalent.
6418   auto *BV1 = dyn_cast<BuildVectorSDNode>(V1);
6419   auto *BV2 = dyn_cast<BuildVectorSDNode>(V2);
6420
6421   for (int i = 0; i < Size; ++i)
6422     if (Mask[i] != -1 && Mask[i] != ExpectedMask[i]) {
6423       auto *MaskBV = Mask[i] < Size ? BV1 : BV2;
6424       auto *ExpectedBV = ExpectedMask[i] < Size ? BV1 : BV2;
6425       if (!MaskBV || !ExpectedBV ||
6426           MaskBV->getOperand(Mask[i] % Size) !=
6427               ExpectedBV->getOperand(ExpectedMask[i] % Size))
6428         return false;
6429     }
6430
6431   return true;
6432 }
6433
6434 /// \brief Get a 4-lane 8-bit shuffle immediate for a mask.
6435 ///
6436 /// This helper function produces an 8-bit shuffle immediate corresponding to
6437 /// the ubiquitous shuffle encoding scheme used in x86 instructions for
6438 /// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
6439 /// example.
6440 ///
6441 /// NB: We rely heavily on "undef" masks preserving the input lane.
6442 static SDValue getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask, SDLoc DL,
6443                                           SelectionDAG &DAG) {
6444   assert(Mask.size() == 4 && "Only 4-lane shuffle masks");
6445   assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!");
6446   assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!");
6447   assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!");
6448   assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!");
6449
6450   unsigned Imm = 0;
6451   Imm |= (Mask[0] == -1 ? 0 : Mask[0]) << 0;
6452   Imm |= (Mask[1] == -1 ? 1 : Mask[1]) << 2;
6453   Imm |= (Mask[2] == -1 ? 2 : Mask[2]) << 4;
6454   Imm |= (Mask[3] == -1 ? 3 : Mask[3]) << 6;
6455   return DAG.getConstant(Imm, DL, MVT::i8);
6456 }
6457
6458 /// \brief Compute whether each element of a shuffle is zeroable.
6459 ///
6460 /// A "zeroable" vector shuffle element is one which can be lowered to zero.
6461 /// Either it is an undef element in the shuffle mask, the element of the input
6462 /// referenced is undef, or the element of the input referenced is known to be
6463 /// zero. Many x86 shuffles can zero lanes cheaply and we often want to handle
6464 /// as many lanes with this technique as possible to simplify the remaining
6465 /// shuffle.
6466 static SmallBitVector computeZeroableShuffleElements(ArrayRef<int> Mask,
6467                                                      SDValue V1, SDValue V2) {
6468   SmallBitVector Zeroable(Mask.size(), false);
6469
6470   while (V1.getOpcode() == ISD::BITCAST)
6471     V1 = V1->getOperand(0);
6472   while (V2.getOpcode() == ISD::BITCAST)
6473     V2 = V2->getOperand(0);
6474
6475   bool V1IsZero = ISD::isBuildVectorAllZeros(V1.getNode());
6476   bool V2IsZero = ISD::isBuildVectorAllZeros(V2.getNode());
6477
6478   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6479     int M = Mask[i];
6480     // Handle the easy cases.
6481     if (M < 0 || (M >= 0 && M < Size && V1IsZero) || (M >= Size && V2IsZero)) {
6482       Zeroable[i] = true;
6483       continue;
6484     }
6485
6486     // If this is an index into a build_vector node (which has the same number
6487     // of elements), dig out the input value and use it.
6488     SDValue V = M < Size ? V1 : V2;
6489     if (V.getOpcode() != ISD::BUILD_VECTOR || Size != (int)V.getNumOperands())
6490       continue;
6491
6492     SDValue Input = V.getOperand(M % Size);
6493     // The UNDEF opcode check really should be dead code here, but not quite
6494     // worth asserting on (it isn't invalid, just unexpected).
6495     if (Input.getOpcode() == ISD::UNDEF || X86::isZeroNode(Input))
6496       Zeroable[i] = true;
6497   }
6498
6499   return Zeroable;
6500 }
6501
6502 /// \brief Try to emit a bitmask instruction for a shuffle.
6503 ///
6504 /// This handles cases where we can model a blend exactly as a bitmask due to
6505 /// one of the inputs being zeroable.
6506 static SDValue lowerVectorShuffleAsBitMask(SDLoc DL, MVT VT, SDValue V1,
6507                                            SDValue V2, ArrayRef<int> Mask,
6508                                            SelectionDAG &DAG) {
6509   MVT EltVT = VT.getScalarType();
6510   int NumEltBits = EltVT.getSizeInBits();
6511   MVT IntEltVT = MVT::getIntegerVT(NumEltBits);
6512   SDValue Zero = DAG.getConstant(0, DL, IntEltVT);
6513   SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
6514                                     IntEltVT);
6515   if (EltVT.isFloatingPoint()) {
6516     Zero = DAG.getBitcast(EltVT, Zero);
6517     AllOnes = DAG.getBitcast(EltVT, AllOnes);
6518   }
6519   SmallVector<SDValue, 16> VMaskOps(Mask.size(), Zero);
6520   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6521   SDValue V;
6522   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6523     if (Zeroable[i])
6524       continue;
6525     if (Mask[i] % Size != i)
6526       return SDValue(); // Not a blend.
6527     if (!V)
6528       V = Mask[i] < Size ? V1 : V2;
6529     else if (V != (Mask[i] < Size ? V1 : V2))
6530       return SDValue(); // Can only let one input through the mask.
6531
6532     VMaskOps[i] = AllOnes;
6533   }
6534   if (!V)
6535     return SDValue(); // No non-zeroable elements!
6536
6537   SDValue VMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, VMaskOps);
6538   V = DAG.getNode(VT.isFloatingPoint()
6539                   ? (unsigned) X86ISD::FAND : (unsigned) ISD::AND,
6540                   DL, VT, V, VMask);
6541   return V;
6542 }
6543
6544 /// \brief Try to emit a blend instruction for a shuffle using bit math.
6545 ///
6546 /// This is used as a fallback approach when first class blend instructions are
6547 /// unavailable. Currently it is only suitable for integer vectors, but could
6548 /// be generalized for floating point vectors if desirable.
6549 static SDValue lowerVectorShuffleAsBitBlend(SDLoc DL, MVT VT, SDValue V1,
6550                                             SDValue V2, ArrayRef<int> Mask,
6551                                             SelectionDAG &DAG) {
6552   assert(VT.isInteger() && "Only supports integer vector types!");
6553   MVT EltVT = VT.getScalarType();
6554   int NumEltBits = EltVT.getSizeInBits();
6555   SDValue Zero = DAG.getConstant(0, DL, EltVT);
6556   SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
6557                                     EltVT);
6558   SmallVector<SDValue, 16> MaskOps;
6559   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6560     if (Mask[i] != -1 && Mask[i] != i && Mask[i] != i + Size)
6561       return SDValue(); // Shuffled input!
6562     MaskOps.push_back(Mask[i] < Size ? AllOnes : Zero);
6563   }
6564
6565   SDValue V1Mask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, MaskOps);
6566   V1 = DAG.getNode(ISD::AND, DL, VT, V1, V1Mask);
6567   // We have to cast V2 around.
6568   MVT MaskVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
6569   V2 = DAG.getBitcast(VT, DAG.getNode(X86ISD::ANDNP, DL, MaskVT,
6570                                       DAG.getBitcast(MaskVT, V1Mask),
6571                                       DAG.getBitcast(MaskVT, V2)));
6572   return DAG.getNode(ISD::OR, DL, VT, V1, V2);
6573 }
6574
6575 /// \brief Try to emit a blend instruction for a shuffle.
6576 ///
6577 /// This doesn't do any checks for the availability of instructions for blending
6578 /// these values. It relies on the availability of the X86ISD::BLENDI pattern to
6579 /// be matched in the backend with the type given. What it does check for is
6580 /// that the shuffle mask is in fact a blend.
6581 static SDValue lowerVectorShuffleAsBlend(SDLoc DL, MVT VT, SDValue V1,
6582                                          SDValue V2, ArrayRef<int> Mask,
6583                                          const X86Subtarget *Subtarget,
6584                                          SelectionDAG &DAG) {
6585   unsigned BlendMask = 0;
6586   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6587     if (Mask[i] >= Size) {
6588       if (Mask[i] != i + Size)
6589         return SDValue(); // Shuffled V2 input!
6590       BlendMask |= 1u << i;
6591       continue;
6592     }
6593     if (Mask[i] >= 0 && Mask[i] != i)
6594       return SDValue(); // Shuffled V1 input!
6595   }
6596   switch (VT.SimpleTy) {
6597   case MVT::v2f64:
6598   case MVT::v4f32:
6599   case MVT::v4f64:
6600   case MVT::v8f32:
6601     return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V2,
6602                        DAG.getConstant(BlendMask, DL, MVT::i8));
6603
6604   case MVT::v4i64:
6605   case MVT::v8i32:
6606     assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6607     // FALLTHROUGH
6608   case MVT::v2i64:
6609   case MVT::v4i32:
6610     // If we have AVX2 it is faster to use VPBLENDD when the shuffle fits into
6611     // that instruction.
6612     if (Subtarget->hasAVX2()) {
6613       // Scale the blend by the number of 32-bit dwords per element.
6614       int Scale =  VT.getScalarSizeInBits() / 32;
6615       BlendMask = 0;
6616       for (int i = 0, Size = Mask.size(); i < Size; ++i)
6617         if (Mask[i] >= Size)
6618           for (int j = 0; j < Scale; ++j)
6619             BlendMask |= 1u << (i * Scale + j);
6620
6621       MVT BlendVT = VT.getSizeInBits() > 128 ? MVT::v8i32 : MVT::v4i32;
6622       V1 = DAG.getBitcast(BlendVT, V1);
6623       V2 = DAG.getBitcast(BlendVT, V2);
6624       return DAG.getBitcast(
6625           VT, DAG.getNode(X86ISD::BLENDI, DL, BlendVT, V1, V2,
6626                           DAG.getConstant(BlendMask, DL, MVT::i8)));
6627     }
6628     // FALLTHROUGH
6629   case MVT::v8i16: {
6630     // For integer shuffles we need to expand the mask and cast the inputs to
6631     // v8i16s prior to blending.
6632     int Scale = 8 / VT.getVectorNumElements();
6633     BlendMask = 0;
6634     for (int i = 0, Size = Mask.size(); i < Size; ++i)
6635       if (Mask[i] >= Size)
6636         for (int j = 0; j < Scale; ++j)
6637           BlendMask |= 1u << (i * Scale + j);
6638
6639     V1 = DAG.getBitcast(MVT::v8i16, V1);
6640     V2 = DAG.getBitcast(MVT::v8i16, V2);
6641     return DAG.getBitcast(VT,
6642                           DAG.getNode(X86ISD::BLENDI, DL, MVT::v8i16, V1, V2,
6643                                       DAG.getConstant(BlendMask, DL, MVT::i8)));
6644   }
6645
6646   case MVT::v16i16: {
6647     assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6648     SmallVector<int, 8> RepeatedMask;
6649     if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
6650       // We can lower these with PBLENDW which is mirrored across 128-bit lanes.
6651       assert(RepeatedMask.size() == 8 && "Repeated mask size doesn't match!");
6652       BlendMask = 0;
6653       for (int i = 0; i < 8; ++i)
6654         if (RepeatedMask[i] >= 16)
6655           BlendMask |= 1u << i;
6656       return DAG.getNode(X86ISD::BLENDI, DL, MVT::v16i16, V1, V2,
6657                          DAG.getConstant(BlendMask, DL, MVT::i8));
6658     }
6659   }
6660     // FALLTHROUGH
6661   case MVT::v16i8:
6662   case MVT::v32i8: {
6663     assert((VT.getSizeInBits() == 128 || Subtarget->hasAVX2()) &&
6664            "256-bit byte-blends require AVX2 support!");
6665
6666     // Attempt to lower to a bitmask if we can. VPAND is faster than VPBLENDVB.
6667     if (SDValue Masked = lowerVectorShuffleAsBitMask(DL, VT, V1, V2, Mask, DAG))
6668       return Masked;
6669
6670     // Scale the blend by the number of bytes per element.
6671     int Scale = VT.getScalarSizeInBits() / 8;
6672
6673     // This form of blend is always done on bytes. Compute the byte vector
6674     // type.
6675     MVT BlendVT = MVT::getVectorVT(MVT::i8, VT.getSizeInBits() / 8);
6676
6677     // Compute the VSELECT mask. Note that VSELECT is really confusing in the
6678     // mix of LLVM's code generator and the x86 backend. We tell the code
6679     // generator that boolean values in the elements of an x86 vector register
6680     // are -1 for true and 0 for false. We then use the LLVM semantics of 'true'
6681     // mapping a select to operand #1, and 'false' mapping to operand #2. The
6682     // reality in x86 is that vector masks (pre-AVX-512) use only the high bit
6683     // of the element (the remaining are ignored) and 0 in that high bit would
6684     // mean operand #1 while 1 in the high bit would mean operand #2. So while
6685     // the LLVM model for boolean values in vector elements gets the relevant
6686     // bit set, it is set backwards and over constrained relative to x86's
6687     // actual model.
6688     SmallVector<SDValue, 32> VSELECTMask;
6689     for (int i = 0, Size = Mask.size(); i < Size; ++i)
6690       for (int j = 0; j < Scale; ++j)
6691         VSELECTMask.push_back(
6692             Mask[i] < 0 ? DAG.getUNDEF(MVT::i8)
6693                         : DAG.getConstant(Mask[i] < Size ? -1 : 0, DL,
6694                                           MVT::i8));
6695
6696     V1 = DAG.getBitcast(BlendVT, V1);
6697     V2 = DAG.getBitcast(BlendVT, V2);
6698     return DAG.getBitcast(VT, DAG.getNode(ISD::VSELECT, DL, BlendVT,
6699                                           DAG.getNode(ISD::BUILD_VECTOR, DL,
6700                                                       BlendVT, VSELECTMask),
6701                                           V1, V2));
6702   }
6703
6704   default:
6705     llvm_unreachable("Not a supported integer vector type!");
6706   }
6707 }
6708
6709 /// \brief Try to lower as a blend of elements from two inputs followed by
6710 /// a single-input permutation.
6711 ///
6712 /// This matches the pattern where we can blend elements from two inputs and
6713 /// then reduce the shuffle to a single-input permutation.
6714 static SDValue lowerVectorShuffleAsBlendAndPermute(SDLoc DL, MVT VT, SDValue V1,
6715                                                    SDValue V2,
6716                                                    ArrayRef<int> Mask,
6717                                                    SelectionDAG &DAG) {
6718   // We build up the blend mask while checking whether a blend is a viable way
6719   // to reduce the shuffle.
6720   SmallVector<int, 32> BlendMask(Mask.size(), -1);
6721   SmallVector<int, 32> PermuteMask(Mask.size(), -1);
6722
6723   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6724     if (Mask[i] < 0)
6725       continue;
6726
6727     assert(Mask[i] < Size * 2 && "Shuffle input is out of bounds.");
6728
6729     if (BlendMask[Mask[i] % Size] == -1)
6730       BlendMask[Mask[i] % Size] = Mask[i];
6731     else if (BlendMask[Mask[i] % Size] != Mask[i])
6732       return SDValue(); // Can't blend in the needed input!
6733
6734     PermuteMask[i] = Mask[i] % Size;
6735   }
6736
6737   SDValue V = DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
6738   return DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), PermuteMask);
6739 }
6740
6741 /// \brief Generic routine to decompose a shuffle and blend into indepndent
6742 /// blends and permutes.
6743 ///
6744 /// This matches the extremely common pattern for handling combined
6745 /// shuffle+blend operations on newer X86 ISAs where we have very fast blend
6746 /// operations. It will try to pick the best arrangement of shuffles and
6747 /// blends.
6748 static SDValue lowerVectorShuffleAsDecomposedShuffleBlend(SDLoc DL, MVT VT,
6749                                                           SDValue V1,
6750                                                           SDValue V2,
6751                                                           ArrayRef<int> Mask,
6752                                                           SelectionDAG &DAG) {
6753   // Shuffle the input elements into the desired positions in V1 and V2 and
6754   // blend them together.
6755   SmallVector<int, 32> V1Mask(Mask.size(), -1);
6756   SmallVector<int, 32> V2Mask(Mask.size(), -1);
6757   SmallVector<int, 32> BlendMask(Mask.size(), -1);
6758   for (int i = 0, Size = Mask.size(); i < Size; ++i)
6759     if (Mask[i] >= 0 && Mask[i] < Size) {
6760       V1Mask[i] = Mask[i];
6761       BlendMask[i] = i;
6762     } else if (Mask[i] >= Size) {
6763       V2Mask[i] = Mask[i] - Size;
6764       BlendMask[i] = i + Size;
6765     }
6766
6767   // Try to lower with the simpler initial blend strategy unless one of the
6768   // input shuffles would be a no-op. We prefer to shuffle inputs as the
6769   // shuffle may be able to fold with a load or other benefit. However, when
6770   // we'll have to do 2x as many shuffles in order to achieve this, blending
6771   // first is a better strategy.
6772   if (!isNoopShuffleMask(V1Mask) && !isNoopShuffleMask(V2Mask))
6773     if (SDValue BlendPerm =
6774             lowerVectorShuffleAsBlendAndPermute(DL, VT, V1, V2, Mask, DAG))
6775       return BlendPerm;
6776
6777   V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
6778   V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
6779   return DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
6780 }
6781
6782 /// \brief Try to lower a vector shuffle as a byte rotation.
6783 ///
6784 /// SSSE3 has a generic PALIGNR instruction in x86 that will do an arbitrary
6785 /// byte-rotation of the concatenation of two vectors; pre-SSSE3 can use
6786 /// a PSRLDQ/PSLLDQ/POR pattern to get a similar effect. This routine will
6787 /// try to generically lower a vector shuffle through such an pattern. It
6788 /// does not check for the profitability of lowering either as PALIGNR or
6789 /// PSRLDQ/PSLLDQ/POR, only whether the mask is valid to lower in that form.
6790 /// This matches shuffle vectors that look like:
6791 ///
6792 ///   v8i16 [11, 12, 13, 14, 15, 0, 1, 2]
6793 ///
6794 /// Essentially it concatenates V1 and V2, shifts right by some number of
6795 /// elements, and takes the low elements as the result. Note that while this is
6796 /// specified as a *right shift* because x86 is little-endian, it is a *left
6797 /// rotate* of the vector lanes.
6798 static SDValue lowerVectorShuffleAsByteRotate(SDLoc DL, MVT VT, SDValue V1,
6799                                               SDValue V2,
6800                                               ArrayRef<int> Mask,
6801                                               const X86Subtarget *Subtarget,
6802                                               SelectionDAG &DAG) {
6803   assert(!isNoopShuffleMask(Mask) && "We shouldn't lower no-op shuffles!");
6804
6805   int NumElts = Mask.size();
6806   int NumLanes = VT.getSizeInBits() / 128;
6807   int NumLaneElts = NumElts / NumLanes;
6808
6809   // We need to detect various ways of spelling a rotation:
6810   //   [11, 12, 13, 14, 15,  0,  1,  2]
6811   //   [-1, 12, 13, 14, -1, -1,  1, -1]
6812   //   [-1, -1, -1, -1, -1, -1,  1,  2]
6813   //   [ 3,  4,  5,  6,  7,  8,  9, 10]
6814   //   [-1,  4,  5,  6, -1, -1,  9, -1]
6815   //   [-1,  4,  5,  6, -1, -1, -1, -1]
6816   int Rotation = 0;
6817   SDValue Lo, Hi;
6818   for (int l = 0; l < NumElts; l += NumLaneElts) {
6819     for (int i = 0; i < NumLaneElts; ++i) {
6820       if (Mask[l + i] == -1)
6821         continue;
6822       assert(Mask[l + i] >= 0 && "Only -1 is a valid negative mask element!");
6823
6824       // Get the mod-Size index and lane correct it.
6825       int LaneIdx = (Mask[l + i] % NumElts) - l;
6826       // Make sure it was in this lane.
6827       if (LaneIdx < 0 || LaneIdx >= NumLaneElts)
6828         return SDValue();
6829
6830       // Determine where a rotated vector would have started.
6831       int StartIdx = i - LaneIdx;
6832       if (StartIdx == 0)
6833         // The identity rotation isn't interesting, stop.
6834         return SDValue();
6835
6836       // If we found the tail of a vector the rotation must be the missing
6837       // front. If we found the head of a vector, it must be how much of the
6838       // head.
6839       int CandidateRotation = StartIdx < 0 ? -StartIdx : NumLaneElts - StartIdx;
6840
6841       if (Rotation == 0)
6842         Rotation = CandidateRotation;
6843       else if (Rotation != CandidateRotation)
6844         // The rotations don't match, so we can't match this mask.
6845         return SDValue();
6846
6847       // Compute which value this mask is pointing at.
6848       SDValue MaskV = Mask[l + i] < NumElts ? V1 : V2;
6849
6850       // Compute which of the two target values this index should be assigned
6851       // to. This reflects whether the high elements are remaining or the low
6852       // elements are remaining.
6853       SDValue &TargetV = StartIdx < 0 ? Hi : Lo;
6854
6855       // Either set up this value if we've not encountered it before, or check
6856       // that it remains consistent.
6857       if (!TargetV)
6858         TargetV = MaskV;
6859       else if (TargetV != MaskV)
6860         // This may be a rotation, but it pulls from the inputs in some
6861         // unsupported interleaving.
6862         return SDValue();
6863     }
6864   }
6865
6866   // Check that we successfully analyzed the mask, and normalize the results.
6867   assert(Rotation != 0 && "Failed to locate a viable rotation!");
6868   assert((Lo || Hi) && "Failed to find a rotated input vector!");
6869   if (!Lo)
6870     Lo = Hi;
6871   else if (!Hi)
6872     Hi = Lo;
6873
6874   // The actual rotate instruction rotates bytes, so we need to scale the
6875   // rotation based on how many bytes are in the vector lane.
6876   int Scale = 16 / NumLaneElts;
6877
6878   // SSSE3 targets can use the palignr instruction.
6879   if (Subtarget->hasSSSE3()) {
6880     // Cast the inputs to i8 vector of correct length to match PALIGNR.
6881     MVT AlignVT = MVT::getVectorVT(MVT::i8, 16 * NumLanes);
6882     Lo = DAG.getBitcast(AlignVT, Lo);
6883     Hi = DAG.getBitcast(AlignVT, Hi);
6884
6885     return DAG.getBitcast(
6886         VT, DAG.getNode(X86ISD::PALIGNR, DL, AlignVT, Hi, Lo,
6887                         DAG.getConstant(Rotation * Scale, DL, MVT::i8)));
6888   }
6889
6890   assert(VT.getSizeInBits() == 128 &&
6891          "Rotate-based lowering only supports 128-bit lowering!");
6892   assert(Mask.size() <= 16 &&
6893          "Can shuffle at most 16 bytes in a 128-bit vector!");
6894
6895   // Default SSE2 implementation
6896   int LoByteShift = 16 - Rotation * Scale;
6897   int HiByteShift = Rotation * Scale;
6898
6899   // Cast the inputs to v2i64 to match PSLLDQ/PSRLDQ.
6900   Lo = DAG.getBitcast(MVT::v2i64, Lo);
6901   Hi = DAG.getBitcast(MVT::v2i64, Hi);
6902
6903   SDValue LoShift = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v2i64, Lo,
6904                                 DAG.getConstant(LoByteShift, DL, MVT::i8));
6905   SDValue HiShift = DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v2i64, Hi,
6906                                 DAG.getConstant(HiByteShift, DL, MVT::i8));
6907   return DAG.getBitcast(VT,
6908                         DAG.getNode(ISD::OR, DL, MVT::v2i64, LoShift, HiShift));
6909 }
6910
6911 /// \brief Try to lower a vector shuffle as a bit shift (shifts in zeros).
6912 ///
6913 /// Attempts to match a shuffle mask against the PSLL(W/D/Q/DQ) and
6914 /// PSRL(W/D/Q/DQ) SSE2 and AVX2 logical bit-shift instructions. The function
6915 /// matches elements from one of the input vectors shuffled to the left or
6916 /// right with zeroable elements 'shifted in'. It handles both the strictly
6917 /// bit-wise element shifts and the byte shift across an entire 128-bit double
6918 /// quad word lane.
6919 ///
6920 /// PSHL : (little-endian) left bit shift.
6921 /// [ zz, 0, zz,  2 ]
6922 /// [ -1, 4, zz, -1 ]
6923 /// PSRL : (little-endian) right bit shift.
6924 /// [  1, zz,  3, zz]
6925 /// [ -1, -1,  7, zz]
6926 /// PSLLDQ : (little-endian) left byte shift
6927 /// [ zz,  0,  1,  2,  3,  4,  5,  6]
6928 /// [ zz, zz, -1, -1,  2,  3,  4, -1]
6929 /// [ zz, zz, zz, zz, zz, zz, -1,  1]
6930 /// PSRLDQ : (little-endian) right byte shift
6931 /// [  5, 6,  7, zz, zz, zz, zz, zz]
6932 /// [ -1, 5,  6,  7, zz, zz, zz, zz]
6933 /// [  1, 2, -1, -1, -1, -1, zz, zz]
6934 static SDValue lowerVectorShuffleAsShift(SDLoc DL, MVT VT, SDValue V1,
6935                                          SDValue V2, ArrayRef<int> Mask,
6936                                          SelectionDAG &DAG) {
6937   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6938
6939   int Size = Mask.size();
6940   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
6941
6942   auto CheckZeros = [&](int Shift, int Scale, bool Left) {
6943     for (int i = 0; i < Size; i += Scale)
6944       for (int j = 0; j < Shift; ++j)
6945         if (!Zeroable[i + j + (Left ? 0 : (Scale - Shift))])
6946           return false;
6947
6948     return true;
6949   };
6950
6951   auto MatchShift = [&](int Shift, int Scale, bool Left, SDValue V) {
6952     for (int i = 0; i != Size; i += Scale) {
6953       unsigned Pos = Left ? i + Shift : i;
6954       unsigned Low = Left ? i : i + Shift;
6955       unsigned Len = Scale - Shift;
6956       if (!isSequentialOrUndefInRange(Mask, Pos, Len,
6957                                       Low + (V == V1 ? 0 : Size)))
6958         return SDValue();
6959     }
6960
6961     int ShiftEltBits = VT.getScalarSizeInBits() * Scale;
6962     bool ByteShift = ShiftEltBits > 64;
6963     unsigned OpCode = Left ? (ByteShift ? X86ISD::VSHLDQ : X86ISD::VSHLI)
6964                            : (ByteShift ? X86ISD::VSRLDQ : X86ISD::VSRLI);
6965     int ShiftAmt = Shift * VT.getScalarSizeInBits() / (ByteShift ? 8 : 1);
6966
6967     // Normalize the scale for byte shifts to still produce an i64 element
6968     // type.
6969     Scale = ByteShift ? Scale / 2 : Scale;
6970
6971     // We need to round trip through the appropriate type for the shift.
6972     MVT ShiftSVT = MVT::getIntegerVT(VT.getScalarSizeInBits() * Scale);
6973     MVT ShiftVT = MVT::getVectorVT(ShiftSVT, Size / Scale);
6974     assert(DAG.getTargetLoweringInfo().isTypeLegal(ShiftVT) &&
6975            "Illegal integer vector type");
6976     V = DAG.getBitcast(ShiftVT, V);
6977
6978     V = DAG.getNode(OpCode, DL, ShiftVT, V,
6979                     DAG.getConstant(ShiftAmt, DL, MVT::i8));
6980     return DAG.getBitcast(VT, V);
6981   };
6982
6983   // SSE/AVX supports logical shifts up to 64-bit integers - so we can just
6984   // keep doubling the size of the integer elements up to that. We can
6985   // then shift the elements of the integer vector by whole multiples of
6986   // their width within the elements of the larger integer vector. Test each
6987   // multiple to see if we can find a match with the moved element indices
6988   // and that the shifted in elements are all zeroable.
6989   for (int Scale = 2; Scale * VT.getScalarSizeInBits() <= 128; Scale *= 2)
6990     for (int Shift = 1; Shift != Scale; ++Shift)
6991       for (bool Left : {true, false})
6992         if (CheckZeros(Shift, Scale, Left))
6993           for (SDValue V : {V1, V2})
6994             if (SDValue Match = MatchShift(Shift, Scale, Left, V))
6995               return Match;
6996
6997   // no match
6998   return SDValue();
6999 }
7000
7001 /// \brief Try to lower a vector shuffle using SSE4a EXTRQ/INSERTQ.
7002 static SDValue lowerVectorShuffleWithSSE4A(SDLoc DL, MVT VT, SDValue V1,
7003                                            SDValue V2, ArrayRef<int> Mask,
7004                                            SelectionDAG &DAG) {
7005   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7006   assert(!Zeroable.all() && "Fully zeroable shuffle mask");
7007
7008   int Size = Mask.size();
7009   int HalfSize = Size / 2;
7010   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
7011
7012   // Upper half must be undefined.
7013   if (!isUndefInRange(Mask, HalfSize, HalfSize))
7014     return SDValue();
7015
7016   // EXTRQ: Extract Len elements from lower half of source, starting at Idx.
7017   // Remainder of lower half result is zero and upper half is all undef.
7018   auto LowerAsEXTRQ = [&]() {
7019     // Determine the extraction length from the part of the
7020     // lower half that isn't zeroable.
7021     int Len = HalfSize;
7022     for (; Len >= 0; --Len)
7023       if (!Zeroable[Len - 1])
7024         break;
7025     assert(Len > 0 && "Zeroable shuffle mask");
7026
7027     // Attempt to match first Len sequential elements from the lower half.
7028     SDValue Src;
7029     int Idx = -1;
7030     for (int i = 0; i != Len; ++i) {
7031       int M = Mask[i];
7032       if (M < 0)
7033         continue;
7034       SDValue &V = (M < Size ? V1 : V2);
7035       M = M % Size;
7036
7037       // All mask elements must be in the lower half.
7038       if (M > HalfSize)
7039         return SDValue();
7040
7041       if (Idx < 0 || (Src == V && Idx == (M - i))) {
7042         Src = V;
7043         Idx = M - i;
7044         continue;
7045       }
7046       return SDValue();
7047     }
7048
7049     if (Idx < 0)
7050       return SDValue();
7051
7052     assert((Idx + Len) <= HalfSize && "Illegal extraction mask");
7053     int BitLen = (Len * VT.getScalarSizeInBits()) & 0x3f;
7054     int BitIdx = (Idx * VT.getScalarSizeInBits()) & 0x3f;
7055     return DAG.getNode(X86ISD::EXTRQI, DL, VT, Src,
7056                        DAG.getConstant(BitLen, DL, MVT::i8),
7057                        DAG.getConstant(BitIdx, DL, MVT::i8));
7058   };
7059
7060   if (SDValue ExtrQ = LowerAsEXTRQ())
7061     return ExtrQ;
7062
7063   // INSERTQ: Extract lowest Len elements from lower half of second source and
7064   // insert over first source, starting at Idx.
7065   // { A[0], .., A[Idx-1], B[0], .., B[Len-1], A[Idx+Len], .., UNDEF, ... }
7066   auto LowerAsInsertQ = [&]() {
7067     for (int Idx = 0; Idx != HalfSize; ++Idx) {
7068       SDValue Base;
7069
7070       // Attempt to match first source from mask before insertion point.
7071       if (isUndefInRange(Mask, 0, Idx)) {
7072         /* EMPTY */
7073       } else if (isSequentialOrUndefInRange(Mask, 0, Idx, 0)) {
7074         Base = V1;
7075       } else if (isSequentialOrUndefInRange(Mask, 0, Idx, Size)) {
7076         Base = V2;
7077       } else {
7078         continue;
7079       }
7080
7081       // Extend the extraction length looking to match both the insertion of
7082       // the second source and the remaining elements of the first.
7083       for (int Hi = Idx + 1; Hi <= HalfSize; ++Hi) {
7084         SDValue Insert;
7085         int Len = Hi - Idx;
7086
7087         // Match insertion.
7088         if (isSequentialOrUndefInRange(Mask, Idx, Len, 0)) {
7089           Insert = V1;
7090         } else if (isSequentialOrUndefInRange(Mask, Idx, Len, Size)) {
7091           Insert = V2;
7092         } else {
7093           continue;
7094         }
7095
7096         // Match the remaining elements of the lower half.
7097         if (isUndefInRange(Mask, Hi, HalfSize - Hi)) {
7098           /* EMPTY */
7099         } else if ((!Base || (Base == V1)) &&
7100                    isSequentialOrUndefInRange(Mask, Hi, HalfSize - Hi, Hi)) {
7101           Base = V1;
7102         } else if ((!Base || (Base == V2)) &&
7103                    isSequentialOrUndefInRange(Mask, Hi, HalfSize - Hi,
7104                                               Size + Hi)) {
7105           Base = V2;
7106         } else {
7107           continue;
7108         }
7109
7110         // We may not have a base (first source) - this can safely be undefined.
7111         if (!Base)
7112           Base = DAG.getUNDEF(VT);
7113
7114         int BitLen = (Len * VT.getScalarSizeInBits()) & 0x3f;
7115         int BitIdx = (Idx * VT.getScalarSizeInBits()) & 0x3f;
7116         return DAG.getNode(X86ISD::INSERTQI, DL, VT, Base, Insert,
7117                            DAG.getConstant(BitLen, DL, MVT::i8),
7118                            DAG.getConstant(BitIdx, DL, MVT::i8));
7119       }
7120     }
7121
7122     return SDValue();
7123   };
7124
7125   if (SDValue InsertQ = LowerAsInsertQ())
7126     return InsertQ;
7127
7128   return SDValue();
7129 }
7130
7131 /// \brief Lower a vector shuffle as a zero or any extension.
7132 ///
7133 /// Given a specific number of elements, element bit width, and extension
7134 /// stride, produce either a zero or any extension based on the available
7135 /// features of the subtarget.
7136 static SDValue lowerVectorShuffleAsSpecificZeroOrAnyExtend(
7137     SDLoc DL, MVT VT, int Scale, bool AnyExt, SDValue InputV,
7138     ArrayRef<int> Mask, const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7139   assert(Scale > 1 && "Need a scale to extend.");
7140   int NumElements = VT.getVectorNumElements();
7141   int EltBits = VT.getScalarSizeInBits();
7142   assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
7143          "Only 8, 16, and 32 bit elements can be extended.");
7144   assert(Scale * EltBits <= 64 && "Cannot zero extend past 64 bits.");
7145
7146   // Found a valid zext mask! Try various lowering strategies based on the
7147   // input type and available ISA extensions.
7148   if (Subtarget->hasSSE41()) {
7149     MVT ExtVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits * Scale),
7150                                  NumElements / Scale);
7151     return DAG.getBitcast(VT, DAG.getNode(X86ISD::VZEXT, DL, ExtVT, InputV));
7152   }
7153
7154   // For any extends we can cheat for larger element sizes and use shuffle
7155   // instructions that can fold with a load and/or copy.
7156   if (AnyExt && EltBits == 32) {
7157     int PSHUFDMask[4] = {0, -1, 1, -1};
7158     return DAG.getBitcast(
7159         VT, DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7160                         DAG.getBitcast(MVT::v4i32, InputV),
7161                         getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
7162   }
7163   if (AnyExt && EltBits == 16 && Scale > 2) {
7164     int PSHUFDMask[4] = {0, -1, 0, -1};
7165     InputV = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7166                          DAG.getBitcast(MVT::v4i32, InputV),
7167                          getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG));
7168     int PSHUFHWMask[4] = {1, -1, -1, -1};
7169     return DAG.getBitcast(
7170         VT, DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16,
7171                         DAG.getBitcast(MVT::v8i16, InputV),
7172                         getV4X86ShuffleImm8ForMask(PSHUFHWMask, DL, DAG)));
7173   }
7174
7175   // The SSE4A EXTRQ instruction can efficiently extend the first 2 lanes
7176   // to 64-bits.
7177   if ((Scale * EltBits) == 64 && EltBits < 32 && Subtarget->hasSSE4A()) {
7178     assert(NumElements == (int)Mask.size() && "Unexpected shuffle mask size!");
7179     assert(VT.getSizeInBits() == 128 && "Unexpected vector width!");
7180
7181     SDValue Lo = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7182                              DAG.getNode(X86ISD::EXTRQI, DL, VT, InputV,
7183                                          DAG.getConstant(EltBits, DL, MVT::i8),
7184                                          DAG.getConstant(0, DL, MVT::i8)));
7185     if (isUndefInRange(Mask, NumElements/2, NumElements/2))
7186       return DAG.getNode(ISD::BITCAST, DL, VT, Lo);
7187
7188     SDValue Hi =
7189         DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7190                     DAG.getNode(X86ISD::EXTRQI, DL, VT, InputV,
7191                                 DAG.getConstant(EltBits, DL, MVT::i8),
7192                                 DAG.getConstant(EltBits, DL, MVT::i8)));
7193     return DAG.getNode(ISD::BITCAST, DL, VT,
7194                        DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, Lo, Hi));
7195   }
7196
7197   // If this would require more than 2 unpack instructions to expand, use
7198   // pshufb when available. We can only use more than 2 unpack instructions
7199   // when zero extending i8 elements which also makes it easier to use pshufb.
7200   if (Scale > 4 && EltBits == 8 && Subtarget->hasSSSE3()) {
7201     assert(NumElements == 16 && "Unexpected byte vector width!");
7202     SDValue PSHUFBMask[16];
7203     for (int i = 0; i < 16; ++i)
7204       PSHUFBMask[i] =
7205           DAG.getConstant((i % Scale == 0) ? i / Scale : 0x80, DL, MVT::i8);
7206     InputV = DAG.getBitcast(MVT::v16i8, InputV);
7207     return DAG.getBitcast(VT,
7208                           DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, InputV,
7209                                       DAG.getNode(ISD::BUILD_VECTOR, DL,
7210                                                   MVT::v16i8, PSHUFBMask)));
7211   }
7212
7213   // Otherwise emit a sequence of unpacks.
7214   do {
7215     MVT InputVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits), NumElements);
7216     SDValue Ext = AnyExt ? DAG.getUNDEF(InputVT)
7217                          : getZeroVector(InputVT, Subtarget, DAG, DL);
7218     InputV = DAG.getBitcast(InputVT, InputV);
7219     InputV = DAG.getNode(X86ISD::UNPCKL, DL, InputVT, InputV, Ext);
7220     Scale /= 2;
7221     EltBits *= 2;
7222     NumElements /= 2;
7223   } while (Scale > 1);
7224   return DAG.getBitcast(VT, InputV);
7225 }
7226
7227 /// \brief Try to lower a vector shuffle as a zero extension on any microarch.
7228 ///
7229 /// This routine will try to do everything in its power to cleverly lower
7230 /// a shuffle which happens to match the pattern of a zero extend. It doesn't
7231 /// check for the profitability of this lowering,  it tries to aggressively
7232 /// match this pattern. It will use all of the micro-architectural details it
7233 /// can to emit an efficient lowering. It handles both blends with all-zero
7234 /// inputs to explicitly zero-extend and undef-lanes (sometimes undef due to
7235 /// masking out later).
7236 ///
7237 /// The reason we have dedicated lowering for zext-style shuffles is that they
7238 /// are both incredibly common and often quite performance sensitive.
7239 static SDValue lowerVectorShuffleAsZeroOrAnyExtend(
7240     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7241     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7242   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7243
7244   int Bits = VT.getSizeInBits();
7245   int NumElements = VT.getVectorNumElements();
7246   assert(VT.getScalarSizeInBits() <= 32 &&
7247          "Exceeds 32-bit integer zero extension limit");
7248   assert((int)Mask.size() == NumElements && "Unexpected shuffle mask size");
7249
7250   // Define a helper function to check a particular ext-scale and lower to it if
7251   // valid.
7252   auto Lower = [&](int Scale) -> SDValue {
7253     SDValue InputV;
7254     bool AnyExt = true;
7255     for (int i = 0; i < NumElements; ++i) {
7256       if (Mask[i] == -1)
7257         continue; // Valid anywhere but doesn't tell us anything.
7258       if (i % Scale != 0) {
7259         // Each of the extended elements need to be zeroable.
7260         if (!Zeroable[i])
7261           return SDValue();
7262
7263         // We no longer are in the anyext case.
7264         AnyExt = false;
7265         continue;
7266       }
7267
7268       // Each of the base elements needs to be consecutive indices into the
7269       // same input vector.
7270       SDValue V = Mask[i] < NumElements ? V1 : V2;
7271       if (!InputV)
7272         InputV = V;
7273       else if (InputV != V)
7274         return SDValue(); // Flip-flopping inputs.
7275
7276       if (Mask[i] % NumElements != i / Scale)
7277         return SDValue(); // Non-consecutive strided elements.
7278     }
7279
7280     // If we fail to find an input, we have a zero-shuffle which should always
7281     // have already been handled.
7282     // FIXME: Maybe handle this here in case during blending we end up with one?
7283     if (!InputV)
7284       return SDValue();
7285
7286     return lowerVectorShuffleAsSpecificZeroOrAnyExtend(
7287         DL, VT, Scale, AnyExt, InputV, Mask, Subtarget, DAG);
7288   };
7289
7290   // The widest scale possible for extending is to a 64-bit integer.
7291   assert(Bits % 64 == 0 &&
7292          "The number of bits in a vector must be divisible by 64 on x86!");
7293   int NumExtElements = Bits / 64;
7294
7295   // Each iteration, try extending the elements half as much, but into twice as
7296   // many elements.
7297   for (; NumExtElements < NumElements; NumExtElements *= 2) {
7298     assert(NumElements % NumExtElements == 0 &&
7299            "The input vector size must be divisible by the extended size.");
7300     if (SDValue V = Lower(NumElements / NumExtElements))
7301       return V;
7302   }
7303
7304   // General extends failed, but 128-bit vectors may be able to use MOVQ.
7305   if (Bits != 128)
7306     return SDValue();
7307
7308   // Returns one of the source operands if the shuffle can be reduced to a
7309   // MOVQ, copying the lower 64-bits and zero-extending to the upper 64-bits.
7310   auto CanZExtLowHalf = [&]() {
7311     for (int i = NumElements / 2; i != NumElements; ++i)
7312       if (!Zeroable[i])
7313         return SDValue();
7314     if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, 0))
7315       return V1;
7316     if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, NumElements))
7317       return V2;
7318     return SDValue();
7319   };
7320
7321   if (SDValue V = CanZExtLowHalf()) {
7322     V = DAG.getBitcast(MVT::v2i64, V);
7323     V = DAG.getNode(X86ISD::VZEXT_MOVL, DL, MVT::v2i64, V);
7324     return DAG.getBitcast(VT, V);
7325   }
7326
7327   // No viable ext lowering found.
7328   return SDValue();
7329 }
7330
7331 /// \brief Try to get a scalar value for a specific element of a vector.
7332 ///
7333 /// Looks through BUILD_VECTOR and SCALAR_TO_VECTOR nodes to find a scalar.
7334 static SDValue getScalarValueForVectorElement(SDValue V, int Idx,
7335                                               SelectionDAG &DAG) {
7336   MVT VT = V.getSimpleValueType();
7337   MVT EltVT = VT.getVectorElementType();
7338   while (V.getOpcode() == ISD::BITCAST)
7339     V = V.getOperand(0);
7340   // If the bitcasts shift the element size, we can't extract an equivalent
7341   // element from it.
7342   MVT NewVT = V.getSimpleValueType();
7343   if (!NewVT.isVector() || NewVT.getScalarSizeInBits() != VT.getScalarSizeInBits())
7344     return SDValue();
7345
7346   if (V.getOpcode() == ISD::BUILD_VECTOR ||
7347       (Idx == 0 && V.getOpcode() == ISD::SCALAR_TO_VECTOR)) {
7348     // Ensure the scalar operand is the same size as the destination.
7349     // FIXME: Add support for scalar truncation where possible.
7350     SDValue S = V.getOperand(Idx);
7351     if (EltVT.getSizeInBits() == S.getSimpleValueType().getSizeInBits())
7352       return DAG.getNode(ISD::BITCAST, SDLoc(V), EltVT, S);
7353   }
7354
7355   return SDValue();
7356 }
7357
7358 /// \brief Helper to test for a load that can be folded with x86 shuffles.
7359 ///
7360 /// This is particularly important because the set of instructions varies
7361 /// significantly based on whether the operand is a load or not.
7362 static bool isShuffleFoldableLoad(SDValue V) {
7363   while (V.getOpcode() == ISD::BITCAST)
7364     V = V.getOperand(0);
7365
7366   return ISD::isNON_EXTLoad(V.getNode());
7367 }
7368
7369 /// \brief Try to lower insertion of a single element into a zero vector.
7370 ///
7371 /// This is a common pattern that we have especially efficient patterns to lower
7372 /// across all subtarget feature sets.
7373 static SDValue lowerVectorShuffleAsElementInsertion(
7374     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7375     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7376   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7377   MVT ExtVT = VT;
7378   MVT EltVT = VT.getVectorElementType();
7379
7380   int V2Index = std::find_if(Mask.begin(), Mask.end(),
7381                              [&Mask](int M) { return M >= (int)Mask.size(); }) -
7382                 Mask.begin();
7383   bool IsV1Zeroable = true;
7384   for (int i = 0, Size = Mask.size(); i < Size; ++i)
7385     if (i != V2Index && !Zeroable[i]) {
7386       IsV1Zeroable = false;
7387       break;
7388     }
7389
7390   // Check for a single input from a SCALAR_TO_VECTOR node.
7391   // FIXME: All of this should be canonicalized into INSERT_VECTOR_ELT and
7392   // all the smarts here sunk into that routine. However, the current
7393   // lowering of BUILD_VECTOR makes that nearly impossible until the old
7394   // vector shuffle lowering is dead.
7395   SDValue V2S = getScalarValueForVectorElement(V2, Mask[V2Index] - Mask.size(),
7396                                                DAG);
7397   if (V2S && DAG.getTargetLoweringInfo().isTypeLegal(V2S.getValueType())) {
7398     // We need to zext the scalar if it is smaller than an i32.
7399     V2S = DAG.getBitcast(EltVT, V2S);
7400     if (EltVT == MVT::i8 || EltVT == MVT::i16) {
7401       // Using zext to expand a narrow element won't work for non-zero
7402       // insertions.
7403       if (!IsV1Zeroable)
7404         return SDValue();
7405
7406       // Zero-extend directly to i32.
7407       ExtVT = MVT::v4i32;
7408       V2S = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, V2S);
7409     }
7410     V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, ExtVT, V2S);
7411   } else if (Mask[V2Index] != (int)Mask.size() || EltVT == MVT::i8 ||
7412              EltVT == MVT::i16) {
7413     // Either not inserting from the low element of the input or the input
7414     // element size is too small to use VZEXT_MOVL to clear the high bits.
7415     return SDValue();
7416   }
7417
7418   if (!IsV1Zeroable) {
7419     // If V1 can't be treated as a zero vector we have fewer options to lower
7420     // this. We can't support integer vectors or non-zero targets cheaply, and
7421     // the V1 elements can't be permuted in any way.
7422     assert(VT == ExtVT && "Cannot change extended type when non-zeroable!");
7423     if (!VT.isFloatingPoint() || V2Index != 0)
7424       return SDValue();
7425     SmallVector<int, 8> V1Mask(Mask.begin(), Mask.end());
7426     V1Mask[V2Index] = -1;
7427     if (!isNoopShuffleMask(V1Mask))
7428       return SDValue();
7429     // This is essentially a special case blend operation, but if we have
7430     // general purpose blend operations, they are always faster. Bail and let
7431     // the rest of the lowering handle these as blends.
7432     if (Subtarget->hasSSE41())
7433       return SDValue();
7434
7435     // Otherwise, use MOVSD or MOVSS.
7436     assert((EltVT == MVT::f32 || EltVT == MVT::f64) &&
7437            "Only two types of floating point element types to handle!");
7438     return DAG.getNode(EltVT == MVT::f32 ? X86ISD::MOVSS : X86ISD::MOVSD, DL,
7439                        ExtVT, V1, V2);
7440   }
7441
7442   // This lowering only works for the low element with floating point vectors.
7443   if (VT.isFloatingPoint() && V2Index != 0)
7444     return SDValue();
7445
7446   V2 = DAG.getNode(X86ISD::VZEXT_MOVL, DL, ExtVT, V2);
7447   if (ExtVT != VT)
7448     V2 = DAG.getBitcast(VT, V2);
7449
7450   if (V2Index != 0) {
7451     // If we have 4 or fewer lanes we can cheaply shuffle the element into
7452     // the desired position. Otherwise it is more efficient to do a vector
7453     // shift left. We know that we can do a vector shift left because all
7454     // the inputs are zero.
7455     if (VT.isFloatingPoint() || VT.getVectorNumElements() <= 4) {
7456       SmallVector<int, 4> V2Shuffle(Mask.size(), 1);
7457       V2Shuffle[V2Index] = 0;
7458       V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Shuffle);
7459     } else {
7460       V2 = DAG.getBitcast(MVT::v2i64, V2);
7461       V2 = DAG.getNode(
7462           X86ISD::VSHLDQ, DL, MVT::v2i64, V2,
7463           DAG.getConstant(V2Index * EltVT.getSizeInBits() / 8, DL,
7464                           DAG.getTargetLoweringInfo().getScalarShiftAmountTy(
7465                               DAG.getDataLayout(), VT)));
7466       V2 = DAG.getBitcast(VT, V2);
7467     }
7468   }
7469   return V2;
7470 }
7471
7472 /// \brief Try to lower broadcast of a single element.
7473 ///
7474 /// For convenience, this code also bundles all of the subtarget feature set
7475 /// filtering. While a little annoying to re-dispatch on type here, there isn't
7476 /// a convenient way to factor it out.
7477 static SDValue lowerVectorShuffleAsBroadcast(SDLoc DL, MVT VT, SDValue V,
7478                                              ArrayRef<int> Mask,
7479                                              const X86Subtarget *Subtarget,
7480                                              SelectionDAG &DAG) {
7481   if (!Subtarget->hasAVX())
7482     return SDValue();
7483   if (VT.isInteger() && !Subtarget->hasAVX2())
7484     return SDValue();
7485
7486   // Check that the mask is a broadcast.
7487   int BroadcastIdx = -1;
7488   for (int M : Mask)
7489     if (M >= 0 && BroadcastIdx == -1)
7490       BroadcastIdx = M;
7491     else if (M >= 0 && M != BroadcastIdx)
7492       return SDValue();
7493
7494   assert(BroadcastIdx < (int)Mask.size() && "We only expect to be called with "
7495                                             "a sorted mask where the broadcast "
7496                                             "comes from V1.");
7497
7498   // Go up the chain of (vector) values to find a scalar load that we can
7499   // combine with the broadcast.
7500   for (;;) {
7501     switch (V.getOpcode()) {
7502     case ISD::CONCAT_VECTORS: {
7503       int OperandSize = Mask.size() / V.getNumOperands();
7504       V = V.getOperand(BroadcastIdx / OperandSize);
7505       BroadcastIdx %= OperandSize;
7506       continue;
7507     }
7508
7509     case ISD::INSERT_SUBVECTOR: {
7510       SDValue VOuter = V.getOperand(0), VInner = V.getOperand(1);
7511       auto ConstantIdx = dyn_cast<ConstantSDNode>(V.getOperand(2));
7512       if (!ConstantIdx)
7513         break;
7514
7515       int BeginIdx = (int)ConstantIdx->getZExtValue();
7516       int EndIdx =
7517           BeginIdx + (int)VInner.getValueType().getVectorNumElements();
7518       if (BroadcastIdx >= BeginIdx && BroadcastIdx < EndIdx) {
7519         BroadcastIdx -= BeginIdx;
7520         V = VInner;
7521       } else {
7522         V = VOuter;
7523       }
7524       continue;
7525     }
7526     }
7527     break;
7528   }
7529
7530   // Check if this is a broadcast of a scalar. We special case lowering
7531   // for scalars so that we can more effectively fold with loads.
7532   if (V.getOpcode() == ISD::BUILD_VECTOR ||
7533       (V.getOpcode() == ISD::SCALAR_TO_VECTOR && BroadcastIdx == 0)) {
7534     V = V.getOperand(BroadcastIdx);
7535
7536     // If the scalar isn't a load, we can't broadcast from it in AVX1.
7537     // Only AVX2 has register broadcasts.
7538     if (!Subtarget->hasAVX2() && !isShuffleFoldableLoad(V))
7539       return SDValue();
7540   } else if (BroadcastIdx != 0 || !Subtarget->hasAVX2()) {
7541     // We can't broadcast from a vector register without AVX2, and we can only
7542     // broadcast from the zero-element of a vector register.
7543     return SDValue();
7544   }
7545
7546   return DAG.getNode(X86ISD::VBROADCAST, DL, VT, V);
7547 }
7548
7549 // Check for whether we can use INSERTPS to perform the shuffle. We only use
7550 // INSERTPS when the V1 elements are already in the correct locations
7551 // because otherwise we can just always use two SHUFPS instructions which
7552 // are much smaller to encode than a SHUFPS and an INSERTPS. We can also
7553 // perform INSERTPS if a single V1 element is out of place and all V2
7554 // elements are zeroable.
7555 static SDValue lowerVectorShuffleAsInsertPS(SDValue Op, SDValue V1, SDValue V2,
7556                                             ArrayRef<int> Mask,
7557                                             SelectionDAG &DAG) {
7558   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
7559   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7560   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7561   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7562
7563   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7564
7565   unsigned ZMask = 0;
7566   int V1DstIndex = -1;
7567   int V2DstIndex = -1;
7568   bool V1UsedInPlace = false;
7569
7570   for (int i = 0; i < 4; ++i) {
7571     // Synthesize a zero mask from the zeroable elements (includes undefs).
7572     if (Zeroable[i]) {
7573       ZMask |= 1 << i;
7574       continue;
7575     }
7576
7577     // Flag if we use any V1 inputs in place.
7578     if (i == Mask[i]) {
7579       V1UsedInPlace = true;
7580       continue;
7581     }
7582
7583     // We can only insert a single non-zeroable element.
7584     if (V1DstIndex != -1 || V2DstIndex != -1)
7585       return SDValue();
7586
7587     if (Mask[i] < 4) {
7588       // V1 input out of place for insertion.
7589       V1DstIndex = i;
7590     } else {
7591       // V2 input for insertion.
7592       V2DstIndex = i;
7593     }
7594   }
7595
7596   // Don't bother if we have no (non-zeroable) element for insertion.
7597   if (V1DstIndex == -1 && V2DstIndex == -1)
7598     return SDValue();
7599
7600   // Determine element insertion src/dst indices. The src index is from the
7601   // start of the inserted vector, not the start of the concatenated vector.
7602   unsigned V2SrcIndex = 0;
7603   if (V1DstIndex != -1) {
7604     // If we have a V1 input out of place, we use V1 as the V2 element insertion
7605     // and don't use the original V2 at all.
7606     V2SrcIndex = Mask[V1DstIndex];
7607     V2DstIndex = V1DstIndex;
7608     V2 = V1;
7609   } else {
7610     V2SrcIndex = Mask[V2DstIndex] - 4;
7611   }
7612
7613   // If no V1 inputs are used in place, then the result is created only from
7614   // the zero mask and the V2 insertion - so remove V1 dependency.
7615   if (!V1UsedInPlace)
7616     V1 = DAG.getUNDEF(MVT::v4f32);
7617
7618   unsigned InsertPSMask = V2SrcIndex << 6 | V2DstIndex << 4 | ZMask;
7619   assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
7620
7621   // Insert the V2 element into the desired position.
7622   SDLoc DL(Op);
7623   return DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
7624                      DAG.getConstant(InsertPSMask, DL, MVT::i8));
7625 }
7626
7627 /// \brief Try to lower a shuffle as a permute of the inputs followed by an
7628 /// UNPCK instruction.
7629 ///
7630 /// This specifically targets cases where we end up with alternating between
7631 /// the two inputs, and so can permute them into something that feeds a single
7632 /// UNPCK instruction. Note that this routine only targets integer vectors
7633 /// because for floating point vectors we have a generalized SHUFPS lowering
7634 /// strategy that handles everything that doesn't *exactly* match an unpack,
7635 /// making this clever lowering unnecessary.
7636 static SDValue lowerVectorShuffleAsUnpack(SDLoc DL, MVT VT, SDValue V1,
7637                                           SDValue V2, ArrayRef<int> Mask,
7638                                           SelectionDAG &DAG) {
7639   assert(!VT.isFloatingPoint() &&
7640          "This routine only supports integer vectors.");
7641   assert(!isSingleInputShuffleMask(Mask) &&
7642          "This routine should only be used when blending two inputs.");
7643   assert(Mask.size() >= 2 && "Single element masks are invalid.");
7644
7645   int Size = Mask.size();
7646
7647   int NumLoInputs = std::count_if(Mask.begin(), Mask.end(), [Size](int M) {
7648     return M >= 0 && M % Size < Size / 2;
7649   });
7650   int NumHiInputs = std::count_if(
7651       Mask.begin(), Mask.end(), [Size](int M) { return M % Size >= Size / 2; });
7652
7653   bool UnpackLo = NumLoInputs >= NumHiInputs;
7654
7655   auto TryUnpack = [&](MVT UnpackVT, int Scale) {
7656     SmallVector<int, 32> V1Mask(Mask.size(), -1);
7657     SmallVector<int, 32> V2Mask(Mask.size(), -1);
7658
7659     for (int i = 0; i < Size; ++i) {
7660       if (Mask[i] < 0)
7661         continue;
7662
7663       // Each element of the unpack contains Scale elements from this mask.
7664       int UnpackIdx = i / Scale;
7665
7666       // We only handle the case where V1 feeds the first slots of the unpack.
7667       // We rely on canonicalization to ensure this is the case.
7668       if ((UnpackIdx % 2 == 0) != (Mask[i] < Size))
7669         return SDValue();
7670
7671       // Setup the mask for this input. The indexing is tricky as we have to
7672       // handle the unpack stride.
7673       SmallVectorImpl<int> &VMask = (UnpackIdx % 2 == 0) ? V1Mask : V2Mask;
7674       VMask[(UnpackIdx / 2) * Scale + i % Scale + (UnpackLo ? 0 : Size / 2)] =
7675           Mask[i] % Size;
7676     }
7677
7678     // If we will have to shuffle both inputs to use the unpack, check whether
7679     // we can just unpack first and shuffle the result. If so, skip this unpack.
7680     if ((NumLoInputs == 0 || NumHiInputs == 0) && !isNoopShuffleMask(V1Mask) &&
7681         !isNoopShuffleMask(V2Mask))
7682       return SDValue();
7683
7684     // Shuffle the inputs into place.
7685     V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
7686     V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
7687
7688     // Cast the inputs to the type we will use to unpack them.
7689     V1 = DAG.getBitcast(UnpackVT, V1);
7690     V2 = DAG.getBitcast(UnpackVT, V2);
7691
7692     // Unpack the inputs and cast the result back to the desired type.
7693     return DAG.getBitcast(
7694         VT, DAG.getNode(UnpackLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
7695                         UnpackVT, V1, V2));
7696   };
7697
7698   // We try each unpack from the largest to the smallest to try and find one
7699   // that fits this mask.
7700   int OrigNumElements = VT.getVectorNumElements();
7701   int OrigScalarSize = VT.getScalarSizeInBits();
7702   for (int ScalarSize = 64; ScalarSize >= OrigScalarSize; ScalarSize /= 2) {
7703     int Scale = ScalarSize / OrigScalarSize;
7704     int NumElements = OrigNumElements / Scale;
7705     MVT UnpackVT = MVT::getVectorVT(MVT::getIntegerVT(ScalarSize), NumElements);
7706     if (SDValue Unpack = TryUnpack(UnpackVT, Scale))
7707       return Unpack;
7708   }
7709
7710   // If none of the unpack-rooted lowerings worked (or were profitable) try an
7711   // initial unpack.
7712   if (NumLoInputs == 0 || NumHiInputs == 0) {
7713     assert((NumLoInputs > 0 || NumHiInputs > 0) &&
7714            "We have to have *some* inputs!");
7715     int HalfOffset = NumLoInputs == 0 ? Size / 2 : 0;
7716
7717     // FIXME: We could consider the total complexity of the permute of each
7718     // possible unpacking. Or at the least we should consider how many
7719     // half-crossings are created.
7720     // FIXME: We could consider commuting the unpacks.
7721
7722     SmallVector<int, 32> PermMask;
7723     PermMask.assign(Size, -1);
7724     for (int i = 0; i < Size; ++i) {
7725       if (Mask[i] < 0)
7726         continue;
7727
7728       assert(Mask[i] % Size >= HalfOffset && "Found input from wrong half!");
7729
7730       PermMask[i] =
7731           2 * ((Mask[i] % Size) - HalfOffset) + (Mask[i] < Size ? 0 : 1);
7732     }
7733     return DAG.getVectorShuffle(
7734         VT, DL, DAG.getNode(NumLoInputs == 0 ? X86ISD::UNPCKH : X86ISD::UNPCKL,
7735                             DL, VT, V1, V2),
7736         DAG.getUNDEF(VT), PermMask);
7737   }
7738
7739   return SDValue();
7740 }
7741
7742 /// \brief Handle lowering of 2-lane 64-bit floating point shuffles.
7743 ///
7744 /// This is the basis function for the 2-lane 64-bit shuffles as we have full
7745 /// support for floating point shuffles but not integer shuffles. These
7746 /// instructions will incur a domain crossing penalty on some chips though so
7747 /// it is better to avoid lowering through this for integer vectors where
7748 /// possible.
7749 static SDValue lowerV2F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7750                                        const X86Subtarget *Subtarget,
7751                                        SelectionDAG &DAG) {
7752   SDLoc DL(Op);
7753   assert(Op.getSimpleValueType() == MVT::v2f64 && "Bad shuffle type!");
7754   assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7755   assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7756   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7757   ArrayRef<int> Mask = SVOp->getMask();
7758   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7759
7760   if (isSingleInputShuffleMask(Mask)) {
7761     // Use low duplicate instructions for masks that match their pattern.
7762     if (Subtarget->hasSSE3())
7763       if (isShuffleEquivalent(V1, V2, Mask, {0, 0}))
7764         return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v2f64, V1);
7765
7766     // Straight shuffle of a single input vector. Simulate this by using the
7767     // single input as both of the "inputs" to this instruction..
7768     unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
7769
7770     if (Subtarget->hasAVX()) {
7771       // If we have AVX, we can use VPERMILPS which will allow folding a load
7772       // into the shuffle.
7773       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v2f64, V1,
7774                          DAG.getConstant(SHUFPDMask, DL, MVT::i8));
7775     }
7776
7777     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V1,
7778                        DAG.getConstant(SHUFPDMask, DL, MVT::i8));
7779   }
7780   assert(Mask[0] >= 0 && Mask[0] < 2 && "Non-canonicalized blend!");
7781   assert(Mask[1] >= 2 && "Non-canonicalized blend!");
7782
7783   // If we have a single input, insert that into V1 if we can do so cheaply.
7784   if ((Mask[0] >= 2) + (Mask[1] >= 2) == 1) {
7785     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7786             DL, MVT::v2f64, V1, V2, Mask, Subtarget, DAG))
7787       return Insertion;
7788     // Try inverting the insertion since for v2 masks it is easy to do and we
7789     // can't reliably sort the mask one way or the other.
7790     int InverseMask[2] = {Mask[0] < 0 ? -1 : (Mask[0] ^ 2),
7791                           Mask[1] < 0 ? -1 : (Mask[1] ^ 2)};
7792     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7793             DL, MVT::v2f64, V2, V1, InverseMask, Subtarget, DAG))
7794       return Insertion;
7795   }
7796
7797   // Try to use one of the special instruction patterns to handle two common
7798   // blend patterns if a zero-blend above didn't work.
7799   if (isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
7800       isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7801     if (SDValue V1S = getScalarValueForVectorElement(V1, Mask[0], DAG))
7802       // We can either use a special instruction to load over the low double or
7803       // to move just the low double.
7804       return DAG.getNode(
7805           isShuffleFoldableLoad(V1S) ? X86ISD::MOVLPD : X86ISD::MOVSD,
7806           DL, MVT::v2f64, V2,
7807           DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64, V1S));
7808
7809   if (Subtarget->hasSSE41())
7810     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2f64, V1, V2, Mask,
7811                                                   Subtarget, DAG))
7812       return Blend;
7813
7814   // Use dedicated unpack instructions for masks that match their pattern.
7815   if (isShuffleEquivalent(V1, V2, Mask, {0, 2}))
7816     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2f64, V1, V2);
7817   if (isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7818     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2f64, V1, V2);
7819
7820   unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
7821   return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V2,
7822                      DAG.getConstant(SHUFPDMask, DL, MVT::i8));
7823 }
7824
7825 /// \brief Handle lowering of 2-lane 64-bit integer shuffles.
7826 ///
7827 /// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
7828 /// the integer unit to minimize domain crossing penalties. However, for blends
7829 /// it falls back to the floating point shuffle operation with appropriate bit
7830 /// casting.
7831 static SDValue lowerV2I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7832                                        const X86Subtarget *Subtarget,
7833                                        SelectionDAG &DAG) {
7834   SDLoc DL(Op);
7835   assert(Op.getSimpleValueType() == MVT::v2i64 && "Bad shuffle type!");
7836   assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7837   assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7838   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7839   ArrayRef<int> Mask = SVOp->getMask();
7840   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7841
7842   if (isSingleInputShuffleMask(Mask)) {
7843     // Check for being able to broadcast a single element.
7844     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v2i64, V1,
7845                                                           Mask, Subtarget, DAG))
7846       return Broadcast;
7847
7848     // Straight shuffle of a single input vector. For everything from SSE2
7849     // onward this has a single fast instruction with no scary immediates.
7850     // We have to map the mask as it is actually a v4i32 shuffle instruction.
7851     V1 = DAG.getBitcast(MVT::v4i32, V1);
7852     int WidenedMask[4] = {
7853         std::max(Mask[0], 0) * 2, std::max(Mask[0], 0) * 2 + 1,
7854         std::max(Mask[1], 0) * 2, std::max(Mask[1], 0) * 2 + 1};
7855     return DAG.getBitcast(
7856         MVT::v2i64,
7857         DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
7858                     getV4X86ShuffleImm8ForMask(WidenedMask, DL, DAG)));
7859   }
7860   assert(Mask[0] != -1 && "No undef lanes in multi-input v2 shuffles!");
7861   assert(Mask[1] != -1 && "No undef lanes in multi-input v2 shuffles!");
7862   assert(Mask[0] < 2 && "We sort V1 to be the first input.");
7863   assert(Mask[1] >= 2 && "We sort V2 to be the second input.");
7864
7865   // If we have a blend of two PACKUS operations an the blend aligns with the
7866   // low and half halves, we can just merge the PACKUS operations. This is
7867   // particularly important as it lets us merge shuffles that this routine itself
7868   // creates.
7869   auto GetPackNode = [](SDValue V) {
7870     while (V.getOpcode() == ISD::BITCAST)
7871       V = V.getOperand(0);
7872
7873     return V.getOpcode() == X86ISD::PACKUS ? V : SDValue();
7874   };
7875   if (SDValue V1Pack = GetPackNode(V1))
7876     if (SDValue V2Pack = GetPackNode(V2))
7877       return DAG.getBitcast(MVT::v2i64,
7878                             DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8,
7879                                         Mask[0] == 0 ? V1Pack.getOperand(0)
7880                                                      : V1Pack.getOperand(1),
7881                                         Mask[1] == 2 ? V2Pack.getOperand(0)
7882                                                      : V2Pack.getOperand(1)));
7883
7884   // Try to use shift instructions.
7885   if (SDValue Shift =
7886           lowerVectorShuffleAsShift(DL, MVT::v2i64, V1, V2, Mask, DAG))
7887     return Shift;
7888
7889   // When loading a scalar and then shuffling it into a vector we can often do
7890   // the insertion cheaply.
7891   if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7892           DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
7893     return Insertion;
7894   // Try inverting the insertion since for v2 masks it is easy to do and we
7895   // can't reliably sort the mask one way or the other.
7896   int InverseMask[2] = {Mask[0] ^ 2, Mask[1] ^ 2};
7897   if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7898           DL, MVT::v2i64, V2, V1, InverseMask, Subtarget, DAG))
7899     return Insertion;
7900
7901   // We have different paths for blend lowering, but they all must use the
7902   // *exact* same predicate.
7903   bool IsBlendSupported = Subtarget->hasSSE41();
7904   if (IsBlendSupported)
7905     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2i64, V1, V2, Mask,
7906                                                   Subtarget, DAG))
7907       return Blend;
7908
7909   // Use dedicated unpack instructions for masks that match their pattern.
7910   if (isShuffleEquivalent(V1, V2, Mask, {0, 2}))
7911     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, V1, V2);
7912   if (isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7913     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2i64, V1, V2);
7914
7915   // Try to use byte rotation instructions.
7916   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
7917   if (Subtarget->hasSSSE3())
7918     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
7919             DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
7920       return Rotate;
7921
7922   // If we have direct support for blends, we should lower by decomposing into
7923   // a permute. That will be faster than the domain cross.
7924   if (IsBlendSupported)
7925     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v2i64, V1, V2,
7926                                                       Mask, DAG);
7927
7928   // We implement this with SHUFPD which is pretty lame because it will likely
7929   // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
7930   // However, all the alternatives are still more cycles and newer chips don't
7931   // have this problem. It would be really nice if x86 had better shuffles here.
7932   V1 = DAG.getBitcast(MVT::v2f64, V1);
7933   V2 = DAG.getBitcast(MVT::v2f64, V2);
7934   return DAG.getBitcast(MVT::v2i64,
7935                         DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
7936 }
7937
7938 /// \brief Test whether this can be lowered with a single SHUFPS instruction.
7939 ///
7940 /// This is used to disable more specialized lowerings when the shufps lowering
7941 /// will happen to be efficient.
7942 static bool isSingleSHUFPSMask(ArrayRef<int> Mask) {
7943   // This routine only handles 128-bit shufps.
7944   assert(Mask.size() == 4 && "Unsupported mask size!");
7945
7946   // To lower with a single SHUFPS we need to have the low half and high half
7947   // each requiring a single input.
7948   if (Mask[0] != -1 && Mask[1] != -1 && (Mask[0] < 4) != (Mask[1] < 4))
7949     return false;
7950   if (Mask[2] != -1 && Mask[3] != -1 && (Mask[2] < 4) != (Mask[3] < 4))
7951     return false;
7952
7953   return true;
7954 }
7955
7956 /// \brief Lower a vector shuffle using the SHUFPS instruction.
7957 ///
7958 /// This is a helper routine dedicated to lowering vector shuffles using SHUFPS.
7959 /// It makes no assumptions about whether this is the *best* lowering, it simply
7960 /// uses it.
7961 static SDValue lowerVectorShuffleWithSHUFPS(SDLoc DL, MVT VT,
7962                                             ArrayRef<int> Mask, SDValue V1,
7963                                             SDValue V2, SelectionDAG &DAG) {
7964   SDValue LowV = V1, HighV = V2;
7965   int NewMask[4] = {Mask[0], Mask[1], Mask[2], Mask[3]};
7966
7967   int NumV2Elements =
7968       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7969
7970   if (NumV2Elements == 1) {
7971     int V2Index =
7972         std::find_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; }) -
7973         Mask.begin();
7974
7975     // Compute the index adjacent to V2Index and in the same half by toggling
7976     // the low bit.
7977     int V2AdjIndex = V2Index ^ 1;
7978
7979     if (Mask[V2AdjIndex] == -1) {
7980       // Handles all the cases where we have a single V2 element and an undef.
7981       // This will only ever happen in the high lanes because we commute the
7982       // vector otherwise.
7983       if (V2Index < 2)
7984         std::swap(LowV, HighV);
7985       NewMask[V2Index] -= 4;
7986     } else {
7987       // Handle the case where the V2 element ends up adjacent to a V1 element.
7988       // To make this work, blend them together as the first step.
7989       int V1Index = V2AdjIndex;
7990       int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
7991       V2 = DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
7992                        getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
7993
7994       // Now proceed to reconstruct the final blend as we have the necessary
7995       // high or low half formed.
7996       if (V2Index < 2) {
7997         LowV = V2;
7998         HighV = V1;
7999       } else {
8000         HighV = V2;
8001       }
8002       NewMask[V1Index] = 2; // We put the V1 element in V2[2].
8003       NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
8004     }
8005   } else if (NumV2Elements == 2) {
8006     if (Mask[0] < 4 && Mask[1] < 4) {
8007       // Handle the easy case where we have V1 in the low lanes and V2 in the
8008       // high lanes.
8009       NewMask[2] -= 4;
8010       NewMask[3] -= 4;
8011     } else if (Mask[2] < 4 && Mask[3] < 4) {
8012       // We also handle the reversed case because this utility may get called
8013       // when we detect a SHUFPS pattern but can't easily commute the shuffle to
8014       // arrange things in the right direction.
8015       NewMask[0] -= 4;
8016       NewMask[1] -= 4;
8017       HighV = V1;
8018       LowV = V2;
8019     } else {
8020       // We have a mixture of V1 and V2 in both low and high lanes. Rather than
8021       // trying to place elements directly, just blend them and set up the final
8022       // shuffle to place them.
8023
8024       // The first two blend mask elements are for V1, the second two are for
8025       // V2.
8026       int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
8027                           Mask[2] < 4 ? Mask[2] : Mask[3],
8028                           (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
8029                           (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
8030       V1 = DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
8031                        getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
8032
8033       // Now we do a normal shuffle of V1 by giving V1 as both operands to
8034       // a blend.
8035       LowV = HighV = V1;
8036       NewMask[0] = Mask[0] < 4 ? 0 : 2;
8037       NewMask[1] = Mask[0] < 4 ? 2 : 0;
8038       NewMask[2] = Mask[2] < 4 ? 1 : 3;
8039       NewMask[3] = Mask[2] < 4 ? 3 : 1;
8040     }
8041   }
8042   return DAG.getNode(X86ISD::SHUFP, DL, VT, LowV, HighV,
8043                      getV4X86ShuffleImm8ForMask(NewMask, DL, DAG));
8044 }
8045
8046 /// \brief Lower 4-lane 32-bit floating point shuffles.
8047 ///
8048 /// Uses instructions exclusively from the floating point unit to minimize
8049 /// domain crossing penalties, as these are sufficient to implement all v4f32
8050 /// shuffles.
8051 static SDValue lowerV4F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8052                                        const X86Subtarget *Subtarget,
8053                                        SelectionDAG &DAG) {
8054   SDLoc DL(Op);
8055   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
8056   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8057   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8058   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8059   ArrayRef<int> Mask = SVOp->getMask();
8060   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8061
8062   int NumV2Elements =
8063       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8064
8065   if (NumV2Elements == 0) {
8066     // Check for being able to broadcast a single element.
8067     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f32, V1,
8068                                                           Mask, Subtarget, DAG))
8069       return Broadcast;
8070
8071     // Use even/odd duplicate instructions for masks that match their pattern.
8072     if (Subtarget->hasSSE3()) {
8073       if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
8074         return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v4f32, V1);
8075       if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3}))
8076         return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v4f32, V1);
8077     }
8078
8079     if (Subtarget->hasAVX()) {
8080       // If we have AVX, we can use VPERMILPS which will allow folding a load
8081       // into the shuffle.
8082       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f32, V1,
8083                          getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8084     }
8085
8086     // Otherwise, use a straight shuffle of a single input vector. We pass the
8087     // input vector to both operands to simulate this with a SHUFPS.
8088     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
8089                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8090   }
8091
8092   // There are special ways we can lower some single-element blends. However, we
8093   // have custom ways we can lower more complex single-element blends below that
8094   // we defer to if both this and BLENDPS fail to match, so restrict this to
8095   // when the V2 input is targeting element 0 of the mask -- that is the fast
8096   // case here.
8097   if (NumV2Elements == 1 && Mask[0] >= 4)
8098     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4f32, V1, V2,
8099                                                          Mask, Subtarget, DAG))
8100       return V;
8101
8102   if (Subtarget->hasSSE41()) {
8103     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f32, V1, V2, Mask,
8104                                                   Subtarget, DAG))
8105       return Blend;
8106
8107     // Use INSERTPS if we can complete the shuffle efficiently.
8108     if (SDValue V = lowerVectorShuffleAsInsertPS(Op, V1, V2, Mask, DAG))
8109       return V;
8110
8111     if (!isSingleSHUFPSMask(Mask))
8112       if (SDValue BlendPerm = lowerVectorShuffleAsBlendAndPermute(
8113               DL, MVT::v4f32, V1, V2, Mask, DAG))
8114         return BlendPerm;
8115   }
8116
8117   // Use dedicated unpack instructions for masks that match their pattern.
8118   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 1, 5}))
8119     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V1, V2);
8120   if (isShuffleEquivalent(V1, V2, Mask, {2, 6, 3, 7}))
8121     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V1, V2);
8122   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 5, 1}))
8123     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V2, V1);
8124   if (isShuffleEquivalent(V1, V2, Mask, {6, 2, 7, 3}))
8125     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V2, V1);
8126
8127   // Otherwise fall back to a SHUFPS lowering strategy.
8128   return lowerVectorShuffleWithSHUFPS(DL, MVT::v4f32, Mask, V1, V2, DAG);
8129 }
8130
8131 /// \brief Lower 4-lane i32 vector shuffles.
8132 ///
8133 /// We try to handle these with integer-domain shuffles where we can, but for
8134 /// blends we use the floating point domain blend instructions.
8135 static SDValue lowerV4I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8136                                        const X86Subtarget *Subtarget,
8137                                        SelectionDAG &DAG) {
8138   SDLoc DL(Op);
8139   assert(Op.getSimpleValueType() == MVT::v4i32 && "Bad shuffle type!");
8140   assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
8141   assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
8142   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8143   ArrayRef<int> Mask = SVOp->getMask();
8144   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8145
8146   // Whenever we can lower this as a zext, that instruction is strictly faster
8147   // than any alternative. It also allows us to fold memory operands into the
8148   // shuffle in many cases.
8149   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v4i32, V1, V2,
8150                                                          Mask, Subtarget, DAG))
8151     return ZExt;
8152
8153   int NumV2Elements =
8154       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8155
8156   if (NumV2Elements == 0) {
8157     // Check for being able to broadcast a single element.
8158     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i32, V1,
8159                                                           Mask, Subtarget, DAG))
8160       return Broadcast;
8161
8162     // Straight shuffle of a single input vector. For everything from SSE2
8163     // onward this has a single fast instruction with no scary immediates.
8164     // We coerce the shuffle pattern to be compatible with UNPCK instructions
8165     // but we aren't actually going to use the UNPCK instruction because doing
8166     // so prevents folding a load into this instruction or making a copy.
8167     const int UnpackLoMask[] = {0, 0, 1, 1};
8168     const int UnpackHiMask[] = {2, 2, 3, 3};
8169     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 1, 1}))
8170       Mask = UnpackLoMask;
8171     else if (isShuffleEquivalent(V1, V2, Mask, {2, 2, 3, 3}))
8172       Mask = UnpackHiMask;
8173
8174     return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
8175                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8176   }
8177
8178   // Try to use shift instructions.
8179   if (SDValue Shift =
8180           lowerVectorShuffleAsShift(DL, MVT::v4i32, V1, V2, Mask, DAG))
8181     return Shift;
8182
8183   // There are special ways we can lower some single-element blends.
8184   if (NumV2Elements == 1)
8185     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4i32, V1, V2,
8186                                                          Mask, Subtarget, DAG))
8187       return V;
8188
8189   // We have different paths for blend lowering, but they all must use the
8190   // *exact* same predicate.
8191   bool IsBlendSupported = Subtarget->hasSSE41();
8192   if (IsBlendSupported)
8193     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i32, V1, V2, Mask,
8194                                                   Subtarget, DAG))
8195       return Blend;
8196
8197   if (SDValue Masked =
8198           lowerVectorShuffleAsBitMask(DL, MVT::v4i32, V1, V2, Mask, DAG))
8199     return Masked;
8200
8201   // Use dedicated unpack instructions for masks that match their pattern.
8202   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 1, 5}))
8203     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V1, V2);
8204   if (isShuffleEquivalent(V1, V2, Mask, {2, 6, 3, 7}))
8205     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V1, V2);
8206   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 5, 1}))
8207     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V2, V1);
8208   if (isShuffleEquivalent(V1, V2, Mask, {6, 2, 7, 3}))
8209     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V2, V1);
8210
8211   // Try to use byte rotation instructions.
8212   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
8213   if (Subtarget->hasSSSE3())
8214     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8215             DL, MVT::v4i32, V1, V2, Mask, Subtarget, DAG))
8216       return Rotate;
8217
8218   // If we have direct support for blends, we should lower by decomposing into
8219   // a permute. That will be faster than the domain cross.
8220   if (IsBlendSupported)
8221     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i32, V1, V2,
8222                                                       Mask, DAG);
8223
8224   // Try to lower by permuting the inputs into an unpack instruction.
8225   if (SDValue Unpack =
8226           lowerVectorShuffleAsUnpack(DL, MVT::v4i32, V1, V2, Mask, DAG))
8227     return Unpack;
8228
8229   // We implement this with SHUFPS because it can blend from two vectors.
8230   // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
8231   // up the inputs, bypassing domain shift penalties that we would encur if we
8232   // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
8233   // relevant.
8234   return DAG.getBitcast(
8235       MVT::v4i32,
8236       DAG.getVectorShuffle(MVT::v4f32, DL, DAG.getBitcast(MVT::v4f32, V1),
8237                            DAG.getBitcast(MVT::v4f32, V2), Mask));
8238 }
8239
8240 /// \brief Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
8241 /// shuffle lowering, and the most complex part.
8242 ///
8243 /// The lowering strategy is to try to form pairs of input lanes which are
8244 /// targeted at the same half of the final vector, and then use a dword shuffle
8245 /// to place them onto the right half, and finally unpack the paired lanes into
8246 /// their final position.
8247 ///
8248 /// The exact breakdown of how to form these dword pairs and align them on the
8249 /// correct sides is really tricky. See the comments within the function for
8250 /// more of the details.
8251 ///
8252 /// This code also handles repeated 128-bit lanes of v8i16 shuffles, but each
8253 /// lane must shuffle the *exact* same way. In fact, you must pass a v8 Mask to
8254 /// this routine for it to work correctly. To shuffle a 256-bit or 512-bit i16
8255 /// vector, form the analogous 128-bit 8-element Mask.
8256 static SDValue lowerV8I16GeneralSingleInputVectorShuffle(
8257     SDLoc DL, MVT VT, SDValue V, MutableArrayRef<int> Mask,
8258     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
8259   assert(VT.getScalarType() == MVT::i16 && "Bad input type!");
8260   MVT PSHUFDVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
8261
8262   assert(Mask.size() == 8 && "Shuffle mask length doen't match!");
8263   MutableArrayRef<int> LoMask = Mask.slice(0, 4);
8264   MutableArrayRef<int> HiMask = Mask.slice(4, 4);
8265
8266   SmallVector<int, 4> LoInputs;
8267   std::copy_if(LoMask.begin(), LoMask.end(), std::back_inserter(LoInputs),
8268                [](int M) { return M >= 0; });
8269   std::sort(LoInputs.begin(), LoInputs.end());
8270   LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()), LoInputs.end());
8271   SmallVector<int, 4> HiInputs;
8272   std::copy_if(HiMask.begin(), HiMask.end(), std::back_inserter(HiInputs),
8273                [](int M) { return M >= 0; });
8274   std::sort(HiInputs.begin(), HiInputs.end());
8275   HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()), HiInputs.end());
8276   int NumLToL =
8277       std::lower_bound(LoInputs.begin(), LoInputs.end(), 4) - LoInputs.begin();
8278   int NumHToL = LoInputs.size() - NumLToL;
8279   int NumLToH =
8280       std::lower_bound(HiInputs.begin(), HiInputs.end(), 4) - HiInputs.begin();
8281   int NumHToH = HiInputs.size() - NumLToH;
8282   MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
8283   MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
8284   MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
8285   MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
8286
8287   // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
8288   // such inputs we can swap two of the dwords across the half mark and end up
8289   // with <=2 inputs to each half in each half. Once there, we can fall through
8290   // to the generic code below. For example:
8291   //
8292   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
8293   // Mask:  [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
8294   //
8295   // However in some very rare cases we have a 1-into-3 or 3-into-1 on one half
8296   // and an existing 2-into-2 on the other half. In this case we may have to
8297   // pre-shuffle the 2-into-2 half to avoid turning it into a 3-into-1 or
8298   // 1-into-3 which could cause us to cycle endlessly fixing each side in turn.
8299   // Fortunately, we don't have to handle anything but a 2-into-2 pattern
8300   // because any other situation (including a 3-into-1 or 1-into-3 in the other
8301   // half than the one we target for fixing) will be fixed when we re-enter this
8302   // path. We will also combine away any sequence of PSHUFD instructions that
8303   // result into a single instruction. Here is an example of the tricky case:
8304   //
8305   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
8306   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -THIS-IS-BAD!!!!-> [5, 7, 1, 0, 4, 7, 5, 3]
8307   //
8308   // This now has a 1-into-3 in the high half! Instead, we do two shuffles:
8309   //
8310   // Input: [a, b, c, d, e, f, g, h] PSHUFHW[0,2,1,3]-> [a, b, c, d, e, g, f, h]
8311   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -----------------> [3, 7, 1, 0, 2, 7, 3, 6]
8312   //
8313   // Input: [a, b, c, d, e, g, f, h] -PSHUFD[0,2,1,3]-> [a, b, e, g, c, d, f, h]
8314   // Mask:  [3, 7, 1, 0, 2, 7, 3, 6] -----------------> [5, 7, 1, 0, 4, 7, 5, 6]
8315   //
8316   // The result is fine to be handled by the generic logic.
8317   auto balanceSides = [&](ArrayRef<int> AToAInputs, ArrayRef<int> BToAInputs,
8318                           ArrayRef<int> BToBInputs, ArrayRef<int> AToBInputs,
8319                           int AOffset, int BOffset) {
8320     assert((AToAInputs.size() == 3 || AToAInputs.size() == 1) &&
8321            "Must call this with A having 3 or 1 inputs from the A half.");
8322     assert((BToAInputs.size() == 1 || BToAInputs.size() == 3) &&
8323            "Must call this with B having 1 or 3 inputs from the B half.");
8324     assert(AToAInputs.size() + BToAInputs.size() == 4 &&
8325            "Must call this with either 3:1 or 1:3 inputs (summing to 4).");
8326
8327     // Compute the index of dword with only one word among the three inputs in
8328     // a half by taking the sum of the half with three inputs and subtracting
8329     // the sum of the actual three inputs. The difference is the remaining
8330     // slot.
8331     int ADWord, BDWord;
8332     int &TripleDWord = AToAInputs.size() == 3 ? ADWord : BDWord;
8333     int &OneInputDWord = AToAInputs.size() == 3 ? BDWord : ADWord;
8334     int TripleInputOffset = AToAInputs.size() == 3 ? AOffset : BOffset;
8335     ArrayRef<int> TripleInputs = AToAInputs.size() == 3 ? AToAInputs : BToAInputs;
8336     int OneInput = AToAInputs.size() == 3 ? BToAInputs[0] : AToAInputs[0];
8337     int TripleInputSum = 0 + 1 + 2 + 3 + (4 * TripleInputOffset);
8338     int TripleNonInputIdx =
8339         TripleInputSum - std::accumulate(TripleInputs.begin(), TripleInputs.end(), 0);
8340     TripleDWord = TripleNonInputIdx / 2;
8341
8342     // We use xor with one to compute the adjacent DWord to whichever one the
8343     // OneInput is in.
8344     OneInputDWord = (OneInput / 2) ^ 1;
8345
8346     // Check for one tricky case: We're fixing a 3<-1 or a 1<-3 shuffle for AToA
8347     // and BToA inputs. If there is also such a problem with the BToB and AToB
8348     // inputs, we don't try to fix it necessarily -- we'll recurse and see it in
8349     // the next pass. However, if we have a 2<-2 in the BToB and AToB inputs, it
8350     // is essential that we don't *create* a 3<-1 as then we might oscillate.
8351     if (BToBInputs.size() == 2 && AToBInputs.size() == 2) {
8352       // Compute how many inputs will be flipped by swapping these DWords. We
8353       // need
8354       // to balance this to ensure we don't form a 3-1 shuffle in the other
8355       // half.
8356       int NumFlippedAToBInputs =
8357           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord) +
8358           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord + 1);
8359       int NumFlippedBToBInputs =
8360           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord) +
8361           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord + 1);
8362       if ((NumFlippedAToBInputs == 1 &&
8363            (NumFlippedBToBInputs == 0 || NumFlippedBToBInputs == 2)) ||
8364           (NumFlippedBToBInputs == 1 &&
8365            (NumFlippedAToBInputs == 0 || NumFlippedAToBInputs == 2))) {
8366         // We choose whether to fix the A half or B half based on whether that
8367         // half has zero flipped inputs. At zero, we may not be able to fix it
8368         // with that half. We also bias towards fixing the B half because that
8369         // will more commonly be the high half, and we have to bias one way.
8370         auto FixFlippedInputs = [&V, &DL, &Mask, &DAG](int PinnedIdx, int DWord,
8371                                                        ArrayRef<int> Inputs) {
8372           int FixIdx = PinnedIdx ^ 1; // The adjacent slot to the pinned slot.
8373           bool IsFixIdxInput = std::find(Inputs.begin(), Inputs.end(),
8374                                          PinnedIdx ^ 1) != Inputs.end();
8375           // Determine whether the free index is in the flipped dword or the
8376           // unflipped dword based on where the pinned index is. We use this bit
8377           // in an xor to conditionally select the adjacent dword.
8378           int FixFreeIdx = 2 * (DWord ^ (PinnedIdx / 2 == DWord));
8379           bool IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
8380                                              FixFreeIdx) != Inputs.end();
8381           if (IsFixIdxInput == IsFixFreeIdxInput)
8382             FixFreeIdx += 1;
8383           IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
8384                                         FixFreeIdx) != Inputs.end();
8385           assert(IsFixIdxInput != IsFixFreeIdxInput &&
8386                  "We need to be changing the number of flipped inputs!");
8387           int PSHUFHalfMask[] = {0, 1, 2, 3};
8388           std::swap(PSHUFHalfMask[FixFreeIdx % 4], PSHUFHalfMask[FixIdx % 4]);
8389           V = DAG.getNode(FixIdx < 4 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW, DL,
8390                           MVT::v8i16, V,
8391                           getV4X86ShuffleImm8ForMask(PSHUFHalfMask, DL, DAG));
8392
8393           for (int &M : Mask)
8394             if (M != -1 && M == FixIdx)
8395               M = FixFreeIdx;
8396             else if (M != -1 && M == FixFreeIdx)
8397               M = FixIdx;
8398         };
8399         if (NumFlippedBToBInputs != 0) {
8400           int BPinnedIdx =
8401               BToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
8402           FixFlippedInputs(BPinnedIdx, BDWord, BToBInputs);
8403         } else {
8404           assert(NumFlippedAToBInputs != 0 && "Impossible given predicates!");
8405           int APinnedIdx =
8406               AToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
8407           FixFlippedInputs(APinnedIdx, ADWord, AToBInputs);
8408         }
8409       }
8410     }
8411
8412     int PSHUFDMask[] = {0, 1, 2, 3};
8413     PSHUFDMask[ADWord] = BDWord;
8414     PSHUFDMask[BDWord] = ADWord;
8415     V = DAG.getBitcast(
8416         VT,
8417         DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, DAG.getBitcast(PSHUFDVT, V),
8418                     getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
8419
8420     // Adjust the mask to match the new locations of A and B.
8421     for (int &M : Mask)
8422       if (M != -1 && M/2 == ADWord)
8423         M = 2 * BDWord + M % 2;
8424       else if (M != -1 && M/2 == BDWord)
8425         M = 2 * ADWord + M % 2;
8426
8427     // Recurse back into this routine to re-compute state now that this isn't
8428     // a 3 and 1 problem.
8429     return lowerV8I16GeneralSingleInputVectorShuffle(DL, VT, V, Mask, Subtarget,
8430                                                      DAG);
8431   };
8432   if ((NumLToL == 3 && NumHToL == 1) || (NumLToL == 1 && NumHToL == 3))
8433     return balanceSides(LToLInputs, HToLInputs, HToHInputs, LToHInputs, 0, 4);
8434   else if ((NumHToH == 3 && NumLToH == 1) || (NumHToH == 1 && NumLToH == 3))
8435     return balanceSides(HToHInputs, LToHInputs, LToLInputs, HToLInputs, 4, 0);
8436
8437   // At this point there are at most two inputs to the low and high halves from
8438   // each half. That means the inputs can always be grouped into dwords and
8439   // those dwords can then be moved to the correct half with a dword shuffle.
8440   // We use at most one low and one high word shuffle to collect these paired
8441   // inputs into dwords, and finally a dword shuffle to place them.
8442   int PSHUFLMask[4] = {-1, -1, -1, -1};
8443   int PSHUFHMask[4] = {-1, -1, -1, -1};
8444   int PSHUFDMask[4] = {-1, -1, -1, -1};
8445
8446   // First fix the masks for all the inputs that are staying in their
8447   // original halves. This will then dictate the targets of the cross-half
8448   // shuffles.
8449   auto fixInPlaceInputs =
8450       [&PSHUFDMask](ArrayRef<int> InPlaceInputs, ArrayRef<int> IncomingInputs,
8451                     MutableArrayRef<int> SourceHalfMask,
8452                     MutableArrayRef<int> HalfMask, int HalfOffset) {
8453     if (InPlaceInputs.empty())
8454       return;
8455     if (InPlaceInputs.size() == 1) {
8456       SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8457           InPlaceInputs[0] - HalfOffset;
8458       PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
8459       return;
8460     }
8461     if (IncomingInputs.empty()) {
8462       // Just fix all of the in place inputs.
8463       for (int Input : InPlaceInputs) {
8464         SourceHalfMask[Input - HalfOffset] = Input - HalfOffset;
8465         PSHUFDMask[Input / 2] = Input / 2;
8466       }
8467       return;
8468     }
8469
8470     assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!");
8471     SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8472         InPlaceInputs[0] - HalfOffset;
8473     // Put the second input next to the first so that they are packed into
8474     // a dword. We find the adjacent index by toggling the low bit.
8475     int AdjIndex = InPlaceInputs[0] ^ 1;
8476     SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
8477     std::replace(HalfMask.begin(), HalfMask.end(), InPlaceInputs[1], AdjIndex);
8478     PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
8479   };
8480   fixInPlaceInputs(LToLInputs, HToLInputs, PSHUFLMask, LoMask, 0);
8481   fixInPlaceInputs(HToHInputs, LToHInputs, PSHUFHMask, HiMask, 4);
8482
8483   // Now gather the cross-half inputs and place them into a free dword of
8484   // their target half.
8485   // FIXME: This operation could almost certainly be simplified dramatically to
8486   // look more like the 3-1 fixing operation.
8487   auto moveInputsToRightHalf = [&PSHUFDMask](
8488       MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
8489       MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
8490       MutableArrayRef<int> FinalSourceHalfMask, int SourceOffset,
8491       int DestOffset) {
8492     auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
8493       return SourceHalfMask[Word] != -1 && SourceHalfMask[Word] != Word;
8494     };
8495     auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
8496                                                int Word) {
8497       int LowWord = Word & ~1;
8498       int HighWord = Word | 1;
8499       return isWordClobbered(SourceHalfMask, LowWord) ||
8500              isWordClobbered(SourceHalfMask, HighWord);
8501     };
8502
8503     if (IncomingInputs.empty())
8504       return;
8505
8506     if (ExistingInputs.empty()) {
8507       // Map any dwords with inputs from them into the right half.
8508       for (int Input : IncomingInputs) {
8509         // If the source half mask maps over the inputs, turn those into
8510         // swaps and use the swapped lane.
8511         if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
8512           if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] == -1) {
8513             SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
8514                 Input - SourceOffset;
8515             // We have to swap the uses in our half mask in one sweep.
8516             for (int &M : HalfMask)
8517               if (M == SourceHalfMask[Input - SourceOffset] + SourceOffset)
8518                 M = Input;
8519               else if (M == Input)
8520                 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8521           } else {
8522             assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==
8523                        Input - SourceOffset &&
8524                    "Previous placement doesn't match!");
8525           }
8526           // Note that this correctly re-maps both when we do a swap and when
8527           // we observe the other side of the swap above. We rely on that to
8528           // avoid swapping the members of the input list directly.
8529           Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8530         }
8531
8532         // Map the input's dword into the correct half.
8533         if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] == -1)
8534           PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
8535         else
8536           assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==
8537                      Input / 2 &&
8538                  "Previous placement doesn't match!");
8539       }
8540
8541       // And just directly shift any other-half mask elements to be same-half
8542       // as we will have mirrored the dword containing the element into the
8543       // same position within that half.
8544       for (int &M : HalfMask)
8545         if (M >= SourceOffset && M < SourceOffset + 4) {
8546           M = M - SourceOffset + DestOffset;
8547           assert(M >= 0 && "This should never wrap below zero!");
8548         }
8549       return;
8550     }
8551
8552     // Ensure we have the input in a viable dword of its current half. This
8553     // is particularly tricky because the original position may be clobbered
8554     // by inputs being moved and *staying* in that half.
8555     if (IncomingInputs.size() == 1) {
8556       if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8557         int InputFixed = std::find(std::begin(SourceHalfMask),
8558                                    std::end(SourceHalfMask), -1) -
8559                          std::begin(SourceHalfMask) + SourceOffset;
8560         SourceHalfMask[InputFixed - SourceOffset] =
8561             IncomingInputs[0] - SourceOffset;
8562         std::replace(HalfMask.begin(), HalfMask.end(), IncomingInputs[0],
8563                      InputFixed);
8564         IncomingInputs[0] = InputFixed;
8565       }
8566     } else if (IncomingInputs.size() == 2) {
8567       if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
8568           isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8569         // We have two non-adjacent or clobbered inputs we need to extract from
8570         // the source half. To do this, we need to map them into some adjacent
8571         // dword slot in the source mask.
8572         int InputsFixed[2] = {IncomingInputs[0] - SourceOffset,
8573                               IncomingInputs[1] - SourceOffset};
8574
8575         // If there is a free slot in the source half mask adjacent to one of
8576         // the inputs, place the other input in it. We use (Index XOR 1) to
8577         // compute an adjacent index.
8578         if (!isWordClobbered(SourceHalfMask, InputsFixed[0]) &&
8579             SourceHalfMask[InputsFixed[0] ^ 1] == -1) {
8580           SourceHalfMask[InputsFixed[0]] = InputsFixed[0];
8581           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8582           InputsFixed[1] = InputsFixed[0] ^ 1;
8583         } else if (!isWordClobbered(SourceHalfMask, InputsFixed[1]) &&
8584                    SourceHalfMask[InputsFixed[1] ^ 1] == -1) {
8585           SourceHalfMask[InputsFixed[1]] = InputsFixed[1];
8586           SourceHalfMask[InputsFixed[1] ^ 1] = InputsFixed[0];
8587           InputsFixed[0] = InputsFixed[1] ^ 1;
8588         } else if (SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] == -1 &&
8589                    SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] == -1) {
8590           // The two inputs are in the same DWord but it is clobbered and the
8591           // adjacent DWord isn't used at all. Move both inputs to the free
8592           // slot.
8593           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] = InputsFixed[0];
8594           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] = InputsFixed[1];
8595           InputsFixed[0] = 2 * ((InputsFixed[0] / 2) ^ 1);
8596           InputsFixed[1] = 2 * ((InputsFixed[0] / 2) ^ 1) + 1;
8597         } else {
8598           // The only way we hit this point is if there is no clobbering
8599           // (because there are no off-half inputs to this half) and there is no
8600           // free slot adjacent to one of the inputs. In this case, we have to
8601           // swap an input with a non-input.
8602           for (int i = 0; i < 4; ++i)
8603             assert((SourceHalfMask[i] == -1 || SourceHalfMask[i] == i) &&
8604                    "We can't handle any clobbers here!");
8605           assert(InputsFixed[1] != (InputsFixed[0] ^ 1) &&
8606                  "Cannot have adjacent inputs here!");
8607
8608           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8609           SourceHalfMask[InputsFixed[1]] = InputsFixed[0] ^ 1;
8610
8611           // We also have to update the final source mask in this case because
8612           // it may need to undo the above swap.
8613           for (int &M : FinalSourceHalfMask)
8614             if (M == (InputsFixed[0] ^ 1) + SourceOffset)
8615               M = InputsFixed[1] + SourceOffset;
8616             else if (M == InputsFixed[1] + SourceOffset)
8617               M = (InputsFixed[0] ^ 1) + SourceOffset;
8618
8619           InputsFixed[1] = InputsFixed[0] ^ 1;
8620         }
8621
8622         // Point everything at the fixed inputs.
8623         for (int &M : HalfMask)
8624           if (M == IncomingInputs[0])
8625             M = InputsFixed[0] + SourceOffset;
8626           else if (M == IncomingInputs[1])
8627             M = InputsFixed[1] + SourceOffset;
8628
8629         IncomingInputs[0] = InputsFixed[0] + SourceOffset;
8630         IncomingInputs[1] = InputsFixed[1] + SourceOffset;
8631       }
8632     } else {
8633       llvm_unreachable("Unhandled input size!");
8634     }
8635
8636     // Now hoist the DWord down to the right half.
8637     int FreeDWord = (PSHUFDMask[DestOffset / 2] == -1 ? 0 : 1) + DestOffset / 2;
8638     assert(PSHUFDMask[FreeDWord] == -1 && "DWord not free");
8639     PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
8640     for (int &M : HalfMask)
8641       for (int Input : IncomingInputs)
8642         if (M == Input)
8643           M = FreeDWord * 2 + Input % 2;
8644   };
8645   moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask, HiMask,
8646                         /*SourceOffset*/ 4, /*DestOffset*/ 0);
8647   moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask, LoMask,
8648                         /*SourceOffset*/ 0, /*DestOffset*/ 4);
8649
8650   // Now enact all the shuffles we've computed to move the inputs into their
8651   // target half.
8652   if (!isNoopShuffleMask(PSHUFLMask))
8653     V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
8654                     getV4X86ShuffleImm8ForMask(PSHUFLMask, DL, DAG));
8655   if (!isNoopShuffleMask(PSHUFHMask))
8656     V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
8657                     getV4X86ShuffleImm8ForMask(PSHUFHMask, DL, DAG));
8658   if (!isNoopShuffleMask(PSHUFDMask))
8659     V = DAG.getBitcast(
8660         VT,
8661         DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, DAG.getBitcast(PSHUFDVT, V),
8662                     getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
8663
8664   // At this point, each half should contain all its inputs, and we can then
8665   // just shuffle them into their final position.
8666   assert(std::count_if(LoMask.begin(), LoMask.end(),
8667                        [](int M) { return M >= 4; }) == 0 &&
8668          "Failed to lift all the high half inputs to the low mask!");
8669   assert(std::count_if(HiMask.begin(), HiMask.end(),
8670                        [](int M) { return M >= 0 && M < 4; }) == 0 &&
8671          "Failed to lift all the low half inputs to the high mask!");
8672
8673   // Do a half shuffle for the low mask.
8674   if (!isNoopShuffleMask(LoMask))
8675     V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
8676                     getV4X86ShuffleImm8ForMask(LoMask, DL, DAG));
8677
8678   // Do a half shuffle with the high mask after shifting its values down.
8679   for (int &M : HiMask)
8680     if (M >= 0)
8681       M -= 4;
8682   if (!isNoopShuffleMask(HiMask))
8683     V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
8684                     getV4X86ShuffleImm8ForMask(HiMask, DL, DAG));
8685
8686   return V;
8687 }
8688
8689 /// \brief Helper to form a PSHUFB-based shuffle+blend.
8690 static SDValue lowerVectorShuffleAsPSHUFB(SDLoc DL, MVT VT, SDValue V1,
8691                                           SDValue V2, ArrayRef<int> Mask,
8692                                           SelectionDAG &DAG, bool &V1InUse,
8693                                           bool &V2InUse) {
8694   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
8695   SDValue V1Mask[16];
8696   SDValue V2Mask[16];
8697   V1InUse = false;
8698   V2InUse = false;
8699
8700   int Size = Mask.size();
8701   int Scale = 16 / Size;
8702   for (int i = 0; i < 16; ++i) {
8703     if (Mask[i / Scale] == -1) {
8704       V1Mask[i] = V2Mask[i] = DAG.getUNDEF(MVT::i8);
8705     } else {
8706       const int ZeroMask = 0x80;
8707       int V1Idx = Mask[i / Scale] < Size ? Mask[i / Scale] * Scale + i % Scale
8708                                           : ZeroMask;
8709       int V2Idx = Mask[i / Scale] < Size
8710                       ? ZeroMask
8711                       : (Mask[i / Scale] - Size) * Scale + i % Scale;
8712       if (Zeroable[i / Scale])
8713         V1Idx = V2Idx = ZeroMask;
8714       V1Mask[i] = DAG.getConstant(V1Idx, DL, MVT::i8);
8715       V2Mask[i] = DAG.getConstant(V2Idx, DL, MVT::i8);
8716       V1InUse |= (ZeroMask != V1Idx);
8717       V2InUse |= (ZeroMask != V2Idx);
8718     }
8719   }
8720
8721   if (V1InUse)
8722     V1 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
8723                      DAG.getBitcast(MVT::v16i8, V1),
8724                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V1Mask));
8725   if (V2InUse)
8726     V2 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
8727                      DAG.getBitcast(MVT::v16i8, V2),
8728                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V2Mask));
8729
8730   // If we need shuffled inputs from both, blend the two.
8731   SDValue V;
8732   if (V1InUse && V2InUse)
8733     V = DAG.getNode(ISD::OR, DL, MVT::v16i8, V1, V2);
8734   else
8735     V = V1InUse ? V1 : V2;
8736
8737   // Cast the result back to the correct type.
8738   return DAG.getBitcast(VT, V);
8739 }
8740
8741 /// \brief Generic lowering of 8-lane i16 shuffles.
8742 ///
8743 /// This handles both single-input shuffles and combined shuffle/blends with
8744 /// two inputs. The single input shuffles are immediately delegated to
8745 /// a dedicated lowering routine.
8746 ///
8747 /// The blends are lowered in one of three fundamental ways. If there are few
8748 /// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
8749 /// of the input is significantly cheaper when lowered as an interleaving of
8750 /// the two inputs, try to interleave them. Otherwise, blend the low and high
8751 /// halves of the inputs separately (making them have relatively few inputs)
8752 /// and then concatenate them.
8753 static SDValue lowerV8I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8754                                        const X86Subtarget *Subtarget,
8755                                        SelectionDAG &DAG) {
8756   SDLoc DL(Op);
8757   assert(Op.getSimpleValueType() == MVT::v8i16 && "Bad shuffle type!");
8758   assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
8759   assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
8760   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8761   ArrayRef<int> OrigMask = SVOp->getMask();
8762   int MaskStorage[8] = {OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
8763                         OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7]};
8764   MutableArrayRef<int> Mask(MaskStorage);
8765
8766   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
8767
8768   // Whenever we can lower this as a zext, that instruction is strictly faster
8769   // than any alternative.
8770   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
8771           DL, MVT::v8i16, V1, V2, OrigMask, Subtarget, DAG))
8772     return ZExt;
8773
8774   auto isV1 = [](int M) { return M >= 0 && M < 8; };
8775   (void)isV1;
8776   auto isV2 = [](int M) { return M >= 8; };
8777
8778   int NumV2Inputs = std::count_if(Mask.begin(), Mask.end(), isV2);
8779
8780   if (NumV2Inputs == 0) {
8781     // Check for being able to broadcast a single element.
8782     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i16, V1,
8783                                                           Mask, Subtarget, DAG))
8784       return Broadcast;
8785
8786     // Try to use shift instructions.
8787     if (SDValue Shift =
8788             lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V1, Mask, DAG))
8789       return Shift;
8790
8791     // Use dedicated unpack instructions for masks that match their pattern.
8792     if (isShuffleEquivalent(V1, V1, Mask, {0, 0, 1, 1, 2, 2, 3, 3}))
8793       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V1, V1);
8794     if (isShuffleEquivalent(V1, V1, Mask, {4, 4, 5, 5, 6, 6, 7, 7}))
8795       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V1, V1);
8796
8797     // Try to use byte rotation instructions.
8798     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(DL, MVT::v8i16, V1, V1,
8799                                                         Mask, Subtarget, DAG))
8800       return Rotate;
8801
8802     return lowerV8I16GeneralSingleInputVectorShuffle(DL, MVT::v8i16, V1, Mask,
8803                                                      Subtarget, DAG);
8804   }
8805
8806   assert(std::any_of(Mask.begin(), Mask.end(), isV1) &&
8807          "All single-input shuffles should be canonicalized to be V1-input "
8808          "shuffles.");
8809
8810   // Try to use shift instructions.
8811   if (SDValue Shift =
8812           lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V2, Mask, DAG))
8813     return Shift;
8814
8815   // See if we can use SSE4A Extraction / Insertion.
8816   if (Subtarget->hasSSE4A())
8817     if (SDValue V = lowerVectorShuffleWithSSE4A(DL, MVT::v8i16, V1, V2, Mask, DAG))
8818       return V;
8819
8820   // There are special ways we can lower some single-element blends.
8821   if (NumV2Inputs == 1)
8822     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v8i16, V1, V2,
8823                                                          Mask, Subtarget, DAG))
8824       return V;
8825
8826   // We have different paths for blend lowering, but they all must use the
8827   // *exact* same predicate.
8828   bool IsBlendSupported = Subtarget->hasSSE41();
8829   if (IsBlendSupported)
8830     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i16, V1, V2, Mask,
8831                                                   Subtarget, DAG))
8832       return Blend;
8833
8834   if (SDValue Masked =
8835           lowerVectorShuffleAsBitMask(DL, MVT::v8i16, V1, V2, Mask, DAG))
8836     return Masked;
8837
8838   // Use dedicated unpack instructions for masks that match their pattern.
8839   if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 2, 10, 3, 11}))
8840     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V1, V2);
8841   if (isShuffleEquivalent(V1, V2, Mask, {4, 12, 5, 13, 6, 14, 7, 15}))
8842     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V1, V2);
8843
8844   // Try to use byte rotation instructions.
8845   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8846           DL, MVT::v8i16, V1, V2, Mask, Subtarget, DAG))
8847     return Rotate;
8848
8849   if (SDValue BitBlend =
8850           lowerVectorShuffleAsBitBlend(DL, MVT::v8i16, V1, V2, Mask, DAG))
8851     return BitBlend;
8852
8853   if (SDValue Unpack =
8854           lowerVectorShuffleAsUnpack(DL, MVT::v8i16, V1, V2, Mask, DAG))
8855     return Unpack;
8856
8857   // If we can't directly blend but can use PSHUFB, that will be better as it
8858   // can both shuffle and set up the inefficient blend.
8859   if (!IsBlendSupported && Subtarget->hasSSSE3()) {
8860     bool V1InUse, V2InUse;
8861     return lowerVectorShuffleAsPSHUFB(DL, MVT::v8i16, V1, V2, Mask, DAG,
8862                                       V1InUse, V2InUse);
8863   }
8864
8865   // We can always bit-blend if we have to so the fallback strategy is to
8866   // decompose into single-input permutes and blends.
8867   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i16, V1, V2,
8868                                                       Mask, DAG);
8869 }
8870
8871 /// \brief Check whether a compaction lowering can be done by dropping even
8872 /// elements and compute how many times even elements must be dropped.
8873 ///
8874 /// This handles shuffles which take every Nth element where N is a power of
8875 /// two. Example shuffle masks:
8876 ///
8877 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14,  0,  2,  4,  6,  8, 10, 12, 14
8878 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30
8879 ///  N = 2:  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12
8880 ///  N = 2:  0,  4,  8, 12, 16, 20, 24, 28,  0,  4,  8, 12, 16, 20, 24, 28
8881 ///  N = 3:  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8
8882 ///  N = 3:  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24
8883 ///
8884 /// Any of these lanes can of course be undef.
8885 ///
8886 /// This routine only supports N <= 3.
8887 /// FIXME: Evaluate whether either AVX or AVX-512 have any opportunities here
8888 /// for larger N.
8889 ///
8890 /// \returns N above, or the number of times even elements must be dropped if
8891 /// there is such a number. Otherwise returns zero.
8892 static int canLowerByDroppingEvenElements(ArrayRef<int> Mask) {
8893   // Figure out whether we're looping over two inputs or just one.
8894   bool IsSingleInput = isSingleInputShuffleMask(Mask);
8895
8896   // The modulus for the shuffle vector entries is based on whether this is
8897   // a single input or not.
8898   int ShuffleModulus = Mask.size() * (IsSingleInput ? 1 : 2);
8899   assert(isPowerOf2_32((uint32_t)ShuffleModulus) &&
8900          "We should only be called with masks with a power-of-2 size!");
8901
8902   uint64_t ModMask = (uint64_t)ShuffleModulus - 1;
8903
8904   // We track whether the input is viable for all power-of-2 strides 2^1, 2^2,
8905   // and 2^3 simultaneously. This is because we may have ambiguity with
8906   // partially undef inputs.
8907   bool ViableForN[3] = {true, true, true};
8908
8909   for (int i = 0, e = Mask.size(); i < e; ++i) {
8910     // Ignore undef lanes, we'll optimistically collapse them to the pattern we
8911     // want.
8912     if (Mask[i] == -1)
8913       continue;
8914
8915     bool IsAnyViable = false;
8916     for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
8917       if (ViableForN[j]) {
8918         uint64_t N = j + 1;
8919
8920         // The shuffle mask must be equal to (i * 2^N) % M.
8921         if ((uint64_t)Mask[i] == (((uint64_t)i << N) & ModMask))
8922           IsAnyViable = true;
8923         else
8924           ViableForN[j] = false;
8925       }
8926     // Early exit if we exhaust the possible powers of two.
8927     if (!IsAnyViable)
8928       break;
8929   }
8930
8931   for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
8932     if (ViableForN[j])
8933       return j + 1;
8934
8935   // Return 0 as there is no viable power of two.
8936   return 0;
8937 }
8938
8939 /// \brief Generic lowering of v16i8 shuffles.
8940 ///
8941 /// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
8942 /// detect any complexity reducing interleaving. If that doesn't help, it uses
8943 /// UNPCK to spread the i8 elements across two i16-element vectors, and uses
8944 /// the existing lowering for v8i16 blends on each half, finally PACK-ing them
8945 /// back together.
8946 static SDValue lowerV16I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8947                                        const X86Subtarget *Subtarget,
8948                                        SelectionDAG &DAG) {
8949   SDLoc DL(Op);
8950   assert(Op.getSimpleValueType() == MVT::v16i8 && "Bad shuffle type!");
8951   assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
8952   assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
8953   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8954   ArrayRef<int> Mask = SVOp->getMask();
8955   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
8956
8957   // Try to use shift instructions.
8958   if (SDValue Shift =
8959           lowerVectorShuffleAsShift(DL, MVT::v16i8, V1, V2, Mask, DAG))
8960     return Shift;
8961
8962   // Try to use byte rotation instructions.
8963   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8964           DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
8965     return Rotate;
8966
8967   // Try to use a zext lowering.
8968   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
8969           DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
8970     return ZExt;
8971
8972   // See if we can use SSE4A Extraction / Insertion.
8973   if (Subtarget->hasSSE4A())
8974     if (SDValue V = lowerVectorShuffleWithSSE4A(DL, MVT::v16i8, V1, V2, Mask, DAG))
8975       return V;
8976
8977   int NumV2Elements =
8978       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 16; });
8979
8980   // For single-input shuffles, there are some nicer lowering tricks we can use.
8981   if (NumV2Elements == 0) {
8982     // Check for being able to broadcast a single element.
8983     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i8, V1,
8984                                                           Mask, Subtarget, DAG))
8985       return Broadcast;
8986
8987     // Check whether we can widen this to an i16 shuffle by duplicating bytes.
8988     // Notably, this handles splat and partial-splat shuffles more efficiently.
8989     // However, it only makes sense if the pre-duplication shuffle simplifies
8990     // things significantly. Currently, this means we need to be able to
8991     // express the pre-duplication shuffle as an i16 shuffle.
8992     //
8993     // FIXME: We should check for other patterns which can be widened into an
8994     // i16 shuffle as well.
8995     auto canWidenViaDuplication = [](ArrayRef<int> Mask) {
8996       for (int i = 0; i < 16; i += 2)
8997         if (Mask[i] != -1 && Mask[i + 1] != -1 && Mask[i] != Mask[i + 1])
8998           return false;
8999
9000       return true;
9001     };
9002     auto tryToWidenViaDuplication = [&]() -> SDValue {
9003       if (!canWidenViaDuplication(Mask))
9004         return SDValue();
9005       SmallVector<int, 4> LoInputs;
9006       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(LoInputs),
9007                    [](int M) { return M >= 0 && M < 8; });
9008       std::sort(LoInputs.begin(), LoInputs.end());
9009       LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()),
9010                      LoInputs.end());
9011       SmallVector<int, 4> HiInputs;
9012       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(HiInputs),
9013                    [](int M) { return M >= 8; });
9014       std::sort(HiInputs.begin(), HiInputs.end());
9015       HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()),
9016                      HiInputs.end());
9017
9018       bool TargetLo = LoInputs.size() >= HiInputs.size();
9019       ArrayRef<int> InPlaceInputs = TargetLo ? LoInputs : HiInputs;
9020       ArrayRef<int> MovingInputs = TargetLo ? HiInputs : LoInputs;
9021
9022       int PreDupI16Shuffle[] = {-1, -1, -1, -1, -1, -1, -1, -1};
9023       SmallDenseMap<int, int, 8> LaneMap;
9024       for (int I : InPlaceInputs) {
9025         PreDupI16Shuffle[I/2] = I/2;
9026         LaneMap[I] = I;
9027       }
9028       int j = TargetLo ? 0 : 4, je = j + 4;
9029       for (int i = 0, ie = MovingInputs.size(); i < ie; ++i) {
9030         // Check if j is already a shuffle of this input. This happens when
9031         // there are two adjacent bytes after we move the low one.
9032         if (PreDupI16Shuffle[j] != MovingInputs[i] / 2) {
9033           // If we haven't yet mapped the input, search for a slot into which
9034           // we can map it.
9035           while (j < je && PreDupI16Shuffle[j] != -1)
9036             ++j;
9037
9038           if (j == je)
9039             // We can't place the inputs into a single half with a simple i16 shuffle, so bail.
9040             return SDValue();
9041
9042           // Map this input with the i16 shuffle.
9043           PreDupI16Shuffle[j] = MovingInputs[i] / 2;
9044         }
9045
9046         // Update the lane map based on the mapping we ended up with.
9047         LaneMap[MovingInputs[i]] = 2 * j + MovingInputs[i] % 2;
9048       }
9049       V1 = DAG.getBitcast(
9050           MVT::v16i8,
9051           DAG.getVectorShuffle(MVT::v8i16, DL, DAG.getBitcast(MVT::v8i16, V1),
9052                                DAG.getUNDEF(MVT::v8i16), PreDupI16Shuffle));
9053
9054       // Unpack the bytes to form the i16s that will be shuffled into place.
9055       V1 = DAG.getNode(TargetLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
9056                        MVT::v16i8, V1, V1);
9057
9058       int PostDupI16Shuffle[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9059       for (int i = 0; i < 16; ++i)
9060         if (Mask[i] != -1) {
9061           int MappedMask = LaneMap[Mask[i]] - (TargetLo ? 0 : 8);
9062           assert(MappedMask < 8 && "Invalid v8 shuffle mask!");
9063           if (PostDupI16Shuffle[i / 2] == -1)
9064             PostDupI16Shuffle[i / 2] = MappedMask;
9065           else
9066             assert(PostDupI16Shuffle[i / 2] == MappedMask &&
9067                    "Conflicting entrties in the original shuffle!");
9068         }
9069       return DAG.getBitcast(
9070           MVT::v16i8,
9071           DAG.getVectorShuffle(MVT::v8i16, DL, DAG.getBitcast(MVT::v8i16, V1),
9072                                DAG.getUNDEF(MVT::v8i16), PostDupI16Shuffle));
9073     };
9074     if (SDValue V = tryToWidenViaDuplication())
9075       return V;
9076   }
9077
9078   if (SDValue Masked =
9079           lowerVectorShuffleAsBitMask(DL, MVT::v16i8, V1, V2, Mask, DAG))
9080     return Masked;
9081
9082   // Use dedicated unpack instructions for masks that match their pattern.
9083   if (isShuffleEquivalent(V1, V2, Mask, {// Low half.
9084                                          0, 16, 1, 17, 2, 18, 3, 19,
9085                                          // High half.
9086                                          4, 20, 5, 21, 6, 22, 7, 23}))
9087     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V1, V2);
9088   if (isShuffleEquivalent(V1, V2, Mask, {// Low half.
9089                                          8, 24, 9, 25, 10, 26, 11, 27,
9090                                          // High half.
9091                                          12, 28, 13, 29, 14, 30, 15, 31}))
9092     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V1, V2);
9093
9094   // Check for SSSE3 which lets us lower all v16i8 shuffles much more directly
9095   // with PSHUFB. It is important to do this before we attempt to generate any
9096   // blends but after all of the single-input lowerings. If the single input
9097   // lowerings can find an instruction sequence that is faster than a PSHUFB, we
9098   // want to preserve that and we can DAG combine any longer sequences into
9099   // a PSHUFB in the end. But once we start blending from multiple inputs,
9100   // the complexity of DAG combining bad patterns back into PSHUFB is too high,
9101   // and there are *very* few patterns that would actually be faster than the
9102   // PSHUFB approach because of its ability to zero lanes.
9103   //
9104   // FIXME: The only exceptions to the above are blends which are exact
9105   // interleavings with direct instructions supporting them. We currently don't
9106   // handle those well here.
9107   if (Subtarget->hasSSSE3()) {
9108     bool V1InUse = false;
9109     bool V2InUse = false;
9110
9111     SDValue PSHUFB = lowerVectorShuffleAsPSHUFB(DL, MVT::v16i8, V1, V2, Mask,
9112                                                 DAG, V1InUse, V2InUse);
9113
9114     // If both V1 and V2 are in use and we can use a direct blend or an unpack,
9115     // do so. This avoids using them to handle blends-with-zero which is
9116     // important as a single pshufb is significantly faster for that.
9117     if (V1InUse && V2InUse) {
9118       if (Subtarget->hasSSE41())
9119         if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i8, V1, V2,
9120                                                       Mask, Subtarget, DAG))
9121           return Blend;
9122
9123       // We can use an unpack to do the blending rather than an or in some
9124       // cases. Even though the or may be (very minorly) more efficient, we
9125       // preference this lowering because there are common cases where part of
9126       // the complexity of the shuffles goes away when we do the final blend as
9127       // an unpack.
9128       // FIXME: It might be worth trying to detect if the unpack-feeding
9129       // shuffles will both be pshufb, in which case we shouldn't bother with
9130       // this.
9131       if (SDValue Unpack =
9132               lowerVectorShuffleAsUnpack(DL, MVT::v16i8, V1, V2, Mask, DAG))
9133         return Unpack;
9134     }
9135
9136     return PSHUFB;
9137   }
9138
9139   // There are special ways we can lower some single-element blends.
9140   if (NumV2Elements == 1)
9141     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v16i8, V1, V2,
9142                                                          Mask, Subtarget, DAG))
9143       return V;
9144
9145   if (SDValue BitBlend =
9146           lowerVectorShuffleAsBitBlend(DL, MVT::v16i8, V1, V2, Mask, DAG))
9147     return BitBlend;
9148
9149   // Check whether a compaction lowering can be done. This handles shuffles
9150   // which take every Nth element for some even N. See the helper function for
9151   // details.
9152   //
9153   // We special case these as they can be particularly efficiently handled with
9154   // the PACKUSB instruction on x86 and they show up in common patterns of
9155   // rearranging bytes to truncate wide elements.
9156   if (int NumEvenDrops = canLowerByDroppingEvenElements(Mask)) {
9157     // NumEvenDrops is the power of two stride of the elements. Another way of
9158     // thinking about it is that we need to drop the even elements this many
9159     // times to get the original input.
9160     bool IsSingleInput = isSingleInputShuffleMask(Mask);
9161
9162     // First we need to zero all the dropped bytes.
9163     assert(NumEvenDrops <= 3 &&
9164            "No support for dropping even elements more than 3 times.");
9165     // We use the mask type to pick which bytes are preserved based on how many
9166     // elements are dropped.
9167     MVT MaskVTs[] = { MVT::v8i16, MVT::v4i32, MVT::v2i64 };
9168     SDValue ByteClearMask = DAG.getBitcast(
9169         MVT::v16i8, DAG.getConstant(0xFF, DL, MaskVTs[NumEvenDrops - 1]));
9170     V1 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V1, ByteClearMask);
9171     if (!IsSingleInput)
9172       V2 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V2, ByteClearMask);
9173
9174     // Now pack things back together.
9175     V1 = DAG.getBitcast(MVT::v8i16, V1);
9176     V2 = IsSingleInput ? V1 : DAG.getBitcast(MVT::v8i16, V2);
9177     SDValue Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, V1, V2);
9178     for (int i = 1; i < NumEvenDrops; ++i) {
9179       Result = DAG.getBitcast(MVT::v8i16, Result);
9180       Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, Result, Result);
9181     }
9182
9183     return Result;
9184   }
9185
9186   // Handle multi-input cases by blending single-input shuffles.
9187   if (NumV2Elements > 0)
9188     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v16i8, V1, V2,
9189                                                       Mask, DAG);
9190
9191   // The fallback path for single-input shuffles widens this into two v8i16
9192   // vectors with unpacks, shuffles those, and then pulls them back together
9193   // with a pack.
9194   SDValue V = V1;
9195
9196   int LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9197   int HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9198   for (int i = 0; i < 16; ++i)
9199     if (Mask[i] >= 0)
9200       (i < 8 ? LoBlendMask[i] : HiBlendMask[i % 8]) = Mask[i];
9201
9202   SDValue Zero = getZeroVector(MVT::v8i16, Subtarget, DAG, DL);
9203
9204   SDValue VLoHalf, VHiHalf;
9205   // Check if any of the odd lanes in the v16i8 are used. If not, we can mask
9206   // them out and avoid using UNPCK{L,H} to extract the elements of V as
9207   // i16s.
9208   if (std::none_of(std::begin(LoBlendMask), std::end(LoBlendMask),
9209                    [](int M) { return M >= 0 && M % 2 == 1; }) &&
9210       std::none_of(std::begin(HiBlendMask), std::end(HiBlendMask),
9211                    [](int M) { return M >= 0 && M % 2 == 1; })) {
9212     // Use a mask to drop the high bytes.
9213     VLoHalf = DAG.getBitcast(MVT::v8i16, V);
9214     VLoHalf = DAG.getNode(ISD::AND, DL, MVT::v8i16, VLoHalf,
9215                      DAG.getConstant(0x00FF, DL, MVT::v8i16));
9216
9217     // This will be a single vector shuffle instead of a blend so nuke VHiHalf.
9218     VHiHalf = DAG.getUNDEF(MVT::v8i16);
9219
9220     // Squash the masks to point directly into VLoHalf.
9221     for (int &M : LoBlendMask)
9222       if (M >= 0)
9223         M /= 2;
9224     for (int &M : HiBlendMask)
9225       if (M >= 0)
9226         M /= 2;
9227   } else {
9228     // Otherwise just unpack the low half of V into VLoHalf and the high half into
9229     // VHiHalf so that we can blend them as i16s.
9230     VLoHalf = DAG.getBitcast(
9231         MVT::v8i16, DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V, Zero));
9232     VHiHalf = DAG.getBitcast(
9233         MVT::v8i16, DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V, Zero));
9234   }
9235
9236   SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, LoBlendMask);
9237   SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, HiBlendMask);
9238
9239   return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
9240 }
9241
9242 /// \brief Dispatching routine to lower various 128-bit x86 vector shuffles.
9243 ///
9244 /// This routine breaks down the specific type of 128-bit shuffle and
9245 /// dispatches to the lowering routines accordingly.
9246 static SDValue lower128BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9247                                         MVT VT, const X86Subtarget *Subtarget,
9248                                         SelectionDAG &DAG) {
9249   switch (VT.SimpleTy) {
9250   case MVT::v2i64:
9251     return lowerV2I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9252   case MVT::v2f64:
9253     return lowerV2F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9254   case MVT::v4i32:
9255     return lowerV4I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9256   case MVT::v4f32:
9257     return lowerV4F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9258   case MVT::v8i16:
9259     return lowerV8I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
9260   case MVT::v16i8:
9261     return lowerV16I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
9262
9263   default:
9264     llvm_unreachable("Unimplemented!");
9265   }
9266 }
9267
9268 /// \brief Helper function to test whether a shuffle mask could be
9269 /// simplified by widening the elements being shuffled.
9270 ///
9271 /// Appends the mask for wider elements in WidenedMask if valid. Otherwise
9272 /// leaves it in an unspecified state.
9273 ///
9274 /// NOTE: This must handle normal vector shuffle masks and *target* vector
9275 /// shuffle masks. The latter have the special property of a '-2' representing
9276 /// a zero-ed lane of a vector.
9277 static bool canWidenShuffleElements(ArrayRef<int> Mask,
9278                                     SmallVectorImpl<int> &WidenedMask) {
9279   for (int i = 0, Size = Mask.size(); i < Size; i += 2) {
9280     // If both elements are undef, its trivial.
9281     if (Mask[i] == SM_SentinelUndef && Mask[i + 1] == SM_SentinelUndef) {
9282       WidenedMask.push_back(SM_SentinelUndef);
9283       continue;
9284     }
9285
9286     // Check for an undef mask and a mask value properly aligned to fit with
9287     // a pair of values. If we find such a case, use the non-undef mask's value.
9288     if (Mask[i] == SM_SentinelUndef && Mask[i + 1] >= 0 && Mask[i + 1] % 2 == 1) {
9289       WidenedMask.push_back(Mask[i + 1] / 2);
9290       continue;
9291     }
9292     if (Mask[i + 1] == SM_SentinelUndef && Mask[i] >= 0 && Mask[i] % 2 == 0) {
9293       WidenedMask.push_back(Mask[i] / 2);
9294       continue;
9295     }
9296
9297     // When zeroing, we need to spread the zeroing across both lanes to widen.
9298     if (Mask[i] == SM_SentinelZero || Mask[i + 1] == SM_SentinelZero) {
9299       if ((Mask[i] == SM_SentinelZero || Mask[i] == SM_SentinelUndef) &&
9300           (Mask[i + 1] == SM_SentinelZero || Mask[i + 1] == SM_SentinelUndef)) {
9301         WidenedMask.push_back(SM_SentinelZero);
9302         continue;
9303       }
9304       return false;
9305     }
9306
9307     // Finally check if the two mask values are adjacent and aligned with
9308     // a pair.
9309     if (Mask[i] != SM_SentinelUndef && Mask[i] % 2 == 0 && Mask[i] + 1 == Mask[i + 1]) {
9310       WidenedMask.push_back(Mask[i] / 2);
9311       continue;
9312     }
9313
9314     // Otherwise we can't safely widen the elements used in this shuffle.
9315     return false;
9316   }
9317   assert(WidenedMask.size() == Mask.size() / 2 &&
9318          "Incorrect size of mask after widening the elements!");
9319
9320   return true;
9321 }
9322
9323 /// \brief Generic routine to split vector shuffle into half-sized shuffles.
9324 ///
9325 /// This routine just extracts two subvectors, shuffles them independently, and
9326 /// then concatenates them back together. This should work effectively with all
9327 /// AVX vector shuffle types.
9328 static SDValue splitAndLowerVectorShuffle(SDLoc DL, MVT VT, SDValue V1,
9329                                           SDValue V2, ArrayRef<int> Mask,
9330                                           SelectionDAG &DAG) {
9331   assert(VT.getSizeInBits() >= 256 &&
9332          "Only for 256-bit or wider vector shuffles!");
9333   assert(V1.getSimpleValueType() == VT && "Bad operand type!");
9334   assert(V2.getSimpleValueType() == VT && "Bad operand type!");
9335
9336   ArrayRef<int> LoMask = Mask.slice(0, Mask.size() / 2);
9337   ArrayRef<int> HiMask = Mask.slice(Mask.size() / 2);
9338
9339   int NumElements = VT.getVectorNumElements();
9340   int SplitNumElements = NumElements / 2;
9341   MVT ScalarVT = VT.getScalarType();
9342   MVT SplitVT = MVT::getVectorVT(ScalarVT, NumElements / 2);
9343
9344   // Rather than splitting build-vectors, just build two narrower build
9345   // vectors. This helps shuffling with splats and zeros.
9346   auto SplitVector = [&](SDValue V) {
9347     while (V.getOpcode() == ISD::BITCAST)
9348       V = V->getOperand(0);
9349
9350     MVT OrigVT = V.getSimpleValueType();
9351     int OrigNumElements = OrigVT.getVectorNumElements();
9352     int OrigSplitNumElements = OrigNumElements / 2;
9353     MVT OrigScalarVT = OrigVT.getScalarType();
9354     MVT OrigSplitVT = MVT::getVectorVT(OrigScalarVT, OrigNumElements / 2);
9355
9356     SDValue LoV, HiV;
9357
9358     auto *BV = dyn_cast<BuildVectorSDNode>(V);
9359     if (!BV) {
9360       LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
9361                         DAG.getIntPtrConstant(0, DL));
9362       HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
9363                         DAG.getIntPtrConstant(OrigSplitNumElements, DL));
9364     } else {
9365
9366       SmallVector<SDValue, 16> LoOps, HiOps;
9367       for (int i = 0; i < OrigSplitNumElements; ++i) {
9368         LoOps.push_back(BV->getOperand(i));
9369         HiOps.push_back(BV->getOperand(i + OrigSplitNumElements));
9370       }
9371       LoV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, LoOps);
9372       HiV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, HiOps);
9373     }
9374     return std::make_pair(DAG.getBitcast(SplitVT, LoV),
9375                           DAG.getBitcast(SplitVT, HiV));
9376   };
9377
9378   SDValue LoV1, HiV1, LoV2, HiV2;
9379   std::tie(LoV1, HiV1) = SplitVector(V1);
9380   std::tie(LoV2, HiV2) = SplitVector(V2);
9381
9382   // Now create two 4-way blends of these half-width vectors.
9383   auto HalfBlend = [&](ArrayRef<int> HalfMask) {
9384     bool UseLoV1 = false, UseHiV1 = false, UseLoV2 = false, UseHiV2 = false;
9385     SmallVector<int, 32> V1BlendMask, V2BlendMask, BlendMask;
9386     for (int i = 0; i < SplitNumElements; ++i) {
9387       int M = HalfMask[i];
9388       if (M >= NumElements) {
9389         if (M >= NumElements + SplitNumElements)
9390           UseHiV2 = true;
9391         else
9392           UseLoV2 = true;
9393         V2BlendMask.push_back(M - NumElements);
9394         V1BlendMask.push_back(-1);
9395         BlendMask.push_back(SplitNumElements + i);
9396       } else if (M >= 0) {
9397         if (M >= SplitNumElements)
9398           UseHiV1 = true;
9399         else
9400           UseLoV1 = true;
9401         V2BlendMask.push_back(-1);
9402         V1BlendMask.push_back(M);
9403         BlendMask.push_back(i);
9404       } else {
9405         V2BlendMask.push_back(-1);
9406         V1BlendMask.push_back(-1);
9407         BlendMask.push_back(-1);
9408       }
9409     }
9410
9411     // Because the lowering happens after all combining takes place, we need to
9412     // manually combine these blend masks as much as possible so that we create
9413     // a minimal number of high-level vector shuffle nodes.
9414
9415     // First try just blending the halves of V1 or V2.
9416     if (!UseLoV1 && !UseHiV1 && !UseLoV2 && !UseHiV2)
9417       return DAG.getUNDEF(SplitVT);
9418     if (!UseLoV2 && !UseHiV2)
9419       return DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9420     if (!UseLoV1 && !UseHiV1)
9421       return DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9422
9423     SDValue V1Blend, V2Blend;
9424     if (UseLoV1 && UseHiV1) {
9425       V1Blend =
9426         DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9427     } else {
9428       // We only use half of V1 so map the usage down into the final blend mask.
9429       V1Blend = UseLoV1 ? LoV1 : HiV1;
9430       for (int i = 0; i < SplitNumElements; ++i)
9431         if (BlendMask[i] >= 0 && BlendMask[i] < SplitNumElements)
9432           BlendMask[i] = V1BlendMask[i] - (UseLoV1 ? 0 : SplitNumElements);
9433     }
9434     if (UseLoV2 && UseHiV2) {
9435       V2Blend =
9436         DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9437     } else {
9438       // We only use half of V2 so map the usage down into the final blend mask.
9439       V2Blend = UseLoV2 ? LoV2 : HiV2;
9440       for (int i = 0; i < SplitNumElements; ++i)
9441         if (BlendMask[i] >= SplitNumElements)
9442           BlendMask[i] = V2BlendMask[i] + (UseLoV2 ? SplitNumElements : 0);
9443     }
9444     return DAG.getVectorShuffle(SplitVT, DL, V1Blend, V2Blend, BlendMask);
9445   };
9446   SDValue Lo = HalfBlend(LoMask);
9447   SDValue Hi = HalfBlend(HiMask);
9448   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
9449 }
9450
9451 /// \brief Either split a vector in halves or decompose the shuffles and the
9452 /// blend.
9453 ///
9454 /// This is provided as a good fallback for many lowerings of non-single-input
9455 /// shuffles with more than one 128-bit lane. In those cases, we want to select
9456 /// between splitting the shuffle into 128-bit components and stitching those
9457 /// back together vs. extracting the single-input shuffles and blending those
9458 /// results.
9459 static SDValue lowerVectorShuffleAsSplitOrBlend(SDLoc DL, MVT VT, SDValue V1,
9460                                                 SDValue V2, ArrayRef<int> Mask,
9461                                                 SelectionDAG &DAG) {
9462   assert(!isSingleInputShuffleMask(Mask) && "This routine must not be used to "
9463                                             "lower single-input shuffles as it "
9464                                             "could then recurse on itself.");
9465   int Size = Mask.size();
9466
9467   // If this can be modeled as a broadcast of two elements followed by a blend,
9468   // prefer that lowering. This is especially important because broadcasts can
9469   // often fold with memory operands.
9470   auto DoBothBroadcast = [&] {
9471     int V1BroadcastIdx = -1, V2BroadcastIdx = -1;
9472     for (int M : Mask)
9473       if (M >= Size) {
9474         if (V2BroadcastIdx == -1)
9475           V2BroadcastIdx = M - Size;
9476         else if (M - Size != V2BroadcastIdx)
9477           return false;
9478       } else if (M >= 0) {
9479         if (V1BroadcastIdx == -1)
9480           V1BroadcastIdx = M;
9481         else if (M != V1BroadcastIdx)
9482           return false;
9483       }
9484     return true;
9485   };
9486   if (DoBothBroadcast())
9487     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask,
9488                                                       DAG);
9489
9490   // If the inputs all stem from a single 128-bit lane of each input, then we
9491   // split them rather than blending because the split will decompose to
9492   // unusually few instructions.
9493   int LaneCount = VT.getSizeInBits() / 128;
9494   int LaneSize = Size / LaneCount;
9495   SmallBitVector LaneInputs[2];
9496   LaneInputs[0].resize(LaneCount, false);
9497   LaneInputs[1].resize(LaneCount, false);
9498   for (int i = 0; i < Size; ++i)
9499     if (Mask[i] >= 0)
9500       LaneInputs[Mask[i] / Size][(Mask[i] % Size) / LaneSize] = true;
9501   if (LaneInputs[0].count() <= 1 && LaneInputs[1].count() <= 1)
9502     return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9503
9504   // Otherwise, just fall back to decomposed shuffles and a blend. This requires
9505   // that the decomposed single-input shuffles don't end up here.
9506   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9507 }
9508
9509 /// \brief Lower a vector shuffle crossing multiple 128-bit lanes as
9510 /// a permutation and blend of those lanes.
9511 ///
9512 /// This essentially blends the out-of-lane inputs to each lane into the lane
9513 /// from a permuted copy of the vector. This lowering strategy results in four
9514 /// instructions in the worst case for a single-input cross lane shuffle which
9515 /// is lower than any other fully general cross-lane shuffle strategy I'm aware
9516 /// of. Special cases for each particular shuffle pattern should be handled
9517 /// prior to trying this lowering.
9518 static SDValue lowerVectorShuffleAsLanePermuteAndBlend(SDLoc DL, MVT VT,
9519                                                        SDValue V1, SDValue V2,
9520                                                        ArrayRef<int> Mask,
9521                                                        SelectionDAG &DAG) {
9522   // FIXME: This should probably be generalized for 512-bit vectors as well.
9523   assert(VT.getSizeInBits() == 256 && "Only for 256-bit vector shuffles!");
9524   int LaneSize = Mask.size() / 2;
9525
9526   // If there are only inputs from one 128-bit lane, splitting will in fact be
9527   // less expensive. The flags track whether the given lane contains an element
9528   // that crosses to another lane.
9529   bool LaneCrossing[2] = {false, false};
9530   for (int i = 0, Size = Mask.size(); i < Size; ++i)
9531     if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
9532       LaneCrossing[(Mask[i] % Size) / LaneSize] = true;
9533   if (!LaneCrossing[0] || !LaneCrossing[1])
9534     return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9535
9536   if (isSingleInputShuffleMask(Mask)) {
9537     SmallVector<int, 32> FlippedBlendMask;
9538     for (int i = 0, Size = Mask.size(); i < Size; ++i)
9539       FlippedBlendMask.push_back(
9540           Mask[i] < 0 ? -1 : (((Mask[i] % Size) / LaneSize == i / LaneSize)
9541                                   ? Mask[i]
9542                                   : Mask[i] % LaneSize +
9543                                         (i / LaneSize) * LaneSize + Size));
9544
9545     // Flip the vector, and blend the results which should now be in-lane. The
9546     // VPERM2X128 mask uses the low 2 bits for the low source and bits 4 and
9547     // 5 for the high source. The value 3 selects the high half of source 2 and
9548     // the value 2 selects the low half of source 2. We only use source 2 to
9549     // allow folding it into a memory operand.
9550     unsigned PERMMask = 3 | 2 << 4;
9551     SDValue Flipped = DAG.getNode(X86ISD::VPERM2X128, DL, VT, DAG.getUNDEF(VT),
9552                                   V1, DAG.getConstant(PERMMask, DL, MVT::i8));
9553     return DAG.getVectorShuffle(VT, DL, V1, Flipped, FlippedBlendMask);
9554   }
9555
9556   // This now reduces to two single-input shuffles of V1 and V2 which at worst
9557   // will be handled by the above logic and a blend of the results, much like
9558   // other patterns in AVX.
9559   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9560 }
9561
9562 /// \brief Handle lowering 2-lane 128-bit shuffles.
9563 static SDValue lowerV2X128VectorShuffle(SDLoc DL, MVT VT, SDValue V1,
9564                                         SDValue V2, ArrayRef<int> Mask,
9565                                         const X86Subtarget *Subtarget,
9566                                         SelectionDAG &DAG) {
9567   // TODO: If minimizing size and one of the inputs is a zero vector and the
9568   // the zero vector has only one use, we could use a VPERM2X128 to save the
9569   // instruction bytes needed to explicitly generate the zero vector.
9570
9571   // Blends are faster and handle all the non-lane-crossing cases.
9572   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, VT, V1, V2, Mask,
9573                                                 Subtarget, DAG))
9574     return Blend;
9575
9576   bool IsV1Zero = ISD::isBuildVectorAllZeros(V1.getNode());
9577   bool IsV2Zero = ISD::isBuildVectorAllZeros(V2.getNode());
9578
9579   // If either input operand is a zero vector, use VPERM2X128 because its mask
9580   // allows us to replace the zero input with an implicit zero.
9581   if (!IsV1Zero && !IsV2Zero) {
9582     // Check for patterns which can be matched with a single insert of a 128-bit
9583     // subvector.
9584     bool OnlyUsesV1 = isShuffleEquivalent(V1, V2, Mask, {0, 1, 0, 1});
9585     if (OnlyUsesV1 || isShuffleEquivalent(V1, V2, Mask, {0, 1, 4, 5})) {
9586       MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(),
9587                                    VT.getVectorNumElements() / 2);
9588       SDValue LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V1,
9589                                 DAG.getIntPtrConstant(0, DL));
9590       SDValue HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT,
9591                                 OnlyUsesV1 ? V1 : V2,
9592                                 DAG.getIntPtrConstant(0, DL));
9593       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LoV, HiV);
9594     }
9595   }
9596
9597   // Otherwise form a 128-bit permutation. After accounting for undefs,
9598   // convert the 64-bit shuffle mask selection values into 128-bit
9599   // selection bits by dividing the indexes by 2 and shifting into positions
9600   // defined by a vperm2*128 instruction's immediate control byte.
9601
9602   // The immediate permute control byte looks like this:
9603   //    [1:0] - select 128 bits from sources for low half of destination
9604   //    [2]   - ignore
9605   //    [3]   - zero low half of destination
9606   //    [5:4] - select 128 bits from sources for high half of destination
9607   //    [6]   - ignore
9608   //    [7]   - zero high half of destination
9609
9610   int MaskLO = Mask[0];
9611   if (MaskLO == SM_SentinelUndef)
9612     MaskLO = Mask[1] == SM_SentinelUndef ? 0 : Mask[1];
9613
9614   int MaskHI = Mask[2];
9615   if (MaskHI == SM_SentinelUndef)
9616     MaskHI = Mask[3] == SM_SentinelUndef ? 0 : Mask[3];
9617
9618   unsigned PermMask = MaskLO / 2 | (MaskHI / 2) << 4;
9619
9620   // If either input is a zero vector, replace it with an undef input.
9621   // Shuffle mask values <  4 are selecting elements of V1.
9622   // Shuffle mask values >= 4 are selecting elements of V2.
9623   // Adjust each half of the permute mask by clearing the half that was
9624   // selecting the zero vector and setting the zero mask bit.
9625   if (IsV1Zero) {
9626     V1 = DAG.getUNDEF(VT);
9627     if (MaskLO < 4)
9628       PermMask = (PermMask & 0xf0) | 0x08;
9629     if (MaskHI < 4)
9630       PermMask = (PermMask & 0x0f) | 0x80;
9631   }
9632   if (IsV2Zero) {
9633     V2 = DAG.getUNDEF(VT);
9634     if (MaskLO >= 4)
9635       PermMask = (PermMask & 0xf0) | 0x08;
9636     if (MaskHI >= 4)
9637       PermMask = (PermMask & 0x0f) | 0x80;
9638   }
9639
9640   return DAG.getNode(X86ISD::VPERM2X128, DL, VT, V1, V2,
9641                      DAG.getConstant(PermMask, DL, MVT::i8));
9642 }
9643
9644 /// \brief Lower a vector shuffle by first fixing the 128-bit lanes and then
9645 /// shuffling each lane.
9646 ///
9647 /// This will only succeed when the result of fixing the 128-bit lanes results
9648 /// in a single-input non-lane-crossing shuffle with a repeating shuffle mask in
9649 /// each 128-bit lanes. This handles many cases where we can quickly blend away
9650 /// the lane crosses early and then use simpler shuffles within each lane.
9651 ///
9652 /// FIXME: It might be worthwhile at some point to support this without
9653 /// requiring the 128-bit lane-relative shuffles to be repeating, but currently
9654 /// in x86 only floating point has interesting non-repeating shuffles, and even
9655 /// those are still *marginally* more expensive.
9656 static SDValue lowerVectorShuffleByMerging128BitLanes(
9657     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
9658     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
9659   assert(!isSingleInputShuffleMask(Mask) &&
9660          "This is only useful with multiple inputs.");
9661
9662   int Size = Mask.size();
9663   int LaneSize = 128 / VT.getScalarSizeInBits();
9664   int NumLanes = Size / LaneSize;
9665   assert(NumLanes > 1 && "Only handles 256-bit and wider shuffles.");
9666
9667   // See if we can build a hypothetical 128-bit lane-fixing shuffle mask. Also
9668   // check whether the in-128-bit lane shuffles share a repeating pattern.
9669   SmallVector<int, 4> Lanes;
9670   Lanes.resize(NumLanes, -1);
9671   SmallVector<int, 4> InLaneMask;
9672   InLaneMask.resize(LaneSize, -1);
9673   for (int i = 0; i < Size; ++i) {
9674     if (Mask[i] < 0)
9675       continue;
9676
9677     int j = i / LaneSize;
9678
9679     if (Lanes[j] < 0) {
9680       // First entry we've seen for this lane.
9681       Lanes[j] = Mask[i] / LaneSize;
9682     } else if (Lanes[j] != Mask[i] / LaneSize) {
9683       // This doesn't match the lane selected previously!
9684       return SDValue();
9685     }
9686
9687     // Check that within each lane we have a consistent shuffle mask.
9688     int k = i % LaneSize;
9689     if (InLaneMask[k] < 0) {
9690       InLaneMask[k] = Mask[i] % LaneSize;
9691     } else if (InLaneMask[k] != Mask[i] % LaneSize) {
9692       // This doesn't fit a repeating in-lane mask.
9693       return SDValue();
9694     }
9695   }
9696
9697   // First shuffle the lanes into place.
9698   MVT LaneVT = MVT::getVectorVT(VT.isFloatingPoint() ? MVT::f64 : MVT::i64,
9699                                 VT.getSizeInBits() / 64);
9700   SmallVector<int, 8> LaneMask;
9701   LaneMask.resize(NumLanes * 2, -1);
9702   for (int i = 0; i < NumLanes; ++i)
9703     if (Lanes[i] >= 0) {
9704       LaneMask[2 * i + 0] = 2*Lanes[i] + 0;
9705       LaneMask[2 * i + 1] = 2*Lanes[i] + 1;
9706     }
9707
9708   V1 = DAG.getBitcast(LaneVT, V1);
9709   V2 = DAG.getBitcast(LaneVT, V2);
9710   SDValue LaneShuffle = DAG.getVectorShuffle(LaneVT, DL, V1, V2, LaneMask);
9711
9712   // Cast it back to the type we actually want.
9713   LaneShuffle = DAG.getBitcast(VT, LaneShuffle);
9714
9715   // Now do a simple shuffle that isn't lane crossing.
9716   SmallVector<int, 8> NewMask;
9717   NewMask.resize(Size, -1);
9718   for (int i = 0; i < Size; ++i)
9719     if (Mask[i] >= 0)
9720       NewMask[i] = (i / LaneSize) * LaneSize + Mask[i] % LaneSize;
9721   assert(!is128BitLaneCrossingShuffleMask(VT, NewMask) &&
9722          "Must not introduce lane crosses at this point!");
9723
9724   return DAG.getVectorShuffle(VT, DL, LaneShuffle, DAG.getUNDEF(VT), NewMask);
9725 }
9726
9727 /// \brief Test whether the specified input (0 or 1) is in-place blended by the
9728 /// given mask.
9729 ///
9730 /// This returns true if the elements from a particular input are already in the
9731 /// slot required by the given mask and require no permutation.
9732 static bool isShuffleMaskInputInPlace(int Input, ArrayRef<int> Mask) {
9733   assert((Input == 0 || Input == 1) && "Only two inputs to shuffles.");
9734   int Size = Mask.size();
9735   for (int i = 0; i < Size; ++i)
9736     if (Mask[i] >= 0 && Mask[i] / Size == Input && Mask[i] % Size != i)
9737       return false;
9738
9739   return true;
9740 }
9741
9742 static SDValue lowerVectorShuffleWithSHUFPD(SDLoc DL, MVT VT,
9743                                             ArrayRef<int> Mask, SDValue V1,
9744                                             SDValue V2, SelectionDAG &DAG) {
9745
9746   // Mask for V8F64: 0/1,  8/9,  2/3,  10/11, 4/5, ..
9747   // Mask for V4F64; 0/1,  4/5,  2/3,  6/7..
9748   assert(VT.getScalarSizeInBits() == 64 && "Unexpected data type for VSHUFPD");
9749   int NumElts = VT.getVectorNumElements();
9750   bool ShufpdMask = true;
9751   bool CommutableMask = true;
9752   unsigned Immediate = 0;
9753   for (int i = 0; i < NumElts; ++i) {
9754     if (Mask[i] < 0)
9755       continue;
9756     int Val = (i & 6) + NumElts * (i & 1);
9757     int CommutVal = (i & 0xe) + NumElts * ((i & 1)^1);
9758     if (Mask[i] < Val ||  Mask[i] > Val + 1)
9759       ShufpdMask = false;
9760     if (Mask[i] < CommutVal ||  Mask[i] > CommutVal + 1)
9761       CommutableMask = false;
9762     Immediate |= (Mask[i] % 2) << i;
9763   }
9764   if (ShufpdMask)
9765     return DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
9766                        DAG.getConstant(Immediate, DL, MVT::i8));
9767   if (CommutableMask)
9768     return DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
9769                        DAG.getConstant(Immediate, DL, MVT::i8));
9770   return SDValue();
9771 }
9772
9773 /// \brief Handle lowering of 4-lane 64-bit floating point shuffles.
9774 ///
9775 /// Also ends up handling lowering of 4-lane 64-bit integer shuffles when AVX2
9776 /// isn't available.
9777 static SDValue lowerV4F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9778                                        const X86Subtarget *Subtarget,
9779                                        SelectionDAG &DAG) {
9780   SDLoc DL(Op);
9781   assert(V1.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
9782   assert(V2.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
9783   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9784   ArrayRef<int> Mask = SVOp->getMask();
9785   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
9786
9787   SmallVector<int, 4> WidenedMask;
9788   if (canWidenShuffleElements(Mask, WidenedMask))
9789     return lowerV2X128VectorShuffle(DL, MVT::v4f64, V1, V2, Mask, Subtarget,
9790                                     DAG);
9791
9792   if (isSingleInputShuffleMask(Mask)) {
9793     // Check for being able to broadcast a single element.
9794     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f64, V1,
9795                                                           Mask, Subtarget, DAG))
9796       return Broadcast;
9797
9798     // Use low duplicate instructions for masks that match their pattern.
9799     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
9800       return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v4f64, V1);
9801
9802     if (!is128BitLaneCrossingShuffleMask(MVT::v4f64, Mask)) {
9803       // Non-half-crossing single input shuffles can be lowerid with an
9804       // interleaved permutation.
9805       unsigned VPERMILPMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1) |
9806                               ((Mask[2] == 3) << 2) | ((Mask[3] == 3) << 3);
9807       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f64, V1,
9808                          DAG.getConstant(VPERMILPMask, DL, MVT::i8));
9809     }
9810
9811     // With AVX2 we have direct support for this permutation.
9812     if (Subtarget->hasAVX2())
9813       return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4f64, V1,
9814                          getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
9815
9816     // Otherwise, fall back.
9817     return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v4f64, V1, V2, Mask,
9818                                                    DAG);
9819   }
9820
9821   // X86 has dedicated unpack instructions that can handle specific blend
9822   // operations: UNPCKH and UNPCKL.
9823   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 2, 6}))
9824     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V1, V2);
9825   if (isShuffleEquivalent(V1, V2, Mask, {1, 5, 3, 7}))
9826     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V1, V2);
9827   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 6, 2}))
9828     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V2, V1);
9829   if (isShuffleEquivalent(V1, V2, Mask, {5, 1, 7, 3}))
9830     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V2, V1);
9831
9832   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f64, V1, V2, Mask,
9833                                                 Subtarget, DAG))
9834     return Blend;
9835
9836   // Check if the blend happens to exactly fit that of SHUFPD.
9837   if (SDValue Op =
9838       lowerVectorShuffleWithSHUFPD(DL, MVT::v4f64, Mask, V1, V2, DAG))
9839     return Op;
9840
9841   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9842   // shuffle. However, if we have AVX2 and either inputs are already in place,
9843   // we will be able to shuffle even across lanes the other input in a single
9844   // instruction so skip this pattern.
9845   if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
9846                                  isShuffleMaskInputInPlace(1, Mask))))
9847     if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9848             DL, MVT::v4f64, V1, V2, Mask, Subtarget, DAG))
9849       return Result;
9850
9851   // If we have AVX2 then we always want to lower with a blend because an v4 we
9852   // can fully permute the elements.
9853   if (Subtarget->hasAVX2())
9854     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4f64, V1, V2,
9855                                                       Mask, DAG);
9856
9857   // Otherwise fall back on generic lowering.
9858   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v4f64, V1, V2, Mask, DAG);
9859 }
9860
9861 /// \brief Handle lowering of 4-lane 64-bit integer shuffles.
9862 ///
9863 /// This routine is only called when we have AVX2 and thus a reasonable
9864 /// instruction set for v4i64 shuffling..
9865 static SDValue lowerV4I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9866                                        const X86Subtarget *Subtarget,
9867                                        SelectionDAG &DAG) {
9868   SDLoc DL(Op);
9869   assert(V1.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
9870   assert(V2.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
9871   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9872   ArrayRef<int> Mask = SVOp->getMask();
9873   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
9874   assert(Subtarget->hasAVX2() && "We can only lower v4i64 with AVX2!");
9875
9876   SmallVector<int, 4> WidenedMask;
9877   if (canWidenShuffleElements(Mask, WidenedMask))
9878     return lowerV2X128VectorShuffle(DL, MVT::v4i64, V1, V2, Mask, Subtarget,
9879                                     DAG);
9880
9881   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i64, V1, V2, Mask,
9882                                                 Subtarget, DAG))
9883     return Blend;
9884
9885   // Check for being able to broadcast a single element.
9886   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i64, V1,
9887                                                         Mask, Subtarget, DAG))
9888     return Broadcast;
9889
9890   // When the shuffle is mirrored between the 128-bit lanes of the unit, we can
9891   // use lower latency instructions that will operate on both 128-bit lanes.
9892   SmallVector<int, 2> RepeatedMask;
9893   if (is128BitLaneRepeatedShuffleMask(MVT::v4i64, Mask, RepeatedMask)) {
9894     if (isSingleInputShuffleMask(Mask)) {
9895       int PSHUFDMask[] = {-1, -1, -1, -1};
9896       for (int i = 0; i < 2; ++i)
9897         if (RepeatedMask[i] >= 0) {
9898           PSHUFDMask[2 * i] = 2 * RepeatedMask[i];
9899           PSHUFDMask[2 * i + 1] = 2 * RepeatedMask[i] + 1;
9900         }
9901       return DAG.getBitcast(
9902           MVT::v4i64,
9903           DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32,
9904                       DAG.getBitcast(MVT::v8i32, V1),
9905                       getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
9906     }
9907   }
9908
9909   // AVX2 provides a direct instruction for permuting a single input across
9910   // lanes.
9911   if (isSingleInputShuffleMask(Mask))
9912     return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4i64, V1,
9913                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
9914
9915   // Try to use shift instructions.
9916   if (SDValue Shift =
9917           lowerVectorShuffleAsShift(DL, MVT::v4i64, V1, V2, Mask, DAG))
9918     return Shift;
9919
9920   // Use dedicated unpack instructions for masks that match their pattern.
9921   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 2, 6}))
9922     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V1, V2);
9923   if (isShuffleEquivalent(V1, V2, Mask, {1, 5, 3, 7}))
9924     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V1, V2);
9925   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 6, 2}))
9926     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V2, V1);
9927   if (isShuffleEquivalent(V1, V2, Mask, {5, 1, 7, 3}))
9928     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V2, V1);
9929
9930   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9931   // shuffle. However, if we have AVX2 and either inputs are already in place,
9932   // we will be able to shuffle even across lanes the other input in a single
9933   // instruction so skip this pattern.
9934   if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
9935                                  isShuffleMaskInputInPlace(1, Mask))))
9936     if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9937             DL, MVT::v4i64, V1, V2, Mask, Subtarget, DAG))
9938       return Result;
9939
9940   // Otherwise fall back on generic blend lowering.
9941   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i64, V1, V2,
9942                                                     Mask, DAG);
9943 }
9944
9945 /// \brief Handle lowering of 8-lane 32-bit floating point shuffles.
9946 ///
9947 /// Also ends up handling lowering of 8-lane 32-bit integer shuffles when AVX2
9948 /// isn't available.
9949 static SDValue lowerV8F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9950                                        const X86Subtarget *Subtarget,
9951                                        SelectionDAG &DAG) {
9952   SDLoc DL(Op);
9953   assert(V1.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
9954   assert(V2.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
9955   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9956   ArrayRef<int> Mask = SVOp->getMask();
9957   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9958
9959   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8f32, V1, V2, Mask,
9960                                                 Subtarget, DAG))
9961     return Blend;
9962
9963   // Check for being able to broadcast a single element.
9964   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8f32, V1,
9965                                                         Mask, Subtarget, DAG))
9966     return Broadcast;
9967
9968   // If the shuffle mask is repeated in each 128-bit lane, we have many more
9969   // options to efficiently lower the shuffle.
9970   SmallVector<int, 4> RepeatedMask;
9971   if (is128BitLaneRepeatedShuffleMask(MVT::v8f32, Mask, RepeatedMask)) {
9972     assert(RepeatedMask.size() == 4 &&
9973            "Repeated masks must be half the mask width!");
9974
9975     // Use even/odd duplicate instructions for masks that match their pattern.
9976     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2, 4, 4, 6, 6}))
9977       return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v8f32, V1);
9978     if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3, 5, 5, 7, 7}))
9979       return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v8f32, V1);
9980
9981     if (isSingleInputShuffleMask(Mask))
9982       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v8f32, V1,
9983                          getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
9984
9985     // Use dedicated unpack instructions for masks that match their pattern.
9986     if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 4, 12, 5, 13}))
9987       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V1, V2);
9988     if (isShuffleEquivalent(V1, V2, Mask, {2, 10, 3, 11, 6, 14, 7, 15}))
9989       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V1, V2);
9990     if (isShuffleEquivalent(V1, V2, Mask, {8, 0, 9, 1, 12, 4, 13, 5}))
9991       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V2, V1);
9992     if (isShuffleEquivalent(V1, V2, Mask, {10, 2, 11, 3, 14, 6, 15, 7}))
9993       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V2, V1);
9994
9995     // Otherwise, fall back to a SHUFPS sequence. Here it is important that we
9996     // have already handled any direct blends. We also need to squash the
9997     // repeated mask into a simulated v4f32 mask.
9998     for (int i = 0; i < 4; ++i)
9999       if (RepeatedMask[i] >= 8)
10000         RepeatedMask[i] -= 4;
10001     return lowerVectorShuffleWithSHUFPS(DL, MVT::v8f32, RepeatedMask, V1, V2, DAG);
10002   }
10003
10004   // If we have a single input shuffle with different shuffle patterns in the
10005   // two 128-bit lanes use the variable mask to VPERMILPS.
10006   if (isSingleInputShuffleMask(Mask)) {
10007     SDValue VPermMask[8];
10008     for (int i = 0; i < 8; ++i)
10009       VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
10010                                  : DAG.getConstant(Mask[i], DL, MVT::i32);
10011     if (!is128BitLaneCrossingShuffleMask(MVT::v8f32, Mask))
10012       return DAG.getNode(
10013           X86ISD::VPERMILPV, DL, MVT::v8f32, V1,
10014           DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask));
10015
10016     if (Subtarget->hasAVX2())
10017       return DAG.getNode(
10018           X86ISD::VPERMV, DL, MVT::v8f32,
10019           DAG.getBitcast(MVT::v8f32, DAG.getNode(ISD::BUILD_VECTOR, DL,
10020                                                  MVT::v8i32, VPermMask)),
10021           V1);
10022
10023     // Otherwise, fall back.
10024     return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v8f32, V1, V2, Mask,
10025                                                    DAG);
10026   }
10027
10028   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10029   // shuffle.
10030   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10031           DL, MVT::v8f32, V1, V2, Mask, Subtarget, DAG))
10032     return Result;
10033
10034   // If we have AVX2 then we always want to lower with a blend because at v8 we
10035   // can fully permute the elements.
10036   if (Subtarget->hasAVX2())
10037     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8f32, V1, V2,
10038                                                       Mask, DAG);
10039
10040   // Otherwise fall back on generic lowering.
10041   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v8f32, V1, V2, Mask, DAG);
10042 }
10043
10044 /// \brief Handle lowering of 8-lane 32-bit integer shuffles.
10045 ///
10046 /// This routine is only called when we have AVX2 and thus a reasonable
10047 /// instruction set for v8i32 shuffling..
10048 static SDValue lowerV8I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10049                                        const X86Subtarget *Subtarget,
10050                                        SelectionDAG &DAG) {
10051   SDLoc DL(Op);
10052   assert(V1.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
10053   assert(V2.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
10054   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10055   ArrayRef<int> Mask = SVOp->getMask();
10056   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10057   assert(Subtarget->hasAVX2() && "We can only lower v8i32 with AVX2!");
10058
10059   // Whenever we can lower this as a zext, that instruction is strictly faster
10060   // than any alternative. It also allows us to fold memory operands into the
10061   // shuffle in many cases.
10062   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v8i32, V1, V2,
10063                                                          Mask, Subtarget, DAG))
10064     return ZExt;
10065
10066   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i32, V1, V2, Mask,
10067                                                 Subtarget, DAG))
10068     return Blend;
10069
10070   // Check for being able to broadcast a single element.
10071   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i32, V1,
10072                                                         Mask, Subtarget, DAG))
10073     return Broadcast;
10074
10075   // If the shuffle mask is repeated in each 128-bit lane we can use more
10076   // efficient instructions that mirror the shuffles across the two 128-bit
10077   // lanes.
10078   SmallVector<int, 4> RepeatedMask;
10079   if (is128BitLaneRepeatedShuffleMask(MVT::v8i32, Mask, RepeatedMask)) {
10080     assert(RepeatedMask.size() == 4 && "Unexpected repeated mask size!");
10081     if (isSingleInputShuffleMask(Mask))
10082       return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32, V1,
10083                          getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
10084
10085     // Use dedicated unpack instructions for masks that match their pattern.
10086     if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 4, 12, 5, 13}))
10087       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V1, V2);
10088     if (isShuffleEquivalent(V1, V2, Mask, {2, 10, 3, 11, 6, 14, 7, 15}))
10089       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V1, V2);
10090     if (isShuffleEquivalent(V1, V2, Mask, {8, 0, 9, 1, 12, 4, 13, 5}))
10091       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V2, V1);
10092     if (isShuffleEquivalent(V1, V2, Mask, {10, 2, 11, 3, 14, 6, 15, 7}))
10093       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V2, V1);
10094   }
10095
10096   // Try to use shift instructions.
10097   if (SDValue Shift =
10098           lowerVectorShuffleAsShift(DL, MVT::v8i32, V1, V2, Mask, DAG))
10099     return Shift;
10100
10101   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10102           DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
10103     return Rotate;
10104
10105   // If the shuffle patterns aren't repeated but it is a single input, directly
10106   // generate a cross-lane VPERMD instruction.
10107   if (isSingleInputShuffleMask(Mask)) {
10108     SDValue VPermMask[8];
10109     for (int i = 0; i < 8; ++i)
10110       VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
10111                                  : DAG.getConstant(Mask[i], DL, MVT::i32);
10112     return DAG.getNode(
10113         X86ISD::VPERMV, DL, MVT::v8i32,
10114         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask), V1);
10115   }
10116
10117   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10118   // shuffle.
10119   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10120           DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
10121     return Result;
10122
10123   // Otherwise fall back on generic blend lowering.
10124   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i32, V1, V2,
10125                                                     Mask, DAG);
10126 }
10127
10128 /// \brief Handle lowering of 16-lane 16-bit integer shuffles.
10129 ///
10130 /// This routine is only called when we have AVX2 and thus a reasonable
10131 /// instruction set for v16i16 shuffling..
10132 static SDValue lowerV16I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10133                                         const X86Subtarget *Subtarget,
10134                                         SelectionDAG &DAG) {
10135   SDLoc DL(Op);
10136   assert(V1.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
10137   assert(V2.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
10138   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10139   ArrayRef<int> Mask = SVOp->getMask();
10140   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10141   assert(Subtarget->hasAVX2() && "We can only lower v16i16 with AVX2!");
10142
10143   // Whenever we can lower this as a zext, that instruction is strictly faster
10144   // than any alternative. It also allows us to fold memory operands into the
10145   // shuffle in many cases.
10146   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v16i16, V1, V2,
10147                                                          Mask, Subtarget, DAG))
10148     return ZExt;
10149
10150   // Check for being able to broadcast a single element.
10151   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i16, V1,
10152                                                         Mask, Subtarget, DAG))
10153     return Broadcast;
10154
10155   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i16, V1, V2, Mask,
10156                                                 Subtarget, DAG))
10157     return Blend;
10158
10159   // Use dedicated unpack instructions for masks that match their pattern.
10160   if (isShuffleEquivalent(V1, V2, Mask,
10161                           {// First 128-bit lane:
10162                            0, 16, 1, 17, 2, 18, 3, 19,
10163                            // Second 128-bit lane:
10164                            8, 24, 9, 25, 10, 26, 11, 27}))
10165     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i16, V1, V2);
10166   if (isShuffleEquivalent(V1, V2, Mask,
10167                           {// First 128-bit lane:
10168                            4, 20, 5, 21, 6, 22, 7, 23,
10169                            // Second 128-bit lane:
10170                            12, 28, 13, 29, 14, 30, 15, 31}))
10171     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i16, V1, V2);
10172
10173   // Try to use shift instructions.
10174   if (SDValue Shift =
10175           lowerVectorShuffleAsShift(DL, MVT::v16i16, V1, V2, Mask, DAG))
10176     return Shift;
10177
10178   // Try to use byte rotation instructions.
10179   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10180           DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
10181     return Rotate;
10182
10183   if (isSingleInputShuffleMask(Mask)) {
10184     // There are no generalized cross-lane shuffle operations available on i16
10185     // element types.
10186     if (is128BitLaneCrossingShuffleMask(MVT::v16i16, Mask))
10187       return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v16i16, V1, V2,
10188                                                      Mask, DAG);
10189
10190     SmallVector<int, 8> RepeatedMask;
10191     if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
10192       // As this is a single-input shuffle, the repeated mask should be
10193       // a strictly valid v8i16 mask that we can pass through to the v8i16
10194       // lowering to handle even the v16 case.
10195       return lowerV8I16GeneralSingleInputVectorShuffle(
10196           DL, MVT::v16i16, V1, RepeatedMask, Subtarget, DAG);
10197     }
10198
10199     SDValue PSHUFBMask[32];
10200     for (int i = 0; i < 16; ++i) {
10201       if (Mask[i] == -1) {
10202         PSHUFBMask[2 * i] = PSHUFBMask[2 * i + 1] = DAG.getUNDEF(MVT::i8);
10203         continue;
10204       }
10205
10206       int M = i < 8 ? Mask[i] : Mask[i] - 8;
10207       assert(M >= 0 && M < 8 && "Invalid single-input mask!");
10208       PSHUFBMask[2 * i] = DAG.getConstant(2 * M, DL, MVT::i8);
10209       PSHUFBMask[2 * i + 1] = DAG.getConstant(2 * M + 1, DL, MVT::i8);
10210     }
10211     return DAG.getBitcast(MVT::v16i16,
10212                           DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8,
10213                                       DAG.getBitcast(MVT::v32i8, V1),
10214                                       DAG.getNode(ISD::BUILD_VECTOR, DL,
10215                                                   MVT::v32i8, PSHUFBMask)));
10216   }
10217
10218   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10219   // shuffle.
10220   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10221           DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
10222     return Result;
10223
10224   // Otherwise fall back on generic lowering.
10225   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v16i16, V1, V2, Mask, DAG);
10226 }
10227
10228 /// \brief Handle lowering of 32-lane 8-bit integer shuffles.
10229 ///
10230 /// This routine is only called when we have AVX2 and thus a reasonable
10231 /// instruction set for v32i8 shuffling..
10232 static SDValue lowerV32I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10233                                        const X86Subtarget *Subtarget,
10234                                        SelectionDAG &DAG) {
10235   SDLoc DL(Op);
10236   assert(V1.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
10237   assert(V2.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
10238   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10239   ArrayRef<int> Mask = SVOp->getMask();
10240   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
10241   assert(Subtarget->hasAVX2() && "We can only lower v32i8 with AVX2!");
10242
10243   // Whenever we can lower this as a zext, that instruction is strictly faster
10244   // than any alternative. It also allows us to fold memory operands into the
10245   // shuffle in many cases.
10246   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v32i8, V1, V2,
10247                                                          Mask, Subtarget, DAG))
10248     return ZExt;
10249
10250   // Check for being able to broadcast a single element.
10251   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v32i8, V1,
10252                                                         Mask, Subtarget, DAG))
10253     return Broadcast;
10254
10255   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v32i8, V1, V2, Mask,
10256                                                 Subtarget, DAG))
10257     return Blend;
10258
10259   // Use dedicated unpack instructions for masks that match their pattern.
10260   // Note that these are repeated 128-bit lane unpacks, not unpacks across all
10261   // 256-bit lanes.
10262   if (isShuffleEquivalent(
10263           V1, V2, Mask,
10264           {// First 128-bit lane:
10265            0, 32, 1, 33, 2, 34, 3, 35, 4, 36, 5, 37, 6, 38, 7, 39,
10266            // Second 128-bit lane:
10267            16, 48, 17, 49, 18, 50, 19, 51, 20, 52, 21, 53, 22, 54, 23, 55}))
10268     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v32i8, V1, V2);
10269   if (isShuffleEquivalent(
10270           V1, V2, Mask,
10271           {// First 128-bit lane:
10272            8, 40, 9, 41, 10, 42, 11, 43, 12, 44, 13, 45, 14, 46, 15, 47,
10273            // Second 128-bit lane:
10274            24, 56, 25, 57, 26, 58, 27, 59, 28, 60, 29, 61, 30, 62, 31, 63}))
10275     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v32i8, V1, V2);
10276
10277   // Try to use shift instructions.
10278   if (SDValue Shift =
10279           lowerVectorShuffleAsShift(DL, MVT::v32i8, V1, V2, Mask, DAG))
10280     return Shift;
10281
10282   // Try to use byte rotation instructions.
10283   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10284           DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
10285     return Rotate;
10286
10287   if (isSingleInputShuffleMask(Mask)) {
10288     // There are no generalized cross-lane shuffle operations available on i8
10289     // element types.
10290     if (is128BitLaneCrossingShuffleMask(MVT::v32i8, Mask))
10291       return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v32i8, V1, V2,
10292                                                      Mask, DAG);
10293
10294     SDValue PSHUFBMask[32];
10295     for (int i = 0; i < 32; ++i)
10296       PSHUFBMask[i] =
10297           Mask[i] < 0
10298               ? DAG.getUNDEF(MVT::i8)
10299               : DAG.getConstant(Mask[i] < 16 ? Mask[i] : Mask[i] - 16, DL,
10300                                 MVT::i8);
10301
10302     return DAG.getNode(
10303         X86ISD::PSHUFB, DL, MVT::v32i8, V1,
10304         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, PSHUFBMask));
10305   }
10306
10307   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10308   // shuffle.
10309   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10310           DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
10311     return Result;
10312
10313   // Otherwise fall back on generic lowering.
10314   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v32i8, V1, V2, Mask, DAG);
10315 }
10316
10317 /// \brief High-level routine to lower various 256-bit x86 vector shuffles.
10318 ///
10319 /// This routine either breaks down the specific type of a 256-bit x86 vector
10320 /// shuffle or splits it into two 128-bit shuffles and fuses the results back
10321 /// together based on the available instructions.
10322 static SDValue lower256BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10323                                         MVT VT, const X86Subtarget *Subtarget,
10324                                         SelectionDAG &DAG) {
10325   SDLoc DL(Op);
10326   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10327   ArrayRef<int> Mask = SVOp->getMask();
10328
10329   // If we have a single input to the zero element, insert that into V1 if we
10330   // can do so cheaply.
10331   int NumElts = VT.getVectorNumElements();
10332   int NumV2Elements = std::count_if(Mask.begin(), Mask.end(), [NumElts](int M) {
10333     return M >= NumElts;
10334   });
10335
10336   if (NumV2Elements == 1 && Mask[0] >= NumElts)
10337     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
10338                               DL, VT, V1, V2, Mask, Subtarget, DAG))
10339       return Insertion;
10340
10341   // There is a really nice hard cut-over between AVX1 and AVX2 that means we can
10342   // check for those subtargets here and avoid much of the subtarget querying in
10343   // the per-vector-type lowering routines. With AVX1 we have essentially *zero*
10344   // ability to manipulate a 256-bit vector with integer types. Since we'll use
10345   // floating point types there eventually, just immediately cast everything to
10346   // a float and operate entirely in that domain.
10347   if (VT.isInteger() && !Subtarget->hasAVX2()) {
10348     int ElementBits = VT.getScalarSizeInBits();
10349     if (ElementBits < 32)
10350       // No floating point type available, decompose into 128-bit vectors.
10351       return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10352
10353     MVT FpVT = MVT::getVectorVT(MVT::getFloatingPointVT(ElementBits),
10354                                 VT.getVectorNumElements());
10355     V1 = DAG.getBitcast(FpVT, V1);
10356     V2 = DAG.getBitcast(FpVT, V2);
10357     return DAG.getBitcast(VT, DAG.getVectorShuffle(FpVT, DL, V1, V2, Mask));
10358   }
10359
10360   switch (VT.SimpleTy) {
10361   case MVT::v4f64:
10362     return lowerV4F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10363   case MVT::v4i64:
10364     return lowerV4I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10365   case MVT::v8f32:
10366     return lowerV8F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10367   case MVT::v8i32:
10368     return lowerV8I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10369   case MVT::v16i16:
10370     return lowerV16I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
10371   case MVT::v32i8:
10372     return lowerV32I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
10373
10374   default:
10375     llvm_unreachable("Not a valid 256-bit x86 vector type!");
10376   }
10377 }
10378
10379 /// \brief Handle lowering of 8-lane 64-bit floating point shuffles.
10380 static SDValue lowerV8F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10381                                        const X86Subtarget *Subtarget,
10382                                        SelectionDAG &DAG) {
10383   SDLoc DL(Op);
10384   assert(V1.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
10385   assert(V2.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
10386   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10387   ArrayRef<int> Mask = SVOp->getMask();
10388   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10389
10390   // X86 has dedicated unpack instructions that can handle specific blend
10391   // operations: UNPCKH and UNPCKL.
10392   if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 2, 10, 4, 12, 6, 14}))
10393     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f64, V1, V2);
10394   if (isShuffleEquivalent(V1, V2, Mask, {1, 9, 3, 11, 5, 13, 7, 15}))
10395     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f64, V1, V2);
10396
10397   // FIXME: Implement direct support for this type!
10398   return splitAndLowerVectorShuffle(DL, MVT::v8f64, V1, V2, Mask, DAG);
10399 }
10400
10401 /// \brief Handle lowering of 16-lane 32-bit floating point shuffles.
10402 static SDValue lowerV16F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10403                                        const X86Subtarget *Subtarget,
10404                                        SelectionDAG &DAG) {
10405   SDLoc DL(Op);
10406   assert(V1.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
10407   assert(V2.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
10408   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10409   ArrayRef<int> Mask = SVOp->getMask();
10410   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10411
10412   // Use dedicated unpack instructions for masks that match their pattern.
10413   if (isShuffleEquivalent(V1, V2, Mask,
10414                           {// First 128-bit lane.
10415                            0, 16, 1, 17, 4, 20, 5, 21,
10416                            // Second 128-bit lane.
10417                            8, 24, 9, 25, 12, 28, 13, 29}))
10418     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16f32, V1, V2);
10419   if (isShuffleEquivalent(V1, V2, Mask,
10420                           {// First 128-bit lane.
10421                            2, 18, 3, 19, 6, 22, 7, 23,
10422                            // Second 128-bit lane.
10423                            10, 26, 11, 27, 14, 30, 15, 31}))
10424     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16f32, V1, V2);
10425
10426   // FIXME: Implement direct support for this type!
10427   return splitAndLowerVectorShuffle(DL, MVT::v16f32, V1, V2, Mask, DAG);
10428 }
10429
10430 /// \brief Handle lowering of 8-lane 64-bit integer shuffles.
10431 static SDValue lowerV8I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10432                                        const X86Subtarget *Subtarget,
10433                                        SelectionDAG &DAG) {
10434   SDLoc DL(Op);
10435   assert(V1.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
10436   assert(V2.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
10437   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10438   ArrayRef<int> Mask = SVOp->getMask();
10439   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10440
10441   // X86 has dedicated unpack instructions that can handle specific blend
10442   // operations: UNPCKH and UNPCKL.
10443   if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 2, 10, 4, 12, 6, 14}))
10444     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i64, V1, V2);
10445   if (isShuffleEquivalent(V1, V2, Mask, {1, 9, 3, 11, 5, 13, 7, 15}))
10446     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i64, V1, V2);
10447
10448   // FIXME: Implement direct support for this type!
10449   return splitAndLowerVectorShuffle(DL, MVT::v8i64, V1, V2, Mask, DAG);
10450 }
10451
10452 /// \brief Handle lowering of 16-lane 32-bit integer shuffles.
10453 static SDValue lowerV16I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10454                                        const X86Subtarget *Subtarget,
10455                                        SelectionDAG &DAG) {
10456   SDLoc DL(Op);
10457   assert(V1.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
10458   assert(V2.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
10459   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10460   ArrayRef<int> Mask = SVOp->getMask();
10461   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10462
10463   // Use dedicated unpack instructions for masks that match their pattern.
10464   if (isShuffleEquivalent(V1, V2, Mask,
10465                           {// First 128-bit lane.
10466                            0, 16, 1, 17, 4, 20, 5, 21,
10467                            // Second 128-bit lane.
10468                            8, 24, 9, 25, 12, 28, 13, 29}))
10469     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i32, V1, V2);
10470   if (isShuffleEquivalent(V1, V2, Mask,
10471                           {// First 128-bit lane.
10472                            2, 18, 3, 19, 6, 22, 7, 23,
10473                            // Second 128-bit lane.
10474                            10, 26, 11, 27, 14, 30, 15, 31}))
10475     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i32, V1, V2);
10476
10477   // FIXME: Implement direct support for this type!
10478   return splitAndLowerVectorShuffle(DL, MVT::v16i32, V1, V2, Mask, DAG);
10479 }
10480
10481 /// \brief Handle lowering of 32-lane 16-bit integer shuffles.
10482 static SDValue lowerV32I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10483                                         const X86Subtarget *Subtarget,
10484                                         SelectionDAG &DAG) {
10485   SDLoc DL(Op);
10486   assert(V1.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10487   assert(V2.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10488   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10489   ArrayRef<int> Mask = SVOp->getMask();
10490   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
10491   assert(Subtarget->hasBWI() && "We can only lower v32i16 with AVX-512-BWI!");
10492
10493   // FIXME: Implement direct support for this type!
10494   return splitAndLowerVectorShuffle(DL, MVT::v32i16, V1, V2, Mask, DAG);
10495 }
10496
10497 /// \brief Handle lowering of 64-lane 8-bit integer shuffles.
10498 static SDValue lowerV64I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10499                                        const X86Subtarget *Subtarget,
10500                                        SelectionDAG &DAG) {
10501   SDLoc DL(Op);
10502   assert(V1.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10503   assert(V2.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10504   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10505   ArrayRef<int> Mask = SVOp->getMask();
10506   assert(Mask.size() == 64 && "Unexpected mask size for v64 shuffle!");
10507   assert(Subtarget->hasBWI() && "We can only lower v64i8 with AVX-512-BWI!");
10508
10509   // FIXME: Implement direct support for this type!
10510   return splitAndLowerVectorShuffle(DL, MVT::v64i8, V1, V2, Mask, DAG);
10511 }
10512
10513 /// \brief High-level routine to lower various 512-bit x86 vector shuffles.
10514 ///
10515 /// This routine either breaks down the specific type of a 512-bit x86 vector
10516 /// shuffle or splits it into two 256-bit shuffles and fuses the results back
10517 /// together based on the available instructions.
10518 static SDValue lower512BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10519                                         MVT VT, const X86Subtarget *Subtarget,
10520                                         SelectionDAG &DAG) {
10521   SDLoc DL(Op);
10522   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10523   ArrayRef<int> Mask = SVOp->getMask();
10524   assert(Subtarget->hasAVX512() &&
10525          "Cannot lower 512-bit vectors w/ basic ISA!");
10526
10527   // Check for being able to broadcast a single element.
10528   if (SDValue Broadcast =
10529           lowerVectorShuffleAsBroadcast(DL, VT, V1, Mask, Subtarget, DAG))
10530     return Broadcast;
10531
10532   // Dispatch to each element type for lowering. If we don't have supprot for
10533   // specific element type shuffles at 512 bits, immediately split them and
10534   // lower them. Each lowering routine of a given type is allowed to assume that
10535   // the requisite ISA extensions for that element type are available.
10536   switch (VT.SimpleTy) {
10537   case MVT::v8f64:
10538     return lowerV8F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10539   case MVT::v16f32:
10540     return lowerV16F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10541   case MVT::v8i64:
10542     return lowerV8I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10543   case MVT::v16i32:
10544     return lowerV16I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10545   case MVT::v32i16:
10546     if (Subtarget->hasBWI())
10547       return lowerV32I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
10548     break;
10549   case MVT::v64i8:
10550     if (Subtarget->hasBWI())
10551       return lowerV64I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
10552     break;
10553
10554   default:
10555     llvm_unreachable("Not a valid 512-bit x86 vector type!");
10556   }
10557
10558   // Otherwise fall back on splitting.
10559   return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10560 }
10561
10562 /// \brief Top-level lowering for x86 vector shuffles.
10563 ///
10564 /// This handles decomposition, canonicalization, and lowering of all x86
10565 /// vector shuffles. Most of the specific lowering strategies are encapsulated
10566 /// above in helper routines. The canonicalization attempts to widen shuffles
10567 /// to involve fewer lanes of wider elements, consolidate symmetric patterns
10568 /// s.t. only one of the two inputs needs to be tested, etc.
10569 static SDValue lowerVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
10570                                   SelectionDAG &DAG) {
10571   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10572   ArrayRef<int> Mask = SVOp->getMask();
10573   SDValue V1 = Op.getOperand(0);
10574   SDValue V2 = Op.getOperand(1);
10575   MVT VT = Op.getSimpleValueType();
10576   int NumElements = VT.getVectorNumElements();
10577   SDLoc dl(Op);
10578
10579   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
10580
10581   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
10582   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
10583   if (V1IsUndef && V2IsUndef)
10584     return DAG.getUNDEF(VT);
10585
10586   // When we create a shuffle node we put the UNDEF node to second operand,
10587   // but in some cases the first operand may be transformed to UNDEF.
10588   // In this case we should just commute the node.
10589   if (V1IsUndef)
10590     return DAG.getCommutedVectorShuffle(*SVOp);
10591
10592   // Check for non-undef masks pointing at an undef vector and make the masks
10593   // undef as well. This makes it easier to match the shuffle based solely on
10594   // the mask.
10595   if (V2IsUndef)
10596     for (int M : Mask)
10597       if (M >= NumElements) {
10598         SmallVector<int, 8> NewMask(Mask.begin(), Mask.end());
10599         for (int &M : NewMask)
10600           if (M >= NumElements)
10601             M = -1;
10602         return DAG.getVectorShuffle(VT, dl, V1, V2, NewMask);
10603       }
10604
10605   // We actually see shuffles that are entirely re-arrangements of a set of
10606   // zero inputs. This mostly happens while decomposing complex shuffles into
10607   // simple ones. Directly lower these as a buildvector of zeros.
10608   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
10609   if (Zeroable.all())
10610     return getZeroVector(VT, Subtarget, DAG, dl);
10611
10612   // Try to collapse shuffles into using a vector type with fewer elements but
10613   // wider element types. We cap this to not form integers or floating point
10614   // elements wider than 64 bits, but it might be interesting to form i128
10615   // integers to handle flipping the low and high halves of AVX 256-bit vectors.
10616   SmallVector<int, 16> WidenedMask;
10617   if (VT.getScalarSizeInBits() < 64 &&
10618       canWidenShuffleElements(Mask, WidenedMask)) {
10619     MVT NewEltVT = VT.isFloatingPoint()
10620                        ? MVT::getFloatingPointVT(VT.getScalarSizeInBits() * 2)
10621                        : MVT::getIntegerVT(VT.getScalarSizeInBits() * 2);
10622     MVT NewVT = MVT::getVectorVT(NewEltVT, VT.getVectorNumElements() / 2);
10623     // Make sure that the new vector type is legal. For example, v2f64 isn't
10624     // legal on SSE1.
10625     if (DAG.getTargetLoweringInfo().isTypeLegal(NewVT)) {
10626       V1 = DAG.getBitcast(NewVT, V1);
10627       V2 = DAG.getBitcast(NewVT, V2);
10628       return DAG.getBitcast(
10629           VT, DAG.getVectorShuffle(NewVT, dl, V1, V2, WidenedMask));
10630     }
10631   }
10632
10633   int NumV1Elements = 0, NumUndefElements = 0, NumV2Elements = 0;
10634   for (int M : SVOp->getMask())
10635     if (M < 0)
10636       ++NumUndefElements;
10637     else if (M < NumElements)
10638       ++NumV1Elements;
10639     else
10640       ++NumV2Elements;
10641
10642   // Commute the shuffle as needed such that more elements come from V1 than
10643   // V2. This allows us to match the shuffle pattern strictly on how many
10644   // elements come from V1 without handling the symmetric cases.
10645   if (NumV2Elements > NumV1Elements)
10646     return DAG.getCommutedVectorShuffle(*SVOp);
10647
10648   // When the number of V1 and V2 elements are the same, try to minimize the
10649   // number of uses of V2 in the low half of the vector. When that is tied,
10650   // ensure that the sum of indices for V1 is equal to or lower than the sum
10651   // indices for V2. When those are equal, try to ensure that the number of odd
10652   // indices for V1 is lower than the number of odd indices for V2.
10653   if (NumV1Elements == NumV2Elements) {
10654     int LowV1Elements = 0, LowV2Elements = 0;
10655     for (int M : SVOp->getMask().slice(0, NumElements / 2))
10656       if (M >= NumElements)
10657         ++LowV2Elements;
10658       else if (M >= 0)
10659         ++LowV1Elements;
10660     if (LowV2Elements > LowV1Elements) {
10661       return DAG.getCommutedVectorShuffle(*SVOp);
10662     } else if (LowV2Elements == LowV1Elements) {
10663       int SumV1Indices = 0, SumV2Indices = 0;
10664       for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
10665         if (SVOp->getMask()[i] >= NumElements)
10666           SumV2Indices += i;
10667         else if (SVOp->getMask()[i] >= 0)
10668           SumV1Indices += i;
10669       if (SumV2Indices < SumV1Indices) {
10670         return DAG.getCommutedVectorShuffle(*SVOp);
10671       } else if (SumV2Indices == SumV1Indices) {
10672         int NumV1OddIndices = 0, NumV2OddIndices = 0;
10673         for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
10674           if (SVOp->getMask()[i] >= NumElements)
10675             NumV2OddIndices += i % 2;
10676           else if (SVOp->getMask()[i] >= 0)
10677             NumV1OddIndices += i % 2;
10678         if (NumV2OddIndices < NumV1OddIndices)
10679           return DAG.getCommutedVectorShuffle(*SVOp);
10680       }
10681     }
10682   }
10683
10684   // For each vector width, delegate to a specialized lowering routine.
10685   if (VT.getSizeInBits() == 128)
10686     return lower128BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10687
10688   if (VT.getSizeInBits() == 256)
10689     return lower256BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10690
10691   // Force AVX-512 vectors to be scalarized for now.
10692   // FIXME: Implement AVX-512 support!
10693   if (VT.getSizeInBits() == 512)
10694     return lower512BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10695
10696   llvm_unreachable("Unimplemented!");
10697 }
10698
10699 // This function assumes its argument is a BUILD_VECTOR of constants or
10700 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
10701 // true.
10702 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
10703                                     unsigned &MaskValue) {
10704   MaskValue = 0;
10705   unsigned NumElems = BuildVector->getNumOperands();
10706   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
10707   unsigned NumLanes = (NumElems - 1) / 8 + 1;
10708   unsigned NumElemsInLane = NumElems / NumLanes;
10709
10710   // Blend for v16i16 should be symetric for the both lanes.
10711   for (unsigned i = 0; i < NumElemsInLane; ++i) {
10712     SDValue EltCond = BuildVector->getOperand(i);
10713     SDValue SndLaneEltCond =
10714         (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
10715
10716     int Lane1Cond = -1, Lane2Cond = -1;
10717     if (isa<ConstantSDNode>(EltCond))
10718       Lane1Cond = !isZero(EltCond);
10719     if (isa<ConstantSDNode>(SndLaneEltCond))
10720       Lane2Cond = !isZero(SndLaneEltCond);
10721
10722     if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
10723       // Lane1Cond != 0, means we want the first argument.
10724       // Lane1Cond == 0, means we want the second argument.
10725       // The encoding of this argument is 0 for the first argument, 1
10726       // for the second. Therefore, invert the condition.
10727       MaskValue |= !Lane1Cond << i;
10728     else if (Lane1Cond < 0)
10729       MaskValue |= !Lane2Cond << i;
10730     else
10731       return false;
10732   }
10733   return true;
10734 }
10735
10736 /// \brief Try to lower a VSELECT instruction to a vector shuffle.
10737 static SDValue lowerVSELECTtoVectorShuffle(SDValue Op,
10738                                            const X86Subtarget *Subtarget,
10739                                            SelectionDAG &DAG) {
10740   SDValue Cond = Op.getOperand(0);
10741   SDValue LHS = Op.getOperand(1);
10742   SDValue RHS = Op.getOperand(2);
10743   SDLoc dl(Op);
10744   MVT VT = Op.getSimpleValueType();
10745
10746   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
10747     return SDValue();
10748   auto *CondBV = cast<BuildVectorSDNode>(Cond);
10749
10750   // Only non-legal VSELECTs reach this lowering, convert those into generic
10751   // shuffles and re-use the shuffle lowering path for blends.
10752   SmallVector<int, 32> Mask;
10753   for (int i = 0, Size = VT.getVectorNumElements(); i < Size; ++i) {
10754     SDValue CondElt = CondBV->getOperand(i);
10755     Mask.push_back(
10756         isa<ConstantSDNode>(CondElt) ? i + (isZero(CondElt) ? Size : 0) : -1);
10757   }
10758   return DAG.getVectorShuffle(VT, dl, LHS, RHS, Mask);
10759 }
10760
10761 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
10762   // A vselect where all conditions and data are constants can be optimized into
10763   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
10764   if (ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(0).getNode()) &&
10765       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(1).getNode()) &&
10766       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(2).getNode()))
10767     return SDValue();
10768
10769   // Try to lower this to a blend-style vector shuffle. This can handle all
10770   // constant condition cases.
10771   if (SDValue BlendOp = lowerVSELECTtoVectorShuffle(Op, Subtarget, DAG))
10772     return BlendOp;
10773
10774   // Variable blends are only legal from SSE4.1 onward.
10775   if (!Subtarget->hasSSE41())
10776     return SDValue();
10777
10778   // Only some types will be legal on some subtargets. If we can emit a legal
10779   // VSELECT-matching blend, return Op, and but if we need to expand, return
10780   // a null value.
10781   switch (Op.getSimpleValueType().SimpleTy) {
10782   default:
10783     // Most of the vector types have blends past SSE4.1.
10784     return Op;
10785
10786   case MVT::v32i8:
10787     // The byte blends for AVX vectors were introduced only in AVX2.
10788     if (Subtarget->hasAVX2())
10789       return Op;
10790
10791     return SDValue();
10792
10793   case MVT::v8i16:
10794   case MVT::v16i16:
10795     // AVX-512 BWI and VLX features support VSELECT with i16 elements.
10796     if (Subtarget->hasBWI() && Subtarget->hasVLX())
10797       return Op;
10798
10799     // FIXME: We should custom lower this by fixing the condition and using i8
10800     // blends.
10801     return SDValue();
10802   }
10803 }
10804
10805 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
10806   MVT VT = Op.getSimpleValueType();
10807   SDLoc dl(Op);
10808
10809   if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
10810     return SDValue();
10811
10812   if (VT.getSizeInBits() == 8) {
10813     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, 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.getSizeInBits() == 16) {
10821     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10822     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
10823     if (Idx == 0)
10824       return DAG.getNode(
10825           ISD::TRUNCATE, dl, MVT::i16,
10826           DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10827                       DAG.getBitcast(MVT::v4i32, Op.getOperand(0)),
10828                       Op.getOperand(1)));
10829     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
10830                                   Op.getOperand(0), Op.getOperand(1));
10831     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
10832                                   DAG.getValueType(VT));
10833     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10834   }
10835
10836   if (VT == MVT::f32) {
10837     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
10838     // the result back to FR32 register. It's only worth matching if the
10839     // result has a single use which is a store or a bitcast to i32.  And in
10840     // the case of a store, it's not worth it if the index is a constant 0,
10841     // because a MOVSSmr can be used instead, which is smaller and faster.
10842     if (!Op.hasOneUse())
10843       return SDValue();
10844     SDNode *User = *Op.getNode()->use_begin();
10845     if ((User->getOpcode() != ISD::STORE ||
10846          (isa<ConstantSDNode>(Op.getOperand(1)) &&
10847           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
10848         (User->getOpcode() != ISD::BITCAST ||
10849          User->getValueType(0) != MVT::i32))
10850       return SDValue();
10851     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10852                                   DAG.getBitcast(MVT::v4i32, Op.getOperand(0)),
10853                                   Op.getOperand(1));
10854     return DAG.getBitcast(MVT::f32, Extract);
10855   }
10856
10857   if (VT == MVT::i32 || VT == MVT::i64) {
10858     // ExtractPS/pextrq works with constant index.
10859     if (isa<ConstantSDNode>(Op.getOperand(1)))
10860       return Op;
10861   }
10862   return SDValue();
10863 }
10864
10865 /// Extract one bit from mask vector, like v16i1 or v8i1.
10866 /// AVX-512 feature.
10867 SDValue
10868 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
10869   SDValue Vec = Op.getOperand(0);
10870   SDLoc dl(Vec);
10871   MVT VecVT = Vec.getSimpleValueType();
10872   SDValue Idx = Op.getOperand(1);
10873   MVT EltVT = Op.getSimpleValueType();
10874
10875   assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
10876   assert((VecVT.getVectorNumElements() <= 16 || Subtarget->hasBWI()) &&
10877          "Unexpected vector type in ExtractBitFromMaskVector");
10878
10879   // variable index can't be handled in mask registers,
10880   // extend vector to VR512
10881   if (!isa<ConstantSDNode>(Idx)) {
10882     MVT ExtVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
10883     SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
10884     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
10885                               ExtVT.getVectorElementType(), Ext, Idx);
10886     return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
10887   }
10888
10889   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10890   const TargetRegisterClass* rc = getRegClassFor(VecVT);
10891   if (!Subtarget->hasDQI() && (VecVT.getVectorNumElements() <= 8))
10892     rc = getRegClassFor(MVT::v16i1);
10893   unsigned MaxSift = rc->getSize()*8 - 1;
10894   Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
10895                     DAG.getConstant(MaxSift - IdxVal, dl, MVT::i8));
10896   Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
10897                     DAG.getConstant(MaxSift, dl, MVT::i8));
10898   return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
10899                        DAG.getIntPtrConstant(0, dl));
10900 }
10901
10902 SDValue
10903 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
10904                                            SelectionDAG &DAG) const {
10905   SDLoc dl(Op);
10906   SDValue Vec = Op.getOperand(0);
10907   MVT VecVT = Vec.getSimpleValueType();
10908   SDValue Idx = Op.getOperand(1);
10909
10910   if (Op.getSimpleValueType() == MVT::i1)
10911     return ExtractBitFromMaskVector(Op, DAG);
10912
10913   if (!isa<ConstantSDNode>(Idx)) {
10914     if (VecVT.is512BitVector() ||
10915         (VecVT.is256BitVector() && Subtarget->hasInt256() &&
10916          VecVT.getVectorElementType().getSizeInBits() == 32)) {
10917
10918       MVT MaskEltVT =
10919         MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
10920       MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
10921                                     MaskEltVT.getSizeInBits());
10922
10923       Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
10924       auto PtrVT = getPointerTy(DAG.getDataLayout());
10925       SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
10926                                  getZeroVector(MaskVT, Subtarget, DAG, dl), Idx,
10927                                  DAG.getConstant(0, dl, PtrVT));
10928       SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
10929       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Perm,
10930                          DAG.getConstant(0, dl, PtrVT));
10931     }
10932     return SDValue();
10933   }
10934
10935   // If this is a 256-bit vector result, first extract the 128-bit vector and
10936   // then extract the element from the 128-bit vector.
10937   if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
10938
10939     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10940     // Get the 128-bit vector.
10941     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
10942     MVT EltVT = VecVT.getVectorElementType();
10943
10944     unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
10945
10946     //if (IdxVal >= NumElems/2)
10947     //  IdxVal -= NumElems/2;
10948     IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
10949     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
10950                        DAG.getConstant(IdxVal, dl, MVT::i32));
10951   }
10952
10953   assert(VecVT.is128BitVector() && "Unexpected vector length");
10954
10955   if (Subtarget->hasSSE41())
10956     if (SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG))
10957       return Res;
10958
10959   MVT VT = Op.getSimpleValueType();
10960   // TODO: handle v16i8.
10961   if (VT.getSizeInBits() == 16) {
10962     SDValue Vec = Op.getOperand(0);
10963     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10964     if (Idx == 0)
10965       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
10966                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10967                                      DAG.getBitcast(MVT::v4i32, Vec),
10968                                      Op.getOperand(1)));
10969     // Transform it so it match pextrw which produces a 32-bit result.
10970     MVT EltVT = MVT::i32;
10971     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
10972                                   Op.getOperand(0), Op.getOperand(1));
10973     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
10974                                   DAG.getValueType(VT));
10975     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10976   }
10977
10978   if (VT.getSizeInBits() == 32) {
10979     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10980     if (Idx == 0)
10981       return Op;
10982
10983     // SHUFPS the element to the lowest double word, then movss.
10984     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
10985     MVT VVT = Op.getOperand(0).getSimpleValueType();
10986     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
10987                                        DAG.getUNDEF(VVT), Mask);
10988     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
10989                        DAG.getIntPtrConstant(0, dl));
10990   }
10991
10992   if (VT.getSizeInBits() == 64) {
10993     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
10994     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
10995     //        to match extract_elt for f64.
10996     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10997     if (Idx == 0)
10998       return Op;
10999
11000     // UNPCKHPD the element to the lowest double word, then movsd.
11001     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
11002     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
11003     int Mask[2] = { 1, -1 };
11004     MVT VVT = Op.getOperand(0).getSimpleValueType();
11005     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
11006                                        DAG.getUNDEF(VVT), Mask);
11007     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
11008                        DAG.getIntPtrConstant(0, dl));
11009   }
11010
11011   return SDValue();
11012 }
11013
11014 /// Insert one bit to mask vector, like v16i1 or v8i1.
11015 /// AVX-512 feature.
11016 SDValue
11017 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
11018   SDLoc dl(Op);
11019   SDValue Vec = Op.getOperand(0);
11020   SDValue Elt = Op.getOperand(1);
11021   SDValue Idx = Op.getOperand(2);
11022   MVT VecVT = Vec.getSimpleValueType();
11023
11024   if (!isa<ConstantSDNode>(Idx)) {
11025     // Non constant index. Extend source and destination,
11026     // insert element and then truncate the result.
11027     MVT ExtVecVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
11028     MVT ExtEltVT = (VecVT == MVT::v8i1 ?  MVT::i64 : MVT::i32);
11029     SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT,
11030       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
11031       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
11032     return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
11033   }
11034
11035   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11036   SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
11037   if (IdxVal)
11038     EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
11039                            DAG.getConstant(IdxVal, dl, MVT::i8));
11040   if (Vec.getOpcode() == ISD::UNDEF)
11041     return EltInVec;
11042   return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
11043 }
11044
11045 SDValue X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
11046                                                   SelectionDAG &DAG) const {
11047   MVT VT = Op.getSimpleValueType();
11048   MVT EltVT = VT.getVectorElementType();
11049
11050   if (EltVT == MVT::i1)
11051     return InsertBitToMaskVector(Op, DAG);
11052
11053   SDLoc dl(Op);
11054   SDValue N0 = Op.getOperand(0);
11055   SDValue N1 = Op.getOperand(1);
11056   SDValue N2 = Op.getOperand(2);
11057   if (!isa<ConstantSDNode>(N2))
11058     return SDValue();
11059   auto *N2C = cast<ConstantSDNode>(N2);
11060   unsigned IdxVal = N2C->getZExtValue();
11061
11062   // If the vector is wider than 128 bits, extract the 128-bit subvector, insert
11063   // into that, and then insert the subvector back into the result.
11064   if (VT.is256BitVector() || VT.is512BitVector()) {
11065     // With a 256-bit vector, we can insert into the zero element efficiently
11066     // using a blend if we have AVX or AVX2 and the right data type.
11067     if (VT.is256BitVector() && IdxVal == 0) {
11068       // TODO: It is worthwhile to cast integer to floating point and back
11069       // and incur a domain crossing penalty if that's what we'll end up
11070       // doing anyway after extracting to a 128-bit vector.
11071       if ((Subtarget->hasAVX() && (EltVT == MVT::f64 || EltVT == MVT::f32)) ||
11072           (Subtarget->hasAVX2() && EltVT == MVT::i32)) {
11073         SDValue N1Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, N1);
11074         N2 = DAG.getIntPtrConstant(1, dl);
11075         return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1Vec, N2);
11076       }
11077     }
11078
11079     // Get the desired 128-bit vector chunk.
11080     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
11081
11082     // Insert the element into the desired chunk.
11083     unsigned NumEltsIn128 = 128 / EltVT.getSizeInBits();
11084     unsigned IdxIn128 = IdxVal - (IdxVal / NumEltsIn128) * NumEltsIn128;
11085
11086     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
11087                     DAG.getConstant(IdxIn128, dl, MVT::i32));
11088
11089     // Insert the changed part back into the bigger vector
11090     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
11091   }
11092   assert(VT.is128BitVector() && "Only 128-bit vector types should be left!");
11093
11094   if (Subtarget->hasSSE41()) {
11095     if (EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) {
11096       unsigned Opc;
11097       if (VT == MVT::v8i16) {
11098         Opc = X86ISD::PINSRW;
11099       } else {
11100         assert(VT == MVT::v16i8);
11101         Opc = X86ISD::PINSRB;
11102       }
11103
11104       // Transform it so it match pinsr{b,w} which expects a GR32 as its second
11105       // argument.
11106       if (N1.getValueType() != MVT::i32)
11107         N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
11108       if (N2.getValueType() != MVT::i32)
11109         N2 = DAG.getIntPtrConstant(IdxVal, dl);
11110       return DAG.getNode(Opc, dl, VT, N0, N1, N2);
11111     }
11112
11113     if (EltVT == MVT::f32) {
11114       // Bits [7:6] of the constant are the source select. This will always be
11115       //   zero here. The DAG Combiner may combine an extract_elt index into
11116       //   these bits. For example (insert (extract, 3), 2) could be matched by
11117       //   putting the '3' into bits [7:6] of X86ISD::INSERTPS.
11118       // Bits [5:4] of the constant are the destination select. This is the
11119       //   value of the incoming immediate.
11120       // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
11121       //   combine either bitwise AND or insert of float 0.0 to set these bits.
11122
11123       const Function *F = DAG.getMachineFunction().getFunction();
11124       bool MinSize = F->hasFnAttribute(Attribute::MinSize);
11125       if (IdxVal == 0 && (!MinSize || !MayFoldLoad(N1))) {
11126         // If this is an insertion of 32-bits into the low 32-bits of
11127         // a vector, we prefer to generate a blend with immediate rather
11128         // than an insertps. Blends are simpler operations in hardware and so
11129         // will always have equal or better performance than insertps.
11130         // But if optimizing for size and there's a load folding opportunity,
11131         // generate insertps because blendps does not have a 32-bit memory
11132         // operand form.
11133         N2 = DAG.getIntPtrConstant(1, dl);
11134         N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
11135         return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1, N2);
11136       }
11137       N2 = DAG.getIntPtrConstant(IdxVal << 4, dl);
11138       // Create this as a scalar to vector..
11139       N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
11140       return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
11141     }
11142
11143     if (EltVT == MVT::i32 || EltVT == MVT::i64) {
11144       // PINSR* works with constant index.
11145       return Op;
11146     }
11147   }
11148
11149   if (EltVT == MVT::i8)
11150     return SDValue();
11151
11152   if (EltVT.getSizeInBits() == 16) {
11153     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
11154     // as its second argument.
11155     if (N1.getValueType() != MVT::i32)
11156       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
11157     if (N2.getValueType() != MVT::i32)
11158       N2 = DAG.getIntPtrConstant(IdxVal, dl);
11159     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
11160   }
11161   return SDValue();
11162 }
11163
11164 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
11165   SDLoc dl(Op);
11166   MVT OpVT = Op.getSimpleValueType();
11167
11168   // If this is a 256-bit vector result, first insert into a 128-bit
11169   // vector and then insert into the 256-bit vector.
11170   if (!OpVT.is128BitVector()) {
11171     // Insert into a 128-bit vector.
11172     unsigned SizeFactor = OpVT.getSizeInBits()/128;
11173     MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
11174                                  OpVT.getVectorNumElements() / SizeFactor);
11175
11176     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
11177
11178     // Insert the 128-bit vector.
11179     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
11180   }
11181
11182   if (OpVT == MVT::v1i64 &&
11183       Op.getOperand(0).getValueType() == MVT::i64)
11184     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
11185
11186   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
11187   assert(OpVT.is128BitVector() && "Expected an SSE type!");
11188   return DAG.getBitcast(
11189       OpVT, DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, AnyExt));
11190 }
11191
11192 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
11193 // a simple subregister reference or explicit instructions to grab
11194 // upper bits of a vector.
11195 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
11196                                       SelectionDAG &DAG) {
11197   SDLoc dl(Op);
11198   SDValue In =  Op.getOperand(0);
11199   SDValue Idx = Op.getOperand(1);
11200   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11201   MVT ResVT   = Op.getSimpleValueType();
11202   MVT InVT    = In.getSimpleValueType();
11203
11204   if (Subtarget->hasFp256()) {
11205     if (ResVT.is128BitVector() &&
11206         (InVT.is256BitVector() || InVT.is512BitVector()) &&
11207         isa<ConstantSDNode>(Idx)) {
11208       return Extract128BitVector(In, IdxVal, DAG, dl);
11209     }
11210     if (ResVT.is256BitVector() && InVT.is512BitVector() &&
11211         isa<ConstantSDNode>(Idx)) {
11212       return Extract256BitVector(In, IdxVal, DAG, dl);
11213     }
11214   }
11215   return SDValue();
11216 }
11217
11218 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
11219 // simple superregister reference or explicit instructions to insert
11220 // the upper bits of a vector.
11221 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
11222                                      SelectionDAG &DAG) {
11223   if (!Subtarget->hasAVX())
11224     return SDValue();
11225
11226   SDLoc dl(Op);
11227   SDValue Vec = Op.getOperand(0);
11228   SDValue SubVec = Op.getOperand(1);
11229   SDValue Idx = Op.getOperand(2);
11230
11231   if (!isa<ConstantSDNode>(Idx))
11232     return SDValue();
11233
11234   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11235   MVT OpVT = Op.getSimpleValueType();
11236   MVT SubVecVT = SubVec.getSimpleValueType();
11237
11238   // Fold two 16-byte subvector loads into one 32-byte load:
11239   // (insert_subvector (insert_subvector undef, (load addr), 0),
11240   //                   (load addr + 16), Elts/2)
11241   // --> load32 addr
11242   if ((IdxVal == OpVT.getVectorNumElements() / 2) &&
11243       Vec.getOpcode() == ISD::INSERT_SUBVECTOR &&
11244       OpVT.is256BitVector() && SubVecVT.is128BitVector() &&
11245       !Subtarget->isUnalignedMem32Slow()) {
11246     SDValue SubVec2 = Vec.getOperand(1);
11247     if (auto *Idx2 = dyn_cast<ConstantSDNode>(Vec.getOperand(2))) {
11248       if (Idx2->getZExtValue() == 0) {
11249         SDValue Ops[] = { SubVec2, SubVec };
11250         if (SDValue Ld = EltsFromConsecutiveLoads(OpVT, Ops, dl, DAG, false))
11251           return Ld;
11252       }
11253     }
11254   }
11255
11256   if ((OpVT.is256BitVector() || OpVT.is512BitVector()) &&
11257       SubVecVT.is128BitVector())
11258     return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
11259
11260   if (OpVT.is512BitVector() && SubVecVT.is256BitVector())
11261     return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
11262
11263   if (OpVT.getVectorElementType() == MVT::i1) {
11264     if (IdxVal == 0  && Vec.getOpcode() == ISD::UNDEF) // the operation is legal
11265       return Op;
11266     SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
11267     SDValue Undef = DAG.getUNDEF(OpVT);
11268     unsigned NumElems = OpVT.getVectorNumElements();
11269     SDValue ShiftBits = DAG.getConstant(NumElems/2, dl, MVT::i8);
11270
11271     if (IdxVal == OpVT.getVectorNumElements() / 2) {
11272       // Zero upper bits of the Vec
11273       Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
11274       Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
11275
11276       SDValue Vec2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef,
11277                                  SubVec, ZeroIdx);
11278       Vec2 = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec2, ShiftBits);
11279       return DAG.getNode(ISD::OR, dl, OpVT, Vec, Vec2);
11280     }
11281     if (IdxVal == 0) {
11282       SDValue Vec2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef,
11283                                  SubVec, ZeroIdx);
11284       // Zero upper bits of the Vec2
11285       Vec2 = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec2, ShiftBits);
11286       Vec2 = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec2, ShiftBits);
11287       // Zero lower bits of the Vec
11288       Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
11289       Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
11290       // Merge them together
11291       return DAG.getNode(ISD::OR, dl, OpVT, Vec, Vec2);
11292     }
11293   }
11294   return SDValue();
11295 }
11296
11297 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
11298 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
11299 // one of the above mentioned nodes. It has to be wrapped because otherwise
11300 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
11301 // be used to form addressing mode. These wrapped nodes will be selected
11302 // into MOV32ri.
11303 SDValue
11304 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
11305   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
11306
11307   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11308   // global base reg.
11309   unsigned char OpFlag = 0;
11310   unsigned WrapperKind = X86ISD::Wrapper;
11311   CodeModel::Model M = DAG.getTarget().getCodeModel();
11312
11313   if (Subtarget->isPICStyleRIPRel() &&
11314       (M == CodeModel::Small || M == CodeModel::Kernel))
11315     WrapperKind = X86ISD::WrapperRIP;
11316   else if (Subtarget->isPICStyleGOT())
11317     OpFlag = X86II::MO_GOTOFF;
11318   else if (Subtarget->isPICStyleStubPIC())
11319     OpFlag = X86II::MO_PIC_BASE_OFFSET;
11320
11321   auto PtrVT = getPointerTy(DAG.getDataLayout());
11322   SDValue Result = DAG.getTargetConstantPool(
11323       CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(), OpFlag);
11324   SDLoc DL(CP);
11325   Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11326   // With PIC, the address is actually $g + Offset.
11327   if (OpFlag) {
11328     Result =
11329         DAG.getNode(ISD::ADD, DL, PtrVT,
11330                     DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
11331   }
11332
11333   return Result;
11334 }
11335
11336 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
11337   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
11338
11339   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11340   // global base reg.
11341   unsigned char OpFlag = 0;
11342   unsigned WrapperKind = X86ISD::Wrapper;
11343   CodeModel::Model M = DAG.getTarget().getCodeModel();
11344
11345   if (Subtarget->isPICStyleRIPRel() &&
11346       (M == CodeModel::Small || M == CodeModel::Kernel))
11347     WrapperKind = X86ISD::WrapperRIP;
11348   else if (Subtarget->isPICStyleGOT())
11349     OpFlag = X86II::MO_GOTOFF;
11350   else if (Subtarget->isPICStyleStubPIC())
11351     OpFlag = X86II::MO_PIC_BASE_OFFSET;
11352
11353   auto PtrVT = getPointerTy(DAG.getDataLayout());
11354   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, OpFlag);
11355   SDLoc DL(JT);
11356   Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11357
11358   // With PIC, the address is actually $g + Offset.
11359   if (OpFlag)
11360     Result =
11361         DAG.getNode(ISD::ADD, DL, PtrVT,
11362                     DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
11363
11364   return Result;
11365 }
11366
11367 SDValue
11368 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
11369   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
11370
11371   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11372   // global base reg.
11373   unsigned char OpFlag = 0;
11374   unsigned WrapperKind = X86ISD::Wrapper;
11375   CodeModel::Model M = DAG.getTarget().getCodeModel();
11376
11377   if (Subtarget->isPICStyleRIPRel() &&
11378       (M == CodeModel::Small || M == CodeModel::Kernel)) {
11379     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
11380       OpFlag = X86II::MO_GOTPCREL;
11381     WrapperKind = X86ISD::WrapperRIP;
11382   } else if (Subtarget->isPICStyleGOT()) {
11383     OpFlag = X86II::MO_GOT;
11384   } else if (Subtarget->isPICStyleStubPIC()) {
11385     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
11386   } else if (Subtarget->isPICStyleStubNoDynamic()) {
11387     OpFlag = X86II::MO_DARWIN_NONLAZY;
11388   }
11389
11390   auto PtrVT = getPointerTy(DAG.getDataLayout());
11391   SDValue Result = DAG.getTargetExternalSymbol(Sym, PtrVT, OpFlag);
11392
11393   SDLoc DL(Op);
11394   Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11395
11396   // With PIC, the address is actually $g + Offset.
11397   if (DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
11398       !Subtarget->is64Bit()) {
11399     Result =
11400         DAG.getNode(ISD::ADD, DL, PtrVT,
11401                     DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
11402   }
11403
11404   // For symbols that require a load from a stub to get the address, emit the
11405   // load.
11406   if (isGlobalStubReference(OpFlag))
11407     Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
11408                          MachinePointerInfo::getGOT(), false, false, false, 0);
11409
11410   return Result;
11411 }
11412
11413 SDValue
11414 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
11415   // Create the TargetBlockAddressAddress node.
11416   unsigned char OpFlags =
11417     Subtarget->ClassifyBlockAddressReference();
11418   CodeModel::Model M = DAG.getTarget().getCodeModel();
11419   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
11420   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
11421   SDLoc dl(Op);
11422   auto PtrVT = getPointerTy(DAG.getDataLayout());
11423   SDValue Result = DAG.getTargetBlockAddress(BA, PtrVT, Offset, OpFlags);
11424
11425   if (Subtarget->isPICStyleRIPRel() &&
11426       (M == CodeModel::Small || M == CodeModel::Kernel))
11427     Result = DAG.getNode(X86ISD::WrapperRIP, dl, PtrVT, Result);
11428   else
11429     Result = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, Result);
11430
11431   // With PIC, the address is actually $g + Offset.
11432   if (isGlobalRelativeToPICBase(OpFlags)) {
11433     Result = DAG.getNode(ISD::ADD, dl, PtrVT,
11434                          DAG.getNode(X86ISD::GlobalBaseReg, dl, PtrVT), Result);
11435   }
11436
11437   return Result;
11438 }
11439
11440 SDValue
11441 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
11442                                       int64_t Offset, SelectionDAG &DAG) const {
11443   // Create the TargetGlobalAddress node, folding in the constant
11444   // offset if it is legal.
11445   unsigned char OpFlags =
11446       Subtarget->ClassifyGlobalReference(GV, DAG.getTarget());
11447   CodeModel::Model M = DAG.getTarget().getCodeModel();
11448   auto PtrVT = getPointerTy(DAG.getDataLayout());
11449   SDValue Result;
11450   if (OpFlags == X86II::MO_NO_FLAG &&
11451       X86::isOffsetSuitableForCodeModel(Offset, M)) {
11452     // A direct static reference to a global.
11453     Result = DAG.getTargetGlobalAddress(GV, dl, PtrVT, Offset);
11454     Offset = 0;
11455   } else {
11456     Result = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, OpFlags);
11457   }
11458
11459   if (Subtarget->isPICStyleRIPRel() &&
11460       (M == CodeModel::Small || M == CodeModel::Kernel))
11461     Result = DAG.getNode(X86ISD::WrapperRIP, dl, PtrVT, Result);
11462   else
11463     Result = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, Result);
11464
11465   // With PIC, the address is actually $g + Offset.
11466   if (isGlobalRelativeToPICBase(OpFlags)) {
11467     Result = DAG.getNode(ISD::ADD, dl, PtrVT,
11468                          DAG.getNode(X86ISD::GlobalBaseReg, dl, PtrVT), Result);
11469   }
11470
11471   // For globals that require a load from a stub to get the address, emit the
11472   // load.
11473   if (isGlobalStubReference(OpFlags))
11474     Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
11475                          MachinePointerInfo::getGOT(), false, false, false, 0);
11476
11477   // If there was a non-zero offset that we didn't fold, create an explicit
11478   // addition for it.
11479   if (Offset != 0)
11480     Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result,
11481                          DAG.getConstant(Offset, dl, PtrVT));
11482
11483   return Result;
11484 }
11485
11486 SDValue
11487 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
11488   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
11489   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
11490   return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
11491 }
11492
11493 static SDValue
11494 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
11495            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
11496            unsigned char OperandFlags, bool LocalDynamic = false) {
11497   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11498   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11499   SDLoc dl(GA);
11500   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11501                                            GA->getValueType(0),
11502                                            GA->getOffset(),
11503                                            OperandFlags);
11504
11505   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
11506                                            : X86ISD::TLSADDR;
11507
11508   if (InFlag) {
11509     SDValue Ops[] = { Chain,  TGA, *InFlag };
11510     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11511   } else {
11512     SDValue Ops[]  = { Chain, TGA };
11513     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11514   }
11515
11516   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
11517   MFI->setAdjustsStack(true);
11518   MFI->setHasCalls(true);
11519
11520   SDValue Flag = Chain.getValue(1);
11521   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
11522 }
11523
11524 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
11525 static SDValue
11526 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11527                                 const EVT PtrVT) {
11528   SDValue InFlag;
11529   SDLoc dl(GA);  // ? function entry point might be better
11530   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
11531                                    DAG.getNode(X86ISD::GlobalBaseReg,
11532                                                SDLoc(), PtrVT), InFlag);
11533   InFlag = Chain.getValue(1);
11534
11535   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
11536 }
11537
11538 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
11539 static SDValue
11540 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11541                                 const EVT PtrVT) {
11542   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
11543                     X86::RAX, X86II::MO_TLSGD);
11544 }
11545
11546 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
11547                                            SelectionDAG &DAG,
11548                                            const EVT PtrVT,
11549                                            bool is64Bit) {
11550   SDLoc dl(GA);
11551
11552   // Get the start address of the TLS block for this module.
11553   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
11554       .getInfo<X86MachineFunctionInfo>();
11555   MFI->incNumLocalDynamicTLSAccesses();
11556
11557   SDValue Base;
11558   if (is64Bit) {
11559     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
11560                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
11561   } else {
11562     SDValue InFlag;
11563     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
11564         DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
11565     InFlag = Chain.getValue(1);
11566     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
11567                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
11568   }
11569
11570   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
11571   // of Base.
11572
11573   // Build x@dtpoff.
11574   unsigned char OperandFlags = X86II::MO_DTPOFF;
11575   unsigned WrapperKind = X86ISD::Wrapper;
11576   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11577                                            GA->getValueType(0),
11578                                            GA->getOffset(), OperandFlags);
11579   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
11580
11581   // Add x@dtpoff with the base.
11582   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
11583 }
11584
11585 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
11586 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11587                                    const EVT PtrVT, TLSModel::Model model,
11588                                    bool is64Bit, bool isPIC) {
11589   SDLoc dl(GA);
11590
11591   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
11592   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
11593                                                          is64Bit ? 257 : 256));
11594
11595   SDValue ThreadPointer =
11596       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0, dl),
11597                   MachinePointerInfo(Ptr), false, false, false, 0);
11598
11599   unsigned char OperandFlags = 0;
11600   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
11601   // initialexec.
11602   unsigned WrapperKind = X86ISD::Wrapper;
11603   if (model == TLSModel::LocalExec) {
11604     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
11605   } else if (model == TLSModel::InitialExec) {
11606     if (is64Bit) {
11607       OperandFlags = X86II::MO_GOTTPOFF;
11608       WrapperKind = X86ISD::WrapperRIP;
11609     } else {
11610       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
11611     }
11612   } else {
11613     llvm_unreachable("Unexpected model");
11614   }
11615
11616   // emit "addl x@ntpoff,%eax" (local exec)
11617   // or "addl x@indntpoff,%eax" (initial exec)
11618   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
11619   SDValue TGA =
11620       DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
11621                                  GA->getOffset(), OperandFlags);
11622   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
11623
11624   if (model == TLSModel::InitialExec) {
11625     if (isPIC && !is64Bit) {
11626       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
11627                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
11628                            Offset);
11629     }
11630
11631     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
11632                          MachinePointerInfo::getGOT(), false, false, false, 0);
11633   }
11634
11635   // The address of the thread local variable is the add of the thread
11636   // pointer with the offset of the variable.
11637   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
11638 }
11639
11640 SDValue
11641 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
11642
11643   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
11644   const GlobalValue *GV = GA->getGlobal();
11645   auto PtrVT = getPointerTy(DAG.getDataLayout());
11646
11647   if (Subtarget->isTargetELF()) {
11648     if (DAG.getTarget().Options.EmulatedTLS)
11649       return LowerToTLSEmulatedModel(GA, DAG);
11650     TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
11651     switch (model) {
11652       case TLSModel::GeneralDynamic:
11653         if (Subtarget->is64Bit())
11654           return LowerToTLSGeneralDynamicModel64(GA, DAG, PtrVT);
11655         return LowerToTLSGeneralDynamicModel32(GA, DAG, PtrVT);
11656       case TLSModel::LocalDynamic:
11657         return LowerToTLSLocalDynamicModel(GA, DAG, PtrVT,
11658                                            Subtarget->is64Bit());
11659       case TLSModel::InitialExec:
11660       case TLSModel::LocalExec:
11661         return LowerToTLSExecModel(GA, DAG, PtrVT, model, Subtarget->is64Bit(),
11662                                    DAG.getTarget().getRelocationModel() ==
11663                                        Reloc::PIC_);
11664     }
11665     llvm_unreachable("Unknown TLS model.");
11666   }
11667
11668   if (Subtarget->isTargetDarwin()) {
11669     // Darwin only has one model of TLS.  Lower to that.
11670     unsigned char OpFlag = 0;
11671     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
11672                            X86ISD::WrapperRIP : X86ISD::Wrapper;
11673
11674     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11675     // global base reg.
11676     bool PIC32 = (DAG.getTarget().getRelocationModel() == Reloc::PIC_) &&
11677                  !Subtarget->is64Bit();
11678     if (PIC32)
11679       OpFlag = X86II::MO_TLVP_PIC_BASE;
11680     else
11681       OpFlag = X86II::MO_TLVP;
11682     SDLoc DL(Op);
11683     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
11684                                                 GA->getValueType(0),
11685                                                 GA->getOffset(), OpFlag);
11686     SDValue Offset = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11687
11688     // With PIC32, the address is actually $g + Offset.
11689     if (PIC32)
11690       Offset = DAG.getNode(ISD::ADD, DL, PtrVT,
11691                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
11692                            Offset);
11693
11694     // Lowering the machine isd will make sure everything is in the right
11695     // location.
11696     SDValue Chain = DAG.getEntryNode();
11697     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11698     SDValue Args[] = { Chain, Offset };
11699     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
11700
11701     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
11702     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11703     MFI->setAdjustsStack(true);
11704
11705     // And our return value (tls address) is in the standard call return value
11706     // location.
11707     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
11708     return DAG.getCopyFromReg(Chain, DL, Reg, PtrVT, Chain.getValue(1));
11709   }
11710
11711   if (Subtarget->isTargetKnownWindowsMSVC() ||
11712       Subtarget->isTargetWindowsGNU()) {
11713     // Just use the implicit TLS architecture
11714     // Need to generate someting similar to:
11715     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
11716     //                                  ; from TEB
11717     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
11718     //   mov     rcx, qword [rdx+rcx*8]
11719     //   mov     eax, .tls$:tlsvar
11720     //   [rax+rcx] contains the address
11721     // Windows 64bit: gs:0x58
11722     // Windows 32bit: fs:__tls_array
11723
11724     SDLoc dl(GA);
11725     SDValue Chain = DAG.getEntryNode();
11726
11727     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
11728     // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
11729     // use its literal value of 0x2C.
11730     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
11731                                         ? Type::getInt8PtrTy(*DAG.getContext(),
11732                                                              256)
11733                                         : Type::getInt32PtrTy(*DAG.getContext(),
11734                                                               257));
11735
11736     SDValue TlsArray = Subtarget->is64Bit()
11737                            ? DAG.getIntPtrConstant(0x58, dl)
11738                            : (Subtarget->isTargetWindowsGNU()
11739                                   ? DAG.getIntPtrConstant(0x2C, dl)
11740                                   : DAG.getExternalSymbol("_tls_array", PtrVT));
11741
11742     SDValue ThreadPointer =
11743         DAG.getLoad(PtrVT, dl, Chain, TlsArray, MachinePointerInfo(Ptr), false,
11744                     false, false, 0);
11745
11746     SDValue res;
11747     if (GV->getThreadLocalMode() == GlobalVariable::LocalExecTLSModel) {
11748       res = ThreadPointer;
11749     } else {
11750       // Load the _tls_index variable
11751       SDValue IDX = DAG.getExternalSymbol("_tls_index", PtrVT);
11752       if (Subtarget->is64Bit())
11753         IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, PtrVT, Chain, IDX,
11754                              MachinePointerInfo(), MVT::i32, false, false,
11755                              false, 0);
11756       else
11757         IDX = DAG.getLoad(PtrVT, dl, Chain, IDX, MachinePointerInfo(), false,
11758                           false, false, 0);
11759
11760       auto &DL = DAG.getDataLayout();
11761       SDValue Scale =
11762           DAG.getConstant(Log2_64_Ceil(DL.getPointerSize()), dl, PtrVT);
11763       IDX = DAG.getNode(ISD::SHL, dl, PtrVT, IDX, Scale);
11764
11765       res = DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, IDX);
11766     }
11767
11768     res = DAG.getLoad(PtrVT, dl, Chain, res, MachinePointerInfo(), false, false,
11769                       false, 0);
11770
11771     // Get the offset of start of .tls section
11772     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11773                                              GA->getValueType(0),
11774                                              GA->getOffset(), X86II::MO_SECREL);
11775     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, TGA);
11776
11777     // The address of the thread local variable is the add of the thread
11778     // pointer with the offset of the variable.
11779     return DAG.getNode(ISD::ADD, dl, PtrVT, res, Offset);
11780   }
11781
11782   llvm_unreachable("TLS not implemented for this target.");
11783 }
11784
11785 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
11786 /// and take a 2 x i32 value to shift plus a shift amount.
11787 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
11788   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
11789   MVT VT = Op.getSimpleValueType();
11790   unsigned VTBits = VT.getSizeInBits();
11791   SDLoc dl(Op);
11792   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
11793   SDValue ShOpLo = Op.getOperand(0);
11794   SDValue ShOpHi = Op.getOperand(1);
11795   SDValue ShAmt  = Op.getOperand(2);
11796   // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
11797   // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
11798   // during isel.
11799   SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
11800                                   DAG.getConstant(VTBits - 1, dl, MVT::i8));
11801   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
11802                                      DAG.getConstant(VTBits - 1, dl, MVT::i8))
11803                        : DAG.getConstant(0, dl, VT);
11804
11805   SDValue Tmp2, Tmp3;
11806   if (Op.getOpcode() == ISD::SHL_PARTS) {
11807     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
11808     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
11809   } else {
11810     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
11811     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
11812   }
11813
11814   // If the shift amount is larger or equal than the width of a part we can't
11815   // rely on the results of shld/shrd. Insert a test and select the appropriate
11816   // values for large shift amounts.
11817   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
11818                                 DAG.getConstant(VTBits, dl, MVT::i8));
11819   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11820                              AndNode, DAG.getConstant(0, dl, MVT::i8));
11821
11822   SDValue Hi, Lo;
11823   SDValue CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
11824   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
11825   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
11826
11827   if (Op.getOpcode() == ISD::SHL_PARTS) {
11828     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
11829     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
11830   } else {
11831     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
11832     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
11833   }
11834
11835   SDValue Ops[2] = { Lo, Hi };
11836   return DAG.getMergeValues(Ops, dl);
11837 }
11838
11839 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
11840                                            SelectionDAG &DAG) const {
11841   SDValue Src = Op.getOperand(0);
11842   MVT SrcVT = Src.getSimpleValueType();
11843   MVT VT = Op.getSimpleValueType();
11844   SDLoc dl(Op);
11845
11846   if (SrcVT.isVector()) {
11847     if (SrcVT == MVT::v2i32 && VT == MVT::v2f64) {
11848       return DAG.getNode(X86ISD::CVTDQ2PD, dl, VT,
11849                          DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4i32, Src,
11850                          DAG.getUNDEF(SrcVT)));
11851     }
11852     if (SrcVT.getVectorElementType() == MVT::i1) {
11853       MVT IntegerVT = MVT::getVectorVT(MVT::i32, SrcVT.getVectorNumElements());
11854       return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
11855                          DAG.getNode(ISD::SIGN_EXTEND, dl, IntegerVT, Src));
11856     }
11857     return SDValue();
11858   }
11859
11860   assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
11861          "Unknown SINT_TO_FP to lower!");
11862
11863   // These are really Legal; return the operand so the caller accepts it as
11864   // Legal.
11865   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
11866     return Op;
11867   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
11868       Subtarget->is64Bit()) {
11869     return Op;
11870   }
11871
11872   unsigned Size = SrcVT.getSizeInBits()/8;
11873   MachineFunction &MF = DAG.getMachineFunction();
11874   auto PtrVT = getPointerTy(MF.getDataLayout());
11875   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
11876   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
11877   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11878                                StackSlot,
11879                                MachinePointerInfo::getFixedStack(SSFI),
11880                                false, false, 0);
11881   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
11882 }
11883
11884 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
11885                                      SDValue StackSlot,
11886                                      SelectionDAG &DAG) const {
11887   // Build the FILD
11888   SDLoc DL(Op);
11889   SDVTList Tys;
11890   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
11891   if (useSSE)
11892     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
11893   else
11894     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
11895
11896   unsigned ByteSize = SrcVT.getSizeInBits()/8;
11897
11898   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
11899   MachineMemOperand *MMO;
11900   if (FI) {
11901     int SSFI = FI->getIndex();
11902     MMO =
11903       DAG.getMachineFunction()
11904       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11905                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
11906   } else {
11907     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
11908     StackSlot = StackSlot.getOperand(1);
11909   }
11910   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
11911   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
11912                                            X86ISD::FILD, DL,
11913                                            Tys, Ops, SrcVT, MMO);
11914
11915   if (useSSE) {
11916     Chain = Result.getValue(1);
11917     SDValue InFlag = Result.getValue(2);
11918
11919     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
11920     // shouldn't be necessary except that RFP cannot be live across
11921     // multiple blocks. When stackifier is fixed, they can be uncoupled.
11922     MachineFunction &MF = DAG.getMachineFunction();
11923     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
11924     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
11925     auto PtrVT = getPointerTy(MF.getDataLayout());
11926     SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
11927     Tys = DAG.getVTList(MVT::Other);
11928     SDValue Ops[] = {
11929       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
11930     };
11931     MachineMemOperand *MMO =
11932       DAG.getMachineFunction()
11933       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11934                             MachineMemOperand::MOStore, SSFISize, SSFISize);
11935
11936     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
11937                                     Ops, Op.getValueType(), MMO);
11938     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
11939                          MachinePointerInfo::getFixedStack(SSFI),
11940                          false, false, false, 0);
11941   }
11942
11943   return Result;
11944 }
11945
11946 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
11947 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
11948                                                SelectionDAG &DAG) const {
11949   // This algorithm is not obvious. Here it is what we're trying to output:
11950   /*
11951      movq       %rax,  %xmm0
11952      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
11953      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
11954      #ifdef __SSE3__
11955        haddpd   %xmm0, %xmm0
11956      #else
11957        pshufd   $0x4e, %xmm0, %xmm1
11958        addpd    %xmm1, %xmm0
11959      #endif
11960   */
11961
11962   SDLoc dl(Op);
11963   LLVMContext *Context = DAG.getContext();
11964
11965   // Build some magic constants.
11966   static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
11967   Constant *C0 = ConstantDataVector::get(*Context, CV0);
11968   auto PtrVT = getPointerTy(DAG.getDataLayout());
11969   SDValue CPIdx0 = DAG.getConstantPool(C0, PtrVT, 16);
11970
11971   SmallVector<Constant*,2> CV1;
11972   CV1.push_back(
11973     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11974                                       APInt(64, 0x4330000000000000ULL))));
11975   CV1.push_back(
11976     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11977                                       APInt(64, 0x4530000000000000ULL))));
11978   Constant *C1 = ConstantVector::get(CV1);
11979   SDValue CPIdx1 = DAG.getConstantPool(C1, PtrVT, 16);
11980
11981   // Load the 64-bit value into an XMM register.
11982   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
11983                             Op.getOperand(0));
11984   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
11985                               MachinePointerInfo::getConstantPool(),
11986                               false, false, false, 16);
11987   SDValue Unpck1 =
11988       getUnpackl(DAG, dl, MVT::v4i32, DAG.getBitcast(MVT::v4i32, XR1), CLod0);
11989
11990   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
11991                               MachinePointerInfo::getConstantPool(),
11992                               false, false, false, 16);
11993   SDValue XR2F = DAG.getBitcast(MVT::v2f64, Unpck1);
11994   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
11995   SDValue Result;
11996
11997   if (Subtarget->hasSSE3()) {
11998     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
11999     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
12000   } else {
12001     SDValue S2F = DAG.getBitcast(MVT::v4i32, Sub);
12002     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
12003                                            S2F, 0x4E, DAG);
12004     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
12005                          DAG.getBitcast(MVT::v2f64, Shuffle), Sub);
12006   }
12007
12008   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
12009                      DAG.getIntPtrConstant(0, dl));
12010 }
12011
12012 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
12013 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
12014                                                SelectionDAG &DAG) const {
12015   SDLoc dl(Op);
12016   // FP constant to bias correct the final result.
12017   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
12018                                    MVT::f64);
12019
12020   // Load the 32-bit value into an XMM register.
12021   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
12022                              Op.getOperand(0));
12023
12024   // Zero out the upper parts of the register.
12025   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
12026
12027   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
12028                      DAG.getBitcast(MVT::v2f64, Load),
12029                      DAG.getIntPtrConstant(0, dl));
12030
12031   // Or the load with the bias.
12032   SDValue Or = DAG.getNode(
12033       ISD::OR, dl, MVT::v2i64,
12034       DAG.getBitcast(MVT::v2i64,
12035                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, Load)),
12036       DAG.getBitcast(MVT::v2i64,
12037                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, Bias)));
12038   Or =
12039       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
12040                   DAG.getBitcast(MVT::v2f64, Or), DAG.getIntPtrConstant(0, dl));
12041
12042   // Subtract the bias.
12043   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
12044
12045   // Handle final rounding.
12046   EVT DestVT = Op.getValueType();
12047
12048   if (DestVT.bitsLT(MVT::f64))
12049     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
12050                        DAG.getIntPtrConstant(0, dl));
12051   if (DestVT.bitsGT(MVT::f64))
12052     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
12053
12054   // Handle final rounding.
12055   return Sub;
12056 }
12057
12058 static SDValue lowerUINT_TO_FP_vXi32(SDValue Op, SelectionDAG &DAG,
12059                                      const X86Subtarget &Subtarget) {
12060   // The algorithm is the following:
12061   // #ifdef __SSE4_1__
12062   //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
12063   //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
12064   //                                 (uint4) 0x53000000, 0xaa);
12065   // #else
12066   //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
12067   //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
12068   // #endif
12069   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
12070   //     return (float4) lo + fhi;
12071
12072   SDLoc DL(Op);
12073   SDValue V = Op->getOperand(0);
12074   EVT VecIntVT = V.getValueType();
12075   bool Is128 = VecIntVT == MVT::v4i32;
12076   EVT VecFloatVT = Is128 ? MVT::v4f32 : MVT::v8f32;
12077   // If we convert to something else than the supported type, e.g., to v4f64,
12078   // abort early.
12079   if (VecFloatVT != Op->getValueType(0))
12080     return SDValue();
12081
12082   unsigned NumElts = VecIntVT.getVectorNumElements();
12083   assert((VecIntVT == MVT::v4i32 || VecIntVT == MVT::v8i32) &&
12084          "Unsupported custom type");
12085   assert(NumElts <= 8 && "The size of the constant array must be fixed");
12086
12087   // In the #idef/#else code, we have in common:
12088   // - The vector of constants:
12089   // -- 0x4b000000
12090   // -- 0x53000000
12091   // - A shift:
12092   // -- v >> 16
12093
12094   // Create the splat vector for 0x4b000000.
12095   SDValue CstLow = DAG.getConstant(0x4b000000, DL, MVT::i32);
12096   SDValue CstLowArray[] = {CstLow, CstLow, CstLow, CstLow,
12097                            CstLow, CstLow, CstLow, CstLow};
12098   SDValue VecCstLow = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12099                                   makeArrayRef(&CstLowArray[0], NumElts));
12100   // Create the splat vector for 0x53000000.
12101   SDValue CstHigh = DAG.getConstant(0x53000000, DL, MVT::i32);
12102   SDValue CstHighArray[] = {CstHigh, CstHigh, CstHigh, CstHigh,
12103                             CstHigh, CstHigh, CstHigh, CstHigh};
12104   SDValue VecCstHigh = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12105                                    makeArrayRef(&CstHighArray[0], NumElts));
12106
12107   // Create the right shift.
12108   SDValue CstShift = DAG.getConstant(16, DL, MVT::i32);
12109   SDValue CstShiftArray[] = {CstShift, CstShift, CstShift, CstShift,
12110                              CstShift, CstShift, CstShift, CstShift};
12111   SDValue VecCstShift = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12112                                     makeArrayRef(&CstShiftArray[0], NumElts));
12113   SDValue HighShift = DAG.getNode(ISD::SRL, DL, VecIntVT, V, VecCstShift);
12114
12115   SDValue Low, High;
12116   if (Subtarget.hasSSE41()) {
12117     EVT VecI16VT = Is128 ? MVT::v8i16 : MVT::v16i16;
12118     //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
12119     SDValue VecCstLowBitcast = DAG.getBitcast(VecI16VT, VecCstLow);
12120     SDValue VecBitcast = DAG.getBitcast(VecI16VT, V);
12121     // Low will be bitcasted right away, so do not bother bitcasting back to its
12122     // original type.
12123     Low = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecBitcast,
12124                       VecCstLowBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
12125     //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
12126     //                                 (uint4) 0x53000000, 0xaa);
12127     SDValue VecCstHighBitcast = DAG.getBitcast(VecI16VT, VecCstHigh);
12128     SDValue VecShiftBitcast = DAG.getBitcast(VecI16VT, HighShift);
12129     // High will be bitcasted right away, so do not bother bitcasting back to
12130     // its original type.
12131     High = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecShiftBitcast,
12132                        VecCstHighBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
12133   } else {
12134     SDValue CstMask = DAG.getConstant(0xffff, DL, MVT::i32);
12135     SDValue VecCstMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT, CstMask,
12136                                      CstMask, CstMask, CstMask);
12137     //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
12138     SDValue LowAnd = DAG.getNode(ISD::AND, DL, VecIntVT, V, VecCstMask);
12139     Low = DAG.getNode(ISD::OR, DL, VecIntVT, LowAnd, VecCstLow);
12140
12141     //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
12142     High = DAG.getNode(ISD::OR, DL, VecIntVT, HighShift, VecCstHigh);
12143   }
12144
12145   // Create the vector constant for -(0x1.0p39f + 0x1.0p23f).
12146   SDValue CstFAdd = DAG.getConstantFP(
12147       APFloat(APFloat::IEEEsingle, APInt(32, 0xD3000080)), DL, MVT::f32);
12148   SDValue CstFAddArray[] = {CstFAdd, CstFAdd, CstFAdd, CstFAdd,
12149                             CstFAdd, CstFAdd, CstFAdd, CstFAdd};
12150   SDValue VecCstFAdd = DAG.getNode(ISD::BUILD_VECTOR, DL, VecFloatVT,
12151                                    makeArrayRef(&CstFAddArray[0], NumElts));
12152
12153   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
12154   SDValue HighBitcast = DAG.getBitcast(VecFloatVT, High);
12155   SDValue FHigh =
12156       DAG.getNode(ISD::FADD, DL, VecFloatVT, HighBitcast, VecCstFAdd);
12157   //     return (float4) lo + fhi;
12158   SDValue LowBitcast = DAG.getBitcast(VecFloatVT, Low);
12159   return DAG.getNode(ISD::FADD, DL, VecFloatVT, LowBitcast, FHigh);
12160 }
12161
12162 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
12163                                                SelectionDAG &DAG) const {
12164   SDValue N0 = Op.getOperand(0);
12165   MVT SVT = N0.getSimpleValueType();
12166   SDLoc dl(Op);
12167
12168   switch (SVT.SimpleTy) {
12169   default:
12170     llvm_unreachable("Custom UINT_TO_FP is not supported!");
12171   case MVT::v4i8:
12172   case MVT::v4i16:
12173   case MVT::v8i8:
12174   case MVT::v8i16: {
12175     MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
12176     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
12177                        DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
12178   }
12179   case MVT::v4i32:
12180   case MVT::v8i32:
12181     return lowerUINT_TO_FP_vXi32(Op, DAG, *Subtarget);
12182   case MVT::v16i8:
12183   case MVT::v16i16:
12184     if (Subtarget->hasAVX512())
12185       return DAG.getNode(ISD::UINT_TO_FP, dl, Op.getValueType(),
12186                          DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v16i32, N0));
12187   }
12188   llvm_unreachable(nullptr);
12189 }
12190
12191 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
12192                                            SelectionDAG &DAG) const {
12193   SDValue N0 = Op.getOperand(0);
12194   SDLoc dl(Op);
12195   auto PtrVT = getPointerTy(DAG.getDataLayout());
12196
12197   if (Op.getValueType().isVector())
12198     return lowerUINT_TO_FP_vec(Op, DAG);
12199
12200   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
12201   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
12202   // the optimization here.
12203   if (DAG.SignBitIsZero(N0))
12204     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
12205
12206   MVT SrcVT = N0.getSimpleValueType();
12207   MVT DstVT = Op.getSimpleValueType();
12208   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
12209     return LowerUINT_TO_FP_i64(Op, DAG);
12210   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
12211     return LowerUINT_TO_FP_i32(Op, DAG);
12212   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
12213     return SDValue();
12214
12215   // Make a 64-bit buffer, and use it to build an FILD.
12216   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
12217   if (SrcVT == MVT::i32) {
12218     SDValue WordOff = DAG.getConstant(4, dl, PtrVT);
12219     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, WordOff);
12220     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
12221                                   StackSlot, MachinePointerInfo(),
12222                                   false, false, 0);
12223     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, dl, MVT::i32),
12224                                   OffsetSlot, MachinePointerInfo(),
12225                                   false, false, 0);
12226     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
12227     return Fild;
12228   }
12229
12230   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
12231   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
12232                                StackSlot, MachinePointerInfo(),
12233                                false, false, 0);
12234   // For i64 source, we need to add the appropriate power of 2 if the input
12235   // was negative.  This is the same as the optimization in
12236   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
12237   // we must be careful to do the computation in x87 extended precision, not
12238   // in SSE. (The generic code can't know it's OK to do this, or how to.)
12239   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
12240   MachineMemOperand *MMO =
12241     DAG.getMachineFunction()
12242     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
12243                           MachineMemOperand::MOLoad, 8, 8);
12244
12245   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
12246   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
12247   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
12248                                          MVT::i64, MMO);
12249
12250   APInt FF(32, 0x5F800000ULL);
12251
12252   // Check whether the sign bit is set.
12253   SDValue SignSet = DAG.getSetCC(
12254       dl, getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i64),
12255       Op.getOperand(0), DAG.getConstant(0, dl, MVT::i64), ISD::SETLT);
12256
12257   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
12258   SDValue FudgePtr = DAG.getConstantPool(
12259       ConstantInt::get(*DAG.getContext(), FF.zext(64)), PtrVT);
12260
12261   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
12262   SDValue Zero = DAG.getIntPtrConstant(0, dl);
12263   SDValue Four = DAG.getIntPtrConstant(4, dl);
12264   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
12265                                Zero, Four);
12266   FudgePtr = DAG.getNode(ISD::ADD, dl, PtrVT, FudgePtr, Offset);
12267
12268   // Load the value out, extending it from f32 to f80.
12269   // FIXME: Avoid the extend by constructing the right constant pool?
12270   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
12271                                  FudgePtr, MachinePointerInfo::getConstantPool(),
12272                                  MVT::f32, false, false, false, 4);
12273   // Extend everything to 80 bits to force it to be done on x87.
12274   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
12275   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add,
12276                      DAG.getIntPtrConstant(0, dl));
12277 }
12278
12279 std::pair<SDValue,SDValue>
12280 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
12281                                     bool IsSigned, bool IsReplace) const {
12282   SDLoc DL(Op);
12283
12284   EVT DstTy = Op.getValueType();
12285   auto PtrVT = getPointerTy(DAG.getDataLayout());
12286
12287   if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
12288     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
12289     DstTy = MVT::i64;
12290   }
12291
12292   assert(DstTy.getSimpleVT() <= MVT::i64 &&
12293          DstTy.getSimpleVT() >= MVT::i16 &&
12294          "Unknown FP_TO_INT to lower!");
12295
12296   // These are really Legal.
12297   if (DstTy == MVT::i32 &&
12298       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
12299     return std::make_pair(SDValue(), SDValue());
12300   if (Subtarget->is64Bit() &&
12301       DstTy == MVT::i64 &&
12302       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
12303     return std::make_pair(SDValue(), SDValue());
12304
12305   // We lower FP->int64 either into FISTP64 followed by a load from a temporary
12306   // stack slot, or into the FTOL runtime function.
12307   MachineFunction &MF = DAG.getMachineFunction();
12308   unsigned MemSize = DstTy.getSizeInBits()/8;
12309   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
12310   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12311
12312   unsigned Opc;
12313   if (!IsSigned && isIntegerTypeFTOL(DstTy))
12314     Opc = X86ISD::WIN_FTOL;
12315   else
12316     switch (DstTy.getSimpleVT().SimpleTy) {
12317     default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
12318     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
12319     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
12320     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
12321     }
12322
12323   SDValue Chain = DAG.getEntryNode();
12324   SDValue Value = Op.getOperand(0);
12325   EVT TheVT = Op.getOperand(0).getValueType();
12326   // FIXME This causes a redundant load/store if the SSE-class value is already
12327   // in memory, such as if it is on the callstack.
12328   if (isScalarFPTypeInSSEReg(TheVT)) {
12329     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
12330     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
12331                          MachinePointerInfo::getFixedStack(SSFI),
12332                          false, false, 0);
12333     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
12334     SDValue Ops[] = {
12335       Chain, StackSlot, DAG.getValueType(TheVT)
12336     };
12337
12338     MachineMemOperand *MMO =
12339       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
12340                               MachineMemOperand::MOLoad, MemSize, MemSize);
12341     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
12342     Chain = Value.getValue(1);
12343     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
12344     StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12345   }
12346
12347   MachineMemOperand *MMO =
12348     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
12349                             MachineMemOperand::MOStore, MemSize, MemSize);
12350
12351   if (Opc != X86ISD::WIN_FTOL) {
12352     // Build the FP_TO_INT*_IN_MEM
12353     SDValue Ops[] = { Chain, Value, StackSlot };
12354     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
12355                                            Ops, DstTy, MMO);
12356     return std::make_pair(FIST, StackSlot);
12357   } else {
12358     SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
12359       DAG.getVTList(MVT::Other, MVT::Glue),
12360       Chain, Value);
12361     SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
12362       MVT::i32, ftol.getValue(1));
12363     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
12364       MVT::i32, eax.getValue(2));
12365     SDValue Ops[] = { eax, edx };
12366     SDValue pair = IsReplace
12367       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops)
12368       : DAG.getMergeValues(Ops, DL);
12369     return std::make_pair(pair, SDValue());
12370   }
12371 }
12372
12373 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
12374                               const X86Subtarget *Subtarget) {
12375   MVT VT = Op->getSimpleValueType(0);
12376   SDValue In = Op->getOperand(0);
12377   MVT InVT = In.getSimpleValueType();
12378   SDLoc dl(Op);
12379
12380   if (VT.is512BitVector() || InVT.getScalarType() == MVT::i1)
12381     return DAG.getNode(ISD::ZERO_EXTEND, dl, VT, In);
12382
12383   // Optimize vectors in AVX mode:
12384   //
12385   //   v8i16 -> v8i32
12386   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
12387   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
12388   //   Concat upper and lower parts.
12389   //
12390   //   v4i32 -> v4i64
12391   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
12392   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
12393   //   Concat upper and lower parts.
12394   //
12395
12396   if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
12397       ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
12398       ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
12399     return SDValue();
12400
12401   if (Subtarget->hasInt256())
12402     return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
12403
12404   SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
12405   SDValue Undef = DAG.getUNDEF(InVT);
12406   bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
12407   SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
12408   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
12409
12410   MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
12411                              VT.getVectorNumElements()/2);
12412
12413   OpLo = DAG.getBitcast(HVT, OpLo);
12414   OpHi = DAG.getBitcast(HVT, OpHi);
12415
12416   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
12417 }
12418
12419 static  SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
12420                   const X86Subtarget *Subtarget, SelectionDAG &DAG) {
12421   MVT VT = Op->getSimpleValueType(0);
12422   SDValue In = Op->getOperand(0);
12423   MVT InVT = In.getSimpleValueType();
12424   SDLoc DL(Op);
12425   unsigned int NumElts = VT.getVectorNumElements();
12426   if (NumElts != 8 && NumElts != 16 && !Subtarget->hasBWI())
12427     return SDValue();
12428
12429   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
12430     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
12431
12432   assert(InVT.getVectorElementType() == MVT::i1);
12433   MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
12434   SDValue One =
12435    DAG.getConstant(APInt(ExtVT.getScalarSizeInBits(), 1), DL, ExtVT);
12436   SDValue Zero =
12437    DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), DL, ExtVT);
12438
12439   SDValue V = DAG.getNode(ISD::VSELECT, DL, ExtVT, In, One, Zero);
12440   if (VT.is512BitVector())
12441     return V;
12442   return DAG.getNode(X86ISD::VTRUNC, DL, VT, V);
12443 }
12444
12445 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
12446                                SelectionDAG &DAG) {
12447   if (Subtarget->hasFp256())
12448     if (SDValue Res = LowerAVXExtend(Op, DAG, Subtarget))
12449       return Res;
12450
12451   return SDValue();
12452 }
12453
12454 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
12455                                 SelectionDAG &DAG) {
12456   SDLoc DL(Op);
12457   MVT VT = Op.getSimpleValueType();
12458   SDValue In = Op.getOperand(0);
12459   MVT SVT = In.getSimpleValueType();
12460
12461   if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
12462     return LowerZERO_EXTEND_AVX512(Op, Subtarget, DAG);
12463
12464   if (Subtarget->hasFp256())
12465     if (SDValue Res = LowerAVXExtend(Op, DAG, Subtarget))
12466       return Res;
12467
12468   assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
12469          VT.getVectorNumElements() != SVT.getVectorNumElements());
12470   return SDValue();
12471 }
12472
12473 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
12474   SDLoc DL(Op);
12475   MVT VT = Op.getSimpleValueType();
12476   SDValue In = Op.getOperand(0);
12477   MVT InVT = In.getSimpleValueType();
12478
12479   if (VT == MVT::i1) {
12480     assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
12481            "Invalid scalar TRUNCATE operation");
12482     if (InVT.getSizeInBits() >= 32)
12483       return SDValue();
12484     In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
12485     return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
12486   }
12487   assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
12488          "Invalid TRUNCATE operation");
12489
12490   // move vector to mask - truncate solution for SKX
12491   if (VT.getVectorElementType() == MVT::i1) {
12492     if (InVT.is512BitVector() && InVT.getScalarSizeInBits() <= 16 &&
12493         Subtarget->hasBWI())
12494       return Op; // legal, will go to VPMOVB2M, VPMOVW2M
12495     if ((InVT.is256BitVector() || InVT.is128BitVector())
12496         && InVT.getScalarSizeInBits() <= 16 &&
12497         Subtarget->hasBWI() && Subtarget->hasVLX())
12498       return Op; // legal, will go to VPMOVB2M, VPMOVW2M
12499     if (InVT.is512BitVector() && InVT.getScalarSizeInBits() >= 32 &&
12500         Subtarget->hasDQI())
12501       return Op; // legal, will go to VPMOVD2M, VPMOVQ2M
12502     if ((InVT.is256BitVector() || InVT.is128BitVector())
12503         && InVT.getScalarSizeInBits() >= 32 &&
12504         Subtarget->hasDQI() && Subtarget->hasVLX())
12505       return Op; // legal, will go to VPMOVB2M, VPMOVQ2M
12506   }
12507
12508   if (VT.getVectorElementType() == MVT::i1) {
12509     assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
12510     unsigned NumElts = InVT.getVectorNumElements();
12511     assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
12512     if (InVT.getSizeInBits() < 512) {
12513       MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
12514       In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
12515       InVT = ExtVT;
12516     }
12517
12518     SDValue OneV =
12519      DAG.getConstant(APInt::getSignBit(InVT.getScalarSizeInBits()), DL, InVT);
12520     SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
12521     return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
12522   }
12523
12524   // vpmovqb/w/d, vpmovdb/w, vpmovwb
12525   if (((!InVT.is512BitVector() && Subtarget->hasVLX()) || InVT.is512BitVector()) &&
12526       (InVT.getVectorElementType() != MVT::i16 || Subtarget->hasBWI()))
12527     return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
12528
12529   if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
12530     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
12531     if (Subtarget->hasInt256()) {
12532       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
12533       In = DAG.getBitcast(MVT::v8i32, In);
12534       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
12535                                 ShufMask);
12536       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
12537                          DAG.getIntPtrConstant(0, DL));
12538     }
12539
12540     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12541                                DAG.getIntPtrConstant(0, DL));
12542     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12543                                DAG.getIntPtrConstant(2, DL));
12544     OpLo = DAG.getBitcast(MVT::v4i32, OpLo);
12545     OpHi = DAG.getBitcast(MVT::v4i32, OpHi);
12546     static const int ShufMask[] = {0, 2, 4, 6};
12547     return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
12548   }
12549
12550   if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
12551     // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
12552     if (Subtarget->hasInt256()) {
12553       In = DAG.getBitcast(MVT::v32i8, In);
12554
12555       SmallVector<SDValue,32> pshufbMask;
12556       for (unsigned i = 0; i < 2; ++i) {
12557         pshufbMask.push_back(DAG.getConstant(0x0, DL, MVT::i8));
12558         pshufbMask.push_back(DAG.getConstant(0x1, DL, MVT::i8));
12559         pshufbMask.push_back(DAG.getConstant(0x4, DL, MVT::i8));
12560         pshufbMask.push_back(DAG.getConstant(0x5, DL, MVT::i8));
12561         pshufbMask.push_back(DAG.getConstant(0x8, DL, MVT::i8));
12562         pshufbMask.push_back(DAG.getConstant(0x9, DL, MVT::i8));
12563         pshufbMask.push_back(DAG.getConstant(0xc, DL, MVT::i8));
12564         pshufbMask.push_back(DAG.getConstant(0xd, DL, MVT::i8));
12565         for (unsigned j = 0; j < 8; ++j)
12566           pshufbMask.push_back(DAG.getConstant(0x80, DL, MVT::i8));
12567       }
12568       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
12569       In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
12570       In = DAG.getBitcast(MVT::v4i64, In);
12571
12572       static const int ShufMask[] = {0,  2,  -1,  -1};
12573       In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, DAG.getUNDEF(MVT::v4i64),
12574                                 &ShufMask[0]);
12575       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12576                        DAG.getIntPtrConstant(0, DL));
12577       return DAG.getBitcast(VT, In);
12578     }
12579
12580     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
12581                                DAG.getIntPtrConstant(0, DL));
12582
12583     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
12584                                DAG.getIntPtrConstant(4, DL));
12585
12586     OpLo = DAG.getBitcast(MVT::v16i8, OpLo);
12587     OpHi = DAG.getBitcast(MVT::v16i8, OpHi);
12588
12589     // The PSHUFB mask:
12590     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
12591                                    -1, -1, -1, -1, -1, -1, -1, -1};
12592
12593     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
12594     OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
12595     OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
12596
12597     OpLo = DAG.getBitcast(MVT::v4i32, OpLo);
12598     OpHi = DAG.getBitcast(MVT::v4i32, OpHi);
12599
12600     // The MOVLHPS Mask:
12601     static const int ShufMask2[] = {0, 1, 4, 5};
12602     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
12603     return DAG.getBitcast(MVT::v8i16, res);
12604   }
12605
12606   // Handle truncation of V256 to V128 using shuffles.
12607   if (!VT.is128BitVector() || !InVT.is256BitVector())
12608     return SDValue();
12609
12610   assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
12611
12612   unsigned NumElems = VT.getVectorNumElements();
12613   MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
12614
12615   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
12616   // Prepare truncation shuffle mask
12617   for (unsigned i = 0; i != NumElems; ++i)
12618     MaskVec[i] = i * 2;
12619   SDValue V = DAG.getVectorShuffle(NVT, DL, DAG.getBitcast(NVT, In),
12620                                    DAG.getUNDEF(NVT), &MaskVec[0]);
12621   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
12622                      DAG.getIntPtrConstant(0, DL));
12623 }
12624
12625 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
12626                                            SelectionDAG &DAG) const {
12627   assert(!Op.getSimpleValueType().isVector());
12628
12629   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
12630     /*IsSigned=*/ true, /*IsReplace=*/ false);
12631   SDValue FIST = Vals.first, StackSlot = Vals.second;
12632   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
12633   if (!FIST.getNode()) return Op;
12634
12635   if (StackSlot.getNode())
12636     // Load the result.
12637     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
12638                        FIST, StackSlot, MachinePointerInfo(),
12639                        false, false, false, 0);
12640
12641   // The node is the result.
12642   return FIST;
12643 }
12644
12645 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
12646                                            SelectionDAG &DAG) const {
12647   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
12648     /*IsSigned=*/ false, /*IsReplace=*/ false);
12649   SDValue FIST = Vals.first, StackSlot = Vals.second;
12650   assert(FIST.getNode() && "Unexpected failure");
12651
12652   if (StackSlot.getNode())
12653     // Load the result.
12654     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
12655                        FIST, StackSlot, MachinePointerInfo(),
12656                        false, false, false, 0);
12657
12658   // The node is the result.
12659   return FIST;
12660 }
12661
12662 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
12663   SDLoc DL(Op);
12664   MVT VT = Op.getSimpleValueType();
12665   SDValue In = Op.getOperand(0);
12666   MVT SVT = In.getSimpleValueType();
12667
12668   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
12669
12670   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
12671                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
12672                                  In, DAG.getUNDEF(SVT)));
12673 }
12674
12675 /// The only differences between FABS and FNEG are the mask and the logic op.
12676 /// FNEG also has a folding opportunity for FNEG(FABS(x)).
12677 static SDValue LowerFABSorFNEG(SDValue Op, SelectionDAG &DAG) {
12678   assert((Op.getOpcode() == ISD::FABS || Op.getOpcode() == ISD::FNEG) &&
12679          "Wrong opcode for lowering FABS or FNEG.");
12680
12681   bool IsFABS = (Op.getOpcode() == ISD::FABS);
12682
12683   // If this is a FABS and it has an FNEG user, bail out to fold the combination
12684   // into an FNABS. We'll lower the FABS after that if it is still in use.
12685   if (IsFABS)
12686     for (SDNode *User : Op->uses())
12687       if (User->getOpcode() == ISD::FNEG)
12688         return Op;
12689
12690   SDLoc dl(Op);
12691   MVT VT = Op.getSimpleValueType();
12692
12693   // FIXME: Use function attribute "OptimizeForSize" and/or CodeGenOpt::Level to
12694   // decide if we should generate a 16-byte constant mask when we only need 4 or
12695   // 8 bytes for the scalar case.
12696
12697   MVT LogicVT;
12698   MVT EltVT;
12699   unsigned NumElts;
12700   
12701   if (VT.isVector()) {
12702     LogicVT = VT;
12703     EltVT = VT.getVectorElementType();
12704     NumElts = VT.getVectorNumElements();
12705   } else {
12706     // There are no scalar bitwise logical SSE/AVX instructions, so we
12707     // generate a 16-byte vector constant and logic op even for the scalar case.
12708     // Using a 16-byte mask allows folding the load of the mask with
12709     // the logic op, so it can save (~4 bytes) on code size.
12710     LogicVT = (VT == MVT::f64) ? MVT::v2f64 : MVT::v4f32;
12711     EltVT = VT;
12712     NumElts = (VT == MVT::f64) ? 2 : 4;
12713   }
12714
12715   unsigned EltBits = EltVT.getSizeInBits();
12716   LLVMContext *Context = DAG.getContext();
12717   // For FABS, mask is 0x7f...; for FNEG, mask is 0x80...
12718   APInt MaskElt =
12719     IsFABS ? APInt::getSignedMaxValue(EltBits) : APInt::getSignBit(EltBits);
12720   Constant *C = ConstantInt::get(*Context, MaskElt);
12721   C = ConstantVector::getSplat(NumElts, C);
12722   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12723   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(DAG.getDataLayout()));
12724   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
12725   SDValue Mask = DAG.getLoad(LogicVT, dl, DAG.getEntryNode(), CPIdx,
12726                              MachinePointerInfo::getConstantPool(),
12727                              false, false, false, Alignment);
12728
12729   SDValue Op0 = Op.getOperand(0);
12730   bool IsFNABS = !IsFABS && (Op0.getOpcode() == ISD::FABS);
12731   unsigned LogicOp =
12732     IsFABS ? X86ISD::FAND : IsFNABS ? X86ISD::FOR : X86ISD::FXOR;
12733   SDValue Operand = IsFNABS ? Op0.getOperand(0) : Op0;
12734
12735   if (VT.isVector())
12736     return DAG.getNode(LogicOp, dl, LogicVT, Operand, Mask);
12737
12738   // For the scalar case extend to a 128-bit vector, perform the logic op,
12739   // and extract the scalar result back out.
12740   Operand = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Operand);
12741   SDValue LogicNode = DAG.getNode(LogicOp, dl, LogicVT, Operand, Mask);
12742   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, LogicNode,
12743                      DAG.getIntPtrConstant(0, dl));
12744 }
12745
12746 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
12747   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12748   LLVMContext *Context = DAG.getContext();
12749   SDValue Op0 = Op.getOperand(0);
12750   SDValue Op1 = Op.getOperand(1);
12751   SDLoc dl(Op);
12752   MVT VT = Op.getSimpleValueType();
12753   MVT SrcVT = Op1.getSimpleValueType();
12754
12755   // If second operand is smaller, extend it first.
12756   if (SrcVT.bitsLT(VT)) {
12757     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
12758     SrcVT = VT;
12759   }
12760   // And if it is bigger, shrink it first.
12761   if (SrcVT.bitsGT(VT)) {
12762     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1, dl));
12763     SrcVT = VT;
12764   }
12765
12766   // At this point the operands and the result should have the same
12767   // type, and that won't be f80 since that is not custom lowered.
12768
12769   const fltSemantics &Sem =
12770       VT == MVT::f64 ? APFloat::IEEEdouble : APFloat::IEEEsingle;
12771   const unsigned SizeInBits = VT.getSizeInBits();
12772
12773   SmallVector<Constant *, 4> CV(
12774       VT == MVT::f64 ? 2 : 4,
12775       ConstantFP::get(*Context, APFloat(Sem, APInt(SizeInBits, 0))));
12776
12777   // First, clear all bits but the sign bit from the second operand (sign).
12778   CV[0] = ConstantFP::get(*Context,
12779                           APFloat(Sem, APInt::getHighBitsSet(SizeInBits, 1)));
12780   Constant *C = ConstantVector::get(CV);
12781   auto PtrVT = TLI.getPointerTy(DAG.getDataLayout());
12782   SDValue CPIdx = DAG.getConstantPool(C, PtrVT, 16);
12783
12784   // Perform all logic operations as 16-byte vectors because there are no
12785   // scalar FP logic instructions in SSE. This allows load folding of the
12786   // constants into the logic instructions.
12787   MVT LogicVT = (VT == MVT::f64) ? MVT::v2f64 : MVT::v4f32;
12788   SDValue Mask1 = DAG.getLoad(LogicVT, dl, DAG.getEntryNode(), CPIdx,
12789                               MachinePointerInfo::getConstantPool(),
12790                               false, false, false, 16);
12791   Op1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Op1);
12792   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, LogicVT, Op1, Mask1);
12793
12794   // Next, clear the sign bit from the first operand (magnitude).
12795   // If it's a constant, we can clear it here.
12796   if (ConstantFPSDNode *Op0CN = dyn_cast<ConstantFPSDNode>(Op0)) {
12797     APFloat APF = Op0CN->getValueAPF();
12798     // If the magnitude is a positive zero, the sign bit alone is enough.
12799     if (APF.isPosZero())
12800       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SrcVT, SignBit,
12801                          DAG.getIntPtrConstant(0, dl));
12802     APF.clearSign();
12803     CV[0] = ConstantFP::get(*Context, APF);
12804   } else {
12805     CV[0] = ConstantFP::get(
12806         *Context,
12807         APFloat(Sem, APInt::getLowBitsSet(SizeInBits, SizeInBits - 1)));
12808   }
12809   C = ConstantVector::get(CV);
12810   CPIdx = DAG.getConstantPool(C, PtrVT, 16);
12811   SDValue Val = DAG.getLoad(LogicVT, dl, DAG.getEntryNode(), CPIdx,
12812                             MachinePointerInfo::getConstantPool(),
12813                             false, false, false, 16);
12814   // If the magnitude operand wasn't a constant, we need to AND out the sign.
12815   if (!isa<ConstantFPSDNode>(Op0)) {
12816     Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Op0);
12817     Val = DAG.getNode(X86ISD::FAND, dl, LogicVT, Op0, Val);
12818   }
12819   // OR the magnitude value with the sign bit.
12820   Val = DAG.getNode(X86ISD::FOR, dl, LogicVT, Val, SignBit);
12821   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SrcVT, Val,
12822                      DAG.getIntPtrConstant(0, dl));
12823 }
12824
12825 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
12826   SDValue N0 = Op.getOperand(0);
12827   SDLoc dl(Op);
12828   MVT VT = Op.getSimpleValueType();
12829
12830   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
12831   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
12832                                   DAG.getConstant(1, dl, VT));
12833   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, dl, VT));
12834 }
12835
12836 // Check whether an OR'd tree is PTEST-able.
12837 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
12838                                       SelectionDAG &DAG) {
12839   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
12840
12841   if (!Subtarget->hasSSE41())
12842     return SDValue();
12843
12844   if (!Op->hasOneUse())
12845     return SDValue();
12846
12847   SDNode *N = Op.getNode();
12848   SDLoc DL(N);
12849
12850   SmallVector<SDValue, 8> Opnds;
12851   DenseMap<SDValue, unsigned> VecInMap;
12852   SmallVector<SDValue, 8> VecIns;
12853   EVT VT = MVT::Other;
12854
12855   // Recognize a special case where a vector is casted into wide integer to
12856   // test all 0s.
12857   Opnds.push_back(N->getOperand(0));
12858   Opnds.push_back(N->getOperand(1));
12859
12860   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
12861     SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
12862     // BFS traverse all OR'd operands.
12863     if (I->getOpcode() == ISD::OR) {
12864       Opnds.push_back(I->getOperand(0));
12865       Opnds.push_back(I->getOperand(1));
12866       // Re-evaluate the number of nodes to be traversed.
12867       e += 2; // 2 more nodes (LHS and RHS) are pushed.
12868       continue;
12869     }
12870
12871     // Quit if a non-EXTRACT_VECTOR_ELT
12872     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
12873       return SDValue();
12874
12875     // Quit if without a constant index.
12876     SDValue Idx = I->getOperand(1);
12877     if (!isa<ConstantSDNode>(Idx))
12878       return SDValue();
12879
12880     SDValue ExtractedFromVec = I->getOperand(0);
12881     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
12882     if (M == VecInMap.end()) {
12883       VT = ExtractedFromVec.getValueType();
12884       // Quit if not 128/256-bit vector.
12885       if (!VT.is128BitVector() && !VT.is256BitVector())
12886         return SDValue();
12887       // Quit if not the same type.
12888       if (VecInMap.begin() != VecInMap.end() &&
12889           VT != VecInMap.begin()->first.getValueType())
12890         return SDValue();
12891       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
12892       VecIns.push_back(ExtractedFromVec);
12893     }
12894     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
12895   }
12896
12897   assert((VT.is128BitVector() || VT.is256BitVector()) &&
12898          "Not extracted from 128-/256-bit vector.");
12899
12900   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
12901
12902   for (DenseMap<SDValue, unsigned>::const_iterator
12903         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
12904     // Quit if not all elements are used.
12905     if (I->second != FullMask)
12906       return SDValue();
12907   }
12908
12909   EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
12910
12911   // Cast all vectors into TestVT for PTEST.
12912   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
12913     VecIns[i] = DAG.getBitcast(TestVT, VecIns[i]);
12914
12915   // If more than one full vectors are evaluated, OR them first before PTEST.
12916   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
12917     // Each iteration will OR 2 nodes and append the result until there is only
12918     // 1 node left, i.e. the final OR'd value of all vectors.
12919     SDValue LHS = VecIns[Slot];
12920     SDValue RHS = VecIns[Slot + 1];
12921     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
12922   }
12923
12924   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
12925                      VecIns.back(), VecIns.back());
12926 }
12927
12928 /// \brief return true if \c Op has a use that doesn't just read flags.
12929 static bool hasNonFlagsUse(SDValue Op) {
12930   for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
12931        ++UI) {
12932     SDNode *User = *UI;
12933     unsigned UOpNo = UI.getOperandNo();
12934     if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
12935       // Look pass truncate.
12936       UOpNo = User->use_begin().getOperandNo();
12937       User = *User->use_begin();
12938     }
12939
12940     if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
12941         !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
12942       return true;
12943   }
12944   return false;
12945 }
12946
12947 /// Emit nodes that will be selected as "test Op0,Op0", or something
12948 /// equivalent.
12949 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
12950                                     SelectionDAG &DAG) const {
12951   if (Op.getValueType() == MVT::i1) {
12952     SDValue ExtOp = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i8, Op);
12953     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, ExtOp,
12954                        DAG.getConstant(0, dl, MVT::i8));
12955   }
12956   // CF and OF aren't always set the way we want. Determine which
12957   // of these we need.
12958   bool NeedCF = false;
12959   bool NeedOF = false;
12960   switch (X86CC) {
12961   default: break;
12962   case X86::COND_A: case X86::COND_AE:
12963   case X86::COND_B: case X86::COND_BE:
12964     NeedCF = true;
12965     break;
12966   case X86::COND_G: case X86::COND_GE:
12967   case X86::COND_L: case X86::COND_LE:
12968   case X86::COND_O: case X86::COND_NO: {
12969     // Check if we really need to set the
12970     // Overflow flag. If NoSignedWrap is present
12971     // that is not actually needed.
12972     switch (Op->getOpcode()) {
12973     case ISD::ADD:
12974     case ISD::SUB:
12975     case ISD::MUL:
12976     case ISD::SHL: {
12977       const auto *BinNode = cast<BinaryWithFlagsSDNode>(Op.getNode());
12978       if (BinNode->Flags.hasNoSignedWrap())
12979         break;
12980     }
12981     default:
12982       NeedOF = true;
12983       break;
12984     }
12985     break;
12986   }
12987   }
12988   // See if we can use the EFLAGS value from the operand instead of
12989   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
12990   // we prove that the arithmetic won't overflow, we can't use OF or CF.
12991   if (Op.getResNo() != 0 || NeedOF || NeedCF) {
12992     // Emit a CMP with 0, which is the TEST pattern.
12993     //if (Op.getValueType() == MVT::i1)
12994     //  return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
12995     //                     DAG.getConstant(0, MVT::i1));
12996     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
12997                        DAG.getConstant(0, dl, Op.getValueType()));
12998   }
12999   unsigned Opcode = 0;
13000   unsigned NumOperands = 0;
13001
13002   // Truncate operations may prevent the merge of the SETCC instruction
13003   // and the arithmetic instruction before it. Attempt to truncate the operands
13004   // of the arithmetic instruction and use a reduced bit-width instruction.
13005   bool NeedTruncation = false;
13006   SDValue ArithOp = Op;
13007   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
13008     SDValue Arith = Op->getOperand(0);
13009     // Both the trunc and the arithmetic op need to have one user each.
13010     if (Arith->hasOneUse())
13011       switch (Arith.getOpcode()) {
13012         default: break;
13013         case ISD::ADD:
13014         case ISD::SUB:
13015         case ISD::AND:
13016         case ISD::OR:
13017         case ISD::XOR: {
13018           NeedTruncation = true;
13019           ArithOp = Arith;
13020         }
13021       }
13022   }
13023
13024   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
13025   // which may be the result of a CAST.  We use the variable 'Op', which is the
13026   // non-casted variable when we check for possible users.
13027   switch (ArithOp.getOpcode()) {
13028   case ISD::ADD:
13029     // Due to an isel shortcoming, be conservative if this add is likely to be
13030     // selected as part of a load-modify-store instruction. When the root node
13031     // in a match is a store, isel doesn't know how to remap non-chain non-flag
13032     // uses of other nodes in the match, such as the ADD in this case. This
13033     // leads to the ADD being left around and reselected, with the result being
13034     // two adds in the output.  Alas, even if none our users are stores, that
13035     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
13036     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
13037     // climbing the DAG back to the root, and it doesn't seem to be worth the
13038     // effort.
13039     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
13040          UE = Op.getNode()->use_end(); UI != UE; ++UI)
13041       if (UI->getOpcode() != ISD::CopyToReg &&
13042           UI->getOpcode() != ISD::SETCC &&
13043           UI->getOpcode() != ISD::STORE)
13044         goto default_case;
13045
13046     if (ConstantSDNode *C =
13047         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
13048       // An add of one will be selected as an INC.
13049       if (C->getAPIntValue() == 1 && !Subtarget->slowIncDec()) {
13050         Opcode = X86ISD::INC;
13051         NumOperands = 1;
13052         break;
13053       }
13054
13055       // An add of negative one (subtract of one) will be selected as a DEC.
13056       if (C->getAPIntValue().isAllOnesValue() && !Subtarget->slowIncDec()) {
13057         Opcode = X86ISD::DEC;
13058         NumOperands = 1;
13059         break;
13060       }
13061     }
13062
13063     // Otherwise use a regular EFLAGS-setting add.
13064     Opcode = X86ISD::ADD;
13065     NumOperands = 2;
13066     break;
13067   case ISD::SHL:
13068   case ISD::SRL:
13069     // If we have a constant logical shift that's only used in a comparison
13070     // against zero turn it into an equivalent AND. This allows turning it into
13071     // a TEST instruction later.
13072     if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
13073         isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
13074       EVT VT = Op.getValueType();
13075       unsigned BitWidth = VT.getSizeInBits();
13076       unsigned ShAmt = Op->getConstantOperandVal(1);
13077       if (ShAmt >= BitWidth) // Avoid undefined shifts.
13078         break;
13079       APInt Mask = ArithOp.getOpcode() == ISD::SRL
13080                        ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
13081                        : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
13082       if (!Mask.isSignedIntN(32)) // Avoid large immediates.
13083         break;
13084       SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
13085                                 DAG.getConstant(Mask, dl, VT));
13086       DAG.ReplaceAllUsesWith(Op, New);
13087       Op = New;
13088     }
13089     break;
13090
13091   case ISD::AND:
13092     // If the primary and result isn't used, don't bother using X86ISD::AND,
13093     // because a TEST instruction will be better.
13094     if (!hasNonFlagsUse(Op))
13095       break;
13096     // FALL THROUGH
13097   case ISD::SUB:
13098   case ISD::OR:
13099   case ISD::XOR:
13100     // Due to the ISEL shortcoming noted above, be conservative if this op is
13101     // likely to be selected as part of a load-modify-store instruction.
13102     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
13103            UE = Op.getNode()->use_end(); UI != UE; ++UI)
13104       if (UI->getOpcode() == ISD::STORE)
13105         goto default_case;
13106
13107     // Otherwise use a regular EFLAGS-setting instruction.
13108     switch (ArithOp.getOpcode()) {
13109     default: llvm_unreachable("unexpected operator!");
13110     case ISD::SUB: Opcode = X86ISD::SUB; break;
13111     case ISD::XOR: Opcode = X86ISD::XOR; break;
13112     case ISD::AND: Opcode = X86ISD::AND; break;
13113     case ISD::OR: {
13114       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
13115         SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
13116         if (EFLAGS.getNode())
13117           return EFLAGS;
13118       }
13119       Opcode = X86ISD::OR;
13120       break;
13121     }
13122     }
13123
13124     NumOperands = 2;
13125     break;
13126   case X86ISD::ADD:
13127   case X86ISD::SUB:
13128   case X86ISD::INC:
13129   case X86ISD::DEC:
13130   case X86ISD::OR:
13131   case X86ISD::XOR:
13132   case X86ISD::AND:
13133     return SDValue(Op.getNode(), 1);
13134   default:
13135   default_case:
13136     break;
13137   }
13138
13139   // If we found that truncation is beneficial, perform the truncation and
13140   // update 'Op'.
13141   if (NeedTruncation) {
13142     EVT VT = Op.getValueType();
13143     SDValue WideVal = Op->getOperand(0);
13144     EVT WideVT = WideVal.getValueType();
13145     unsigned ConvertedOp = 0;
13146     // Use a target machine opcode to prevent further DAGCombine
13147     // optimizations that may separate the arithmetic operations
13148     // from the setcc node.
13149     switch (WideVal.getOpcode()) {
13150       default: break;
13151       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
13152       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
13153       case ISD::AND: ConvertedOp = X86ISD::AND; break;
13154       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
13155       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
13156     }
13157
13158     if (ConvertedOp) {
13159       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13160       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
13161         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
13162         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
13163         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
13164       }
13165     }
13166   }
13167
13168   if (Opcode == 0)
13169     // Emit a CMP with 0, which is the TEST pattern.
13170     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
13171                        DAG.getConstant(0, dl, Op.getValueType()));
13172
13173   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
13174   SmallVector<SDValue, 4> Ops(Op->op_begin(), Op->op_begin() + NumOperands);
13175
13176   SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
13177   DAG.ReplaceAllUsesWith(Op, New);
13178   return SDValue(New.getNode(), 1);
13179 }
13180
13181 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
13182 /// equivalent.
13183 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
13184                                    SDLoc dl, SelectionDAG &DAG) const {
13185   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
13186     if (C->getAPIntValue() == 0)
13187       return EmitTest(Op0, X86CC, dl, DAG);
13188
13189      if (Op0.getValueType() == MVT::i1)
13190        llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
13191   }
13192
13193   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
13194        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
13195     // Do the comparison at i32 if it's smaller, besides the Atom case.
13196     // This avoids subregister aliasing issues. Keep the smaller reference
13197     // if we're optimizing for size, however, as that'll allow better folding
13198     // of memory operations.
13199     if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
13200         !DAG.getMachineFunction().getFunction()->hasFnAttribute(
13201             Attribute::MinSize) &&
13202         !Subtarget->isAtom()) {
13203       unsigned ExtendOp =
13204           isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
13205       Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
13206       Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
13207     }
13208     // Use SUB instead of CMP to enable CSE between SUB and CMP.
13209     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
13210     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
13211                               Op0, Op1);
13212     return SDValue(Sub.getNode(), 1);
13213   }
13214   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
13215 }
13216
13217 /// Convert a comparison if required by the subtarget.
13218 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
13219                                                  SelectionDAG &DAG) const {
13220   // If the subtarget does not support the FUCOMI instruction, floating-point
13221   // comparisons have to be converted.
13222   if (Subtarget->hasCMov() ||
13223       Cmp.getOpcode() != X86ISD::CMP ||
13224       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
13225       !Cmp.getOperand(1).getValueType().isFloatingPoint())
13226     return Cmp;
13227
13228   // The instruction selector will select an FUCOM instruction instead of
13229   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
13230   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
13231   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
13232   SDLoc dl(Cmp);
13233   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
13234   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
13235   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
13236                             DAG.getConstant(8, dl, MVT::i8));
13237   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
13238   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
13239 }
13240
13241 /// The minimum architected relative accuracy is 2^-12. We need one
13242 /// Newton-Raphson step to have a good float result (24 bits of precision).
13243 SDValue X86TargetLowering::getRsqrtEstimate(SDValue Op,
13244                                             DAGCombinerInfo &DCI,
13245                                             unsigned &RefinementSteps,
13246                                             bool &UseOneConstNR) const {
13247   EVT VT = Op.getValueType();
13248   const char *RecipOp;
13249
13250   // SSE1 has rsqrtss and rsqrtps. AVX adds a 256-bit variant for rsqrtps.
13251   // TODO: Add support for AVX512 (v16f32).
13252   // It is likely not profitable to do this for f64 because a double-precision
13253   // rsqrt estimate with refinement on x86 prior to FMA requires at least 16
13254   // instructions: convert to single, rsqrtss, convert back to double, refine
13255   // (3 steps = at least 13 insts). If an 'rsqrtsd' variant was added to the ISA
13256   // along with FMA, this could be a throughput win.
13257   if (VT == MVT::f32 && Subtarget->hasSSE1())
13258     RecipOp = "sqrtf";
13259   else if ((VT == MVT::v4f32 && Subtarget->hasSSE1()) ||
13260            (VT == MVT::v8f32 && Subtarget->hasAVX()))
13261     RecipOp = "vec-sqrtf";
13262   else
13263     return SDValue();
13264
13265   TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
13266   if (!Recips.isEnabled(RecipOp))
13267     return SDValue();
13268
13269   RefinementSteps = Recips.getRefinementSteps(RecipOp);
13270   UseOneConstNR = false;
13271   return DCI.DAG.getNode(X86ISD::FRSQRT, SDLoc(Op), VT, Op);
13272 }
13273
13274 /// The minimum architected relative accuracy is 2^-12. We need one
13275 /// Newton-Raphson step to have a good float result (24 bits of precision).
13276 SDValue X86TargetLowering::getRecipEstimate(SDValue Op,
13277                                             DAGCombinerInfo &DCI,
13278                                             unsigned &RefinementSteps) const {
13279   EVT VT = Op.getValueType();
13280   const char *RecipOp;
13281
13282   // SSE1 has rcpss and rcpps. AVX adds a 256-bit variant for rcpps.
13283   // TODO: Add support for AVX512 (v16f32).
13284   // It is likely not profitable to do this for f64 because a double-precision
13285   // reciprocal estimate with refinement on x86 prior to FMA requires
13286   // 15 instructions: convert to single, rcpss, convert back to double, refine
13287   // (3 steps = 12 insts). If an 'rcpsd' variant was added to the ISA
13288   // along with FMA, this could be a throughput win.
13289   if (VT == MVT::f32 && Subtarget->hasSSE1())
13290     RecipOp = "divf";
13291   else if ((VT == MVT::v4f32 && Subtarget->hasSSE1()) ||
13292            (VT == MVT::v8f32 && Subtarget->hasAVX()))
13293     RecipOp = "vec-divf";
13294   else
13295     return SDValue();
13296
13297   TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
13298   if (!Recips.isEnabled(RecipOp))
13299     return SDValue();
13300
13301   RefinementSteps = Recips.getRefinementSteps(RecipOp);
13302   return DCI.DAG.getNode(X86ISD::FRCP, SDLoc(Op), VT, Op);
13303 }
13304
13305 /// If we have at least two divisions that use the same divisor, convert to
13306 /// multplication by a reciprocal. This may need to be adjusted for a given
13307 /// CPU if a division's cost is not at least twice the cost of a multiplication.
13308 /// This is because we still need one division to calculate the reciprocal and
13309 /// then we need two multiplies by that reciprocal as replacements for the
13310 /// original divisions.
13311 bool X86TargetLowering::combineRepeatedFPDivisors(unsigned NumUsers) const {
13312   return NumUsers > 1;
13313 }
13314
13315 static bool isAllOnes(SDValue V) {
13316   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
13317   return C && C->isAllOnesValue();
13318 }
13319
13320 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
13321 /// if it's possible.
13322 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
13323                                      SDLoc dl, SelectionDAG &DAG) const {
13324   SDValue Op0 = And.getOperand(0);
13325   SDValue Op1 = And.getOperand(1);
13326   if (Op0.getOpcode() == ISD::TRUNCATE)
13327     Op0 = Op0.getOperand(0);
13328   if (Op1.getOpcode() == ISD::TRUNCATE)
13329     Op1 = Op1.getOperand(0);
13330
13331   SDValue LHS, RHS;
13332   if (Op1.getOpcode() == ISD::SHL)
13333     std::swap(Op0, Op1);
13334   if (Op0.getOpcode() == ISD::SHL) {
13335     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
13336       if (And00C->getZExtValue() == 1) {
13337         // If we looked past a truncate, check that it's only truncating away
13338         // known zeros.
13339         unsigned BitWidth = Op0.getValueSizeInBits();
13340         unsigned AndBitWidth = And.getValueSizeInBits();
13341         if (BitWidth > AndBitWidth) {
13342           APInt Zeros, Ones;
13343           DAG.computeKnownBits(Op0, Zeros, Ones);
13344           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
13345             return SDValue();
13346         }
13347         LHS = Op1;
13348         RHS = Op0.getOperand(1);
13349       }
13350   } else if (Op1.getOpcode() == ISD::Constant) {
13351     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
13352     uint64_t AndRHSVal = AndRHS->getZExtValue();
13353     SDValue AndLHS = Op0;
13354
13355     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
13356       LHS = AndLHS.getOperand(0);
13357       RHS = AndLHS.getOperand(1);
13358     }
13359
13360     // Use BT if the immediate can't be encoded in a TEST instruction.
13361     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
13362       LHS = AndLHS;
13363       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), dl, LHS.getValueType());
13364     }
13365   }
13366
13367   if (LHS.getNode()) {
13368     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
13369     // instruction.  Since the shift amount is in-range-or-undefined, we know
13370     // that doing a bittest on the i32 value is ok.  We extend to i32 because
13371     // the encoding for the i16 version is larger than the i32 version.
13372     // Also promote i16 to i32 for performance / code size reason.
13373     if (LHS.getValueType() == MVT::i8 ||
13374         LHS.getValueType() == MVT::i16)
13375       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
13376
13377     // If the operand types disagree, extend the shift amount to match.  Since
13378     // BT ignores high bits (like shifts) we can use anyextend.
13379     if (LHS.getValueType() != RHS.getValueType())
13380       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
13381
13382     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
13383     X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
13384     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13385                        DAG.getConstant(Cond, dl, MVT::i8), BT);
13386   }
13387
13388   return SDValue();
13389 }
13390
13391 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
13392 /// mask CMPs.
13393 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
13394                               SDValue &Op1) {
13395   unsigned SSECC;
13396   bool Swap = false;
13397
13398   // SSE Condition code mapping:
13399   //  0 - EQ
13400   //  1 - LT
13401   //  2 - LE
13402   //  3 - UNORD
13403   //  4 - NEQ
13404   //  5 - NLT
13405   //  6 - NLE
13406   //  7 - ORD
13407   switch (SetCCOpcode) {
13408   default: llvm_unreachable("Unexpected SETCC condition");
13409   case ISD::SETOEQ:
13410   case ISD::SETEQ:  SSECC = 0; break;
13411   case ISD::SETOGT:
13412   case ISD::SETGT:  Swap = true; // Fallthrough
13413   case ISD::SETLT:
13414   case ISD::SETOLT: SSECC = 1; break;
13415   case ISD::SETOGE:
13416   case ISD::SETGE:  Swap = true; // Fallthrough
13417   case ISD::SETLE:
13418   case ISD::SETOLE: SSECC = 2; break;
13419   case ISD::SETUO:  SSECC = 3; break;
13420   case ISD::SETUNE:
13421   case ISD::SETNE:  SSECC = 4; break;
13422   case ISD::SETULE: Swap = true; // Fallthrough
13423   case ISD::SETUGE: SSECC = 5; break;
13424   case ISD::SETULT: Swap = true; // Fallthrough
13425   case ISD::SETUGT: SSECC = 6; break;
13426   case ISD::SETO:   SSECC = 7; break;
13427   case ISD::SETUEQ:
13428   case ISD::SETONE: SSECC = 8; break;
13429   }
13430   if (Swap)
13431     std::swap(Op0, Op1);
13432
13433   return SSECC;
13434 }
13435
13436 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
13437 // ones, and then concatenate the result back.
13438 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
13439   MVT VT = Op.getSimpleValueType();
13440
13441   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
13442          "Unsupported value type for operation");
13443
13444   unsigned NumElems = VT.getVectorNumElements();
13445   SDLoc dl(Op);
13446   SDValue CC = Op.getOperand(2);
13447
13448   // Extract the LHS vectors
13449   SDValue LHS = Op.getOperand(0);
13450   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
13451   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
13452
13453   // Extract the RHS vectors
13454   SDValue RHS = Op.getOperand(1);
13455   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
13456   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
13457
13458   // Issue the operation on the smaller types and concatenate the result back
13459   MVT EltVT = VT.getVectorElementType();
13460   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13461   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
13462                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
13463                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
13464 }
13465
13466 static SDValue LowerBoolVSETCC_AVX512(SDValue Op, SelectionDAG &DAG) {
13467   SDValue Op0 = Op.getOperand(0);
13468   SDValue Op1 = Op.getOperand(1);
13469   SDValue CC = Op.getOperand(2);
13470   MVT VT = Op.getSimpleValueType();
13471   SDLoc dl(Op);
13472
13473   assert(Op0.getValueType().getVectorElementType() == MVT::i1 &&
13474          "Unexpected type for boolean compare operation");
13475   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13476   SDValue NotOp0 = DAG.getNode(ISD::XOR, dl, VT, Op0,
13477                                DAG.getConstant(-1, dl, VT));
13478   SDValue NotOp1 = DAG.getNode(ISD::XOR, dl, VT, Op1,
13479                                DAG.getConstant(-1, dl, VT));
13480   switch (SetCCOpcode) {
13481   default: llvm_unreachable("Unexpected SETCC condition");
13482   case ISD::SETEQ:
13483     // (x == y) -> ~(x ^ y)
13484     return DAG.getNode(ISD::XOR, dl, VT,
13485                        DAG.getNode(ISD::XOR, dl, VT, Op0, Op1),
13486                        DAG.getConstant(-1, dl, VT));
13487   case ISD::SETNE:
13488     // (x != y) -> (x ^ y)
13489     return DAG.getNode(ISD::XOR, dl, VT, Op0, Op1);
13490   case ISD::SETUGT:
13491   case ISD::SETGT:
13492     // (x > y) -> (x & ~y)
13493     return DAG.getNode(ISD::AND, dl, VT, Op0, NotOp1);
13494   case ISD::SETULT:
13495   case ISD::SETLT:
13496     // (x < y) -> (~x & y)
13497     return DAG.getNode(ISD::AND, dl, VT, NotOp0, Op1);
13498   case ISD::SETULE:
13499   case ISD::SETLE:
13500     // (x <= y) -> (~x | y)
13501     return DAG.getNode(ISD::OR, dl, VT, NotOp0, Op1);
13502   case ISD::SETUGE:
13503   case ISD::SETGE:
13504     // (x >=y) -> (x | ~y)
13505     return DAG.getNode(ISD::OR, dl, VT, Op0, NotOp1);
13506   }
13507 }
13508
13509 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
13510                                      const X86Subtarget *Subtarget) {
13511   SDValue Op0 = Op.getOperand(0);
13512   SDValue Op1 = Op.getOperand(1);
13513   SDValue CC = Op.getOperand(2);
13514   MVT VT = Op.getSimpleValueType();
13515   SDLoc dl(Op);
13516
13517   assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 8 &&
13518          Op.getValueType().getScalarType() == MVT::i1 &&
13519          "Cannot set masked compare for this operation");
13520
13521   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13522   unsigned  Opc = 0;
13523   bool Unsigned = false;
13524   bool Swap = false;
13525   unsigned SSECC;
13526   switch (SetCCOpcode) {
13527   default: llvm_unreachable("Unexpected SETCC condition");
13528   case ISD::SETNE:  SSECC = 4; break;
13529   case ISD::SETEQ:  Opc = X86ISD::PCMPEQM; break;
13530   case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
13531   case ISD::SETLT:  Swap = true; //fall-through
13532   case ISD::SETGT:  Opc = X86ISD::PCMPGTM; break;
13533   case ISD::SETULT: SSECC = 1; Unsigned = true; break;
13534   case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
13535   case ISD::SETGE:  Swap = true; SSECC = 2; break; // LE + swap
13536   case ISD::SETULE: Unsigned = true; //fall-through
13537   case ISD::SETLE:  SSECC = 2; break;
13538   }
13539
13540   if (Swap)
13541     std::swap(Op0, Op1);
13542   if (Opc)
13543     return DAG.getNode(Opc, dl, VT, Op0, Op1);
13544   Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
13545   return DAG.getNode(Opc, dl, VT, Op0, Op1,
13546                      DAG.getConstant(SSECC, dl, MVT::i8));
13547 }
13548
13549 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
13550 /// operand \p Op1.  If non-trivial (for example because it's not constant)
13551 /// return an empty value.
13552 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
13553 {
13554   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
13555   if (!BV)
13556     return SDValue();
13557
13558   MVT VT = Op1.getSimpleValueType();
13559   MVT EVT = VT.getVectorElementType();
13560   unsigned n = VT.getVectorNumElements();
13561   SmallVector<SDValue, 8> ULTOp1;
13562
13563   for (unsigned i = 0; i < n; ++i) {
13564     ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
13565     if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
13566       return SDValue();
13567
13568     // Avoid underflow.
13569     APInt Val = Elt->getAPIntValue();
13570     if (Val == 0)
13571       return SDValue();
13572
13573     ULTOp1.push_back(DAG.getConstant(Val - 1, dl, EVT));
13574   }
13575
13576   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
13577 }
13578
13579 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
13580                            SelectionDAG &DAG) {
13581   SDValue Op0 = Op.getOperand(0);
13582   SDValue Op1 = Op.getOperand(1);
13583   SDValue CC = Op.getOperand(2);
13584   MVT VT = Op.getSimpleValueType();
13585   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13586   bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
13587   SDLoc dl(Op);
13588
13589   if (isFP) {
13590 #ifndef NDEBUG
13591     MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
13592     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
13593 #endif
13594
13595     unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
13596     unsigned Opc = X86ISD::CMPP;
13597     if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
13598       assert(VT.getVectorNumElements() <= 16);
13599       Opc = X86ISD::CMPM;
13600     }
13601     // In the two special cases we can't handle, emit two comparisons.
13602     if (SSECC == 8) {
13603       unsigned CC0, CC1;
13604       unsigned CombineOpc;
13605       if (SetCCOpcode == ISD::SETUEQ) {
13606         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
13607       } else {
13608         assert(SetCCOpcode == ISD::SETONE);
13609         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
13610       }
13611
13612       SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
13613                                  DAG.getConstant(CC0, dl, MVT::i8));
13614       SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
13615                                  DAG.getConstant(CC1, dl, MVT::i8));
13616       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
13617     }
13618     // Handle all other FP comparisons here.
13619     return DAG.getNode(Opc, dl, VT, Op0, Op1,
13620                        DAG.getConstant(SSECC, dl, MVT::i8));
13621   }
13622
13623   // Break 256-bit integer vector compare into smaller ones.
13624   if (VT.is256BitVector() && !Subtarget->hasInt256())
13625     return Lower256IntVSETCC(Op, DAG);
13626
13627   EVT OpVT = Op1.getValueType();
13628   if (OpVT.getVectorElementType() == MVT::i1)
13629     return LowerBoolVSETCC_AVX512(Op, DAG);
13630
13631   bool MaskResult = (VT.getVectorElementType() == MVT::i1);
13632   if (Subtarget->hasAVX512()) {
13633     if (Op1.getValueType().is512BitVector() ||
13634         (Subtarget->hasBWI() && Subtarget->hasVLX()) ||
13635         (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
13636       return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
13637
13638     // In AVX-512 architecture setcc returns mask with i1 elements,
13639     // But there is no compare instruction for i8 and i16 elements in KNL.
13640     // We are not talking about 512-bit operands in this case, these
13641     // types are illegal.
13642     if (MaskResult &&
13643         (OpVT.getVectorElementType().getSizeInBits() < 32 &&
13644          OpVT.getVectorElementType().getSizeInBits() >= 8))
13645       return DAG.getNode(ISD::TRUNCATE, dl, VT,
13646                          DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
13647   }
13648
13649   // We are handling one of the integer comparisons here.  Since SSE only has
13650   // GT and EQ comparisons for integer, swapping operands and multiple
13651   // operations may be required for some comparisons.
13652   unsigned Opc;
13653   bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
13654   bool Subus = false;
13655
13656   switch (SetCCOpcode) {
13657   default: llvm_unreachable("Unexpected SETCC condition");
13658   case ISD::SETNE:  Invert = true;
13659   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
13660   case ISD::SETLT:  Swap = true;
13661   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
13662   case ISD::SETGE:  Swap = true;
13663   case ISD::SETLE:  Opc = X86ISD::PCMPGT;
13664                     Invert = true; break;
13665   case ISD::SETULT: Swap = true;
13666   case ISD::SETUGT: Opc = X86ISD::PCMPGT;
13667                     FlipSigns = true; break;
13668   case ISD::SETUGE: Swap = true;
13669   case ISD::SETULE: Opc = X86ISD::PCMPGT;
13670                     FlipSigns = true; Invert = true; break;
13671   }
13672
13673   // Special case: Use min/max operations for SETULE/SETUGE
13674   MVT VET = VT.getVectorElementType();
13675   bool hasMinMax =
13676        (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
13677     || (Subtarget->hasSSE2()  && (VET == MVT::i8));
13678
13679   if (hasMinMax) {
13680     switch (SetCCOpcode) {
13681     default: break;
13682     case ISD::SETULE: Opc = ISD::UMIN; MinMax = true; break;
13683     case ISD::SETUGE: Opc = ISD::UMAX; MinMax = true; break;
13684     }
13685
13686     if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
13687   }
13688
13689   bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
13690   if (!MinMax && hasSubus) {
13691     // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
13692     // Op0 u<= Op1:
13693     //   t = psubus Op0, Op1
13694     //   pcmpeq t, <0..0>
13695     switch (SetCCOpcode) {
13696     default: break;
13697     case ISD::SETULT: {
13698       // If the comparison is against a constant we can turn this into a
13699       // setule.  With psubus, setule does not require a swap.  This is
13700       // beneficial because the constant in the register is no longer
13701       // destructed as the destination so it can be hoisted out of a loop.
13702       // Only do this pre-AVX since vpcmp* is no longer destructive.
13703       if (Subtarget->hasAVX())
13704         break;
13705       SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
13706       if (ULEOp1.getNode()) {
13707         Op1 = ULEOp1;
13708         Subus = true; Invert = false; Swap = false;
13709       }
13710       break;
13711     }
13712     // Psubus is better than flip-sign because it requires no inversion.
13713     case ISD::SETUGE: Subus = true; Invert = false; Swap = true;  break;
13714     case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
13715     }
13716
13717     if (Subus) {
13718       Opc = X86ISD::SUBUS;
13719       FlipSigns = false;
13720     }
13721   }
13722
13723   if (Swap)
13724     std::swap(Op0, Op1);
13725
13726   // Check that the operation in question is available (most are plain SSE2,
13727   // but PCMPGTQ and PCMPEQQ have different requirements).
13728   if (VT == MVT::v2i64) {
13729     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
13730       assert(Subtarget->hasSSE2() && "Don't know how to lower!");
13731
13732       // First cast everything to the right type.
13733       Op0 = DAG.getBitcast(MVT::v4i32, Op0);
13734       Op1 = DAG.getBitcast(MVT::v4i32, Op1);
13735
13736       // Since SSE has no unsigned integer comparisons, we need to flip the sign
13737       // bits of the inputs before performing those operations. The lower
13738       // compare is always unsigned.
13739       SDValue SB;
13740       if (FlipSigns) {
13741         SB = DAG.getConstant(0x80000000U, dl, MVT::v4i32);
13742       } else {
13743         SDValue Sign = DAG.getConstant(0x80000000U, dl, MVT::i32);
13744         SDValue Zero = DAG.getConstant(0x00000000U, dl, MVT::i32);
13745         SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
13746                          Sign, Zero, Sign, Zero);
13747       }
13748       Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
13749       Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
13750
13751       // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
13752       SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
13753       SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
13754
13755       // Create masks for only the low parts/high parts of the 64 bit integers.
13756       static const int MaskHi[] = { 1, 1, 3, 3 };
13757       static const int MaskLo[] = { 0, 0, 2, 2 };
13758       SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
13759       SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
13760       SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
13761
13762       SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
13763       Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
13764
13765       if (Invert)
13766         Result = DAG.getNOT(dl, Result, MVT::v4i32);
13767
13768       return DAG.getBitcast(VT, Result);
13769     }
13770
13771     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
13772       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
13773       // pcmpeqd + pshufd + pand.
13774       assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
13775
13776       // First cast everything to the right type.
13777       Op0 = DAG.getBitcast(MVT::v4i32, Op0);
13778       Op1 = DAG.getBitcast(MVT::v4i32, Op1);
13779
13780       // Do the compare.
13781       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
13782
13783       // Make sure the lower and upper halves are both all-ones.
13784       static const int Mask[] = { 1, 0, 3, 2 };
13785       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
13786       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
13787
13788       if (Invert)
13789         Result = DAG.getNOT(dl, Result, MVT::v4i32);
13790
13791       return DAG.getBitcast(VT, Result);
13792     }
13793   }
13794
13795   // Since SSE has no unsigned integer comparisons, we need to flip the sign
13796   // bits of the inputs before performing those operations.
13797   if (FlipSigns) {
13798     EVT EltVT = VT.getVectorElementType();
13799     SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), dl,
13800                                  VT);
13801     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
13802     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
13803   }
13804
13805   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
13806
13807   // If the logical-not of the result is required, perform that now.
13808   if (Invert)
13809     Result = DAG.getNOT(dl, Result, VT);
13810
13811   if (MinMax)
13812     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
13813
13814   if (Subus)
13815     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
13816                          getZeroVector(VT, Subtarget, DAG, dl));
13817
13818   return Result;
13819 }
13820
13821 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
13822
13823   MVT VT = Op.getSimpleValueType();
13824
13825   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
13826
13827   assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
13828          && "SetCC type must be 8-bit or 1-bit integer");
13829   SDValue Op0 = Op.getOperand(0);
13830   SDValue Op1 = Op.getOperand(1);
13831   SDLoc dl(Op);
13832   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
13833
13834   // Optimize to BT if possible.
13835   // Lower (X & (1 << N)) == 0 to BT(X, N).
13836   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
13837   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
13838   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
13839       Op1.getOpcode() == ISD::Constant &&
13840       cast<ConstantSDNode>(Op1)->isNullValue() &&
13841       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13842     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
13843     if (NewSetCC.getNode()) {
13844       if (VT == MVT::i1)
13845         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewSetCC);
13846       return NewSetCC;
13847     }
13848   }
13849
13850   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
13851   // these.
13852   if (Op1.getOpcode() == ISD::Constant &&
13853       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
13854        cast<ConstantSDNode>(Op1)->isNullValue()) &&
13855       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13856
13857     // If the input is a setcc, then reuse the input setcc or use a new one with
13858     // the inverted condition.
13859     if (Op0.getOpcode() == X86ISD::SETCC) {
13860       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
13861       bool Invert = (CC == ISD::SETNE) ^
13862         cast<ConstantSDNode>(Op1)->isNullValue();
13863       if (!Invert)
13864         return Op0;
13865
13866       CCode = X86::GetOppositeBranchCondition(CCode);
13867       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13868                                   DAG.getConstant(CCode, dl, MVT::i8),
13869                                   Op0.getOperand(1));
13870       if (VT == MVT::i1)
13871         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
13872       return SetCC;
13873     }
13874   }
13875   if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
13876       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
13877       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13878
13879     ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
13880     return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, dl, MVT::i1), NewCC);
13881   }
13882
13883   bool isFP = Op1.getSimpleValueType().isFloatingPoint();
13884   unsigned X86CC = TranslateX86CC(CC, dl, isFP, Op0, Op1, DAG);
13885   if (X86CC == X86::COND_INVALID)
13886     return SDValue();
13887
13888   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
13889   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
13890   SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13891                               DAG.getConstant(X86CC, dl, MVT::i8), EFLAGS);
13892   if (VT == MVT::i1)
13893     return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
13894   return SetCC;
13895 }
13896
13897 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
13898 static bool isX86LogicalCmp(SDValue Op) {
13899   unsigned Opc = Op.getNode()->getOpcode();
13900   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
13901       Opc == X86ISD::SAHF)
13902     return true;
13903   if (Op.getResNo() == 1 &&
13904       (Opc == X86ISD::ADD ||
13905        Opc == X86ISD::SUB ||
13906        Opc == X86ISD::ADC ||
13907        Opc == X86ISD::SBB ||
13908        Opc == X86ISD::SMUL ||
13909        Opc == X86ISD::UMUL ||
13910        Opc == X86ISD::INC ||
13911        Opc == X86ISD::DEC ||
13912        Opc == X86ISD::OR ||
13913        Opc == X86ISD::XOR ||
13914        Opc == X86ISD::AND))
13915     return true;
13916
13917   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
13918     return true;
13919
13920   return false;
13921 }
13922
13923 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
13924   if (V.getOpcode() != ISD::TRUNCATE)
13925     return false;
13926
13927   SDValue VOp0 = V.getOperand(0);
13928   unsigned InBits = VOp0.getValueSizeInBits();
13929   unsigned Bits = V.getValueSizeInBits();
13930   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
13931 }
13932
13933 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
13934   bool addTest = true;
13935   SDValue Cond  = Op.getOperand(0);
13936   SDValue Op1 = Op.getOperand(1);
13937   SDValue Op2 = Op.getOperand(2);
13938   SDLoc DL(Op);
13939   EVT VT = Op1.getValueType();
13940   SDValue CC;
13941
13942   // Lower FP selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
13943   // are available or VBLENDV if AVX is available.
13944   // Otherwise FP cmovs get lowered into a less efficient branch sequence later.
13945   if (Cond.getOpcode() == ISD::SETCC &&
13946       ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
13947        (Subtarget->hasSSE1() && VT == MVT::f32)) &&
13948       VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
13949     SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
13950     int SSECC = translateX86FSETCC(
13951         cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
13952
13953     if (SSECC != 8) {
13954       if (Subtarget->hasAVX512()) {
13955         SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
13956                                   DAG.getConstant(SSECC, DL, MVT::i8));
13957         return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
13958       }
13959
13960       SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
13961                                 DAG.getConstant(SSECC, DL, MVT::i8));
13962
13963       // If we have AVX, we can use a variable vector select (VBLENDV) instead
13964       // of 3 logic instructions for size savings and potentially speed.
13965       // Unfortunately, there is no scalar form of VBLENDV.
13966
13967       // If either operand is a constant, don't try this. We can expect to
13968       // optimize away at least one of the logic instructions later in that
13969       // case, so that sequence would be faster than a variable blend.
13970
13971       // BLENDV was introduced with SSE 4.1, but the 2 register form implicitly
13972       // uses XMM0 as the selection register. That may need just as many
13973       // instructions as the AND/ANDN/OR sequence due to register moves, so
13974       // don't bother.
13975
13976       if (Subtarget->hasAVX() &&
13977           !isa<ConstantFPSDNode>(Op1) && !isa<ConstantFPSDNode>(Op2)) {
13978
13979         // Convert to vectors, do a VSELECT, and convert back to scalar.
13980         // All of the conversions should be optimized away.
13981
13982         EVT VecVT = VT == MVT::f32 ? MVT::v4f32 : MVT::v2f64;
13983         SDValue VOp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op1);
13984         SDValue VOp2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op2);
13985         SDValue VCmp = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Cmp);
13986
13987         EVT VCmpVT = VT == MVT::f32 ? MVT::v4i32 : MVT::v2i64;
13988         VCmp = DAG.getBitcast(VCmpVT, VCmp);
13989
13990         SDValue VSel = DAG.getNode(ISD::VSELECT, DL, VecVT, VCmp, VOp1, VOp2);
13991
13992         return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
13993                            VSel, DAG.getIntPtrConstant(0, DL));
13994       }
13995       SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
13996       SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
13997       return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
13998     }
13999   }
14000
14001   if (VT.isVector() && VT.getScalarType() == MVT::i1) {
14002     SDValue Op1Scalar;
14003     if (ISD::isBuildVectorOfConstantSDNodes(Op1.getNode()))
14004       Op1Scalar = ConvertI1VectorToInteger(Op1, DAG);
14005     else if (Op1.getOpcode() == ISD::BITCAST && Op1.getOperand(0))
14006       Op1Scalar = Op1.getOperand(0);
14007     SDValue Op2Scalar;
14008     if (ISD::isBuildVectorOfConstantSDNodes(Op2.getNode()))
14009       Op2Scalar = ConvertI1VectorToInteger(Op2, DAG);
14010     else if (Op2.getOpcode() == ISD::BITCAST && Op2.getOperand(0))
14011       Op2Scalar = Op2.getOperand(0);
14012     if (Op1Scalar.getNode() && Op2Scalar.getNode()) {
14013       SDValue newSelect = DAG.getNode(ISD::SELECT, DL,
14014                                       Op1Scalar.getValueType(),
14015                                       Cond, Op1Scalar, Op2Scalar);
14016       if (newSelect.getValueSizeInBits() == VT.getSizeInBits())
14017         return DAG.getBitcast(VT, newSelect);
14018       SDValue ExtVec = DAG.getBitcast(MVT::v8i1, newSelect);
14019       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, ExtVec,
14020                          DAG.getIntPtrConstant(0, DL));
14021     }
14022   }
14023
14024   if (VT == MVT::v4i1 || VT == MVT::v2i1) {
14025     SDValue zeroConst = DAG.getIntPtrConstant(0, DL);
14026     Op1 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
14027                       DAG.getUNDEF(MVT::v8i1), Op1, zeroConst);
14028     Op2 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
14029                       DAG.getUNDEF(MVT::v8i1), Op2, zeroConst);
14030     SDValue newSelect = DAG.getNode(ISD::SELECT, DL, MVT::v8i1,
14031                                     Cond, Op1, Op2);
14032     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, newSelect, zeroConst);
14033   }
14034
14035   if (Cond.getOpcode() == ISD::SETCC) {
14036     SDValue NewCond = LowerSETCC(Cond, DAG);
14037     if (NewCond.getNode())
14038       Cond = NewCond;
14039   }
14040
14041   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
14042   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
14043   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
14044   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
14045   if (Cond.getOpcode() == X86ISD::SETCC &&
14046       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
14047       isZero(Cond.getOperand(1).getOperand(1))) {
14048     SDValue Cmp = Cond.getOperand(1);
14049
14050     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
14051
14052     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
14053         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
14054       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
14055
14056       SDValue CmpOp0 = Cmp.getOperand(0);
14057       // Apply further optimizations for special cases
14058       // (select (x != 0), -1, 0) -> neg & sbb
14059       // (select (x == 0), 0, -1) -> neg & sbb
14060       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
14061         if (YC->isNullValue() &&
14062             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
14063           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
14064           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
14065                                     DAG.getConstant(0, DL,
14066                                                     CmpOp0.getValueType()),
14067                                     CmpOp0);
14068           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
14069                                     DAG.getConstant(X86::COND_B, DL, MVT::i8),
14070                                     SDValue(Neg.getNode(), 1));
14071           return Res;
14072         }
14073
14074       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
14075                         CmpOp0, DAG.getConstant(1, DL, CmpOp0.getValueType()));
14076       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14077
14078       SDValue Res =   // Res = 0 or -1.
14079         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
14080                     DAG.getConstant(X86::COND_B, DL, MVT::i8), Cmp);
14081
14082       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
14083         Res = DAG.getNOT(DL, Res, Res.getValueType());
14084
14085       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
14086       if (!N2C || !N2C->isNullValue())
14087         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
14088       return Res;
14089     }
14090   }
14091
14092   // Look past (and (setcc_carry (cmp ...)), 1).
14093   if (Cond.getOpcode() == ISD::AND &&
14094       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
14095     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
14096     if (C && C->getAPIntValue() == 1)
14097       Cond = Cond.getOperand(0);
14098   }
14099
14100   // If condition flag is set by a X86ISD::CMP, then use it as the condition
14101   // setting operand in place of the X86ISD::SETCC.
14102   unsigned CondOpcode = Cond.getOpcode();
14103   if (CondOpcode == X86ISD::SETCC ||
14104       CondOpcode == X86ISD::SETCC_CARRY) {
14105     CC = Cond.getOperand(0);
14106
14107     SDValue Cmp = Cond.getOperand(1);
14108     unsigned Opc = Cmp.getOpcode();
14109     MVT VT = Op.getSimpleValueType();
14110
14111     bool IllegalFPCMov = false;
14112     if (VT.isFloatingPoint() && !VT.isVector() &&
14113         !isScalarFPTypeInSSEReg(VT))  // FPStack?
14114       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
14115
14116     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
14117         Opc == X86ISD::BT) { // FIXME
14118       Cond = Cmp;
14119       addTest = false;
14120     }
14121   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
14122              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
14123              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
14124               Cond.getOperand(0).getValueType() != MVT::i8)) {
14125     SDValue LHS = Cond.getOperand(0);
14126     SDValue RHS = Cond.getOperand(1);
14127     unsigned X86Opcode;
14128     unsigned X86Cond;
14129     SDVTList VTs;
14130     switch (CondOpcode) {
14131     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
14132     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
14133     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
14134     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
14135     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
14136     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
14137     default: llvm_unreachable("unexpected overflowing operator");
14138     }
14139     if (CondOpcode == ISD::UMULO)
14140       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
14141                           MVT::i32);
14142     else
14143       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
14144
14145     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
14146
14147     if (CondOpcode == ISD::UMULO)
14148       Cond = X86Op.getValue(2);
14149     else
14150       Cond = X86Op.getValue(1);
14151
14152     CC = DAG.getConstant(X86Cond, DL, MVT::i8);
14153     addTest = false;
14154   }
14155
14156   if (addTest) {
14157     // Look past the truncate if the high bits are known zero.
14158     if (isTruncWithZeroHighBitsInput(Cond, DAG))
14159       Cond = Cond.getOperand(0);
14160
14161     // We know the result of AND is compared against zero. Try to match
14162     // it to BT.
14163     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
14164       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
14165       if (NewSetCC.getNode()) {
14166         CC = NewSetCC.getOperand(0);
14167         Cond = NewSetCC.getOperand(1);
14168         addTest = false;
14169       }
14170     }
14171   }
14172
14173   if (addTest) {
14174     CC = DAG.getConstant(X86::COND_NE, DL, MVT::i8);
14175     Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
14176   }
14177
14178   // a <  b ? -1 :  0 -> RES = ~setcc_carry
14179   // a <  b ?  0 : -1 -> RES = setcc_carry
14180   // a >= b ? -1 :  0 -> RES = setcc_carry
14181   // a >= b ?  0 : -1 -> RES = ~setcc_carry
14182   if (Cond.getOpcode() == X86ISD::SUB) {
14183     Cond = ConvertCmpIfNecessary(Cond, DAG);
14184     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
14185
14186     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
14187         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
14188       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
14189                                 DAG.getConstant(X86::COND_B, DL, MVT::i8),
14190                                 Cond);
14191       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
14192         return DAG.getNOT(DL, Res, Res.getValueType());
14193       return Res;
14194     }
14195   }
14196
14197   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
14198   // widen the cmov and push the truncate through. This avoids introducing a new
14199   // branch during isel and doesn't add any extensions.
14200   if (Op.getValueType() == MVT::i8 &&
14201       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
14202     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
14203     if (T1.getValueType() == T2.getValueType() &&
14204         // Blacklist CopyFromReg to avoid partial register stalls.
14205         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
14206       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
14207       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
14208       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
14209     }
14210   }
14211
14212   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
14213   // condition is true.
14214   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
14215   SDValue Ops[] = { Op2, Op1, CC, Cond };
14216   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
14217 }
14218
14219 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op,
14220                                        const X86Subtarget *Subtarget,
14221                                        SelectionDAG &DAG) {
14222   MVT VT = Op->getSimpleValueType(0);
14223   SDValue In = Op->getOperand(0);
14224   MVT InVT = In.getSimpleValueType();
14225   MVT VTElt = VT.getVectorElementType();
14226   MVT InVTElt = InVT.getVectorElementType();
14227   SDLoc dl(Op);
14228
14229   // SKX processor
14230   if ((InVTElt == MVT::i1) &&
14231       (((Subtarget->hasBWI() && Subtarget->hasVLX() &&
14232         VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() <= 16)) ||
14233
14234        ((Subtarget->hasBWI() && VT.is512BitVector() &&
14235         VTElt.getSizeInBits() <= 16)) ||
14236
14237        ((Subtarget->hasDQI() && Subtarget->hasVLX() &&
14238         VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() >= 32)) ||
14239
14240        ((Subtarget->hasDQI() && VT.is512BitVector() &&
14241         VTElt.getSizeInBits() >= 32))))
14242     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14243
14244   unsigned int NumElts = VT.getVectorNumElements();
14245
14246   if (NumElts != 8 && NumElts != 16 && !Subtarget->hasBWI())
14247     return SDValue();
14248
14249   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1) {
14250     if (In.getOpcode() == X86ISD::VSEXT || In.getOpcode() == X86ISD::VZEXT)
14251       return DAG.getNode(In.getOpcode(), dl, VT, In.getOperand(0));
14252     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14253   }
14254
14255   assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
14256   MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
14257   SDValue NegOne =
14258    DAG.getConstant(APInt::getAllOnesValue(ExtVT.getScalarSizeInBits()), dl,
14259                    ExtVT);
14260   SDValue Zero =
14261    DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), dl, ExtVT);
14262
14263   SDValue V = DAG.getNode(ISD::VSELECT, dl, ExtVT, In, NegOne, Zero);
14264   if (VT.is512BitVector())
14265     return V;
14266   return DAG.getNode(X86ISD::VTRUNC, dl, VT, V);
14267 }
14268
14269 static SDValue LowerSIGN_EXTEND_VECTOR_INREG(SDValue Op,
14270                                              const X86Subtarget *Subtarget,
14271                                              SelectionDAG &DAG) {
14272   SDValue In = Op->getOperand(0);
14273   MVT VT = Op->getSimpleValueType(0);
14274   MVT InVT = In.getSimpleValueType();
14275   assert(VT.getSizeInBits() == InVT.getSizeInBits());
14276
14277   MVT InSVT = InVT.getScalarType();
14278   assert(VT.getScalarType().getScalarSizeInBits() > InSVT.getScalarSizeInBits());
14279
14280   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
14281     return SDValue();
14282   if (InSVT != MVT::i32 && InSVT != MVT::i16 && InSVT != MVT::i8)
14283     return SDValue();
14284
14285   SDLoc dl(Op);
14286
14287   // SSE41 targets can use the pmovsx* instructions directly.
14288   if (Subtarget->hasSSE41())
14289     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14290
14291   // pre-SSE41 targets unpack lower lanes and then sign-extend using SRAI.
14292   SDValue Curr = In;
14293   MVT CurrVT = InVT;
14294
14295   // As SRAI is only available on i16/i32 types, we expand only up to i32
14296   // and handle i64 separately.
14297   while (CurrVT != VT && CurrVT.getScalarType() != MVT::i32) {
14298     Curr = DAG.getNode(X86ISD::UNPCKL, dl, CurrVT, DAG.getUNDEF(CurrVT), Curr);
14299     MVT CurrSVT = MVT::getIntegerVT(CurrVT.getScalarSizeInBits() * 2);
14300     CurrVT = MVT::getVectorVT(CurrSVT, CurrVT.getVectorNumElements() / 2);
14301     Curr = DAG.getBitcast(CurrVT, Curr);
14302   }
14303
14304   SDValue SignExt = Curr;
14305   if (CurrVT != InVT) {
14306     unsigned SignExtShift =
14307         CurrVT.getScalarSizeInBits() - InSVT.getScalarSizeInBits();
14308     SignExt = DAG.getNode(X86ISD::VSRAI, dl, CurrVT, Curr,
14309                           DAG.getConstant(SignExtShift, dl, MVT::i8));
14310   }
14311
14312   if (CurrVT == VT)
14313     return SignExt;
14314
14315   if (VT == MVT::v2i64 && CurrVT == MVT::v4i32) {
14316     SDValue Sign = DAG.getNode(X86ISD::VSRAI, dl, CurrVT, Curr,
14317                                DAG.getConstant(31, dl, MVT::i8));
14318     SDValue Ext = DAG.getVectorShuffle(CurrVT, dl, SignExt, Sign, {0, 4, 1, 5});
14319     return DAG.getBitcast(VT, Ext);
14320   }
14321
14322   return SDValue();
14323 }
14324
14325 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
14326                                 SelectionDAG &DAG) {
14327   MVT VT = Op->getSimpleValueType(0);
14328   SDValue In = Op->getOperand(0);
14329   MVT InVT = In.getSimpleValueType();
14330   SDLoc dl(Op);
14331
14332   if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
14333     return LowerSIGN_EXTEND_AVX512(Op, Subtarget, DAG);
14334
14335   if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
14336       (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
14337       (VT != MVT::v16i16 || InVT != MVT::v16i8))
14338     return SDValue();
14339
14340   if (Subtarget->hasInt256())
14341     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14342
14343   // Optimize vectors in AVX mode
14344   // Sign extend  v8i16 to v8i32 and
14345   //              v4i32 to v4i64
14346   //
14347   // Divide input vector into two parts
14348   // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
14349   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
14350   // concat the vectors to original VT
14351
14352   unsigned NumElems = InVT.getVectorNumElements();
14353   SDValue Undef = DAG.getUNDEF(InVT);
14354
14355   SmallVector<int,8> ShufMask1(NumElems, -1);
14356   for (unsigned i = 0; i != NumElems/2; ++i)
14357     ShufMask1[i] = i;
14358
14359   SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
14360
14361   SmallVector<int,8> ShufMask2(NumElems, -1);
14362   for (unsigned i = 0; i != NumElems/2; ++i)
14363     ShufMask2[i] = i + NumElems/2;
14364
14365   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
14366
14367   MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
14368                                 VT.getVectorNumElements()/2);
14369
14370   OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
14371   OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
14372
14373   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
14374 }
14375
14376 // Lower vector extended loads using a shuffle. If SSSE3 is not available we
14377 // may emit an illegal shuffle but the expansion is still better than scalar
14378 // code. We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise
14379 // we'll emit a shuffle and a arithmetic shift.
14380 // FIXME: Is the expansion actually better than scalar code? It doesn't seem so.
14381 // TODO: It is possible to support ZExt by zeroing the undef values during
14382 // the shuffle phase or after the shuffle.
14383 static SDValue LowerExtendedLoad(SDValue Op, const X86Subtarget *Subtarget,
14384                                  SelectionDAG &DAG) {
14385   MVT RegVT = Op.getSimpleValueType();
14386   assert(RegVT.isVector() && "We only custom lower vector sext loads.");
14387   assert(RegVT.isInteger() &&
14388          "We only custom lower integer vector sext loads.");
14389
14390   // Nothing useful we can do without SSE2 shuffles.
14391   assert(Subtarget->hasSSE2() && "We only custom lower sext loads with SSE2.");
14392
14393   LoadSDNode *Ld = cast<LoadSDNode>(Op.getNode());
14394   SDLoc dl(Ld);
14395   EVT MemVT = Ld->getMemoryVT();
14396   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14397   unsigned RegSz = RegVT.getSizeInBits();
14398
14399   ISD::LoadExtType Ext = Ld->getExtensionType();
14400
14401   assert((Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)
14402          && "Only anyext and sext are currently implemented.");
14403   assert(MemVT != RegVT && "Cannot extend to the same type");
14404   assert(MemVT.isVector() && "Must load a vector from memory");
14405
14406   unsigned NumElems = RegVT.getVectorNumElements();
14407   unsigned MemSz = MemVT.getSizeInBits();
14408   assert(RegSz > MemSz && "Register size must be greater than the mem size");
14409
14410   if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256()) {
14411     // The only way in which we have a legal 256-bit vector result but not the
14412     // integer 256-bit operations needed to directly lower a sextload is if we
14413     // have AVX1 but not AVX2. In that case, we can always emit a sextload to
14414     // a 128-bit vector and a normal sign_extend to 256-bits that should get
14415     // correctly legalized. We do this late to allow the canonical form of
14416     // sextload to persist throughout the rest of the DAG combiner -- it wants
14417     // to fold together any extensions it can, and so will fuse a sign_extend
14418     // of an sextload into a sextload targeting a wider value.
14419     SDValue Load;
14420     if (MemSz == 128) {
14421       // Just switch this to a normal load.
14422       assert(TLI.isTypeLegal(MemVT) && "If the memory type is a 128-bit type, "
14423                                        "it must be a legal 128-bit vector "
14424                                        "type!");
14425       Load = DAG.getLoad(MemVT, dl, Ld->getChain(), Ld->getBasePtr(),
14426                   Ld->getPointerInfo(), Ld->isVolatile(), Ld->isNonTemporal(),
14427                   Ld->isInvariant(), Ld->getAlignment());
14428     } else {
14429       assert(MemSz < 128 &&
14430              "Can't extend a type wider than 128 bits to a 256 bit vector!");
14431       // Do an sext load to a 128-bit vector type. We want to use the same
14432       // number of elements, but elements half as wide. This will end up being
14433       // recursively lowered by this routine, but will succeed as we definitely
14434       // have all the necessary features if we're using AVX1.
14435       EVT HalfEltVT =
14436           EVT::getIntegerVT(*DAG.getContext(), RegVT.getScalarSizeInBits() / 2);
14437       EVT HalfVecVT = EVT::getVectorVT(*DAG.getContext(), HalfEltVT, NumElems);
14438       Load =
14439           DAG.getExtLoad(Ext, dl, HalfVecVT, Ld->getChain(), Ld->getBasePtr(),
14440                          Ld->getPointerInfo(), MemVT, Ld->isVolatile(),
14441                          Ld->isNonTemporal(), Ld->isInvariant(),
14442                          Ld->getAlignment());
14443     }
14444
14445     // Replace chain users with the new chain.
14446     assert(Load->getNumValues() == 2 && "Loads must carry a chain!");
14447     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Load.getValue(1));
14448
14449     // Finally, do a normal sign-extend to the desired register.
14450     return DAG.getSExtOrTrunc(Load, dl, RegVT);
14451   }
14452
14453   // All sizes must be a power of two.
14454   assert(isPowerOf2_32(RegSz * MemSz * NumElems) &&
14455          "Non-power-of-two elements are not custom lowered!");
14456
14457   // Attempt to load the original value using scalar loads.
14458   // Find the largest scalar type that divides the total loaded size.
14459   MVT SclrLoadTy = MVT::i8;
14460   for (MVT Tp : MVT::integer_valuetypes()) {
14461     if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
14462       SclrLoadTy = Tp;
14463     }
14464   }
14465
14466   // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
14467   if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
14468       (64 <= MemSz))
14469     SclrLoadTy = MVT::f64;
14470
14471   // Calculate the number of scalar loads that we need to perform
14472   // in order to load our vector from memory.
14473   unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
14474
14475   assert((Ext != ISD::SEXTLOAD || NumLoads == 1) &&
14476          "Can only lower sext loads with a single scalar load!");
14477
14478   unsigned loadRegZize = RegSz;
14479   if (Ext == ISD::SEXTLOAD && RegSz >= 256)
14480     loadRegZize = 128;
14481
14482   // Represent our vector as a sequence of elements which are the
14483   // largest scalar that we can load.
14484   EVT LoadUnitVecVT = EVT::getVectorVT(
14485       *DAG.getContext(), SclrLoadTy, loadRegZize / SclrLoadTy.getSizeInBits());
14486
14487   // Represent the data using the same element type that is stored in
14488   // memory. In practice, we ''widen'' MemVT.
14489   EVT WideVecVT =
14490       EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
14491                        loadRegZize / MemVT.getScalarType().getSizeInBits());
14492
14493   assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
14494          "Invalid vector type");
14495
14496   // We can't shuffle using an illegal type.
14497   assert(TLI.isTypeLegal(WideVecVT) &&
14498          "We only lower types that form legal widened vector types");
14499
14500   SmallVector<SDValue, 8> Chains;
14501   SDValue Ptr = Ld->getBasePtr();
14502   SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits() / 8, dl,
14503                                       TLI.getPointerTy(DAG.getDataLayout()));
14504   SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
14505
14506   for (unsigned i = 0; i < NumLoads; ++i) {
14507     // Perform a single load.
14508     SDValue ScalarLoad =
14509         DAG.getLoad(SclrLoadTy, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
14510                     Ld->isVolatile(), Ld->isNonTemporal(), Ld->isInvariant(),
14511                     Ld->getAlignment());
14512     Chains.push_back(ScalarLoad.getValue(1));
14513     // Create the first element type using SCALAR_TO_VECTOR in order to avoid
14514     // another round of DAGCombining.
14515     if (i == 0)
14516       Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
14517     else
14518       Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
14519                         ScalarLoad, DAG.getIntPtrConstant(i, dl));
14520
14521     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
14522   }
14523
14524   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
14525
14526   // Bitcast the loaded value to a vector of the original element type, in
14527   // the size of the target vector type.
14528   SDValue SlicedVec = DAG.getBitcast(WideVecVT, Res);
14529   unsigned SizeRatio = RegSz / MemSz;
14530
14531   if (Ext == ISD::SEXTLOAD) {
14532     // If we have SSE4.1, we can directly emit a VSEXT node.
14533     if (Subtarget->hasSSE41()) {
14534       SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
14535       DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14536       return Sext;
14537     }
14538
14539     // Otherwise we'll shuffle the small elements in the high bits of the
14540     // larger type and perform an arithmetic shift. If the shift is not legal
14541     // it's better to scalarize.
14542     assert(TLI.isOperationLegalOrCustom(ISD::SRA, RegVT) &&
14543            "We can't implement a sext load without an arithmetic right shift!");
14544
14545     // Redistribute the loaded elements into the different locations.
14546     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
14547     for (unsigned i = 0; i != NumElems; ++i)
14548       ShuffleVec[i * SizeRatio + SizeRatio - 1] = i;
14549
14550     SDValue Shuff = DAG.getVectorShuffle(
14551         WideVecVT, dl, SlicedVec, DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
14552
14553     Shuff = DAG.getBitcast(RegVT, Shuff);
14554
14555     // Build the arithmetic shift.
14556     unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
14557                    MemVT.getVectorElementType().getSizeInBits();
14558     Shuff =
14559         DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
14560                     DAG.getConstant(Amt, dl, RegVT));
14561
14562     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14563     return Shuff;
14564   }
14565
14566   // Redistribute the loaded elements into the different locations.
14567   SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
14568   for (unsigned i = 0; i != NumElems; ++i)
14569     ShuffleVec[i * SizeRatio] = i;
14570
14571   SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
14572                                        DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
14573
14574   // Bitcast to the requested type.
14575   Shuff = DAG.getBitcast(RegVT, Shuff);
14576   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14577   return Shuff;
14578 }
14579
14580 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
14581 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
14582 // from the AND / OR.
14583 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
14584   Opc = Op.getOpcode();
14585   if (Opc != ISD::OR && Opc != ISD::AND)
14586     return false;
14587   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
14588           Op.getOperand(0).hasOneUse() &&
14589           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
14590           Op.getOperand(1).hasOneUse());
14591 }
14592
14593 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
14594 // 1 and that the SETCC node has a single use.
14595 static bool isXor1OfSetCC(SDValue Op) {
14596   if (Op.getOpcode() != ISD::XOR)
14597     return false;
14598   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
14599   if (N1C && N1C->getAPIntValue() == 1) {
14600     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
14601       Op.getOperand(0).hasOneUse();
14602   }
14603   return false;
14604 }
14605
14606 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
14607   bool addTest = true;
14608   SDValue Chain = Op.getOperand(0);
14609   SDValue Cond  = Op.getOperand(1);
14610   SDValue Dest  = Op.getOperand(2);
14611   SDLoc dl(Op);
14612   SDValue CC;
14613   bool Inverted = false;
14614
14615   if (Cond.getOpcode() == ISD::SETCC) {
14616     // Check for setcc([su]{add,sub,mul}o == 0).
14617     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
14618         isa<ConstantSDNode>(Cond.getOperand(1)) &&
14619         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
14620         Cond.getOperand(0).getResNo() == 1 &&
14621         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
14622          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
14623          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
14624          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
14625          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
14626          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
14627       Inverted = true;
14628       Cond = Cond.getOperand(0);
14629     } else {
14630       SDValue NewCond = LowerSETCC(Cond, DAG);
14631       if (NewCond.getNode())
14632         Cond = NewCond;
14633     }
14634   }
14635 #if 0
14636   // FIXME: LowerXALUO doesn't handle these!!
14637   else if (Cond.getOpcode() == X86ISD::ADD  ||
14638            Cond.getOpcode() == X86ISD::SUB  ||
14639            Cond.getOpcode() == X86ISD::SMUL ||
14640            Cond.getOpcode() == X86ISD::UMUL)
14641     Cond = LowerXALUO(Cond, DAG);
14642 #endif
14643
14644   // Look pass (and (setcc_carry (cmp ...)), 1).
14645   if (Cond.getOpcode() == ISD::AND &&
14646       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
14647     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
14648     if (C && C->getAPIntValue() == 1)
14649       Cond = Cond.getOperand(0);
14650   }
14651
14652   // If condition flag is set by a X86ISD::CMP, then use it as the condition
14653   // setting operand in place of the X86ISD::SETCC.
14654   unsigned CondOpcode = Cond.getOpcode();
14655   if (CondOpcode == X86ISD::SETCC ||
14656       CondOpcode == X86ISD::SETCC_CARRY) {
14657     CC = Cond.getOperand(0);
14658
14659     SDValue Cmp = Cond.getOperand(1);
14660     unsigned Opc = Cmp.getOpcode();
14661     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
14662     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
14663       Cond = Cmp;
14664       addTest = false;
14665     } else {
14666       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
14667       default: break;
14668       case X86::COND_O:
14669       case X86::COND_B:
14670         // These can only come from an arithmetic instruction with overflow,
14671         // e.g. SADDO, UADDO.
14672         Cond = Cond.getNode()->getOperand(1);
14673         addTest = false;
14674         break;
14675       }
14676     }
14677   }
14678   CondOpcode = Cond.getOpcode();
14679   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
14680       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
14681       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
14682        Cond.getOperand(0).getValueType() != MVT::i8)) {
14683     SDValue LHS = Cond.getOperand(0);
14684     SDValue RHS = Cond.getOperand(1);
14685     unsigned X86Opcode;
14686     unsigned X86Cond;
14687     SDVTList VTs;
14688     // Keep this in sync with LowerXALUO, otherwise we might create redundant
14689     // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
14690     // X86ISD::INC).
14691     switch (CondOpcode) {
14692     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
14693     case ISD::SADDO:
14694       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
14695         if (C->isOne()) {
14696           X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
14697           break;
14698         }
14699       X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
14700     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
14701     case ISD::SSUBO:
14702       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
14703         if (C->isOne()) {
14704           X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
14705           break;
14706         }
14707       X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
14708     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
14709     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
14710     default: llvm_unreachable("unexpected overflowing operator");
14711     }
14712     if (Inverted)
14713       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
14714     if (CondOpcode == ISD::UMULO)
14715       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
14716                           MVT::i32);
14717     else
14718       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
14719
14720     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
14721
14722     if (CondOpcode == ISD::UMULO)
14723       Cond = X86Op.getValue(2);
14724     else
14725       Cond = X86Op.getValue(1);
14726
14727     CC = DAG.getConstant(X86Cond, dl, MVT::i8);
14728     addTest = false;
14729   } else {
14730     unsigned CondOpc;
14731     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
14732       SDValue Cmp = Cond.getOperand(0).getOperand(1);
14733       if (CondOpc == ISD::OR) {
14734         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
14735         // two branches instead of an explicit OR instruction with a
14736         // separate test.
14737         if (Cmp == Cond.getOperand(1).getOperand(1) &&
14738             isX86LogicalCmp(Cmp)) {
14739           CC = Cond.getOperand(0).getOperand(0);
14740           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14741                               Chain, Dest, CC, Cmp);
14742           CC = Cond.getOperand(1).getOperand(0);
14743           Cond = Cmp;
14744           addTest = false;
14745         }
14746       } else { // ISD::AND
14747         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
14748         // two branches instead of an explicit AND instruction with a
14749         // separate test. However, we only do this if this block doesn't
14750         // have a fall-through edge, because this requires an explicit
14751         // jmp when the condition is false.
14752         if (Cmp == Cond.getOperand(1).getOperand(1) &&
14753             isX86LogicalCmp(Cmp) &&
14754             Op.getNode()->hasOneUse()) {
14755           X86::CondCode CCode =
14756             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
14757           CCode = X86::GetOppositeBranchCondition(CCode);
14758           CC = DAG.getConstant(CCode, dl, MVT::i8);
14759           SDNode *User = *Op.getNode()->use_begin();
14760           // Look for an unconditional branch following this conditional branch.
14761           // We need this because we need to reverse the successors in order
14762           // to implement FCMP_OEQ.
14763           if (User->getOpcode() == ISD::BR) {
14764             SDValue FalseBB = User->getOperand(1);
14765             SDNode *NewBR =
14766               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14767             assert(NewBR == User);
14768             (void)NewBR;
14769             Dest = FalseBB;
14770
14771             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14772                                 Chain, Dest, CC, Cmp);
14773             X86::CondCode CCode =
14774               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
14775             CCode = X86::GetOppositeBranchCondition(CCode);
14776             CC = DAG.getConstant(CCode, dl, MVT::i8);
14777             Cond = Cmp;
14778             addTest = false;
14779           }
14780         }
14781       }
14782     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
14783       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
14784       // It should be transformed during dag combiner except when the condition
14785       // is set by a arithmetics with overflow node.
14786       X86::CondCode CCode =
14787         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
14788       CCode = X86::GetOppositeBranchCondition(CCode);
14789       CC = DAG.getConstant(CCode, dl, MVT::i8);
14790       Cond = Cond.getOperand(0).getOperand(1);
14791       addTest = false;
14792     } else if (Cond.getOpcode() == ISD::SETCC &&
14793                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
14794       // For FCMP_OEQ, we can emit
14795       // two branches instead of an explicit AND instruction with a
14796       // separate test. However, we only do this if this block doesn't
14797       // have a fall-through edge, because this requires an explicit
14798       // jmp when the condition is false.
14799       if (Op.getNode()->hasOneUse()) {
14800         SDNode *User = *Op.getNode()->use_begin();
14801         // Look for an unconditional branch following this conditional branch.
14802         // We need this because we need to reverse the successors in order
14803         // to implement FCMP_OEQ.
14804         if (User->getOpcode() == ISD::BR) {
14805           SDValue FalseBB = User->getOperand(1);
14806           SDNode *NewBR =
14807             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14808           assert(NewBR == User);
14809           (void)NewBR;
14810           Dest = FalseBB;
14811
14812           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
14813                                     Cond.getOperand(0), Cond.getOperand(1));
14814           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14815           CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
14816           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14817                               Chain, Dest, CC, Cmp);
14818           CC = DAG.getConstant(X86::COND_P, dl, MVT::i8);
14819           Cond = Cmp;
14820           addTest = false;
14821         }
14822       }
14823     } else if (Cond.getOpcode() == ISD::SETCC &&
14824                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
14825       // For FCMP_UNE, we can emit
14826       // two branches instead of an explicit AND instruction with a
14827       // separate test. However, we only do this if this block doesn't
14828       // have a fall-through edge, because this requires an explicit
14829       // jmp when the condition is false.
14830       if (Op.getNode()->hasOneUse()) {
14831         SDNode *User = *Op.getNode()->use_begin();
14832         // Look for an unconditional branch following this conditional branch.
14833         // We need this because we need to reverse the successors in order
14834         // to implement FCMP_UNE.
14835         if (User->getOpcode() == ISD::BR) {
14836           SDValue FalseBB = User->getOperand(1);
14837           SDNode *NewBR =
14838             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14839           assert(NewBR == User);
14840           (void)NewBR;
14841
14842           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
14843                                     Cond.getOperand(0), Cond.getOperand(1));
14844           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14845           CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
14846           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14847                               Chain, Dest, CC, Cmp);
14848           CC = DAG.getConstant(X86::COND_NP, dl, MVT::i8);
14849           Cond = Cmp;
14850           addTest = false;
14851           Dest = FalseBB;
14852         }
14853       }
14854     }
14855   }
14856
14857   if (addTest) {
14858     // Look pass the truncate if the high bits are known zero.
14859     if (isTruncWithZeroHighBitsInput(Cond, DAG))
14860         Cond = Cond.getOperand(0);
14861
14862     // We know the result of AND is compared against zero. Try to match
14863     // it to BT.
14864     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
14865       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
14866       if (NewSetCC.getNode()) {
14867         CC = NewSetCC.getOperand(0);
14868         Cond = NewSetCC.getOperand(1);
14869         addTest = false;
14870       }
14871     }
14872   }
14873
14874   if (addTest) {
14875     X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
14876     CC = DAG.getConstant(X86Cond, dl, MVT::i8);
14877     Cond = EmitTest(Cond, X86Cond, dl, DAG);
14878   }
14879   Cond = ConvertCmpIfNecessary(Cond, DAG);
14880   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14881                      Chain, Dest, CC, Cond);
14882 }
14883
14884 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
14885 // Calls to _alloca are needed to probe the stack when allocating more than 4k
14886 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
14887 // that the guard pages used by the OS virtual memory manager are allocated in
14888 // correct sequence.
14889 SDValue
14890 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
14891                                            SelectionDAG &DAG) const {
14892   MachineFunction &MF = DAG.getMachineFunction();
14893   bool SplitStack = MF.shouldSplitStack();
14894   bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMachO()) ||
14895                SplitStack;
14896   SDLoc dl(Op);
14897
14898   if (!Lower) {
14899     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14900     SDNode* Node = Op.getNode();
14901
14902     unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
14903     assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
14904         " not tell us which reg is the stack pointer!");
14905     EVT VT = Node->getValueType(0);
14906     SDValue Tmp1 = SDValue(Node, 0);
14907     SDValue Tmp2 = SDValue(Node, 1);
14908     SDValue Tmp3 = Node->getOperand(2);
14909     SDValue Chain = Tmp1.getOperand(0);
14910
14911     // Chain the dynamic stack allocation so that it doesn't modify the stack
14912     // pointer when other instructions are using the stack.
14913     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, dl, true),
14914         SDLoc(Node));
14915
14916     SDValue Size = Tmp2.getOperand(1);
14917     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
14918     Chain = SP.getValue(1);
14919     unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
14920     const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
14921     unsigned StackAlign = TFI.getStackAlignment();
14922     Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
14923     if (Align > StackAlign)
14924       Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
14925           DAG.getConstant(-(uint64_t)Align, dl, VT));
14926     Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
14927
14928     Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, dl, true),
14929         DAG.getIntPtrConstant(0, dl, true), SDValue(),
14930         SDLoc(Node));
14931
14932     SDValue Ops[2] = { Tmp1, Tmp2 };
14933     return DAG.getMergeValues(Ops, dl);
14934   }
14935
14936   // Get the inputs.
14937   SDValue Chain = Op.getOperand(0);
14938   SDValue Size  = Op.getOperand(1);
14939   unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
14940   EVT VT = Op.getNode()->getValueType(0);
14941
14942   bool Is64Bit = Subtarget->is64Bit();
14943   MVT SPTy = getPointerTy(DAG.getDataLayout());
14944
14945   if (SplitStack) {
14946     MachineRegisterInfo &MRI = MF.getRegInfo();
14947
14948     if (Is64Bit) {
14949       // The 64 bit implementation of segmented stacks needs to clobber both r10
14950       // r11. This makes it impossible to use it along with nested parameters.
14951       const Function *F = MF.getFunction();
14952
14953       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
14954            I != E; ++I)
14955         if (I->hasNestAttr())
14956           report_fatal_error("Cannot use segmented stacks with functions that "
14957                              "have nested arguments.");
14958     }
14959
14960     const TargetRegisterClass *AddrRegClass = getRegClassFor(SPTy);
14961     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
14962     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
14963     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
14964                                 DAG.getRegister(Vreg, SPTy));
14965     SDValue Ops1[2] = { Value, Chain };
14966     return DAG.getMergeValues(Ops1, dl);
14967   } else {
14968     SDValue Flag;
14969     const unsigned Reg = (Subtarget->isTarget64BitLP64() ? X86::RAX : X86::EAX);
14970
14971     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
14972     Flag = Chain.getValue(1);
14973     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
14974
14975     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
14976
14977     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
14978     unsigned SPReg = RegInfo->getStackRegister();
14979     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
14980     Chain = SP.getValue(1);
14981
14982     if (Align) {
14983       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
14984                        DAG.getConstant(-(uint64_t)Align, dl, VT));
14985       Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
14986     }
14987
14988     SDValue Ops1[2] = { SP, Chain };
14989     return DAG.getMergeValues(Ops1, dl);
14990   }
14991 }
14992
14993 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
14994   MachineFunction &MF = DAG.getMachineFunction();
14995   auto PtrVT = getPointerTy(MF.getDataLayout());
14996   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
14997
14998   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
14999   SDLoc DL(Op);
15000
15001   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
15002     // vastart just stores the address of the VarArgsFrameIndex slot into the
15003     // memory location argument.
15004     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
15005     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
15006                         MachinePointerInfo(SV), false, false, 0);
15007   }
15008
15009   // __va_list_tag:
15010   //   gp_offset         (0 - 6 * 8)
15011   //   fp_offset         (48 - 48 + 8 * 16)
15012   //   overflow_arg_area (point to parameters coming in memory).
15013   //   reg_save_area
15014   SmallVector<SDValue, 8> MemOps;
15015   SDValue FIN = Op.getOperand(1);
15016   // Store gp_offset
15017   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
15018                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
15019                                                DL, MVT::i32),
15020                                FIN, MachinePointerInfo(SV), false, false, 0);
15021   MemOps.push_back(Store);
15022
15023   // Store fp_offset
15024   FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(4, DL));
15025   Store = DAG.getStore(Op.getOperand(0), DL,
15026                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(), DL,
15027                                        MVT::i32),
15028                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
15029   MemOps.push_back(Store);
15030
15031   // Store ptr to overflow_arg_area
15032   FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(4, DL));
15033   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
15034   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
15035                        MachinePointerInfo(SV, 8),
15036                        false, false, 0);
15037   MemOps.push_back(Store);
15038
15039   // Store ptr to reg_save_area.
15040   FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(8, DL));
15041   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(), PtrVT);
15042   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
15043                        MachinePointerInfo(SV, 16), false, false, 0);
15044   MemOps.push_back(Store);
15045   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
15046 }
15047
15048 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
15049   assert(Subtarget->is64Bit() &&
15050          "LowerVAARG only handles 64-bit va_arg!");
15051   assert((Subtarget->isTargetLinux() ||
15052           Subtarget->isTargetDarwin()) &&
15053           "Unhandled target in LowerVAARG");
15054   assert(Op.getNode()->getNumOperands() == 4);
15055   SDValue Chain = Op.getOperand(0);
15056   SDValue SrcPtr = Op.getOperand(1);
15057   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
15058   unsigned Align = Op.getConstantOperandVal(3);
15059   SDLoc dl(Op);
15060
15061   EVT ArgVT = Op.getNode()->getValueType(0);
15062   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
15063   uint32_t ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy);
15064   uint8_t ArgMode;
15065
15066   // Decide which area this value should be read from.
15067   // TODO: Implement the AMD64 ABI in its entirety. This simple
15068   // selection mechanism works only for the basic types.
15069   if (ArgVT == MVT::f80) {
15070     llvm_unreachable("va_arg for f80 not yet implemented");
15071   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
15072     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
15073   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
15074     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
15075   } else {
15076     llvm_unreachable("Unhandled argument type in LowerVAARG");
15077   }
15078
15079   if (ArgMode == 2) {
15080     // Sanity Check: Make sure using fp_offset makes sense.
15081     assert(!Subtarget->useSoftFloat() &&
15082            !(DAG.getMachineFunction().getFunction()->hasFnAttribute(
15083                Attribute::NoImplicitFloat)) &&
15084            Subtarget->hasSSE1());
15085   }
15086
15087   // Insert VAARG_64 node into the DAG
15088   // VAARG_64 returns two values: Variable Argument Address, Chain
15089   SDValue InstOps[] = {Chain, SrcPtr, DAG.getConstant(ArgSize, dl, MVT::i32),
15090                        DAG.getConstant(ArgMode, dl, MVT::i8),
15091                        DAG.getConstant(Align, dl, MVT::i32)};
15092   SDVTList VTs = DAG.getVTList(getPointerTy(DAG.getDataLayout()), MVT::Other);
15093   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
15094                                           VTs, InstOps, MVT::i64,
15095                                           MachinePointerInfo(SV),
15096                                           /*Align=*/0,
15097                                           /*Volatile=*/false,
15098                                           /*ReadMem=*/true,
15099                                           /*WriteMem=*/true);
15100   Chain = VAARG.getValue(1);
15101
15102   // Load the next argument and return it
15103   return DAG.getLoad(ArgVT, dl,
15104                      Chain,
15105                      VAARG,
15106                      MachinePointerInfo(),
15107                      false, false, false, 0);
15108 }
15109
15110 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
15111                            SelectionDAG &DAG) {
15112   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
15113   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
15114   SDValue Chain = Op.getOperand(0);
15115   SDValue DstPtr = Op.getOperand(1);
15116   SDValue SrcPtr = Op.getOperand(2);
15117   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
15118   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
15119   SDLoc DL(Op);
15120
15121   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
15122                        DAG.getIntPtrConstant(24, DL), 8, /*isVolatile*/false,
15123                        false, false,
15124                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
15125 }
15126
15127 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
15128 // amount is a constant. Takes immediate version of shift as input.
15129 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
15130                                           SDValue SrcOp, uint64_t ShiftAmt,
15131                                           SelectionDAG &DAG) {
15132   MVT ElementType = VT.getVectorElementType();
15133
15134   // Fold this packed shift into its first operand if ShiftAmt is 0.
15135   if (ShiftAmt == 0)
15136     return SrcOp;
15137
15138   // Check for ShiftAmt >= element width
15139   if (ShiftAmt >= ElementType.getSizeInBits()) {
15140     if (Opc == X86ISD::VSRAI)
15141       ShiftAmt = ElementType.getSizeInBits() - 1;
15142     else
15143       return DAG.getConstant(0, dl, VT);
15144   }
15145
15146   assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
15147          && "Unknown target vector shift-by-constant node");
15148
15149   // Fold this packed vector shift into a build vector if SrcOp is a
15150   // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
15151   if (VT == SrcOp.getSimpleValueType() &&
15152       ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
15153     SmallVector<SDValue, 8> Elts;
15154     unsigned NumElts = SrcOp->getNumOperands();
15155     ConstantSDNode *ND;
15156
15157     switch(Opc) {
15158     default: llvm_unreachable(nullptr);
15159     case X86ISD::VSHLI:
15160       for (unsigned i=0; i!=NumElts; ++i) {
15161         SDValue CurrentOp = SrcOp->getOperand(i);
15162         if (CurrentOp->getOpcode() == ISD::UNDEF) {
15163           Elts.push_back(CurrentOp);
15164           continue;
15165         }
15166         ND = cast<ConstantSDNode>(CurrentOp);
15167         const APInt &C = ND->getAPIntValue();
15168         Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), dl, ElementType));
15169       }
15170       break;
15171     case X86ISD::VSRLI:
15172       for (unsigned i=0; i!=NumElts; ++i) {
15173         SDValue CurrentOp = SrcOp->getOperand(i);
15174         if (CurrentOp->getOpcode() == ISD::UNDEF) {
15175           Elts.push_back(CurrentOp);
15176           continue;
15177         }
15178         ND = cast<ConstantSDNode>(CurrentOp);
15179         const APInt &C = ND->getAPIntValue();
15180         Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), dl, ElementType));
15181       }
15182       break;
15183     case X86ISD::VSRAI:
15184       for (unsigned i=0; i!=NumElts; ++i) {
15185         SDValue CurrentOp = SrcOp->getOperand(i);
15186         if (CurrentOp->getOpcode() == ISD::UNDEF) {
15187           Elts.push_back(CurrentOp);
15188           continue;
15189         }
15190         ND = cast<ConstantSDNode>(CurrentOp);
15191         const APInt &C = ND->getAPIntValue();
15192         Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), dl, ElementType));
15193       }
15194       break;
15195     }
15196
15197     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
15198   }
15199
15200   return DAG.getNode(Opc, dl, VT, SrcOp,
15201                      DAG.getConstant(ShiftAmt, dl, MVT::i8));
15202 }
15203
15204 // getTargetVShiftNode - Handle vector element shifts where the shift amount
15205 // may or may not be a constant. Takes immediate version of shift as input.
15206 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
15207                                    SDValue SrcOp, SDValue ShAmt,
15208                                    SelectionDAG &DAG) {
15209   MVT SVT = ShAmt.getSimpleValueType();
15210   assert((SVT == MVT::i32 || SVT == MVT::i64) && "Unexpected value type!");
15211
15212   // Catch shift-by-constant.
15213   if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
15214     return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
15215                                       CShAmt->getZExtValue(), DAG);
15216
15217   // Change opcode to non-immediate version
15218   switch (Opc) {
15219     default: llvm_unreachable("Unknown target vector shift node");
15220     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
15221     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
15222     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
15223   }
15224
15225   const X86Subtarget &Subtarget =
15226       static_cast<const X86Subtarget &>(DAG.getSubtarget());
15227   if (Subtarget.hasSSE41() && ShAmt.getOpcode() == ISD::ZERO_EXTEND &&
15228       ShAmt.getOperand(0).getSimpleValueType() == MVT::i16) {
15229     // Let the shuffle legalizer expand this shift amount node.
15230     SDValue Op0 = ShAmt.getOperand(0);
15231     Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(Op0), MVT::v8i16, Op0);
15232     ShAmt = getShuffleVectorZeroOrUndef(Op0, 0, true, &Subtarget, DAG);
15233   } else {
15234     // Need to build a vector containing shift amount.
15235     // SSE/AVX packed shifts only use the lower 64-bit of the shift count.
15236     SmallVector<SDValue, 4> ShOps;
15237     ShOps.push_back(ShAmt);
15238     if (SVT == MVT::i32) {
15239       ShOps.push_back(DAG.getConstant(0, dl, SVT));
15240       ShOps.push_back(DAG.getUNDEF(SVT));
15241     }
15242     ShOps.push_back(DAG.getUNDEF(SVT));
15243
15244     MVT BVT = SVT == MVT::i32 ? MVT::v4i32 : MVT::v2i64;
15245     ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, BVT, ShOps);
15246   }
15247
15248   // The return type has to be a 128-bit type with the same element
15249   // type as the input type.
15250   MVT EltVT = VT.getVectorElementType();
15251   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
15252
15253   ShAmt = DAG.getBitcast(ShVT, ShAmt);
15254   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
15255 }
15256
15257 /// \brief Return (and \p Op, \p Mask) for compare instructions or
15258 /// (vselect \p Mask, \p Op, \p PreservedSrc) for others along with the
15259 /// necessary casting or extending for \p Mask when lowering masking intrinsics
15260 static SDValue getVectorMaskingNode(SDValue Op, SDValue Mask,
15261                                     SDValue PreservedSrc,
15262                                     const X86Subtarget *Subtarget,
15263                                     SelectionDAG &DAG) {
15264     EVT VT = Op.getValueType();
15265     EVT MaskVT = EVT::getVectorVT(*DAG.getContext(),
15266                                   MVT::i1, VT.getVectorNumElements());
15267     SDValue VMask = SDValue();
15268     unsigned OpcodeSelect = ISD::VSELECT;
15269     SDLoc dl(Op);
15270
15271     assert(MaskVT.isSimple() && "invalid mask type");
15272
15273     if (isAllOnes(Mask))
15274       return Op;
15275
15276     if (MaskVT.bitsGT(Mask.getValueType())) {
15277       EVT newMaskVT =  EVT::getIntegerVT(*DAG.getContext(),
15278                                          MaskVT.getSizeInBits());
15279       VMask = DAG.getBitcast(MaskVT,
15280                              DAG.getNode(ISD::ANY_EXTEND, dl, newMaskVT, Mask));
15281     } else {
15282       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15283                                        Mask.getValueType().getSizeInBits());
15284       // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
15285       // are extracted by EXTRACT_SUBVECTOR.
15286       VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15287                           DAG.getBitcast(BitcastVT, Mask),
15288                           DAG.getIntPtrConstant(0, dl));
15289     }
15290
15291     switch (Op.getOpcode()) {
15292       default: break;
15293       case X86ISD::PCMPEQM:
15294       case X86ISD::PCMPGTM:
15295       case X86ISD::CMPM:
15296       case X86ISD::CMPMU:
15297         return DAG.getNode(ISD::AND, dl, VT, Op, VMask);
15298       case X86ISD::VTRUNC:
15299       case X86ISD::VTRUNCS:
15300       case X86ISD::VTRUNCUS:
15301         // We can't use ISD::VSELECT here because it is not always "Legal"
15302         // for the destination type. For example vpmovqb require only AVX512
15303         // and vselect that can operate on byte element type require BWI
15304         OpcodeSelect = X86ISD::SELECT;
15305         break;
15306     }
15307     if (PreservedSrc.getOpcode() == ISD::UNDEF)
15308       PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
15309     return DAG.getNode(OpcodeSelect, dl, VT, VMask, Op, PreservedSrc);
15310 }
15311
15312 /// \brief Creates an SDNode for a predicated scalar operation.
15313 /// \returns (X86vselect \p Mask, \p Op, \p PreservedSrc).
15314 /// The mask is comming as MVT::i8 and it should be truncated
15315 /// to MVT::i1 while lowering masking intrinsics.
15316 /// The main difference between ScalarMaskingNode and VectorMaskingNode is using
15317 /// "X86select" instead of "vselect". We just can't create the "vselect" node for
15318 /// a scalar instruction.
15319 static SDValue getScalarMaskingNode(SDValue Op, SDValue Mask,
15320                                     SDValue PreservedSrc,
15321                                     const X86Subtarget *Subtarget,
15322                                     SelectionDAG &DAG) {
15323     if (isAllOnes(Mask))
15324       return Op;
15325
15326     EVT VT = Op.getValueType();
15327     SDLoc dl(Op);
15328     // The mask should be of type MVT::i1
15329     SDValue IMask = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Mask);
15330
15331     if (PreservedSrc.getOpcode() == ISD::UNDEF)
15332       PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
15333     return DAG.getNode(X86ISD::SELECT, dl, VT, IMask, Op, PreservedSrc);
15334 }
15335
15336 static int getSEHRegistrationNodeSize(const Function *Fn) {
15337   if (!Fn->hasPersonalityFn())
15338     report_fatal_error(
15339         "querying registration node size for function without personality");
15340   // The RegNodeSize is 6 32-bit words for SEH and 4 for C++ EH. See
15341   // WinEHStatePass for the full struct definition.
15342   switch (classifyEHPersonality(Fn->getPersonalityFn())) {
15343   case EHPersonality::MSVC_X86SEH: return 24;
15344   case EHPersonality::MSVC_CXX: return 16;
15345   default: break;
15346   }
15347   report_fatal_error("can only recover FP for MSVC EH personality functions");
15348 }
15349
15350 /// When the 32-bit MSVC runtime transfers control to us, either to an outlined
15351 /// function or when returning to a parent frame after catching an exception, we
15352 /// recover the parent frame pointer by doing arithmetic on the incoming EBP.
15353 /// Here's the math:
15354 ///   RegNodeBase = EntryEBP - RegNodeSize
15355 ///   ParentFP = RegNodeBase - RegNodeFrameOffset
15356 /// Subtracting RegNodeSize takes us to the offset of the registration node, and
15357 /// subtracting the offset (negative on x86) takes us back to the parent FP.
15358 static SDValue recoverFramePointer(SelectionDAG &DAG, const Function *Fn,
15359                                    SDValue EntryEBP) {
15360   MachineFunction &MF = DAG.getMachineFunction();
15361   SDLoc dl;
15362
15363   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15364   MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
15365
15366   // It's possible that the parent function no longer has a personality function
15367   // if the exceptional code was optimized away, in which case we just return
15368   // the incoming EBP.
15369   if (!Fn->hasPersonalityFn())
15370     return EntryEBP;
15371
15372   int RegNodeSize = getSEHRegistrationNodeSize(Fn);
15373
15374   // Get an MCSymbol that will ultimately resolve to the frame offset of the EH
15375   // registration.
15376   MCSymbol *OffsetSym =
15377       MF.getMMI().getContext().getOrCreateParentFrameOffsetSymbol(
15378           GlobalValue::getRealLinkageName(Fn->getName()));
15379   SDValue OffsetSymVal = DAG.getMCSymbol(OffsetSym, PtrVT);
15380   SDValue RegNodeFrameOffset =
15381       DAG.getNode(ISD::LOCAL_RECOVER, dl, PtrVT, OffsetSymVal);
15382
15383   // RegNodeBase = EntryEBP - RegNodeSize
15384   // ParentFP = RegNodeBase - RegNodeFrameOffset
15385   SDValue RegNodeBase = DAG.getNode(ISD::SUB, dl, PtrVT, EntryEBP,
15386                                     DAG.getConstant(RegNodeSize, dl, PtrVT));
15387   return DAG.getNode(ISD::SUB, dl, PtrVT, RegNodeBase, RegNodeFrameOffset);
15388 }
15389
15390 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
15391                                        SelectionDAG &DAG) {
15392   SDLoc dl(Op);
15393   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15394   EVT VT = Op.getValueType();
15395   const IntrinsicData* IntrData = getIntrinsicWithoutChain(IntNo);
15396   if (IntrData) {
15397     switch(IntrData->Type) {
15398     case INTR_TYPE_1OP:
15399       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1));
15400     case INTR_TYPE_2OP:
15401       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
15402         Op.getOperand(2));
15403     case INTR_TYPE_3OP:
15404       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
15405         Op.getOperand(2), Op.getOperand(3));
15406     case INTR_TYPE_4OP:
15407       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
15408         Op.getOperand(2), Op.getOperand(3), Op.getOperand(4));
15409     case INTR_TYPE_1OP_MASK_RM: {
15410       SDValue Src = Op.getOperand(1);
15411       SDValue PassThru = Op.getOperand(2);
15412       SDValue Mask = Op.getOperand(3);
15413       SDValue RoundingMode;
15414       // We allways add rounding mode to the Node.
15415       // If the rounding mode is not specified, we add the 
15416       // "current direction" mode.
15417       if (Op.getNumOperands() == 4)
15418         RoundingMode =
15419           DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
15420       else
15421         RoundingMode = Op.getOperand(4);
15422       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15423       if (IntrWithRoundingModeOpcode != 0)
15424         if (cast<ConstantSDNode>(RoundingMode)->getZExtValue() !=
15425             X86::STATIC_ROUNDING::CUR_DIRECTION)
15426           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15427                                       dl, Op.getValueType(), Src, RoundingMode),
15428                                       Mask, PassThru, Subtarget, DAG);
15429       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src,
15430                                               RoundingMode),
15431                                   Mask, PassThru, Subtarget, DAG);
15432     }
15433     case INTR_TYPE_1OP_MASK: {
15434       SDValue Src = Op.getOperand(1);
15435       SDValue PassThru = Op.getOperand(2);
15436       SDValue Mask = Op.getOperand(3);
15437       // We add rounding mode to the Node when
15438       //   - RM Opcode is specified and
15439       //   - RM is not "current direction".
15440       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15441       if (IntrWithRoundingModeOpcode != 0) {
15442         SDValue Rnd = Op.getOperand(4);
15443         unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
15444         if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
15445           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15446                                       dl, Op.getValueType(),
15447                                       Src, Rnd),
15448                                       Mask, PassThru, Subtarget, DAG);
15449         }
15450       }
15451       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src),
15452                                   Mask, PassThru, Subtarget, DAG);
15453     }
15454     case INTR_TYPE_SCALAR_MASK_RM: {
15455       SDValue Src1 = Op.getOperand(1);
15456       SDValue Src2 = Op.getOperand(2);
15457       SDValue Src0 = Op.getOperand(3);
15458       SDValue Mask = Op.getOperand(4);
15459       // There are 2 kinds of intrinsics in this group:
15460       // (1) With supress-all-exceptions (sae) or rounding mode- 6 operands
15461       // (2) With rounding mode and sae - 7 operands.
15462       if (Op.getNumOperands() == 6) {
15463         SDValue Sae  = Op.getOperand(5);
15464         unsigned Opc = IntrData->Opc1 ? IntrData->Opc1 : IntrData->Opc0;
15465         return getScalarMaskingNode(DAG.getNode(Opc, dl, VT, Src1, Src2,
15466                                                 Sae),
15467                                     Mask, Src0, Subtarget, DAG);
15468       }
15469       assert(Op.getNumOperands() == 7 && "Unexpected intrinsic form");
15470       SDValue RoundingMode  = Op.getOperand(5);
15471       SDValue Sae  = Op.getOperand(6);
15472       return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2,
15473                                               RoundingMode, Sae),
15474                                   Mask, Src0, Subtarget, DAG);
15475     }
15476     case INTR_TYPE_2OP_MASK: {
15477       SDValue Src1 = Op.getOperand(1);
15478       SDValue Src2 = Op.getOperand(2);
15479       SDValue PassThru = Op.getOperand(3);
15480       SDValue Mask = Op.getOperand(4);
15481       // We specify 2 possible opcodes for intrinsics with rounding modes.
15482       // First, we check if the intrinsic may have non-default rounding mode,
15483       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15484       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15485       if (IntrWithRoundingModeOpcode != 0) {
15486         SDValue Rnd = Op.getOperand(5);
15487         unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
15488         if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
15489           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15490                                       dl, Op.getValueType(),
15491                                       Src1, Src2, Rnd),
15492                                       Mask, PassThru, Subtarget, DAG);
15493         }
15494       }
15495       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15496                                               Src1,Src2),
15497                                   Mask, PassThru, Subtarget, DAG);
15498     }
15499     case INTR_TYPE_2OP_MASK_RM: {
15500       SDValue Src1 = Op.getOperand(1);
15501       SDValue Src2 = Op.getOperand(2);
15502       SDValue PassThru = Op.getOperand(3);
15503       SDValue Mask = Op.getOperand(4);
15504       // We specify 2 possible modes for intrinsics, with/without rounding modes.
15505       // First, we check if the intrinsic have rounding mode (6 operands),
15506       // if not, we set rounding mode to "current".
15507       SDValue Rnd;
15508       if (Op.getNumOperands() == 6)
15509         Rnd = Op.getOperand(5);
15510       else
15511         Rnd = DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
15512       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15513                                               Src1, Src2, Rnd),
15514                                   Mask, PassThru, Subtarget, DAG);
15515     }
15516     case INTR_TYPE_3OP_MASK_RM: {
15517       SDValue Src1 = Op.getOperand(1);
15518       SDValue Src2 = Op.getOperand(2);
15519       SDValue Imm = Op.getOperand(3);
15520       SDValue PassThru = Op.getOperand(4);
15521       SDValue Mask = Op.getOperand(5);
15522       // We specify 2 possible modes for intrinsics, with/without rounding modes.
15523       // First, we check if the intrinsic have rounding mode (7 operands),
15524       // if not, we set rounding mode to "current".
15525       SDValue Rnd;
15526       if (Op.getNumOperands() == 7)
15527         Rnd = Op.getOperand(6);
15528       else
15529         Rnd = DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
15530       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15531         Src1, Src2, Imm, Rnd),
15532         Mask, PassThru, Subtarget, DAG);
15533     }
15534     case INTR_TYPE_3OP_MASK: {
15535       SDValue Src1 = Op.getOperand(1);
15536       SDValue Src2 = Op.getOperand(2);
15537       SDValue Src3 = Op.getOperand(3);
15538       SDValue PassThru = Op.getOperand(4);
15539       SDValue Mask = Op.getOperand(5);
15540       // We specify 2 possible opcodes for intrinsics with rounding modes.
15541       // First, we check if the intrinsic may have non-default rounding mode,
15542       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15543       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15544       if (IntrWithRoundingModeOpcode != 0) {
15545         SDValue Rnd = Op.getOperand(6);
15546         unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
15547         if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
15548           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15549                                       dl, Op.getValueType(),
15550                                       Src1, Src2, Src3, Rnd),
15551                                       Mask, PassThru, Subtarget, DAG);
15552         }
15553       }
15554       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15555                                               Src1, Src2, Src3),
15556                                   Mask, PassThru, Subtarget, DAG);
15557     }
15558     case VPERM_3OP_MASKZ:
15559     case VPERM_3OP_MASK:
15560     case FMA_OP_MASK3:
15561     case FMA_OP_MASKZ:
15562     case FMA_OP_MASK: {
15563       SDValue Src1 = Op.getOperand(1);
15564       SDValue Src2 = Op.getOperand(2);
15565       SDValue Src3 = Op.getOperand(3);
15566       SDValue Mask = Op.getOperand(4);
15567       EVT VT = Op.getValueType();
15568       SDValue PassThru = SDValue();
15569
15570       // set PassThru element
15571       if (IntrData->Type == VPERM_3OP_MASKZ || IntrData->Type == FMA_OP_MASKZ)
15572         PassThru = getZeroVector(VT, Subtarget, DAG, dl);
15573       else if (IntrData->Type == FMA_OP_MASK3)
15574         PassThru = Src3;
15575       else
15576         PassThru = Src1;
15577
15578       // We specify 2 possible opcodes for intrinsics with rounding modes.
15579       // First, we check if the intrinsic may have non-default rounding mode,
15580       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15581       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15582       if (IntrWithRoundingModeOpcode != 0) {
15583         SDValue Rnd = Op.getOperand(5);
15584         if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
15585             X86::STATIC_ROUNDING::CUR_DIRECTION)
15586           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15587                                                   dl, Op.getValueType(),
15588                                                   Src1, Src2, Src3, Rnd),
15589                                       Mask, PassThru, Subtarget, DAG);
15590       }
15591       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0,
15592                                               dl, Op.getValueType(),
15593                                               Src1, Src2, Src3),
15594                                   Mask, PassThru, Subtarget, DAG);
15595     }
15596     case CMP_MASK:
15597     case CMP_MASK_CC: {
15598       // Comparison intrinsics with masks.
15599       // Example of transformation:
15600       // (i8 (int_x86_avx512_mask_pcmpeq_q_128
15601       //             (v2i64 %a), (v2i64 %b), (i8 %mask))) ->
15602       // (i8 (bitcast
15603       //   (v8i1 (insert_subvector undef,
15604       //           (v2i1 (and (PCMPEQM %a, %b),
15605       //                      (extract_subvector
15606       //                         (v8i1 (bitcast %mask)), 0))), 0))))
15607       EVT VT = Op.getOperand(1).getValueType();
15608       EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15609                                     VT.getVectorNumElements());
15610       SDValue Mask = Op.getOperand((IntrData->Type == CMP_MASK_CC) ? 4 : 3);
15611       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15612                                        Mask.getValueType().getSizeInBits());
15613       SDValue Cmp;
15614       if (IntrData->Type == CMP_MASK_CC) {
15615         SDValue CC = Op.getOperand(3);
15616         CC = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, CC);
15617         // We specify 2 possible opcodes for intrinsics with rounding modes.
15618         // First, we check if the intrinsic may have non-default rounding mode,
15619         // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15620         if (IntrData->Opc1 != 0) {
15621           SDValue Rnd = Op.getOperand(5);
15622           if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
15623               X86::STATIC_ROUNDING::CUR_DIRECTION)
15624             Cmp = DAG.getNode(IntrData->Opc1, dl, MaskVT, Op.getOperand(1),
15625                               Op.getOperand(2), CC, Rnd);
15626         }
15627         //default rounding mode
15628         if(!Cmp.getNode())
15629             Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
15630                               Op.getOperand(2), CC);
15631
15632       } else {
15633         assert(IntrData->Type == CMP_MASK && "Unexpected intrinsic type!");
15634         Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
15635                           Op.getOperand(2));
15636       }
15637       SDValue CmpMask = getVectorMaskingNode(Cmp, Mask,
15638                                              DAG.getTargetConstant(0, dl,
15639                                                                    MaskVT),
15640                                              Subtarget, DAG);
15641       SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, BitcastVT,
15642                                 DAG.getUNDEF(BitcastVT), CmpMask,
15643                                 DAG.getIntPtrConstant(0, dl));
15644       return DAG.getBitcast(Op.getValueType(), Res);
15645     }
15646     case COMI: { // Comparison intrinsics
15647       ISD::CondCode CC = (ISD::CondCode)IntrData->Opc1;
15648       SDValue LHS = Op.getOperand(1);
15649       SDValue RHS = Op.getOperand(2);
15650       unsigned X86CC = TranslateX86CC(CC, dl, true, LHS, RHS, DAG);
15651       assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
15652       SDValue Cond = DAG.getNode(IntrData->Opc0, dl, MVT::i32, LHS, RHS);
15653       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15654                                   DAG.getConstant(X86CC, dl, MVT::i8), Cond);
15655       return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15656     }
15657     case VSHIFT:
15658       return getTargetVShiftNode(IntrData->Opc0, dl, Op.getSimpleValueType(),
15659                                  Op.getOperand(1), Op.getOperand(2), DAG);
15660     case VSHIFT_MASK:
15661       return getVectorMaskingNode(getTargetVShiftNode(IntrData->Opc0, dl,
15662                                                       Op.getSimpleValueType(),
15663                                                       Op.getOperand(1),
15664                                                       Op.getOperand(2), DAG),
15665                                   Op.getOperand(4), Op.getOperand(3), Subtarget,
15666                                   DAG);
15667     case COMPRESS_EXPAND_IN_REG: {
15668       SDValue Mask = Op.getOperand(3);
15669       SDValue DataToCompress = Op.getOperand(1);
15670       SDValue PassThru = Op.getOperand(2);
15671       if (isAllOnes(Mask)) // return data as is
15672         return Op.getOperand(1);
15673
15674       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15675                                               DataToCompress),
15676                                   Mask, PassThru, Subtarget, DAG);
15677     }
15678     case BLEND: {
15679       SDValue Mask = Op.getOperand(3);
15680       EVT VT = Op.getValueType();
15681       EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15682                                     VT.getVectorNumElements());
15683       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15684                                        Mask.getValueType().getSizeInBits());
15685       SDLoc dl(Op);
15686       SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15687                                   DAG.getBitcast(BitcastVT, Mask),
15688                                   DAG.getIntPtrConstant(0, dl));
15689       return DAG.getNode(IntrData->Opc0, dl, VT, VMask, Op.getOperand(1),
15690                          Op.getOperand(2));
15691     }
15692     default:
15693       break;
15694     }
15695   }
15696
15697   switch (IntNo) {
15698   default: return SDValue();    // Don't custom lower most intrinsics.
15699
15700   case Intrinsic::x86_avx2_permd:
15701   case Intrinsic::x86_avx2_permps:
15702     // Operands intentionally swapped. Mask is last operand to intrinsic,
15703     // but second operand for node/instruction.
15704     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
15705                        Op.getOperand(2), Op.getOperand(1));
15706
15707   // ptest and testp intrinsics. The intrinsic these come from are designed to
15708   // return an integer value, not just an instruction so lower it to the ptest
15709   // or testp pattern and a setcc for the result.
15710   case Intrinsic::x86_sse41_ptestz:
15711   case Intrinsic::x86_sse41_ptestc:
15712   case Intrinsic::x86_sse41_ptestnzc:
15713   case Intrinsic::x86_avx_ptestz_256:
15714   case Intrinsic::x86_avx_ptestc_256:
15715   case Intrinsic::x86_avx_ptestnzc_256:
15716   case Intrinsic::x86_avx_vtestz_ps:
15717   case Intrinsic::x86_avx_vtestc_ps:
15718   case Intrinsic::x86_avx_vtestnzc_ps:
15719   case Intrinsic::x86_avx_vtestz_pd:
15720   case Intrinsic::x86_avx_vtestc_pd:
15721   case Intrinsic::x86_avx_vtestnzc_pd:
15722   case Intrinsic::x86_avx_vtestz_ps_256:
15723   case Intrinsic::x86_avx_vtestc_ps_256:
15724   case Intrinsic::x86_avx_vtestnzc_ps_256:
15725   case Intrinsic::x86_avx_vtestz_pd_256:
15726   case Intrinsic::x86_avx_vtestc_pd_256:
15727   case Intrinsic::x86_avx_vtestnzc_pd_256: {
15728     bool IsTestPacked = false;
15729     unsigned X86CC;
15730     switch (IntNo) {
15731     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
15732     case Intrinsic::x86_avx_vtestz_ps:
15733     case Intrinsic::x86_avx_vtestz_pd:
15734     case Intrinsic::x86_avx_vtestz_ps_256:
15735     case Intrinsic::x86_avx_vtestz_pd_256:
15736       IsTestPacked = true; // Fallthrough
15737     case Intrinsic::x86_sse41_ptestz:
15738     case Intrinsic::x86_avx_ptestz_256:
15739       // ZF = 1
15740       X86CC = X86::COND_E;
15741       break;
15742     case Intrinsic::x86_avx_vtestc_ps:
15743     case Intrinsic::x86_avx_vtestc_pd:
15744     case Intrinsic::x86_avx_vtestc_ps_256:
15745     case Intrinsic::x86_avx_vtestc_pd_256:
15746       IsTestPacked = true; // Fallthrough
15747     case Intrinsic::x86_sse41_ptestc:
15748     case Intrinsic::x86_avx_ptestc_256:
15749       // CF = 1
15750       X86CC = X86::COND_B;
15751       break;
15752     case Intrinsic::x86_avx_vtestnzc_ps:
15753     case Intrinsic::x86_avx_vtestnzc_pd:
15754     case Intrinsic::x86_avx_vtestnzc_ps_256:
15755     case Intrinsic::x86_avx_vtestnzc_pd_256:
15756       IsTestPacked = true; // Fallthrough
15757     case Intrinsic::x86_sse41_ptestnzc:
15758     case Intrinsic::x86_avx_ptestnzc_256:
15759       // ZF and CF = 0
15760       X86CC = X86::COND_A;
15761       break;
15762     }
15763
15764     SDValue LHS = Op.getOperand(1);
15765     SDValue RHS = Op.getOperand(2);
15766     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
15767     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
15768     SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
15769     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
15770     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15771   }
15772   case Intrinsic::x86_avx512_kortestz_w:
15773   case Intrinsic::x86_avx512_kortestc_w: {
15774     unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
15775     SDValue LHS = DAG.getBitcast(MVT::v16i1, Op.getOperand(1));
15776     SDValue RHS = DAG.getBitcast(MVT::v16i1, Op.getOperand(2));
15777     SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
15778     SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
15779     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
15780     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15781   }
15782
15783   case Intrinsic::x86_sse42_pcmpistria128:
15784   case Intrinsic::x86_sse42_pcmpestria128:
15785   case Intrinsic::x86_sse42_pcmpistric128:
15786   case Intrinsic::x86_sse42_pcmpestric128:
15787   case Intrinsic::x86_sse42_pcmpistrio128:
15788   case Intrinsic::x86_sse42_pcmpestrio128:
15789   case Intrinsic::x86_sse42_pcmpistris128:
15790   case Intrinsic::x86_sse42_pcmpestris128:
15791   case Intrinsic::x86_sse42_pcmpistriz128:
15792   case Intrinsic::x86_sse42_pcmpestriz128: {
15793     unsigned Opcode;
15794     unsigned X86CC;
15795     switch (IntNo) {
15796     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
15797     case Intrinsic::x86_sse42_pcmpistria128:
15798       Opcode = X86ISD::PCMPISTRI;
15799       X86CC = X86::COND_A;
15800       break;
15801     case Intrinsic::x86_sse42_pcmpestria128:
15802       Opcode = X86ISD::PCMPESTRI;
15803       X86CC = X86::COND_A;
15804       break;
15805     case Intrinsic::x86_sse42_pcmpistric128:
15806       Opcode = X86ISD::PCMPISTRI;
15807       X86CC = X86::COND_B;
15808       break;
15809     case Intrinsic::x86_sse42_pcmpestric128:
15810       Opcode = X86ISD::PCMPESTRI;
15811       X86CC = X86::COND_B;
15812       break;
15813     case Intrinsic::x86_sse42_pcmpistrio128:
15814       Opcode = X86ISD::PCMPISTRI;
15815       X86CC = X86::COND_O;
15816       break;
15817     case Intrinsic::x86_sse42_pcmpestrio128:
15818       Opcode = X86ISD::PCMPESTRI;
15819       X86CC = X86::COND_O;
15820       break;
15821     case Intrinsic::x86_sse42_pcmpistris128:
15822       Opcode = X86ISD::PCMPISTRI;
15823       X86CC = X86::COND_S;
15824       break;
15825     case Intrinsic::x86_sse42_pcmpestris128:
15826       Opcode = X86ISD::PCMPESTRI;
15827       X86CC = X86::COND_S;
15828       break;
15829     case Intrinsic::x86_sse42_pcmpistriz128:
15830       Opcode = X86ISD::PCMPISTRI;
15831       X86CC = X86::COND_E;
15832       break;
15833     case Intrinsic::x86_sse42_pcmpestriz128:
15834       Opcode = X86ISD::PCMPESTRI;
15835       X86CC = X86::COND_E;
15836       break;
15837     }
15838     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
15839     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
15840     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
15841     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15842                                 DAG.getConstant(X86CC, dl, MVT::i8),
15843                                 SDValue(PCMP.getNode(), 1));
15844     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15845   }
15846
15847   case Intrinsic::x86_sse42_pcmpistri128:
15848   case Intrinsic::x86_sse42_pcmpestri128: {
15849     unsigned Opcode;
15850     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
15851       Opcode = X86ISD::PCMPISTRI;
15852     else
15853       Opcode = X86ISD::PCMPESTRI;
15854
15855     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
15856     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
15857     return DAG.getNode(Opcode, dl, VTs, NewOps);
15858   }
15859
15860   case Intrinsic::x86_seh_lsda: {
15861     // Compute the symbol for the LSDA. We know it'll get emitted later.
15862     MachineFunction &MF = DAG.getMachineFunction();
15863     SDValue Op1 = Op.getOperand(1);
15864     auto *Fn = cast<Function>(cast<GlobalAddressSDNode>(Op1)->getGlobal());
15865     MCSymbol *LSDASym = MF.getMMI().getContext().getOrCreateLSDASymbol(
15866         GlobalValue::getRealLinkageName(Fn->getName()));
15867
15868     // Generate a simple absolute symbol reference. This intrinsic is only
15869     // supported on 32-bit Windows, which isn't PIC.
15870     SDValue Result = DAG.getMCSymbol(LSDASym, VT);
15871     return DAG.getNode(X86ISD::Wrapper, dl, VT, Result);
15872   }
15873
15874   case Intrinsic::x86_seh_recoverfp: {
15875     SDValue FnOp = Op.getOperand(1);
15876     SDValue IncomingFPOp = Op.getOperand(2);
15877     GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(FnOp);
15878     auto *Fn = dyn_cast_or_null<Function>(GSD ? GSD->getGlobal() : nullptr);
15879     if (!Fn)
15880       report_fatal_error(
15881           "llvm.x86.seh.recoverfp must take a function as the first argument");
15882     return recoverFramePointer(DAG, Fn, IncomingFPOp);
15883   }
15884
15885   case Intrinsic::localaddress: {
15886     // Returns one of the stack, base, or frame pointer registers, depending on
15887     // which is used to reference local variables.
15888     MachineFunction &MF = DAG.getMachineFunction();
15889     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15890     unsigned Reg;
15891     if (RegInfo->hasBasePointer(MF))
15892       Reg = RegInfo->getBaseRegister();
15893     else // This function handles the SP or FP case.
15894       Reg = RegInfo->getPtrSizedFrameRegister(MF);
15895     return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
15896   }
15897   }
15898 }
15899
15900 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15901                               SDValue Src, SDValue Mask, SDValue Base,
15902                               SDValue Index, SDValue ScaleOp, SDValue Chain,
15903                               const X86Subtarget * Subtarget) {
15904   SDLoc dl(Op);
15905   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15906   if (!C)
15907     llvm_unreachable("Invalid scale type");
15908   unsigned ScaleVal = C->getZExtValue();
15909   if (ScaleVal > 2 && ScaleVal != 4 && ScaleVal != 8)
15910     llvm_unreachable("Valid scale values are 1, 2, 4, 8");
15911
15912   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
15913   EVT MaskVT = MVT::getVectorVT(MVT::i1,
15914                              Index.getSimpleValueType().getVectorNumElements());
15915   SDValue MaskInReg;
15916   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15917   if (MaskC)
15918     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
15919   else {
15920     EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15921                                      Mask.getValueType().getSizeInBits());
15922
15923     // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
15924     // are extracted by EXTRACT_SUBVECTOR.
15925     MaskInReg = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15926                             DAG.getBitcast(BitcastVT, Mask),
15927                             DAG.getIntPtrConstant(0, dl));
15928   }
15929   SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
15930   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
15931   SDValue Segment = DAG.getRegister(0, MVT::i32);
15932   if (Src.getOpcode() == ISD::UNDEF)
15933     Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
15934   SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
15935   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
15936   SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
15937   return DAG.getMergeValues(RetOps, dl);
15938 }
15939
15940 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15941                                SDValue Src, SDValue Mask, SDValue Base,
15942                                SDValue Index, SDValue ScaleOp, SDValue Chain) {
15943   SDLoc dl(Op);
15944   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15945   if (!C)
15946     llvm_unreachable("Invalid scale type");
15947   unsigned ScaleVal = C->getZExtValue();
15948   if (ScaleVal > 2 && ScaleVal != 4 && ScaleVal != 8)
15949     llvm_unreachable("Valid scale values are 1, 2, 4, 8");
15950
15951   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
15952   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
15953   SDValue Segment = DAG.getRegister(0, MVT::i32);
15954   EVT MaskVT = MVT::getVectorVT(MVT::i1,
15955                              Index.getSimpleValueType().getVectorNumElements());
15956   SDValue MaskInReg;
15957   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15958   if (MaskC)
15959     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
15960   else {
15961     EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15962                                      Mask.getValueType().getSizeInBits());
15963
15964     // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
15965     // are extracted by EXTRACT_SUBVECTOR.
15966     MaskInReg = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15967                             DAG.getBitcast(BitcastVT, Mask),
15968                             DAG.getIntPtrConstant(0, dl));
15969   }
15970   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
15971   SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
15972   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
15973   return SDValue(Res, 1);
15974 }
15975
15976 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15977                                SDValue Mask, SDValue Base, SDValue Index,
15978                                SDValue ScaleOp, SDValue Chain) {
15979   SDLoc dl(Op);
15980   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15981   assert(C && "Invalid scale type");
15982   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
15983   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
15984   SDValue Segment = DAG.getRegister(0, MVT::i32);
15985   EVT MaskVT =
15986     MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
15987   SDValue MaskInReg;
15988   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15989   if (MaskC)
15990     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
15991   else
15992     MaskInReg = DAG.getBitcast(MaskVT, Mask);
15993   //SDVTList VTs = DAG.getVTList(MVT::Other);
15994   SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
15995   SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
15996   return SDValue(Res, 0);
15997 }
15998
15999 // getReadPerformanceCounter - Handles the lowering of builtin intrinsics that
16000 // read performance monitor counters (x86_rdpmc).
16001 static void getReadPerformanceCounter(SDNode *N, SDLoc DL,
16002                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
16003                               SmallVectorImpl<SDValue> &Results) {
16004   assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
16005   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
16006   SDValue LO, HI;
16007
16008   // The ECX register is used to select the index of the performance counter
16009   // to read.
16010   SDValue Chain = DAG.getCopyToReg(N->getOperand(0), DL, X86::ECX,
16011                                    N->getOperand(2));
16012   SDValue rd = DAG.getNode(X86ISD::RDPMC_DAG, DL, Tys, Chain);
16013
16014   // Reads the content of a 64-bit performance counter and returns it in the
16015   // registers EDX:EAX.
16016   if (Subtarget->is64Bit()) {
16017     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
16018     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
16019                             LO.getValue(2));
16020   } else {
16021     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
16022     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
16023                             LO.getValue(2));
16024   }
16025   Chain = HI.getValue(1);
16026
16027   if (Subtarget->is64Bit()) {
16028     // The EAX register is loaded with the low-order 32 bits. The EDX register
16029     // is loaded with the supported high-order bits of the counter.
16030     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
16031                               DAG.getConstant(32, DL, MVT::i8));
16032     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
16033     Results.push_back(Chain);
16034     return;
16035   }
16036
16037   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
16038   SDValue Ops[] = { LO, HI };
16039   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
16040   Results.push_back(Pair);
16041   Results.push_back(Chain);
16042 }
16043
16044 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
16045 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
16046 // also used to custom lower READCYCLECOUNTER nodes.
16047 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
16048                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
16049                               SmallVectorImpl<SDValue> &Results) {
16050   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
16051   SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
16052   SDValue LO, HI;
16053
16054   // The processor's time-stamp counter (a 64-bit MSR) is stored into the
16055   // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
16056   // and the EAX register is loaded with the low-order 32 bits.
16057   if (Subtarget->is64Bit()) {
16058     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
16059     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
16060                             LO.getValue(2));
16061   } else {
16062     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
16063     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
16064                             LO.getValue(2));
16065   }
16066   SDValue Chain = HI.getValue(1);
16067
16068   if (Opcode == X86ISD::RDTSCP_DAG) {
16069     assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
16070
16071     // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
16072     // the ECX register. Add 'ecx' explicitly to the chain.
16073     SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
16074                                      HI.getValue(2));
16075     // Explicitly store the content of ECX at the location passed in input
16076     // to the 'rdtscp' intrinsic.
16077     Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
16078                          MachinePointerInfo(), false, false, 0);
16079   }
16080
16081   if (Subtarget->is64Bit()) {
16082     // The EDX register is loaded with the high-order 32 bits of the MSR, and
16083     // the EAX register is loaded with the low-order 32 bits.
16084     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
16085                               DAG.getConstant(32, DL, MVT::i8));
16086     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
16087     Results.push_back(Chain);
16088     return;
16089   }
16090
16091   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
16092   SDValue Ops[] = { LO, HI };
16093   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
16094   Results.push_back(Pair);
16095   Results.push_back(Chain);
16096 }
16097
16098 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
16099                                      SelectionDAG &DAG) {
16100   SmallVector<SDValue, 2> Results;
16101   SDLoc DL(Op);
16102   getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
16103                           Results);
16104   return DAG.getMergeValues(Results, DL);
16105 }
16106
16107 static SDValue LowerSEHRESTOREFRAME(SDValue Op, const X86Subtarget *Subtarget,
16108                                     SelectionDAG &DAG) {
16109   MachineFunction &MF = DAG.getMachineFunction();
16110   const Function *Fn = MF.getFunction();
16111   SDLoc dl(Op);
16112   SDValue Chain = Op.getOperand(0);
16113
16114   assert(Subtarget->getFrameLowering()->hasFP(MF) &&
16115          "using llvm.x86.seh.restoreframe requires a frame pointer");
16116
16117   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16118   MVT VT = TLI.getPointerTy(DAG.getDataLayout());
16119
16120   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16121   unsigned FrameReg =
16122       RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
16123   unsigned SPReg = RegInfo->getStackRegister();
16124   unsigned SlotSize = RegInfo->getSlotSize();
16125
16126   // Get incoming EBP.
16127   SDValue IncomingEBP =
16128       DAG.getCopyFromReg(Chain, dl, FrameReg, VT);
16129
16130   // SP is saved in the first field of every registration node, so load
16131   // [EBP-RegNodeSize] into SP.
16132   int RegNodeSize = getSEHRegistrationNodeSize(Fn);
16133   SDValue SPAddr = DAG.getNode(ISD::ADD, dl, VT, IncomingEBP,
16134                                DAG.getConstant(-RegNodeSize, dl, VT));
16135   SDValue NewSP =
16136       DAG.getLoad(VT, dl, Chain, SPAddr, MachinePointerInfo(), false, false,
16137                   false, VT.getScalarSizeInBits() / 8);
16138   Chain = DAG.getCopyToReg(Chain, dl, SPReg, NewSP);
16139
16140   if (!RegInfo->needsStackRealignment(MF)) {
16141     // Adjust EBP to point back to the original frame position.
16142     SDValue NewFP = recoverFramePointer(DAG, Fn, IncomingEBP);
16143     Chain = DAG.getCopyToReg(Chain, dl, FrameReg, NewFP);
16144   } else {
16145     assert(RegInfo->hasBasePointer(MF) &&
16146            "functions with Win32 EH must use frame or base pointer register");
16147
16148     // Reload the base pointer (ESI) with the adjusted incoming EBP.
16149     SDValue NewBP = recoverFramePointer(DAG, Fn, IncomingEBP);
16150     Chain = DAG.getCopyToReg(Chain, dl, RegInfo->getBaseRegister(), NewBP);
16151
16152     // Reload the spilled EBP value, now that the stack and base pointers are
16153     // set up.
16154     X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
16155     X86FI->setHasSEHFramePtrSave(true);
16156     int FI = MF.getFrameInfo()->CreateSpillStackObject(SlotSize, SlotSize);
16157     X86FI->setSEHFramePtrSaveIndex(FI);
16158     SDValue NewFP = DAG.getLoad(VT, dl, Chain, DAG.getFrameIndex(FI, VT),
16159                                 MachinePointerInfo(), false, false, false,
16160                                 VT.getScalarSizeInBits() / 8);
16161     Chain = DAG.getCopyToReg(NewFP, dl, FrameReg, NewFP);
16162   }
16163
16164   return Chain;
16165 }
16166
16167 /// \brief Lower intrinsics for TRUNCATE_TO_MEM case
16168 /// return truncate Store/MaskedStore Node
16169 static SDValue LowerINTRINSIC_TRUNCATE_TO_MEM(const SDValue & Op,
16170                                                SelectionDAG &DAG,
16171                                                MVT ElementType) {
16172   SDLoc dl(Op);
16173   SDValue Mask = Op.getOperand(4);
16174   SDValue DataToTruncate = Op.getOperand(3);
16175   SDValue Addr = Op.getOperand(2);
16176   SDValue Chain = Op.getOperand(0);
16177
16178   EVT VT  = DataToTruncate.getValueType();
16179   EVT SVT = EVT::getVectorVT(*DAG.getContext(),
16180                              ElementType, VT.getVectorNumElements());
16181
16182   if (isAllOnes(Mask)) // return just a truncate store
16183     return DAG.getTruncStore(Chain, dl, DataToTruncate, Addr,
16184                              MachinePointerInfo(), SVT, false, false,
16185                              SVT.getScalarSizeInBits()/8);
16186
16187   EVT MaskVT = EVT::getVectorVT(*DAG.getContext(),
16188                                 MVT::i1, VT.getVectorNumElements());
16189   EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16190                                    Mask.getValueType().getSizeInBits());
16191   // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
16192   // are extracted by EXTRACT_SUBVECTOR.
16193   SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
16194                               DAG.getBitcast(BitcastVT, Mask),
16195                               DAG.getIntPtrConstant(0, dl));
16196
16197   MachineMemOperand *MMO = DAG.getMachineFunction().
16198     getMachineMemOperand(MachinePointerInfo(),
16199                          MachineMemOperand::MOStore, SVT.getStoreSize(),
16200                          SVT.getScalarSizeInBits()/8);
16201
16202   return DAG.getMaskedStore(Chain, dl, DataToTruncate, Addr,
16203                             VMask, SVT, MMO, true);
16204 }
16205
16206 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
16207                                       SelectionDAG &DAG) {
16208   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
16209
16210   const IntrinsicData* IntrData = getIntrinsicWithChain(IntNo);
16211   if (!IntrData) {
16212     if (IntNo == llvm::Intrinsic::x86_seh_restoreframe)
16213       return LowerSEHRESTOREFRAME(Op, Subtarget, DAG);
16214     return SDValue();
16215   }
16216
16217   SDLoc dl(Op);
16218   switch(IntrData->Type) {
16219   default:
16220     llvm_unreachable("Unknown Intrinsic Type");
16221     break;
16222   case RDSEED:
16223   case RDRAND: {
16224     // Emit the node with the right value type.
16225     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
16226     SDValue Result = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
16227
16228     // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
16229     // Otherwise return the value from Rand, which is always 0, casted to i32.
16230     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
16231                       DAG.getConstant(1, dl, Op->getValueType(1)),
16232                       DAG.getConstant(X86::COND_B, dl, MVT::i32),
16233                       SDValue(Result.getNode(), 1) };
16234     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
16235                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
16236                                   Ops);
16237
16238     // Return { result, isValid, chain }.
16239     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
16240                        SDValue(Result.getNode(), 2));
16241   }
16242   case GATHER: {
16243   //gather(v1, mask, index, base, scale);
16244     SDValue Chain = Op.getOperand(0);
16245     SDValue Src   = Op.getOperand(2);
16246     SDValue Base  = Op.getOperand(3);
16247     SDValue Index = Op.getOperand(4);
16248     SDValue Mask  = Op.getOperand(5);
16249     SDValue Scale = Op.getOperand(6);
16250     return getGatherNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index, Scale,
16251                          Chain, Subtarget);
16252   }
16253   case SCATTER: {
16254   //scatter(base, mask, index, v1, scale);
16255     SDValue Chain = Op.getOperand(0);
16256     SDValue Base  = Op.getOperand(2);
16257     SDValue Mask  = Op.getOperand(3);
16258     SDValue Index = Op.getOperand(4);
16259     SDValue Src   = Op.getOperand(5);
16260     SDValue Scale = Op.getOperand(6);
16261     return getScatterNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index,
16262                           Scale, Chain);
16263   }
16264   case PREFETCH: {
16265     SDValue Hint = Op.getOperand(6);
16266     unsigned HintVal = cast<ConstantSDNode>(Hint)->getZExtValue();
16267     assert(HintVal < 2 && "Wrong prefetch hint in intrinsic: should be 0 or 1");
16268     unsigned Opcode = (HintVal ? IntrData->Opc1 : IntrData->Opc0);
16269     SDValue Chain = Op.getOperand(0);
16270     SDValue Mask  = Op.getOperand(2);
16271     SDValue Index = Op.getOperand(3);
16272     SDValue Base  = Op.getOperand(4);
16273     SDValue Scale = Op.getOperand(5);
16274     return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
16275   }
16276   // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
16277   case RDTSC: {
16278     SmallVector<SDValue, 2> Results;
16279     getReadTimeStampCounter(Op.getNode(), dl, IntrData->Opc0, DAG, Subtarget,
16280                             Results);
16281     return DAG.getMergeValues(Results, dl);
16282   }
16283   // Read Performance Monitoring Counters.
16284   case RDPMC: {
16285     SmallVector<SDValue, 2> Results;
16286     getReadPerformanceCounter(Op.getNode(), dl, DAG, Subtarget, Results);
16287     return DAG.getMergeValues(Results, dl);
16288   }
16289   // XTEST intrinsics.
16290   case XTEST: {
16291     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
16292     SDValue InTrans = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
16293     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16294                                 DAG.getConstant(X86::COND_NE, dl, MVT::i8),
16295                                 InTrans);
16296     SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
16297     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
16298                        Ret, SDValue(InTrans.getNode(), 1));
16299   }
16300   // ADC/ADCX/SBB
16301   case ADX: {
16302     SmallVector<SDValue, 2> Results;
16303     SDVTList CFVTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
16304     SDVTList VTs = DAG.getVTList(Op.getOperand(3)->getValueType(0), MVT::Other);
16305     SDValue GenCF = DAG.getNode(X86ISD::ADD, dl, CFVTs, Op.getOperand(2),
16306                                 DAG.getConstant(-1, dl, MVT::i8));
16307     SDValue Res = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(3),
16308                               Op.getOperand(4), GenCF.getValue(1));
16309     SDValue Store = DAG.getStore(Op.getOperand(0), dl, Res.getValue(0),
16310                                  Op.getOperand(5), MachinePointerInfo(),
16311                                  false, false, 0);
16312     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16313                                 DAG.getConstant(X86::COND_B, dl, MVT::i8),
16314                                 Res.getValue(1));
16315     Results.push_back(SetCC);
16316     Results.push_back(Store);
16317     return DAG.getMergeValues(Results, dl);
16318   }
16319   case COMPRESS_TO_MEM: {
16320     SDLoc dl(Op);
16321     SDValue Mask = Op.getOperand(4);
16322     SDValue DataToCompress = Op.getOperand(3);
16323     SDValue Addr = Op.getOperand(2);
16324     SDValue Chain = Op.getOperand(0);
16325
16326     EVT VT = DataToCompress.getValueType();
16327     if (isAllOnes(Mask)) // return just a store
16328       return DAG.getStore(Chain, dl, DataToCompress, Addr,
16329                           MachinePointerInfo(), false, false,
16330                           VT.getScalarSizeInBits()/8);
16331
16332     SDValue Compressed =
16333       getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, DataToCompress),
16334                            Mask, DAG.getUNDEF(VT), Subtarget, DAG);
16335     return DAG.getStore(Chain, dl, Compressed, Addr,
16336                         MachinePointerInfo(), false, false,
16337                         VT.getScalarSizeInBits()/8);
16338   }
16339   case TRUNCATE_TO_MEM_VI8:
16340     return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i8);
16341   case TRUNCATE_TO_MEM_VI16:
16342     return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i16);
16343   case TRUNCATE_TO_MEM_VI32:
16344     return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i32);
16345   case EXPAND_FROM_MEM: {
16346     SDLoc dl(Op);
16347     SDValue Mask = Op.getOperand(4);
16348     SDValue PassThru = Op.getOperand(3);
16349     SDValue Addr = Op.getOperand(2);
16350     SDValue Chain = Op.getOperand(0);
16351     EVT VT = Op.getValueType();
16352
16353     if (isAllOnes(Mask)) // return just a load
16354       return DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(), false, false,
16355                          false, VT.getScalarSizeInBits()/8);
16356
16357     SDValue DataToExpand = DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(),
16358                                        false, false, false,
16359                                        VT.getScalarSizeInBits()/8);
16360
16361     SDValue Results[] = {
16362       getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, DataToExpand),
16363                            Mask, PassThru, Subtarget, DAG), Chain};
16364     return DAG.getMergeValues(Results, dl);
16365   }
16366   }
16367 }
16368
16369 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
16370                                            SelectionDAG &DAG) const {
16371   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
16372   MFI->setReturnAddressIsTaken(true);
16373
16374   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
16375     return SDValue();
16376
16377   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16378   SDLoc dl(Op);
16379   EVT PtrVT = getPointerTy(DAG.getDataLayout());
16380
16381   if (Depth > 0) {
16382     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
16383     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16384     SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), dl, PtrVT);
16385     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
16386                        DAG.getNode(ISD::ADD, dl, PtrVT,
16387                                    FrameAddr, Offset),
16388                        MachinePointerInfo(), false, false, false, 0);
16389   }
16390
16391   // Just load the return address.
16392   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
16393   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
16394                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
16395 }
16396
16397 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
16398   MachineFunction &MF = DAG.getMachineFunction();
16399   MachineFrameInfo *MFI = MF.getFrameInfo();
16400   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
16401   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16402   EVT VT = Op.getValueType();
16403
16404   MFI->setFrameAddressIsTaken(true);
16405
16406   if (MF.getTarget().getMCAsmInfo()->usesWindowsCFI()) {
16407     // Depth > 0 makes no sense on targets which use Windows unwind codes.  It
16408     // is not possible to crawl up the stack without looking at the unwind codes
16409     // simultaneously.
16410     int FrameAddrIndex = FuncInfo->getFAIndex();
16411     if (!FrameAddrIndex) {
16412       // Set up a frame object for the return address.
16413       unsigned SlotSize = RegInfo->getSlotSize();
16414       FrameAddrIndex = MF.getFrameInfo()->CreateFixedObject(
16415           SlotSize, /*Offset=*/0, /*IsImmutable=*/false);
16416       FuncInfo->setFAIndex(FrameAddrIndex);
16417     }
16418     return DAG.getFrameIndex(FrameAddrIndex, VT);
16419   }
16420
16421   unsigned FrameReg =
16422       RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
16423   SDLoc dl(Op);  // FIXME probably not meaningful
16424   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16425   assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
16426           (FrameReg == X86::EBP && VT == MVT::i32)) &&
16427          "Invalid Frame Register!");
16428   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
16429   while (Depth--)
16430     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
16431                             MachinePointerInfo(),
16432                             false, false, false, 0);
16433   return FrameAddr;
16434 }
16435
16436 // FIXME? Maybe this could be a TableGen attribute on some registers and
16437 // this table could be generated automatically from RegInfo.
16438 unsigned X86TargetLowering::getRegisterByName(const char* RegName, EVT VT,
16439                                               SelectionDAG &DAG) const {
16440   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
16441   const MachineFunction &MF = DAG.getMachineFunction();
16442
16443   unsigned Reg = StringSwitch<unsigned>(RegName)
16444                        .Case("esp", X86::ESP)
16445                        .Case("rsp", X86::RSP)
16446                        .Case("ebp", X86::EBP)
16447                        .Case("rbp", X86::RBP)
16448                        .Default(0);
16449
16450   if (Reg == X86::EBP || Reg == X86::RBP) {
16451     if (!TFI.hasFP(MF))
16452       report_fatal_error("register " + StringRef(RegName) +
16453                          " is allocatable: function has no frame pointer");
16454 #ifndef NDEBUG
16455     else {
16456       const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16457       unsigned FrameReg =
16458           RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
16459       assert((FrameReg == X86::EBP || FrameReg == X86::RBP) &&
16460              "Invalid Frame Register!");
16461     }
16462 #endif
16463   }
16464
16465   if (Reg)
16466     return Reg;
16467
16468   report_fatal_error("Invalid register name global variable");
16469 }
16470
16471 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
16472                                                      SelectionDAG &DAG) const {
16473   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16474   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize(), SDLoc(Op));
16475 }
16476
16477 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
16478   SDValue Chain     = Op.getOperand(0);
16479   SDValue Offset    = Op.getOperand(1);
16480   SDValue Handler   = Op.getOperand(2);
16481   SDLoc dl      (Op);
16482
16483   EVT PtrVT = getPointerTy(DAG.getDataLayout());
16484   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16485   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
16486   assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
16487           (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
16488          "Invalid Frame Register!");
16489   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
16490   unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
16491
16492   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
16493                                  DAG.getIntPtrConstant(RegInfo->getSlotSize(),
16494                                                        dl));
16495   StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
16496   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
16497                        false, false, 0);
16498   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
16499
16500   return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
16501                      DAG.getRegister(StoreAddrReg, PtrVT));
16502 }
16503
16504 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
16505                                                SelectionDAG &DAG) const {
16506   SDLoc DL(Op);
16507   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
16508                      DAG.getVTList(MVT::i32, MVT::Other),
16509                      Op.getOperand(0), Op.getOperand(1));
16510 }
16511
16512 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
16513                                                 SelectionDAG &DAG) const {
16514   SDLoc DL(Op);
16515   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
16516                      Op.getOperand(0), Op.getOperand(1));
16517 }
16518
16519 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
16520   return Op.getOperand(0);
16521 }
16522
16523 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
16524                                                 SelectionDAG &DAG) const {
16525   SDValue Root = Op.getOperand(0);
16526   SDValue Trmp = Op.getOperand(1); // trampoline
16527   SDValue FPtr = Op.getOperand(2); // nested function
16528   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
16529   SDLoc dl (Op);
16530
16531   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
16532   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
16533
16534   if (Subtarget->is64Bit()) {
16535     SDValue OutChains[6];
16536
16537     // Large code-model.
16538     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
16539     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
16540
16541     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
16542     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
16543
16544     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
16545
16546     // Load the pointer to the nested function into R11.
16547     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
16548     SDValue Addr = Trmp;
16549     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
16550                                 Addr, MachinePointerInfo(TrmpAddr),
16551                                 false, false, 0);
16552
16553     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16554                        DAG.getConstant(2, dl, MVT::i64));
16555     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
16556                                 MachinePointerInfo(TrmpAddr, 2),
16557                                 false, false, 2);
16558
16559     // Load the 'nest' parameter value into R10.
16560     // R10 is specified in X86CallingConv.td
16561     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
16562     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16563                        DAG.getConstant(10, dl, MVT::i64));
16564     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
16565                                 Addr, MachinePointerInfo(TrmpAddr, 10),
16566                                 false, false, 0);
16567
16568     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16569                        DAG.getConstant(12, dl, MVT::i64));
16570     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
16571                                 MachinePointerInfo(TrmpAddr, 12),
16572                                 false, false, 2);
16573
16574     // Jump to the nested function.
16575     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
16576     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16577                        DAG.getConstant(20, dl, MVT::i64));
16578     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
16579                                 Addr, MachinePointerInfo(TrmpAddr, 20),
16580                                 false, false, 0);
16581
16582     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
16583     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16584                        DAG.getConstant(22, dl, MVT::i64));
16585     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, dl, MVT::i8),
16586                                 Addr, MachinePointerInfo(TrmpAddr, 22),
16587                                 false, false, 0);
16588
16589     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
16590   } else {
16591     const Function *Func =
16592       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
16593     CallingConv::ID CC = Func->getCallingConv();
16594     unsigned NestReg;
16595
16596     switch (CC) {
16597     default:
16598       llvm_unreachable("Unsupported calling convention");
16599     case CallingConv::C:
16600     case CallingConv::X86_StdCall: {
16601       // Pass 'nest' parameter in ECX.
16602       // Must be kept in sync with X86CallingConv.td
16603       NestReg = X86::ECX;
16604
16605       // Check that ECX wasn't needed by an 'inreg' parameter.
16606       FunctionType *FTy = Func->getFunctionType();
16607       const AttributeSet &Attrs = Func->getAttributes();
16608
16609       if (!Attrs.isEmpty() && !Func->isVarArg()) {
16610         unsigned InRegCount = 0;
16611         unsigned Idx = 1;
16612
16613         for (FunctionType::param_iterator I = FTy->param_begin(),
16614              E = FTy->param_end(); I != E; ++I, ++Idx)
16615           if (Attrs.hasAttribute(Idx, Attribute::InReg)) {
16616             auto &DL = DAG.getDataLayout();
16617             // FIXME: should only count parameters that are lowered to integers.
16618             InRegCount += (DL.getTypeSizeInBits(*I) + 31) / 32;
16619           }
16620
16621         if (InRegCount > 2) {
16622           report_fatal_error("Nest register in use - reduce number of inreg"
16623                              " parameters!");
16624         }
16625       }
16626       break;
16627     }
16628     case CallingConv::X86_FastCall:
16629     case CallingConv::X86_ThisCall:
16630     case CallingConv::Fast:
16631       // Pass 'nest' parameter in EAX.
16632       // Must be kept in sync with X86CallingConv.td
16633       NestReg = X86::EAX;
16634       break;
16635     }
16636
16637     SDValue OutChains[4];
16638     SDValue Addr, Disp;
16639
16640     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
16641                        DAG.getConstant(10, dl, MVT::i32));
16642     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
16643
16644     // This is storing the opcode for MOV32ri.
16645     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
16646     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
16647     OutChains[0] = DAG.getStore(Root, dl,
16648                                 DAG.getConstant(MOV32ri|N86Reg, dl, MVT::i8),
16649                                 Trmp, MachinePointerInfo(TrmpAddr),
16650                                 false, false, 0);
16651
16652     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
16653                        DAG.getConstant(1, dl, MVT::i32));
16654     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
16655                                 MachinePointerInfo(TrmpAddr, 1),
16656                                 false, false, 1);
16657
16658     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
16659     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
16660                        DAG.getConstant(5, dl, MVT::i32));
16661     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, dl, MVT::i8),
16662                                 Addr, MachinePointerInfo(TrmpAddr, 5),
16663                                 false, false, 1);
16664
16665     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
16666                        DAG.getConstant(6, dl, MVT::i32));
16667     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
16668                                 MachinePointerInfo(TrmpAddr, 6),
16669                                 false, false, 1);
16670
16671     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
16672   }
16673 }
16674
16675 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
16676                                             SelectionDAG &DAG) const {
16677   /*
16678    The rounding mode is in bits 11:10 of FPSR, and has the following
16679    settings:
16680      00 Round to nearest
16681      01 Round to -inf
16682      10 Round to +inf
16683      11 Round to 0
16684
16685   FLT_ROUNDS, on the other hand, expects the following:
16686     -1 Undefined
16687      0 Round to 0
16688      1 Round to nearest
16689      2 Round to +inf
16690      3 Round to -inf
16691
16692   To perform the conversion, we do:
16693     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
16694   */
16695
16696   MachineFunction &MF = DAG.getMachineFunction();
16697   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
16698   unsigned StackAlignment = TFI.getStackAlignment();
16699   MVT VT = Op.getSimpleValueType();
16700   SDLoc DL(Op);
16701
16702   // Save FP Control Word to stack slot
16703   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
16704   SDValue StackSlot =
16705       DAG.getFrameIndex(SSFI, getPointerTy(DAG.getDataLayout()));
16706
16707   MachineMemOperand *MMO =
16708    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
16709                            MachineMemOperand::MOStore, 2, 2);
16710
16711   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
16712   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
16713                                           DAG.getVTList(MVT::Other),
16714                                           Ops, MVT::i16, MMO);
16715
16716   // Load FP Control Word from stack slot
16717   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
16718                             MachinePointerInfo(), false, false, false, 0);
16719
16720   // Transform as necessary
16721   SDValue CWD1 =
16722     DAG.getNode(ISD::SRL, DL, MVT::i16,
16723                 DAG.getNode(ISD::AND, DL, MVT::i16,
16724                             CWD, DAG.getConstant(0x800, DL, MVT::i16)),
16725                 DAG.getConstant(11, DL, MVT::i8));
16726   SDValue CWD2 =
16727     DAG.getNode(ISD::SRL, DL, MVT::i16,
16728                 DAG.getNode(ISD::AND, DL, MVT::i16,
16729                             CWD, DAG.getConstant(0x400, DL, MVT::i16)),
16730                 DAG.getConstant(9, DL, MVT::i8));
16731
16732   SDValue RetVal =
16733     DAG.getNode(ISD::AND, DL, MVT::i16,
16734                 DAG.getNode(ISD::ADD, DL, MVT::i16,
16735                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
16736                             DAG.getConstant(1, DL, MVT::i16)),
16737                 DAG.getConstant(3, DL, MVT::i16));
16738
16739   return DAG.getNode((VT.getSizeInBits() < 16 ?
16740                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
16741 }
16742
16743 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
16744   MVT VT = Op.getSimpleValueType();
16745   EVT OpVT = VT;
16746   unsigned NumBits = VT.getSizeInBits();
16747   SDLoc dl(Op);
16748
16749   Op = Op.getOperand(0);
16750   if (VT == MVT::i8) {
16751     // Zero extend to i32 since there is not an i8 bsr.
16752     OpVT = MVT::i32;
16753     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
16754   }
16755
16756   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
16757   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
16758   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
16759
16760   // If src is zero (i.e. bsr sets ZF), returns NumBits.
16761   SDValue Ops[] = {
16762     Op,
16763     DAG.getConstant(NumBits + NumBits - 1, dl, OpVT),
16764     DAG.getConstant(X86::COND_E, dl, MVT::i8),
16765     Op.getValue(1)
16766   };
16767   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
16768
16769   // Finally xor with NumBits-1.
16770   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
16771                    DAG.getConstant(NumBits - 1, dl, OpVT));
16772
16773   if (VT == MVT::i8)
16774     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
16775   return Op;
16776 }
16777
16778 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
16779   MVT VT = Op.getSimpleValueType();
16780   EVT OpVT = VT;
16781   unsigned NumBits = VT.getSizeInBits();
16782   SDLoc dl(Op);
16783
16784   Op = Op.getOperand(0);
16785   if (VT == MVT::i8) {
16786     // Zero extend to i32 since there is not an i8 bsr.
16787     OpVT = MVT::i32;
16788     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
16789   }
16790
16791   // Issue a bsr (scan bits in reverse).
16792   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
16793   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
16794
16795   // And xor with NumBits-1.
16796   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
16797                    DAG.getConstant(NumBits - 1, dl, OpVT));
16798
16799   if (VT == MVT::i8)
16800     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
16801   return Op;
16802 }
16803
16804 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
16805   MVT VT = Op.getSimpleValueType();
16806   unsigned NumBits = VT.getSizeInBits();
16807   SDLoc dl(Op);
16808   Op = Op.getOperand(0);
16809
16810   // Issue a bsf (scan bits forward) which also sets EFLAGS.
16811   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
16812   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
16813
16814   // If src is zero (i.e. bsf sets ZF), returns NumBits.
16815   SDValue Ops[] = {
16816     Op,
16817     DAG.getConstant(NumBits, dl, VT),
16818     DAG.getConstant(X86::COND_E, dl, MVT::i8),
16819     Op.getValue(1)
16820   };
16821   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
16822 }
16823
16824 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
16825 // ones, and then concatenate the result back.
16826 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
16827   MVT VT = Op.getSimpleValueType();
16828
16829   assert(VT.is256BitVector() && VT.isInteger() &&
16830          "Unsupported value type for operation");
16831
16832   unsigned NumElems = VT.getVectorNumElements();
16833   SDLoc dl(Op);
16834
16835   // Extract the LHS vectors
16836   SDValue LHS = Op.getOperand(0);
16837   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
16838   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
16839
16840   // Extract the RHS vectors
16841   SDValue RHS = Op.getOperand(1);
16842   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
16843   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
16844
16845   MVT EltVT = VT.getVectorElementType();
16846   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
16847
16848   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
16849                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
16850                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
16851 }
16852
16853 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
16854   if (Op.getValueType() == MVT::i1)
16855     return DAG.getNode(ISD::XOR, SDLoc(Op), Op.getValueType(),
16856                        Op.getOperand(0), Op.getOperand(1));
16857   assert(Op.getSimpleValueType().is256BitVector() &&
16858          Op.getSimpleValueType().isInteger() &&
16859          "Only handle AVX 256-bit vector integer operation");
16860   return Lower256IntArith(Op, DAG);
16861 }
16862
16863 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
16864   if (Op.getValueType() == MVT::i1)
16865     return DAG.getNode(ISD::XOR, SDLoc(Op), Op.getValueType(),
16866                        Op.getOperand(0), Op.getOperand(1));
16867   assert(Op.getSimpleValueType().is256BitVector() &&
16868          Op.getSimpleValueType().isInteger() &&
16869          "Only handle AVX 256-bit vector integer operation");
16870   return Lower256IntArith(Op, DAG);
16871 }
16872
16873 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
16874                         SelectionDAG &DAG) {
16875   SDLoc dl(Op);
16876   MVT VT = Op.getSimpleValueType();
16877
16878   if (VT == MVT::i1)
16879     return DAG.getNode(ISD::AND, dl, VT, Op.getOperand(0), Op.getOperand(1));
16880
16881   // Decompose 256-bit ops into smaller 128-bit ops.
16882   if (VT.is256BitVector() && !Subtarget->hasInt256())
16883     return Lower256IntArith(Op, DAG);
16884
16885   SDValue A = Op.getOperand(0);
16886   SDValue B = Op.getOperand(1);
16887
16888   // Lower v16i8/v32i8 mul as promotion to v8i16/v16i16 vector
16889   // pairs, multiply and truncate.
16890   if (VT == MVT::v16i8 || VT == MVT::v32i8) {
16891     if (Subtarget->hasInt256()) {
16892       if (VT == MVT::v32i8) {
16893         MVT SubVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() / 2);
16894         SDValue Lo = DAG.getIntPtrConstant(0, dl);
16895         SDValue Hi = DAG.getIntPtrConstant(VT.getVectorNumElements() / 2, dl);
16896         SDValue ALo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Lo);
16897         SDValue BLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Lo);
16898         SDValue AHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Hi);
16899         SDValue BHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Hi);
16900         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
16901                            DAG.getNode(ISD::MUL, dl, SubVT, ALo, BLo),
16902                            DAG.getNode(ISD::MUL, dl, SubVT, AHi, BHi));
16903       }
16904
16905       MVT ExVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements());
16906       return DAG.getNode(
16907           ISD::TRUNCATE, dl, VT,
16908           DAG.getNode(ISD::MUL, dl, ExVT,
16909                       DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, A),
16910                       DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, B)));
16911     }
16912
16913     assert(VT == MVT::v16i8 &&
16914            "Pre-AVX2 support only supports v16i8 multiplication");
16915     MVT ExVT = MVT::v8i16;
16916
16917     // Extract the lo parts and sign extend to i16
16918     SDValue ALo, BLo;
16919     if (Subtarget->hasSSE41()) {
16920       ALo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, A);
16921       BLo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, B);
16922     } else {
16923       const int ShufMask[] = {-1, 0, -1, 1, -1, 2, -1, 3,
16924                               -1, 4, -1, 5, -1, 6, -1, 7};
16925       ALo = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
16926       BLo = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
16927       ALo = DAG.getBitcast(ExVT, ALo);
16928       BLo = DAG.getBitcast(ExVT, BLo);
16929       ALo = DAG.getNode(ISD::SRA, dl, ExVT, ALo, DAG.getConstant(8, dl, ExVT));
16930       BLo = DAG.getNode(ISD::SRA, dl, ExVT, BLo, DAG.getConstant(8, dl, ExVT));
16931     }
16932
16933     // Extract the hi parts and sign extend to i16
16934     SDValue AHi, BHi;
16935     if (Subtarget->hasSSE41()) {
16936       const int ShufMask[] = {8,  9,  10, 11, 12, 13, 14, 15,
16937                               -1, -1, -1, -1, -1, -1, -1, -1};
16938       AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
16939       BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
16940       AHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, AHi);
16941       BHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, BHi);
16942     } else {
16943       const int ShufMask[] = {-1, 8,  -1, 9,  -1, 10, -1, 11,
16944                               -1, 12, -1, 13, -1, 14, -1, 15};
16945       AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
16946       BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
16947       AHi = DAG.getBitcast(ExVT, AHi);
16948       BHi = DAG.getBitcast(ExVT, BHi);
16949       AHi = DAG.getNode(ISD::SRA, dl, ExVT, AHi, DAG.getConstant(8, dl, ExVT));
16950       BHi = DAG.getNode(ISD::SRA, dl, ExVT, BHi, DAG.getConstant(8, dl, ExVT));
16951     }
16952
16953     // Multiply, mask the lower 8bits of the lo/hi results and pack
16954     SDValue RLo = DAG.getNode(ISD::MUL, dl, ExVT, ALo, BLo);
16955     SDValue RHi = DAG.getNode(ISD::MUL, dl, ExVT, AHi, BHi);
16956     RLo = DAG.getNode(ISD::AND, dl, ExVT, RLo, DAG.getConstant(255, dl, ExVT));
16957     RHi = DAG.getNode(ISD::AND, dl, ExVT, RHi, DAG.getConstant(255, dl, ExVT));
16958     return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
16959   }
16960
16961   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
16962   if (VT == MVT::v4i32) {
16963     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
16964            "Should not custom lower when pmuldq is available!");
16965
16966     // Extract the odd parts.
16967     static const int UnpackMask[] = { 1, -1, 3, -1 };
16968     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
16969     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
16970
16971     // Multiply the even parts.
16972     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
16973     // Now multiply odd parts.
16974     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
16975
16976     Evens = DAG.getBitcast(VT, Evens);
16977     Odds = DAG.getBitcast(VT, Odds);
16978
16979     // Merge the two vectors back together with a shuffle. This expands into 2
16980     // shuffles.
16981     static const int ShufMask[] = { 0, 4, 2, 6 };
16982     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
16983   }
16984
16985   assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
16986          "Only know how to lower V2I64/V4I64/V8I64 multiply");
16987
16988   //  Ahi = psrlqi(a, 32);
16989   //  Bhi = psrlqi(b, 32);
16990   //
16991   //  AloBlo = pmuludq(a, b);
16992   //  AloBhi = pmuludq(a, Bhi);
16993   //  AhiBlo = pmuludq(Ahi, b);
16994
16995   //  AloBhi = psllqi(AloBhi, 32);
16996   //  AhiBlo = psllqi(AhiBlo, 32);
16997   //  return AloBlo + AloBhi + AhiBlo;
16998
16999   SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
17000   SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
17001
17002   SDValue AhiBlo = Ahi;
17003   SDValue AloBhi = Bhi;
17004   // Bit cast to 32-bit vectors for MULUDQ
17005   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
17006                                   (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
17007   A = DAG.getBitcast(MulVT, A);
17008   B = DAG.getBitcast(MulVT, B);
17009   Ahi = DAG.getBitcast(MulVT, Ahi);
17010   Bhi = DAG.getBitcast(MulVT, Bhi);
17011
17012   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
17013   // After shifting right const values the result may be all-zero.
17014   if (!ISD::isBuildVectorAllZeros(Ahi.getNode())) {
17015     AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
17016     AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
17017   }
17018   if (!ISD::isBuildVectorAllZeros(Bhi.getNode())) {
17019     AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
17020     AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
17021   }
17022
17023   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
17024   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
17025 }
17026
17027 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
17028   assert(Subtarget->isTargetWin64() && "Unexpected target");
17029   EVT VT = Op.getValueType();
17030   assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
17031          "Unexpected return type for lowering");
17032
17033   RTLIB::Libcall LC;
17034   bool isSigned;
17035   switch (Op->getOpcode()) {
17036   default: llvm_unreachable("Unexpected request for libcall!");
17037   case ISD::SDIV:      isSigned = true;  LC = RTLIB::SDIV_I128;    break;
17038   case ISD::UDIV:      isSigned = false; LC = RTLIB::UDIV_I128;    break;
17039   case ISD::SREM:      isSigned = true;  LC = RTLIB::SREM_I128;    break;
17040   case ISD::UREM:      isSigned = false; LC = RTLIB::UREM_I128;    break;
17041   case ISD::SDIVREM:   isSigned = true;  LC = RTLIB::SDIVREM_I128; break;
17042   case ISD::UDIVREM:   isSigned = false; LC = RTLIB::UDIVREM_I128; break;
17043   }
17044
17045   SDLoc dl(Op);
17046   SDValue InChain = DAG.getEntryNode();
17047
17048   TargetLowering::ArgListTy Args;
17049   TargetLowering::ArgListEntry Entry;
17050   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
17051     EVT ArgVT = Op->getOperand(i).getValueType();
17052     assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
17053            "Unexpected argument type for lowering");
17054     SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
17055     Entry.Node = StackPtr;
17056     InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
17057                            false, false, 16);
17058     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
17059     Entry.Ty = PointerType::get(ArgTy,0);
17060     Entry.isSExt = false;
17061     Entry.isZExt = false;
17062     Args.push_back(Entry);
17063   }
17064
17065   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
17066                                          getPointerTy(DAG.getDataLayout()));
17067
17068   TargetLowering::CallLoweringInfo CLI(DAG);
17069   CLI.setDebugLoc(dl).setChain(InChain)
17070     .setCallee(getLibcallCallingConv(LC),
17071                static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
17072                Callee, std::move(Args), 0)
17073     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
17074
17075   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
17076   return DAG.getBitcast(VT, CallInfo.first);
17077 }
17078
17079 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
17080                              SelectionDAG &DAG) {
17081   SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
17082   EVT VT = Op0.getValueType();
17083   SDLoc dl(Op);
17084
17085   assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
17086          (VT == MVT::v8i32 && Subtarget->hasInt256()));
17087
17088   // PMULxD operations multiply each even value (starting at 0) of LHS with
17089   // the related value of RHS and produce a widen result.
17090   // E.g., PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
17091   // => <2 x i64> <ae|cg>
17092   //
17093   // In other word, to have all the results, we need to perform two PMULxD:
17094   // 1. one with the even values.
17095   // 2. one with the odd values.
17096   // To achieve #2, with need to place the odd values at an even position.
17097   //
17098   // Place the odd value at an even position (basically, shift all values 1
17099   // step to the left):
17100   const int Mask[] = {1, -1, 3, -1, 5, -1, 7, -1};
17101   // <a|b|c|d> => <b|undef|d|undef>
17102   SDValue Odd0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
17103   // <e|f|g|h> => <f|undef|h|undef>
17104   SDValue Odd1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
17105
17106   // Emit two multiplies, one for the lower 2 ints and one for the higher 2
17107   // ints.
17108   MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
17109   bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
17110   unsigned Opcode =
17111       (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
17112   // PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
17113   // => <2 x i64> <ae|cg>
17114   SDValue Mul1 = DAG.getBitcast(VT, DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
17115   // PMULUDQ <4 x i32> <b|undef|d|undef>, <4 x i32> <f|undef|h|undef>
17116   // => <2 x i64> <bf|dh>
17117   SDValue Mul2 = DAG.getBitcast(VT, DAG.getNode(Opcode, dl, MulVT, Odd0, Odd1));
17118
17119   // Shuffle it back into the right order.
17120   SDValue Highs, Lows;
17121   if (VT == MVT::v8i32) {
17122     const int HighMask[] = {1, 9, 3, 11, 5, 13, 7, 15};
17123     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
17124     const int LowMask[] = {0, 8, 2, 10, 4, 12, 6, 14};
17125     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
17126   } else {
17127     const int HighMask[] = {1, 5, 3, 7};
17128     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
17129     const int LowMask[] = {0, 4, 2, 6};
17130     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
17131   }
17132
17133   // If we have a signed multiply but no PMULDQ fix up the high parts of a
17134   // unsigned multiply.
17135   if (IsSigned && !Subtarget->hasSSE41()) {
17136     SDValue ShAmt = DAG.getConstant(
17137         31, dl,
17138         DAG.getTargetLoweringInfo().getShiftAmountTy(VT, DAG.getDataLayout()));
17139     SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
17140                              DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
17141     SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
17142                              DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
17143
17144     SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
17145     Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
17146   }
17147
17148   // The first result of MUL_LOHI is actually the low value, followed by the
17149   // high value.
17150   SDValue Ops[] = {Lows, Highs};
17151   return DAG.getMergeValues(Ops, dl);
17152 }
17153
17154 // Return true if the required (according to Opcode) shift-imm form is natively
17155 // supported by the Subtarget
17156 static bool SupportedVectorShiftWithImm(MVT VT, const X86Subtarget *Subtarget,
17157                                         unsigned Opcode) {
17158   if (VT.getScalarSizeInBits() < 16)
17159     return false;
17160
17161   if (VT.is512BitVector() &&
17162       (VT.getScalarSizeInBits() > 16 || Subtarget->hasBWI()))
17163     return true;
17164
17165   bool LShift = VT.is128BitVector() ||
17166     (VT.is256BitVector() && Subtarget->hasInt256());
17167
17168   bool AShift = LShift && (Subtarget->hasVLX() ||
17169     (VT != MVT::v2i64 && VT != MVT::v4i64));
17170   return (Opcode == ISD::SRA) ? AShift : LShift;
17171 }
17172
17173 // The shift amount is a variable, but it is the same for all vector lanes.
17174 // These instructions are defined together with shift-immediate.
17175 static
17176 bool SupportedVectorShiftWithBaseAmnt(MVT VT, const X86Subtarget *Subtarget,
17177                                       unsigned Opcode) {
17178   return SupportedVectorShiftWithImm(VT, Subtarget, Opcode);
17179 }
17180
17181 // Return true if the required (according to Opcode) variable-shift form is
17182 // natively supported by the Subtarget
17183 static bool SupportedVectorVarShift(MVT VT, const X86Subtarget *Subtarget,
17184                                     unsigned Opcode) {
17185
17186   if (!Subtarget->hasInt256() || VT.getScalarSizeInBits() < 16)
17187     return false;
17188
17189   // vXi16 supported only on AVX-512, BWI
17190   if (VT.getScalarSizeInBits() == 16 && !Subtarget->hasBWI())
17191     return false;
17192
17193   if (VT.is512BitVector() || Subtarget->hasVLX())
17194     return true;
17195
17196   bool LShift = VT.is128BitVector() || VT.is256BitVector();
17197   bool AShift = LShift &&  VT != MVT::v2i64 && VT != MVT::v4i64;
17198   return (Opcode == ISD::SRA) ? AShift : LShift;
17199 }
17200
17201 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
17202                                          const X86Subtarget *Subtarget) {
17203   MVT VT = Op.getSimpleValueType();
17204   SDLoc dl(Op);
17205   SDValue R = Op.getOperand(0);
17206   SDValue Amt = Op.getOperand(1);
17207
17208   unsigned X86Opc = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHLI :
17209     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRLI : X86ISD::VSRAI;
17210
17211   auto ArithmeticShiftRight64 = [&](uint64_t ShiftAmt) {
17212     assert((VT == MVT::v2i64 || VT == MVT::v4i64) && "Unexpected SRA type");
17213     MVT ExVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() * 2);
17214     SDValue Ex = DAG.getBitcast(ExVT, R);
17215
17216     if (ShiftAmt >= 32) {
17217       // Splat sign to upper i32 dst, and SRA upper i32 src to lower i32.
17218       SDValue Upper =
17219           getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex, 31, DAG);
17220       SDValue Lower = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex,
17221                                                  ShiftAmt - 32, DAG);
17222       if (VT == MVT::v2i64)
17223         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower, {5, 1, 7, 3});
17224       if (VT == MVT::v4i64)
17225         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower,
17226                                   {9, 1, 11, 3, 13, 5, 15, 7});
17227     } else {
17228       // SRA upper i32, SHL whole i64 and select lower i32.
17229       SDValue Upper = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex,
17230                                                  ShiftAmt, DAG);
17231       SDValue Lower =
17232           getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt, DAG);
17233       Lower = DAG.getBitcast(ExVT, Lower);
17234       if (VT == MVT::v2i64)
17235         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower, {4, 1, 6, 3});
17236       if (VT == MVT::v4i64)
17237         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower,
17238                                   {8, 1, 10, 3, 12, 5, 14, 7});
17239     }
17240     return DAG.getBitcast(VT, Ex);
17241   };
17242
17243   // Optimize shl/srl/sra with constant shift amount.
17244   if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
17245     if (auto *ShiftConst = BVAmt->getConstantSplatNode()) {
17246       uint64_t ShiftAmt = ShiftConst->getZExtValue();
17247
17248       if (SupportedVectorShiftWithImm(VT, Subtarget, Op.getOpcode()))
17249         return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
17250
17251       // i64 SRA needs to be performed as partial shifts.
17252       if ((VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
17253           Op.getOpcode() == ISD::SRA)
17254         return ArithmeticShiftRight64(ShiftAmt);
17255
17256       if (VT == MVT::v16i8 || (Subtarget->hasInt256() && VT == MVT::v32i8)) {
17257         unsigned NumElts = VT.getVectorNumElements();
17258         MVT ShiftVT = MVT::getVectorVT(MVT::i16, NumElts / 2);
17259
17260         if (Op.getOpcode() == ISD::SHL) {
17261           // Simple i8 add case
17262           if (ShiftAmt == 1)
17263             return DAG.getNode(ISD::ADD, dl, VT, R, R);
17264
17265           // Make a large shift.
17266           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, ShiftVT,
17267                                                    R, ShiftAmt, DAG);
17268           SHL = DAG.getBitcast(VT, SHL);
17269           // Zero out the rightmost bits.
17270           SmallVector<SDValue, 32> V(
17271               NumElts, DAG.getConstant(uint8_t(-1U << ShiftAmt), dl, MVT::i8));
17272           return DAG.getNode(ISD::AND, dl, VT, SHL,
17273                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
17274         }
17275         if (Op.getOpcode() == ISD::SRL) {
17276           // Make a large shift.
17277           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ShiftVT,
17278                                                    R, ShiftAmt, DAG);
17279           SRL = DAG.getBitcast(VT, SRL);
17280           // Zero out the leftmost bits.
17281           SmallVector<SDValue, 32> V(
17282               NumElts, DAG.getConstant(uint8_t(-1U) >> ShiftAmt, dl, MVT::i8));
17283           return DAG.getNode(ISD::AND, dl, VT, SRL,
17284                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
17285         }
17286         if (Op.getOpcode() == ISD::SRA) {
17287           if (ShiftAmt == 7) {
17288             // R s>> 7  ===  R s< 0
17289             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
17290             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
17291           }
17292
17293           // R s>> a === ((R u>> a) ^ m) - m
17294           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
17295           SmallVector<SDValue, 32> V(NumElts,
17296                                      DAG.getConstant(128 >> ShiftAmt, dl,
17297                                                      MVT::i8));
17298           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
17299           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
17300           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
17301           return Res;
17302         }
17303         llvm_unreachable("Unknown shift opcode.");
17304       }
17305     }
17306   }
17307
17308   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
17309   if (!Subtarget->is64Bit() &&
17310       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
17311       Amt.getOpcode() == ISD::BITCAST &&
17312       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
17313     Amt = Amt.getOperand(0);
17314     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
17315                      VT.getVectorNumElements();
17316     unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
17317     uint64_t ShiftAmt = 0;
17318     for (unsigned i = 0; i != Ratio; ++i) {
17319       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
17320       if (!C)
17321         return SDValue();
17322       // 6 == Log2(64)
17323       ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
17324     }
17325     // Check remaining shift amounts.
17326     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
17327       uint64_t ShAmt = 0;
17328       for (unsigned j = 0; j != Ratio; ++j) {
17329         ConstantSDNode *C =
17330           dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
17331         if (!C)
17332           return SDValue();
17333         // 6 == Log2(64)
17334         ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
17335       }
17336       if (ShAmt != ShiftAmt)
17337         return SDValue();
17338     }
17339
17340     if (SupportedVectorShiftWithImm(VT, Subtarget, Op.getOpcode()))
17341       return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
17342
17343     if (Op.getOpcode() == ISD::SRA)
17344       return ArithmeticShiftRight64(ShiftAmt);
17345   }
17346
17347   return SDValue();
17348 }
17349
17350 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
17351                                         const X86Subtarget* Subtarget) {
17352   MVT VT = Op.getSimpleValueType();
17353   SDLoc dl(Op);
17354   SDValue R = Op.getOperand(0);
17355   SDValue Amt = Op.getOperand(1);
17356
17357   unsigned X86OpcI = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHLI :
17358     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRLI : X86ISD::VSRAI;
17359
17360   unsigned X86OpcV = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHL :
17361     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRL : X86ISD::VSRA;
17362
17363   if (SupportedVectorShiftWithBaseAmnt(VT, Subtarget, Op.getOpcode())) {
17364     SDValue BaseShAmt;
17365     EVT EltVT = VT.getVectorElementType();
17366
17367     if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Amt)) {
17368       // Check if this build_vector node is doing a splat.
17369       // If so, then set BaseShAmt equal to the splat value.
17370       BaseShAmt = BV->getSplatValue();
17371       if (BaseShAmt && BaseShAmt.getOpcode() == ISD::UNDEF)
17372         BaseShAmt = SDValue();
17373     } else {
17374       if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
17375         Amt = Amt.getOperand(0);
17376
17377       ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(Amt);
17378       if (SVN && SVN->isSplat()) {
17379         unsigned SplatIdx = (unsigned)SVN->getSplatIndex();
17380         SDValue InVec = Amt.getOperand(0);
17381         if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
17382           assert((SplatIdx < InVec.getValueType().getVectorNumElements()) &&
17383                  "Unexpected shuffle index found!");
17384           BaseShAmt = InVec.getOperand(SplatIdx);
17385         } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
17386            if (ConstantSDNode *C =
17387                dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
17388              if (C->getZExtValue() == SplatIdx)
17389                BaseShAmt = InVec.getOperand(1);
17390            }
17391         }
17392
17393         if (!BaseShAmt)
17394           // Avoid introducing an extract element from a shuffle.
17395           BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, InVec,
17396                                   DAG.getIntPtrConstant(SplatIdx, dl));
17397       }
17398     }
17399
17400     if (BaseShAmt.getNode()) {
17401       assert(EltVT.bitsLE(MVT::i64) && "Unexpected element type!");
17402       if (EltVT != MVT::i64 && EltVT.bitsGT(MVT::i32))
17403         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, BaseShAmt);
17404       else if (EltVT.bitsLT(MVT::i32))
17405         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
17406
17407       return getTargetVShiftNode(X86OpcI, dl, VT, R, BaseShAmt, DAG);
17408     }
17409   }
17410
17411   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
17412   if (!Subtarget->is64Bit() && VT == MVT::v2i64  &&
17413       Amt.getOpcode() == ISD::BITCAST &&
17414       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
17415     Amt = Amt.getOperand(0);
17416     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
17417                      VT.getVectorNumElements();
17418     std::vector<SDValue> Vals(Ratio);
17419     for (unsigned i = 0; i != Ratio; ++i)
17420       Vals[i] = Amt.getOperand(i);
17421     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
17422       for (unsigned j = 0; j != Ratio; ++j)
17423         if (Vals[j] != Amt.getOperand(i + j))
17424           return SDValue();
17425     }
17426
17427     if (SupportedVectorShiftWithBaseAmnt(VT, Subtarget, Op.getOpcode()))
17428       return DAG.getNode(X86OpcV, dl, VT, R, Op.getOperand(1));
17429   }
17430   return SDValue();
17431 }
17432
17433 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
17434                           SelectionDAG &DAG) {
17435   MVT VT = Op.getSimpleValueType();
17436   SDLoc dl(Op);
17437   SDValue R = Op.getOperand(0);
17438   SDValue Amt = Op.getOperand(1);
17439
17440   assert(VT.isVector() && "Custom lowering only for vector shifts!");
17441   assert(Subtarget->hasSSE2() && "Only custom lower when we have SSE2!");
17442
17443   if (SDValue V = LowerScalarImmediateShift(Op, DAG, Subtarget))
17444     return V;
17445
17446   if (SDValue V = LowerScalarVariableShift(Op, DAG, Subtarget))
17447       return V;
17448
17449   if (SupportedVectorVarShift(VT, Subtarget, Op.getOpcode()))
17450     return Op;
17451
17452   // 2i64 vector logical shifts can efficiently avoid scalarization - do the
17453   // shifts per-lane and then shuffle the partial results back together.
17454   if (VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) {
17455     // Splat the shift amounts so the scalar shifts above will catch it.
17456     SDValue Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {0, 0});
17457     SDValue Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {1, 1});
17458     SDValue R0 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt0);
17459     SDValue R1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt1);
17460     return DAG.getVectorShuffle(VT, dl, R0, R1, {0, 3});
17461   }
17462
17463   // If possible, lower this packed shift into a vector multiply instead of
17464   // expanding it into a sequence of scalar shifts.
17465   // Do this only if the vector shift count is a constant build_vector.
17466   if (Op.getOpcode() == ISD::SHL &&
17467       (VT == MVT::v8i16 || VT == MVT::v4i32 ||
17468        (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
17469       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
17470     SmallVector<SDValue, 8> Elts;
17471     EVT SVT = VT.getScalarType();
17472     unsigned SVTBits = SVT.getSizeInBits();
17473     const APInt &One = APInt(SVTBits, 1);
17474     unsigned NumElems = VT.getVectorNumElements();
17475
17476     for (unsigned i=0; i !=NumElems; ++i) {
17477       SDValue Op = Amt->getOperand(i);
17478       if (Op->getOpcode() == ISD::UNDEF) {
17479         Elts.push_back(Op);
17480         continue;
17481       }
17482
17483       ConstantSDNode *ND = cast<ConstantSDNode>(Op);
17484       const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
17485       uint64_t ShAmt = C.getZExtValue();
17486       if (ShAmt >= SVTBits) {
17487         Elts.push_back(DAG.getUNDEF(SVT));
17488         continue;
17489       }
17490       Elts.push_back(DAG.getConstant(One.shl(ShAmt), dl, SVT));
17491     }
17492     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
17493     return DAG.getNode(ISD::MUL, dl, VT, R, BV);
17494   }
17495
17496   // Lower SHL with variable shift amount.
17497   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
17498     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, dl, VT));
17499
17500     Op = DAG.getNode(ISD::ADD, dl, VT, Op,
17501                      DAG.getConstant(0x3f800000U, dl, VT));
17502     Op = DAG.getBitcast(MVT::v4f32, Op);
17503     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
17504     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
17505   }
17506
17507   // If possible, lower this shift as a sequence of two shifts by
17508   // constant plus a MOVSS/MOVSD instead of scalarizing it.
17509   // Example:
17510   //   (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
17511   //
17512   // Could be rewritten as:
17513   //   (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
17514   //
17515   // The advantage is that the two shifts from the example would be
17516   // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
17517   // the vector shift into four scalar shifts plus four pairs of vector
17518   // insert/extract.
17519   if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
17520       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
17521     unsigned TargetOpcode = X86ISD::MOVSS;
17522     bool CanBeSimplified;
17523     // The splat value for the first packed shift (the 'X' from the example).
17524     SDValue Amt1 = Amt->getOperand(0);
17525     // The splat value for the second packed shift (the 'Y' from the example).
17526     SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
17527                                         Amt->getOperand(2);
17528
17529     // See if it is possible to replace this node with a sequence of
17530     // two shifts followed by a MOVSS/MOVSD
17531     if (VT == MVT::v4i32) {
17532       // Check if it is legal to use a MOVSS.
17533       CanBeSimplified = Amt2 == Amt->getOperand(2) &&
17534                         Amt2 == Amt->getOperand(3);
17535       if (!CanBeSimplified) {
17536         // Otherwise, check if we can still simplify this node using a MOVSD.
17537         CanBeSimplified = Amt1 == Amt->getOperand(1) &&
17538                           Amt->getOperand(2) == Amt->getOperand(3);
17539         TargetOpcode = X86ISD::MOVSD;
17540         Amt2 = Amt->getOperand(2);
17541       }
17542     } else {
17543       // Do similar checks for the case where the machine value type
17544       // is MVT::v8i16.
17545       CanBeSimplified = Amt1 == Amt->getOperand(1);
17546       for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
17547         CanBeSimplified = Amt2 == Amt->getOperand(i);
17548
17549       if (!CanBeSimplified) {
17550         TargetOpcode = X86ISD::MOVSD;
17551         CanBeSimplified = true;
17552         Amt2 = Amt->getOperand(4);
17553         for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
17554           CanBeSimplified = Amt1 == Amt->getOperand(i);
17555         for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
17556           CanBeSimplified = Amt2 == Amt->getOperand(j);
17557       }
17558     }
17559
17560     if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
17561         isa<ConstantSDNode>(Amt2)) {
17562       // Replace this node with two shifts followed by a MOVSS/MOVSD.
17563       EVT CastVT = MVT::v4i32;
17564       SDValue Splat1 =
17565         DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), dl, VT);
17566       SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
17567       SDValue Splat2 =
17568         DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), dl, VT);
17569       SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
17570       if (TargetOpcode == X86ISD::MOVSD)
17571         CastVT = MVT::v2i64;
17572       SDValue BitCast1 = DAG.getBitcast(CastVT, Shift1);
17573       SDValue BitCast2 = DAG.getBitcast(CastVT, Shift2);
17574       SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
17575                                             BitCast1, DAG);
17576       return DAG.getBitcast(VT, Result);
17577     }
17578   }
17579
17580   // v4i32 Non Uniform Shifts.
17581   // If the shift amount is constant we can shift each lane using the SSE2
17582   // immediate shifts, else we need to zero-extend each lane to the lower i64
17583   // and shift using the SSE2 variable shifts.
17584   // The separate results can then be blended together.
17585   if (VT == MVT::v4i32) {
17586     unsigned Opc = Op.getOpcode();
17587     SDValue Amt0, Amt1, Amt2, Amt3;
17588     if (ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
17589       Amt0 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {0, 0, 0, 0});
17590       Amt1 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {1, 1, 1, 1});
17591       Amt2 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {2, 2, 2, 2});
17592       Amt3 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {3, 3, 3, 3});
17593     } else {
17594       // ISD::SHL is handled above but we include it here for completeness.
17595       switch (Opc) {
17596       default:
17597         llvm_unreachable("Unknown target vector shift node");
17598       case ISD::SHL:
17599         Opc = X86ISD::VSHL;
17600         break;
17601       case ISD::SRL:
17602         Opc = X86ISD::VSRL;
17603         break;
17604       case ISD::SRA:
17605         Opc = X86ISD::VSRA;
17606         break;
17607       }
17608       // The SSE2 shifts use the lower i64 as the same shift amount for
17609       // all lanes and the upper i64 is ignored. These shuffle masks
17610       // optimally zero-extend each lanes on SSE2/SSE41/AVX targets.
17611       SDValue Z = getZeroVector(VT, Subtarget, DAG, dl);
17612       Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Z, {0, 4, -1, -1});
17613       Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Z, {1, 5, -1, -1});
17614       Amt2 = DAG.getVectorShuffle(VT, dl, Amt, Z, {2, 6, -1, -1});
17615       Amt3 = DAG.getVectorShuffle(VT, dl, Amt, Z, {3, 7, -1, -1});
17616     }
17617
17618     SDValue R0 = DAG.getNode(Opc, dl, VT, R, Amt0);
17619     SDValue R1 = DAG.getNode(Opc, dl, VT, R, Amt1);
17620     SDValue R2 = DAG.getNode(Opc, dl, VT, R, Amt2);
17621     SDValue R3 = DAG.getNode(Opc, dl, VT, R, Amt3);
17622     SDValue R02 = DAG.getVectorShuffle(VT, dl, R0, R2, {0, -1, 6, -1});
17623     SDValue R13 = DAG.getVectorShuffle(VT, dl, R1, R3, {-1, 1, -1, 7});
17624     return DAG.getVectorShuffle(VT, dl, R02, R13, {0, 5, 2, 7});
17625   }
17626
17627   if (VT == MVT::v16i8 || (VT == MVT::v32i8 && Subtarget->hasInt256())) {
17628     MVT ExtVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements() / 2);
17629     unsigned ShiftOpcode = Op->getOpcode();
17630
17631     auto SignBitSelect = [&](MVT SelVT, SDValue Sel, SDValue V0, SDValue V1) {
17632       // On SSE41 targets we make use of the fact that VSELECT lowers
17633       // to PBLENDVB which selects bytes based just on the sign bit.
17634       if (Subtarget->hasSSE41()) {
17635         V0 = DAG.getBitcast(VT, V0);
17636         V1 = DAG.getBitcast(VT, V1);
17637         Sel = DAG.getBitcast(VT, Sel);
17638         return DAG.getBitcast(SelVT,
17639                               DAG.getNode(ISD::VSELECT, dl, VT, Sel, V0, V1));
17640       }
17641       // On pre-SSE41 targets we test for the sign bit by comparing to
17642       // zero - a negative value will set all bits of the lanes to true
17643       // and VSELECT uses that in its OR(AND(V0,C),AND(V1,~C)) lowering.
17644       SDValue Z = getZeroVector(SelVT, Subtarget, DAG, dl);
17645       SDValue C = DAG.getNode(X86ISD::PCMPGT, dl, SelVT, Z, Sel);
17646       return DAG.getNode(ISD::VSELECT, dl, SelVT, C, V0, V1);
17647     };
17648
17649     // Turn 'a' into a mask suitable for VSELECT: a = a << 5;
17650     // We can safely do this using i16 shifts as we're only interested in
17651     // the 3 lower bits of each byte.
17652     Amt = DAG.getBitcast(ExtVT, Amt);
17653     Amt = DAG.getNode(ISD::SHL, dl, ExtVT, Amt, DAG.getConstant(5, dl, ExtVT));
17654     Amt = DAG.getBitcast(VT, Amt);
17655
17656     if (Op->getOpcode() == ISD::SHL || Op->getOpcode() == ISD::SRL) {
17657       // r = VSELECT(r, shift(r, 4), a);
17658       SDValue M =
17659           DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(4, dl, VT));
17660       R = SignBitSelect(VT, Amt, M, R);
17661
17662       // a += a
17663       Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
17664
17665       // r = VSELECT(r, shift(r, 2), a);
17666       M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(2, dl, VT));
17667       R = SignBitSelect(VT, Amt, M, R);
17668
17669       // a += a
17670       Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
17671
17672       // return VSELECT(r, shift(r, 1), a);
17673       M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(1, dl, VT));
17674       R = SignBitSelect(VT, Amt, M, R);
17675       return R;
17676     }
17677
17678     if (Op->getOpcode() == ISD::SRA) {
17679       // For SRA we need to unpack each byte to the higher byte of a i16 vector
17680       // so we can correctly sign extend. We don't care what happens to the
17681       // lower byte.
17682       SDValue ALo = DAG.getNode(X86ISD::UNPCKL, dl, VT, DAG.getUNDEF(VT), Amt);
17683       SDValue AHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, DAG.getUNDEF(VT), Amt);
17684       SDValue RLo = DAG.getNode(X86ISD::UNPCKL, dl, VT, DAG.getUNDEF(VT), R);
17685       SDValue RHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, DAG.getUNDEF(VT), R);
17686       ALo = DAG.getBitcast(ExtVT, ALo);
17687       AHi = DAG.getBitcast(ExtVT, AHi);
17688       RLo = DAG.getBitcast(ExtVT, RLo);
17689       RHi = DAG.getBitcast(ExtVT, RHi);
17690
17691       // r = VSELECT(r, shift(r, 4), a);
17692       SDValue MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
17693                                 DAG.getConstant(4, dl, ExtVT));
17694       SDValue MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
17695                                 DAG.getConstant(4, dl, ExtVT));
17696       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
17697       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
17698
17699       // a += a
17700       ALo = DAG.getNode(ISD::ADD, dl, ExtVT, ALo, ALo);
17701       AHi = DAG.getNode(ISD::ADD, dl, ExtVT, AHi, AHi);
17702
17703       // r = VSELECT(r, shift(r, 2), a);
17704       MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
17705                         DAG.getConstant(2, dl, ExtVT));
17706       MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
17707                         DAG.getConstant(2, dl, ExtVT));
17708       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
17709       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
17710
17711       // a += a
17712       ALo = DAG.getNode(ISD::ADD, dl, ExtVT, ALo, ALo);
17713       AHi = DAG.getNode(ISD::ADD, dl, ExtVT, AHi, AHi);
17714
17715       // r = VSELECT(r, shift(r, 1), a);
17716       MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
17717                         DAG.getConstant(1, dl, ExtVT));
17718       MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
17719                         DAG.getConstant(1, dl, ExtVT));
17720       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
17721       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
17722
17723       // Logical shift the result back to the lower byte, leaving a zero upper
17724       // byte
17725       // meaning that we can safely pack with PACKUSWB.
17726       RLo =
17727           DAG.getNode(ISD::SRL, dl, ExtVT, RLo, DAG.getConstant(8, dl, ExtVT));
17728       RHi =
17729           DAG.getNode(ISD::SRL, dl, ExtVT, RHi, DAG.getConstant(8, dl, ExtVT));
17730       return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
17731     }
17732   }
17733
17734   // It's worth extending once and using the v8i32 shifts for 16-bit types, but
17735   // the extra overheads to get from v16i8 to v8i32 make the existing SSE
17736   // solution better.
17737   if (Subtarget->hasInt256() && VT == MVT::v8i16) {
17738     MVT ExtVT = MVT::v8i32;
17739     unsigned ExtOpc =
17740         Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
17741     R = DAG.getNode(ExtOpc, dl, ExtVT, R);
17742     Amt = DAG.getNode(ISD::ANY_EXTEND, dl, ExtVT, Amt);
17743     return DAG.getNode(ISD::TRUNCATE, dl, VT,
17744                        DAG.getNode(Op.getOpcode(), dl, ExtVT, R, Amt));
17745   }
17746
17747   if (Subtarget->hasInt256() && VT == MVT::v16i16) {
17748     MVT ExtVT = MVT::v8i32;
17749     SDValue Z = getZeroVector(VT, Subtarget, DAG, dl);
17750     SDValue ALo = DAG.getNode(X86ISD::UNPCKL, dl, VT, Amt, Z);
17751     SDValue AHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, Amt, Z);
17752     SDValue RLo = DAG.getNode(X86ISD::UNPCKL, dl, VT, R, R);
17753     SDValue RHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, R, R);
17754     ALo = DAG.getBitcast(ExtVT, ALo);
17755     AHi = DAG.getBitcast(ExtVT, AHi);
17756     RLo = DAG.getBitcast(ExtVT, RLo);
17757     RHi = DAG.getBitcast(ExtVT, RHi);
17758     SDValue Lo = DAG.getNode(Op.getOpcode(), dl, ExtVT, RLo, ALo);
17759     SDValue Hi = DAG.getNode(Op.getOpcode(), dl, ExtVT, RHi, AHi);
17760     Lo = DAG.getNode(ISD::SRL, dl, ExtVT, Lo, DAG.getConstant(16, dl, ExtVT));
17761     Hi = DAG.getNode(ISD::SRL, dl, ExtVT, Hi, DAG.getConstant(16, dl, ExtVT));
17762     return DAG.getNode(X86ISD::PACKUS, dl, VT, Lo, Hi);
17763   }
17764
17765   if (VT == MVT::v8i16) {
17766     unsigned ShiftOpcode = Op->getOpcode();
17767
17768     auto SignBitSelect = [&](SDValue Sel, SDValue V0, SDValue V1) {
17769       // On SSE41 targets we make use of the fact that VSELECT lowers
17770       // to PBLENDVB which selects bytes based just on the sign bit.
17771       if (Subtarget->hasSSE41()) {
17772         MVT ExtVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() * 2);
17773         V0 = DAG.getBitcast(ExtVT, V0);
17774         V1 = DAG.getBitcast(ExtVT, V1);
17775         Sel = DAG.getBitcast(ExtVT, Sel);
17776         return DAG.getBitcast(
17777             VT, DAG.getNode(ISD::VSELECT, dl, ExtVT, Sel, V0, V1));
17778       }
17779       // On pre-SSE41 targets we splat the sign bit - a negative value will
17780       // set all bits of the lanes to true and VSELECT uses that in
17781       // its OR(AND(V0,C),AND(V1,~C)) lowering.
17782       SDValue C =
17783           DAG.getNode(ISD::SRA, dl, VT, Sel, DAG.getConstant(15, dl, VT));
17784       return DAG.getNode(ISD::VSELECT, dl, VT, C, V0, V1);
17785     };
17786
17787     // Turn 'a' into a mask suitable for VSELECT: a = a << 12;
17788     if (Subtarget->hasSSE41()) {
17789       // On SSE41 targets we need to replicate the shift mask in both
17790       // bytes for PBLENDVB.
17791       Amt = DAG.getNode(
17792           ISD::OR, dl, VT,
17793           DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(4, dl, VT)),
17794           DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(12, dl, VT)));
17795     } else {
17796       Amt = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(12, dl, VT));
17797     }
17798
17799     // r = VSELECT(r, shift(r, 8), a);
17800     SDValue M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(8, dl, VT));
17801     R = SignBitSelect(Amt, M, R);
17802
17803     // a += a
17804     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
17805
17806     // r = VSELECT(r, shift(r, 4), a);
17807     M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(4, dl, VT));
17808     R = SignBitSelect(Amt, M, R);
17809
17810     // a += a
17811     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
17812
17813     // r = VSELECT(r, shift(r, 2), a);
17814     M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(2, dl, VT));
17815     R = SignBitSelect(Amt, M, R);
17816
17817     // a += a
17818     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
17819
17820     // return VSELECT(r, shift(r, 1), a);
17821     M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(1, dl, VT));
17822     R = SignBitSelect(Amt, M, R);
17823     return R;
17824   }
17825
17826   // Decompose 256-bit shifts into smaller 128-bit shifts.
17827   if (VT.is256BitVector()) {
17828     unsigned NumElems = VT.getVectorNumElements();
17829     MVT EltVT = VT.getVectorElementType();
17830     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
17831
17832     // Extract the two vectors
17833     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
17834     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
17835
17836     // Recreate the shift amount vectors
17837     SDValue Amt1, Amt2;
17838     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
17839       // Constant shift amount
17840       SmallVector<SDValue, 8> Ops(Amt->op_begin(), Amt->op_begin() + NumElems);
17841       ArrayRef<SDValue> Amt1Csts = makeArrayRef(Ops).slice(0, NumElems / 2);
17842       ArrayRef<SDValue> Amt2Csts = makeArrayRef(Ops).slice(NumElems / 2);
17843
17844       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
17845       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
17846     } else {
17847       // Variable shift amount
17848       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
17849       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
17850     }
17851
17852     // Issue new vector shifts for the smaller types
17853     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
17854     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
17855
17856     // Concatenate the result back
17857     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
17858   }
17859
17860   return SDValue();
17861 }
17862
17863 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
17864   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
17865   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
17866   // looks for this combo and may remove the "setcc" instruction if the "setcc"
17867   // has only one use.
17868   SDNode *N = Op.getNode();
17869   SDValue LHS = N->getOperand(0);
17870   SDValue RHS = N->getOperand(1);
17871   unsigned BaseOp = 0;
17872   unsigned Cond = 0;
17873   SDLoc DL(Op);
17874   switch (Op.getOpcode()) {
17875   default: llvm_unreachable("Unknown ovf instruction!");
17876   case ISD::SADDO:
17877     // A subtract of one will be selected as a INC. Note that INC doesn't
17878     // set CF, so we can't do this for UADDO.
17879     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
17880       if (C->isOne()) {
17881         BaseOp = X86ISD::INC;
17882         Cond = X86::COND_O;
17883         break;
17884       }
17885     BaseOp = X86ISD::ADD;
17886     Cond = X86::COND_O;
17887     break;
17888   case ISD::UADDO:
17889     BaseOp = X86ISD::ADD;
17890     Cond = X86::COND_B;
17891     break;
17892   case ISD::SSUBO:
17893     // A subtract of one will be selected as a DEC. Note that DEC doesn't
17894     // set CF, so we can't do this for USUBO.
17895     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
17896       if (C->isOne()) {
17897         BaseOp = X86ISD::DEC;
17898         Cond = X86::COND_O;
17899         break;
17900       }
17901     BaseOp = X86ISD::SUB;
17902     Cond = X86::COND_O;
17903     break;
17904   case ISD::USUBO:
17905     BaseOp = X86ISD::SUB;
17906     Cond = X86::COND_B;
17907     break;
17908   case ISD::SMULO:
17909     BaseOp = N->getValueType(0) == MVT::i8 ? X86ISD::SMUL8 : X86ISD::SMUL;
17910     Cond = X86::COND_O;
17911     break;
17912   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
17913     if (N->getValueType(0) == MVT::i8) {
17914       BaseOp = X86ISD::UMUL8;
17915       Cond = X86::COND_O;
17916       break;
17917     }
17918     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
17919                                  MVT::i32);
17920     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
17921
17922     SDValue SetCC =
17923       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
17924                   DAG.getConstant(X86::COND_O, DL, MVT::i32),
17925                   SDValue(Sum.getNode(), 2));
17926
17927     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
17928   }
17929   }
17930
17931   // Also sets EFLAGS.
17932   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
17933   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
17934
17935   SDValue SetCC =
17936     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
17937                 DAG.getConstant(Cond, DL, MVT::i32),
17938                 SDValue(Sum.getNode(), 1));
17939
17940   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
17941 }
17942
17943 /// Returns true if the operand type is exactly twice the native width, and
17944 /// the corresponding cmpxchg8b or cmpxchg16b instruction is available.
17945 /// Used to know whether to use cmpxchg8/16b when expanding atomic operations
17946 /// (otherwise we leave them alone to become __sync_fetch_and_... calls).
17947 bool X86TargetLowering::needsCmpXchgNb(const Type *MemType) const {
17948   unsigned OpWidth = MemType->getPrimitiveSizeInBits();
17949
17950   if (OpWidth == 64)
17951     return !Subtarget->is64Bit(); // FIXME this should be Subtarget.hasCmpxchg8b
17952   else if (OpWidth == 128)
17953     return Subtarget->hasCmpxchg16b();
17954   else
17955     return false;
17956 }
17957
17958 bool X86TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
17959   return needsCmpXchgNb(SI->getValueOperand()->getType());
17960 }
17961
17962 // Note: this turns large loads into lock cmpxchg8b/16b.
17963 // FIXME: On 32 bits x86, fild/movq might be faster than lock cmpxchg8b.
17964 bool X86TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
17965   auto PTy = cast<PointerType>(LI->getPointerOperand()->getType());
17966   return needsCmpXchgNb(PTy->getElementType());
17967 }
17968
17969 TargetLoweringBase::AtomicRMWExpansionKind
17970 X86TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
17971   unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
17972   const Type *MemType = AI->getType();
17973
17974   // If the operand is too big, we must see if cmpxchg8/16b is available
17975   // and default to library calls otherwise.
17976   if (MemType->getPrimitiveSizeInBits() > NativeWidth) {
17977     return needsCmpXchgNb(MemType) ? AtomicRMWExpansionKind::CmpXChg
17978                                    : AtomicRMWExpansionKind::None;
17979   }
17980
17981   AtomicRMWInst::BinOp Op = AI->getOperation();
17982   switch (Op) {
17983   default:
17984     llvm_unreachable("Unknown atomic operation");
17985   case AtomicRMWInst::Xchg:
17986   case AtomicRMWInst::Add:
17987   case AtomicRMWInst::Sub:
17988     // It's better to use xadd, xsub or xchg for these in all cases.
17989     return AtomicRMWExpansionKind::None;
17990   case AtomicRMWInst::Or:
17991   case AtomicRMWInst::And:
17992   case AtomicRMWInst::Xor:
17993     // If the atomicrmw's result isn't actually used, we can just add a "lock"
17994     // prefix to a normal instruction for these operations.
17995     return !AI->use_empty() ? AtomicRMWExpansionKind::CmpXChg
17996                             : AtomicRMWExpansionKind::None;
17997   case AtomicRMWInst::Nand:
17998   case AtomicRMWInst::Max:
17999   case AtomicRMWInst::Min:
18000   case AtomicRMWInst::UMax:
18001   case AtomicRMWInst::UMin:
18002     // These always require a non-trivial set of data operations on x86. We must
18003     // use a cmpxchg loop.
18004     return AtomicRMWExpansionKind::CmpXChg;
18005   }
18006 }
18007
18008 static bool hasMFENCE(const X86Subtarget& Subtarget) {
18009   // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
18010   // no-sse2). There isn't any reason to disable it if the target processor
18011   // supports it.
18012   return Subtarget.hasSSE2() || Subtarget.is64Bit();
18013 }
18014
18015 LoadInst *
18016 X86TargetLowering::lowerIdempotentRMWIntoFencedLoad(AtomicRMWInst *AI) const {
18017   unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
18018   const Type *MemType = AI->getType();
18019   // Accesses larger than the native width are turned into cmpxchg/libcalls, so
18020   // there is no benefit in turning such RMWs into loads, and it is actually
18021   // harmful as it introduces a mfence.
18022   if (MemType->getPrimitiveSizeInBits() > NativeWidth)
18023     return nullptr;
18024
18025   auto Builder = IRBuilder<>(AI);
18026   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
18027   auto SynchScope = AI->getSynchScope();
18028   // We must restrict the ordering to avoid generating loads with Release or
18029   // ReleaseAcquire orderings.
18030   auto Order = AtomicCmpXchgInst::getStrongestFailureOrdering(AI->getOrdering());
18031   auto Ptr = AI->getPointerOperand();
18032
18033   // Before the load we need a fence. Here is an example lifted from
18034   // http://www.hpl.hp.com/techreports/2012/HPL-2012-68.pdf showing why a fence
18035   // is required:
18036   // Thread 0:
18037   //   x.store(1, relaxed);
18038   //   r1 = y.fetch_add(0, release);
18039   // Thread 1:
18040   //   y.fetch_add(42, acquire);
18041   //   r2 = x.load(relaxed);
18042   // r1 = r2 = 0 is impossible, but becomes possible if the idempotent rmw is
18043   // lowered to just a load without a fence. A mfence flushes the store buffer,
18044   // making the optimization clearly correct.
18045   // FIXME: it is required if isAtLeastRelease(Order) but it is not clear
18046   // otherwise, we might be able to be more agressive on relaxed idempotent
18047   // rmw. In practice, they do not look useful, so we don't try to be
18048   // especially clever.
18049   if (SynchScope == SingleThread)
18050     // FIXME: we could just insert an X86ISD::MEMBARRIER here, except we are at
18051     // the IR level, so we must wrap it in an intrinsic.
18052     return nullptr;
18053
18054   if (!hasMFENCE(*Subtarget))
18055     // FIXME: it might make sense to use a locked operation here but on a
18056     // different cache-line to prevent cache-line bouncing. In practice it
18057     // is probably a small win, and x86 processors without mfence are rare
18058     // enough that we do not bother.
18059     return nullptr;
18060
18061   Function *MFence =
18062       llvm::Intrinsic::getDeclaration(M, Intrinsic::x86_sse2_mfence);
18063   Builder.CreateCall(MFence, {});
18064
18065   // Finally we can emit the atomic load.
18066   LoadInst *Loaded = Builder.CreateAlignedLoad(Ptr,
18067           AI->getType()->getPrimitiveSizeInBits());
18068   Loaded->setAtomic(Order, SynchScope);
18069   AI->replaceAllUsesWith(Loaded);
18070   AI->eraseFromParent();
18071   return Loaded;
18072 }
18073
18074 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
18075                                  SelectionDAG &DAG) {
18076   SDLoc dl(Op);
18077   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
18078     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
18079   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
18080     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
18081
18082   // The only fence that needs an instruction is a sequentially-consistent
18083   // cross-thread fence.
18084   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
18085     if (hasMFENCE(*Subtarget))
18086       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
18087
18088     SDValue Chain = Op.getOperand(0);
18089     SDValue Zero = DAG.getConstant(0, dl, MVT::i32);
18090     SDValue Ops[] = {
18091       DAG.getRegister(X86::ESP, MVT::i32),     // Base
18092       DAG.getTargetConstant(1, dl, MVT::i8),   // Scale
18093       DAG.getRegister(0, MVT::i32),            // Index
18094       DAG.getTargetConstant(0, dl, MVT::i32),  // Disp
18095       DAG.getRegister(0, MVT::i32),            // Segment.
18096       Zero,
18097       Chain
18098     };
18099     SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
18100     return SDValue(Res, 0);
18101   }
18102
18103   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
18104   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
18105 }
18106
18107 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
18108                              SelectionDAG &DAG) {
18109   MVT T = Op.getSimpleValueType();
18110   SDLoc DL(Op);
18111   unsigned Reg = 0;
18112   unsigned size = 0;
18113   switch(T.SimpleTy) {
18114   default: llvm_unreachable("Invalid value type!");
18115   case MVT::i8:  Reg = X86::AL;  size = 1; break;
18116   case MVT::i16: Reg = X86::AX;  size = 2; break;
18117   case MVT::i32: Reg = X86::EAX; size = 4; break;
18118   case MVT::i64:
18119     assert(Subtarget->is64Bit() && "Node not type legal!");
18120     Reg = X86::RAX; size = 8;
18121     break;
18122   }
18123   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
18124                                   Op.getOperand(2), SDValue());
18125   SDValue Ops[] = { cpIn.getValue(0),
18126                     Op.getOperand(1),
18127                     Op.getOperand(3),
18128                     DAG.getTargetConstant(size, DL, MVT::i8),
18129                     cpIn.getValue(1) };
18130   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
18131   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
18132   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
18133                                            Ops, T, MMO);
18134
18135   SDValue cpOut =
18136     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
18137   SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
18138                                       MVT::i32, cpOut.getValue(2));
18139   SDValue Success = DAG.getNode(X86ISD::SETCC, DL, Op->getValueType(1),
18140                                 DAG.getConstant(X86::COND_E, DL, MVT::i8),
18141                                 EFLAGS);
18142
18143   DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), cpOut);
18144   DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
18145   DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), EFLAGS.getValue(1));
18146   return SDValue();
18147 }
18148
18149 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
18150                             SelectionDAG &DAG) {
18151   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
18152   MVT DstVT = Op.getSimpleValueType();
18153
18154   if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
18155     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
18156     if (DstVT != MVT::f64)
18157       // This conversion needs to be expanded.
18158       return SDValue();
18159
18160     SDValue InVec = Op->getOperand(0);
18161     SDLoc dl(Op);
18162     unsigned NumElts = SrcVT.getVectorNumElements();
18163     EVT SVT = SrcVT.getVectorElementType();
18164
18165     // Widen the vector in input in the case of MVT::v2i32.
18166     // Example: from MVT::v2i32 to MVT::v4i32.
18167     SmallVector<SDValue, 16> Elts;
18168     for (unsigned i = 0, e = NumElts; i != e; ++i)
18169       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
18170                                  DAG.getIntPtrConstant(i, dl)));
18171
18172     // Explicitly mark the extra elements as Undef.
18173     Elts.append(NumElts, DAG.getUNDEF(SVT));
18174
18175     EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
18176     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
18177     SDValue ToV2F64 = DAG.getBitcast(MVT::v2f64, BV);
18178     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
18179                        DAG.getIntPtrConstant(0, dl));
18180   }
18181
18182   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
18183          Subtarget->hasMMX() && "Unexpected custom BITCAST");
18184   assert((DstVT == MVT::i64 ||
18185           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
18186          "Unexpected custom BITCAST");
18187   // i64 <=> MMX conversions are Legal.
18188   if (SrcVT==MVT::i64 && DstVT.isVector())
18189     return Op;
18190   if (DstVT==MVT::i64 && SrcVT.isVector())
18191     return Op;
18192   // MMX <=> MMX conversions are Legal.
18193   if (SrcVT.isVector() && DstVT.isVector())
18194     return Op;
18195   // All other conversions need to be expanded.
18196   return SDValue();
18197 }
18198
18199 /// Compute the horizontal sum of bytes in V for the elements of VT.
18200 ///
18201 /// Requires V to be a byte vector and VT to be an integer vector type with
18202 /// wider elements than V's type. The width of the elements of VT determines
18203 /// how many bytes of V are summed horizontally to produce each element of the
18204 /// result.
18205 static SDValue LowerHorizontalByteSum(SDValue V, MVT VT,
18206                                       const X86Subtarget *Subtarget,
18207                                       SelectionDAG &DAG) {
18208   SDLoc DL(V);
18209   MVT ByteVecVT = V.getSimpleValueType();
18210   MVT EltVT = VT.getVectorElementType();
18211   int NumElts = VT.getVectorNumElements();
18212   assert(ByteVecVT.getVectorElementType() == MVT::i8 &&
18213          "Expected value to have byte element type.");
18214   assert(EltVT != MVT::i8 &&
18215          "Horizontal byte sum only makes sense for wider elements!");
18216   unsigned VecSize = VT.getSizeInBits();
18217   assert(ByteVecVT.getSizeInBits() == VecSize && "Cannot change vector size!");
18218
18219   // PSADBW instruction horizontally add all bytes and leave the result in i64
18220   // chunks, thus directly computes the pop count for v2i64 and v4i64.
18221   if (EltVT == MVT::i64) {
18222     SDValue Zeros = getZeroVector(ByteVecVT, Subtarget, DAG, DL);
18223     V = DAG.getNode(X86ISD::PSADBW, DL, ByteVecVT, V, Zeros);
18224     return DAG.getBitcast(VT, V);
18225   }
18226
18227   if (EltVT == MVT::i32) {
18228     // We unpack the low half and high half into i32s interleaved with zeros so
18229     // that we can use PSADBW to horizontally sum them. The most useful part of
18230     // this is that it lines up the results of two PSADBW instructions to be
18231     // two v2i64 vectors which concatenated are the 4 population counts. We can
18232     // then use PACKUSWB to shrink and concatenate them into a v4i32 again.
18233     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, DL);
18234     SDValue Low = DAG.getNode(X86ISD::UNPCKL, DL, VT, V, Zeros);
18235     SDValue High = DAG.getNode(X86ISD::UNPCKH, DL, VT, V, Zeros);
18236
18237     // Do the horizontal sums into two v2i64s.
18238     Zeros = getZeroVector(ByteVecVT, Subtarget, DAG, DL);
18239     Low = DAG.getNode(X86ISD::PSADBW, DL, ByteVecVT,
18240                       DAG.getBitcast(ByteVecVT, Low), Zeros);
18241     High = DAG.getNode(X86ISD::PSADBW, DL, ByteVecVT,
18242                        DAG.getBitcast(ByteVecVT, High), Zeros);
18243
18244     // Merge them together.
18245     MVT ShortVecVT = MVT::getVectorVT(MVT::i16, VecSize / 16);
18246     V = DAG.getNode(X86ISD::PACKUS, DL, ByteVecVT,
18247                     DAG.getBitcast(ShortVecVT, Low),
18248                     DAG.getBitcast(ShortVecVT, High));
18249
18250     return DAG.getBitcast(VT, V);
18251   }
18252
18253   // The only element type left is i16.
18254   assert(EltVT == MVT::i16 && "Unknown how to handle type");
18255
18256   // To obtain pop count for each i16 element starting from the pop count for
18257   // i8 elements, shift the i16s left by 8, sum as i8s, and then shift as i16s
18258   // right by 8. It is important to shift as i16s as i8 vector shift isn't
18259   // directly supported.
18260   SmallVector<SDValue, 16> Shifters(NumElts, DAG.getConstant(8, DL, EltVT));
18261   SDValue Shifter = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Shifters);
18262   SDValue Shl = DAG.getNode(ISD::SHL, DL, VT, DAG.getBitcast(VT, V), Shifter);
18263   V = DAG.getNode(ISD::ADD, DL, ByteVecVT, DAG.getBitcast(ByteVecVT, Shl),
18264                   DAG.getBitcast(ByteVecVT, V));
18265   return DAG.getNode(ISD::SRL, DL, VT, DAG.getBitcast(VT, V), Shifter);
18266 }
18267
18268 static SDValue LowerVectorCTPOPInRegLUT(SDValue Op, SDLoc DL,
18269                                         const X86Subtarget *Subtarget,
18270                                         SelectionDAG &DAG) {
18271   MVT VT = Op.getSimpleValueType();
18272   MVT EltVT = VT.getVectorElementType();
18273   unsigned VecSize = VT.getSizeInBits();
18274
18275   // Implement a lookup table in register by using an algorithm based on:
18276   // http://wm.ite.pl/articles/sse-popcount.html
18277   //
18278   // The general idea is that every lower byte nibble in the input vector is an
18279   // index into a in-register pre-computed pop count table. We then split up the
18280   // input vector in two new ones: (1) a vector with only the shifted-right
18281   // higher nibbles for each byte and (2) a vector with the lower nibbles (and
18282   // masked out higher ones) for each byte. PSHUB is used separately with both
18283   // to index the in-register table. Next, both are added and the result is a
18284   // i8 vector where each element contains the pop count for input byte.
18285   //
18286   // To obtain the pop count for elements != i8, we follow up with the same
18287   // approach and use additional tricks as described below.
18288   //
18289   const int LUT[16] = {/* 0 */ 0, /* 1 */ 1, /* 2 */ 1, /* 3 */ 2,
18290                        /* 4 */ 1, /* 5 */ 2, /* 6 */ 2, /* 7 */ 3,
18291                        /* 8 */ 1, /* 9 */ 2, /* a */ 2, /* b */ 3,
18292                        /* c */ 2, /* d */ 3, /* e */ 3, /* f */ 4};
18293
18294   int NumByteElts = VecSize / 8;
18295   MVT ByteVecVT = MVT::getVectorVT(MVT::i8, NumByteElts);
18296   SDValue In = DAG.getBitcast(ByteVecVT, Op);
18297   SmallVector<SDValue, 16> LUTVec;
18298   for (int i = 0; i < NumByteElts; ++i)
18299     LUTVec.push_back(DAG.getConstant(LUT[i % 16], DL, MVT::i8));
18300   SDValue InRegLUT = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, LUTVec);
18301   SmallVector<SDValue, 16> Mask0F(NumByteElts,
18302                                   DAG.getConstant(0x0F, DL, MVT::i8));
18303   SDValue M0F = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, Mask0F);
18304
18305   // High nibbles
18306   SmallVector<SDValue, 16> Four(NumByteElts, DAG.getConstant(4, DL, MVT::i8));
18307   SDValue FourV = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, Four);
18308   SDValue HighNibbles = DAG.getNode(ISD::SRL, DL, ByteVecVT, In, FourV);
18309
18310   // Low nibbles
18311   SDValue LowNibbles = DAG.getNode(ISD::AND, DL, ByteVecVT, In, M0F);
18312
18313   // The input vector is used as the shuffle mask that index elements into the
18314   // LUT. After counting low and high nibbles, add the vector to obtain the
18315   // final pop count per i8 element.
18316   SDValue HighPopCnt =
18317       DAG.getNode(X86ISD::PSHUFB, DL, ByteVecVT, InRegLUT, HighNibbles);
18318   SDValue LowPopCnt =
18319       DAG.getNode(X86ISD::PSHUFB, DL, ByteVecVT, InRegLUT, LowNibbles);
18320   SDValue PopCnt = DAG.getNode(ISD::ADD, DL, ByteVecVT, HighPopCnt, LowPopCnt);
18321
18322   if (EltVT == MVT::i8)
18323     return PopCnt;
18324
18325   return LowerHorizontalByteSum(PopCnt, VT, Subtarget, DAG);
18326 }
18327
18328 static SDValue LowerVectorCTPOPBitmath(SDValue Op, SDLoc DL,
18329                                        const X86Subtarget *Subtarget,
18330                                        SelectionDAG &DAG) {
18331   MVT VT = Op.getSimpleValueType();
18332   assert(VT.is128BitVector() &&
18333          "Only 128-bit vector bitmath lowering supported.");
18334
18335   int VecSize = VT.getSizeInBits();
18336   MVT EltVT = VT.getVectorElementType();
18337   int Len = EltVT.getSizeInBits();
18338
18339   // This is the vectorized version of the "best" algorithm from
18340   // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
18341   // with a minor tweak to use a series of adds + shifts instead of vector
18342   // multiplications. Implemented for all integer vector types. We only use
18343   // this when we don't have SSSE3 which allows a LUT-based lowering that is
18344   // much faster, even faster than using native popcnt instructions.
18345
18346   auto GetShift = [&](unsigned OpCode, SDValue V, int Shifter) {
18347     MVT VT = V.getSimpleValueType();
18348     SmallVector<SDValue, 32> Shifters(
18349         VT.getVectorNumElements(),
18350         DAG.getConstant(Shifter, DL, VT.getVectorElementType()));
18351     return DAG.getNode(OpCode, DL, VT, V,
18352                        DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Shifters));
18353   };
18354   auto GetMask = [&](SDValue V, APInt Mask) {
18355     MVT VT = V.getSimpleValueType();
18356     SmallVector<SDValue, 32> Masks(
18357         VT.getVectorNumElements(),
18358         DAG.getConstant(Mask, DL, VT.getVectorElementType()));
18359     return DAG.getNode(ISD::AND, DL, VT, V,
18360                        DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Masks));
18361   };
18362
18363   // We don't want to incur the implicit masks required to SRL vNi8 vectors on
18364   // x86, so set the SRL type to have elements at least i16 wide. This is
18365   // correct because all of our SRLs are followed immediately by a mask anyways
18366   // that handles any bits that sneak into the high bits of the byte elements.
18367   MVT SrlVT = Len > 8 ? VT : MVT::getVectorVT(MVT::i16, VecSize / 16);
18368
18369   SDValue V = Op;
18370
18371   // v = v - ((v >> 1) & 0x55555555...)
18372   SDValue Srl =
18373       DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 1));
18374   SDValue And = GetMask(Srl, APInt::getSplat(Len, APInt(8, 0x55)));
18375   V = DAG.getNode(ISD::SUB, DL, VT, V, And);
18376
18377   // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...)
18378   SDValue AndLHS = GetMask(V, APInt::getSplat(Len, APInt(8, 0x33)));
18379   Srl = DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 2));
18380   SDValue AndRHS = GetMask(Srl, APInt::getSplat(Len, APInt(8, 0x33)));
18381   V = DAG.getNode(ISD::ADD, DL, VT, AndLHS, AndRHS);
18382
18383   // v = (v + (v >> 4)) & 0x0F0F0F0F...
18384   Srl = DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 4));
18385   SDValue Add = DAG.getNode(ISD::ADD, DL, VT, V, Srl);
18386   V = GetMask(Add, APInt::getSplat(Len, APInt(8, 0x0F)));
18387
18388   // At this point, V contains the byte-wise population count, and we are
18389   // merely doing a horizontal sum if necessary to get the wider element
18390   // counts.
18391   if (EltVT == MVT::i8)
18392     return V;
18393
18394   return LowerHorizontalByteSum(
18395       DAG.getBitcast(MVT::getVectorVT(MVT::i8, VecSize / 8), V), VT, Subtarget,
18396       DAG);
18397 }
18398
18399 static SDValue LowerVectorCTPOP(SDValue Op, const X86Subtarget *Subtarget,
18400                                 SelectionDAG &DAG) {
18401   MVT VT = Op.getSimpleValueType();
18402   // FIXME: Need to add AVX-512 support here!
18403   assert((VT.is256BitVector() || VT.is128BitVector()) &&
18404          "Unknown CTPOP type to handle");
18405   SDLoc DL(Op.getNode());
18406   SDValue Op0 = Op.getOperand(0);
18407
18408   if (!Subtarget->hasSSSE3()) {
18409     // We can't use the fast LUT approach, so fall back on vectorized bitmath.
18410     assert(VT.is128BitVector() && "Only 128-bit vectors supported in SSE!");
18411     return LowerVectorCTPOPBitmath(Op0, DL, Subtarget, DAG);
18412   }
18413
18414   if (VT.is256BitVector() && !Subtarget->hasInt256()) {
18415     unsigned NumElems = VT.getVectorNumElements();
18416
18417     // Extract each 128-bit vector, compute pop count and concat the result.
18418     SDValue LHS = Extract128BitVector(Op0, 0, DAG, DL);
18419     SDValue RHS = Extract128BitVector(Op0, NumElems/2, DAG, DL);
18420
18421     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT,
18422                        LowerVectorCTPOPInRegLUT(LHS, DL, Subtarget, DAG),
18423                        LowerVectorCTPOPInRegLUT(RHS, DL, Subtarget, DAG));
18424   }
18425
18426   return LowerVectorCTPOPInRegLUT(Op0, DL, Subtarget, DAG);
18427 }
18428
18429 static SDValue LowerCTPOP(SDValue Op, const X86Subtarget *Subtarget,
18430                           SelectionDAG &DAG) {
18431   assert(Op.getValueType().isVector() &&
18432          "We only do custom lowering for vector population count.");
18433   return LowerVectorCTPOP(Op, Subtarget, DAG);
18434 }
18435
18436 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
18437   SDNode *Node = Op.getNode();
18438   SDLoc dl(Node);
18439   EVT T = Node->getValueType(0);
18440   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
18441                               DAG.getConstant(0, dl, T), Node->getOperand(2));
18442   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
18443                        cast<AtomicSDNode>(Node)->getMemoryVT(),
18444                        Node->getOperand(0),
18445                        Node->getOperand(1), negOp,
18446                        cast<AtomicSDNode>(Node)->getMemOperand(),
18447                        cast<AtomicSDNode>(Node)->getOrdering(),
18448                        cast<AtomicSDNode>(Node)->getSynchScope());
18449 }
18450
18451 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
18452   SDNode *Node = Op.getNode();
18453   SDLoc dl(Node);
18454   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
18455
18456   // Convert seq_cst store -> xchg
18457   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
18458   // FIXME: On 32-bit, store -> fist or movq would be more efficient
18459   //        (The only way to get a 16-byte store is cmpxchg16b)
18460   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
18461   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
18462       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
18463     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
18464                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
18465                                  Node->getOperand(0),
18466                                  Node->getOperand(1), Node->getOperand(2),
18467                                  cast<AtomicSDNode>(Node)->getMemOperand(),
18468                                  cast<AtomicSDNode>(Node)->getOrdering(),
18469                                  cast<AtomicSDNode>(Node)->getSynchScope());
18470     return Swap.getValue(1);
18471   }
18472   // Other atomic stores have a simple pattern.
18473   return Op;
18474 }
18475
18476 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
18477   EVT VT = Op.getNode()->getSimpleValueType(0);
18478
18479   // Let legalize expand this if it isn't a legal type yet.
18480   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
18481     return SDValue();
18482
18483   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
18484
18485   unsigned Opc;
18486   bool ExtraOp = false;
18487   switch (Op.getOpcode()) {
18488   default: llvm_unreachable("Invalid code");
18489   case ISD::ADDC: Opc = X86ISD::ADD; break;
18490   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
18491   case ISD::SUBC: Opc = X86ISD::SUB; break;
18492   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
18493   }
18494
18495   if (!ExtraOp)
18496     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
18497                        Op.getOperand(1));
18498   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
18499                      Op.getOperand(1), Op.getOperand(2));
18500 }
18501
18502 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
18503                             SelectionDAG &DAG) {
18504   assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
18505
18506   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
18507   // which returns the values as { float, float } (in XMM0) or
18508   // { double, double } (which is returned in XMM0, XMM1).
18509   SDLoc dl(Op);
18510   SDValue Arg = Op.getOperand(0);
18511   EVT ArgVT = Arg.getValueType();
18512   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
18513
18514   TargetLowering::ArgListTy Args;
18515   TargetLowering::ArgListEntry Entry;
18516
18517   Entry.Node = Arg;
18518   Entry.Ty = ArgTy;
18519   Entry.isSExt = false;
18520   Entry.isZExt = false;
18521   Args.push_back(Entry);
18522
18523   bool isF64 = ArgVT == MVT::f64;
18524   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
18525   // the small struct {f32, f32} is returned in (eax, edx). For f64,
18526   // the results are returned via SRet in memory.
18527   const char *LibcallName =  isF64 ? "__sincos_stret" : "__sincosf_stret";
18528   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18529   SDValue Callee =
18530       DAG.getExternalSymbol(LibcallName, TLI.getPointerTy(DAG.getDataLayout()));
18531
18532   Type *RetTy = isF64
18533     ? (Type*)StructType::get(ArgTy, ArgTy, nullptr)
18534     : (Type*)VectorType::get(ArgTy, 4);
18535
18536   TargetLowering::CallLoweringInfo CLI(DAG);
18537   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
18538     .setCallee(CallingConv::C, RetTy, Callee, std::move(Args), 0);
18539
18540   std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
18541
18542   if (isF64)
18543     // Returned in xmm0 and xmm1.
18544     return CallResult.first;
18545
18546   // Returned in bits 0:31 and 32:64 xmm0.
18547   SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
18548                                CallResult.first, DAG.getIntPtrConstant(0, dl));
18549   SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
18550                                CallResult.first, DAG.getIntPtrConstant(1, dl));
18551   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
18552   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
18553 }
18554
18555 static SDValue LowerMSCATTER(SDValue Op, const X86Subtarget *Subtarget,
18556                              SelectionDAG &DAG) {
18557   assert(Subtarget->hasAVX512() &&
18558          "MGATHER/MSCATTER are supported on AVX-512 arch only");
18559
18560   MaskedScatterSDNode *N = cast<MaskedScatterSDNode>(Op.getNode());
18561   EVT VT = N->getValue().getValueType();
18562   assert(VT.getScalarSizeInBits() >= 32 && "Unsupported scatter op");
18563   SDLoc dl(Op);
18564
18565   // X86 scatter kills mask register, so its type should be added to
18566   // the list of return values
18567   if (N->getNumValues() == 1) {
18568     SDValue Index = N->getIndex();
18569     if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
18570         !Index.getValueType().is512BitVector())
18571       Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
18572
18573     SDVTList VTs = DAG.getVTList(N->getMask().getValueType(), MVT::Other);
18574     SDValue Ops[] = { N->getOperand(0), N->getOperand(1),  N->getOperand(2),
18575                       N->getOperand(3), Index };
18576
18577     SDValue NewScatter = DAG.getMaskedScatter(VTs, VT, dl, Ops, N->getMemOperand());
18578     DAG.ReplaceAllUsesWith(Op, SDValue(NewScatter.getNode(), 1));
18579     return SDValue(NewScatter.getNode(), 0);
18580   }
18581   return Op;
18582 }
18583
18584 static SDValue LowerMGATHER(SDValue Op, const X86Subtarget *Subtarget,
18585                             SelectionDAG &DAG) {
18586   assert(Subtarget->hasAVX512() &&
18587          "MGATHER/MSCATTER are supported on AVX-512 arch only");
18588
18589   MaskedGatherSDNode *N = cast<MaskedGatherSDNode>(Op.getNode());
18590   EVT VT = Op.getValueType();
18591   assert(VT.getScalarSizeInBits() >= 32 && "Unsupported gather op");
18592   SDLoc dl(Op);
18593
18594   SDValue Index = N->getIndex();
18595   if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
18596       !Index.getValueType().is512BitVector()) {
18597     Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
18598     SDValue Ops[] = { N->getOperand(0), N->getOperand(1),  N->getOperand(2),
18599                       N->getOperand(3), Index };
18600     DAG.UpdateNodeOperands(N, Ops);
18601   }
18602   return Op;
18603 }
18604
18605 SDValue X86TargetLowering::LowerGC_TRANSITION_START(SDValue Op,
18606                                                     SelectionDAG &DAG) const {
18607   // TODO: Eventually, the lowering of these nodes should be informed by or
18608   // deferred to the GC strategy for the function in which they appear. For
18609   // now, however, they must be lowered to something. Since they are logically
18610   // no-ops in the case of a null GC strategy (or a GC strategy which does not
18611   // require special handling for these nodes), lower them as literal NOOPs for
18612   // the time being.
18613   SmallVector<SDValue, 2> Ops;
18614
18615   Ops.push_back(Op.getOperand(0));
18616   if (Op->getGluedNode())
18617     Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
18618
18619   SDLoc OpDL(Op);
18620   SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
18621   SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
18622
18623   return NOOP;
18624 }
18625
18626 SDValue X86TargetLowering::LowerGC_TRANSITION_END(SDValue Op,
18627                                                   SelectionDAG &DAG) const {
18628   // TODO: Eventually, the lowering of these nodes should be informed by or
18629   // deferred to the GC strategy for the function in which they appear. For
18630   // now, however, they must be lowered to something. Since they are logically
18631   // no-ops in the case of a null GC strategy (or a GC strategy which does not
18632   // require special handling for these nodes), lower them as literal NOOPs for
18633   // the time being.
18634   SmallVector<SDValue, 2> Ops;
18635
18636   Ops.push_back(Op.getOperand(0));
18637   if (Op->getGluedNode())
18638     Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
18639
18640   SDLoc OpDL(Op);
18641   SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
18642   SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
18643
18644   return NOOP;
18645 }
18646
18647 /// LowerOperation - Provide custom lowering hooks for some operations.
18648 ///
18649 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
18650   switch (Op.getOpcode()) {
18651   default: llvm_unreachable("Should not custom lower this!");
18652   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
18653   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
18654     return LowerCMP_SWAP(Op, Subtarget, DAG);
18655   case ISD::CTPOP:              return LowerCTPOP(Op, Subtarget, DAG);
18656   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
18657   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
18658   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
18659   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, Subtarget, DAG);
18660   case ISD::VECTOR_SHUFFLE:     return lowerVectorShuffle(Op, Subtarget, DAG);
18661   case ISD::VSELECT:            return LowerVSELECT(Op, DAG);
18662   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
18663   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
18664   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
18665   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
18666   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
18667   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
18668   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
18669   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
18670   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
18671   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
18672   case ISD::SHL_PARTS:
18673   case ISD::SRA_PARTS:
18674   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
18675   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
18676   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
18677   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
18678   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, Subtarget, DAG);
18679   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, Subtarget, DAG);
18680   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, Subtarget, DAG);
18681   case ISD::SIGN_EXTEND_VECTOR_INREG:
18682     return LowerSIGN_EXTEND_VECTOR_INREG(Op, Subtarget, DAG);
18683   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
18684   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
18685   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
18686   case ISD::LOAD:               return LowerExtendedLoad(Op, Subtarget, DAG);
18687   case ISD::FABS:
18688   case ISD::FNEG:               return LowerFABSorFNEG(Op, DAG);
18689   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
18690   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
18691   case ISD::SETCC:              return LowerSETCC(Op, DAG);
18692   case ISD::SELECT:             return LowerSELECT(Op, DAG);
18693   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
18694   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
18695   case ISD::VASTART:            return LowerVASTART(Op, DAG);
18696   case ISD::VAARG:              return LowerVAARG(Op, DAG);
18697   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
18698   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, Subtarget, DAG);
18699   case ISD::INTRINSIC_VOID:
18700   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
18701   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
18702   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
18703   case ISD::FRAME_TO_ARGS_OFFSET:
18704                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
18705   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
18706   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
18707   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
18708   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
18709   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
18710   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
18711   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
18712   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
18713   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
18714   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
18715   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
18716   case ISD::UMUL_LOHI:
18717   case ISD::SMUL_LOHI:          return LowerMUL_LOHI(Op, Subtarget, DAG);
18718   case ISD::SRA:
18719   case ISD::SRL:
18720   case ISD::SHL:                return LowerShift(Op, Subtarget, DAG);
18721   case ISD::SADDO:
18722   case ISD::UADDO:
18723   case ISD::SSUBO:
18724   case ISD::USUBO:
18725   case ISD::SMULO:
18726   case ISD::UMULO:              return LowerXALUO(Op, DAG);
18727   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
18728   case ISD::BITCAST:            return LowerBITCAST(Op, Subtarget, DAG);
18729   case ISD::ADDC:
18730   case ISD::ADDE:
18731   case ISD::SUBC:
18732   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
18733   case ISD::ADD:                return LowerADD(Op, DAG);
18734   case ISD::SUB:                return LowerSUB(Op, DAG);
18735   case ISD::FSINCOS:            return LowerFSINCOS(Op, Subtarget, DAG);
18736   case ISD::MGATHER:            return LowerMGATHER(Op, Subtarget, DAG);
18737   case ISD::MSCATTER:           return LowerMSCATTER(Op, Subtarget, DAG);
18738   case ISD::GC_TRANSITION_START:
18739                                 return LowerGC_TRANSITION_START(Op, DAG);
18740   case ISD::GC_TRANSITION_END:  return LowerGC_TRANSITION_END(Op, DAG);
18741   }
18742 }
18743
18744 /// ReplaceNodeResults - Replace a node with an illegal result type
18745 /// with a new node built out of custom code.
18746 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
18747                                            SmallVectorImpl<SDValue>&Results,
18748                                            SelectionDAG &DAG) const {
18749   SDLoc dl(N);
18750   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18751   switch (N->getOpcode()) {
18752   default:
18753     llvm_unreachable("Do not know how to custom type legalize this operation!");
18754   // We might have generated v2f32 FMIN/FMAX operations. Widen them to v4f32.
18755   case X86ISD::FMINC:
18756   case X86ISD::FMIN:
18757   case X86ISD::FMAXC:
18758   case X86ISD::FMAX: {
18759     EVT VT = N->getValueType(0);
18760     if (VT != MVT::v2f32)
18761       llvm_unreachable("Unexpected type (!= v2f32) on FMIN/FMAX.");
18762     SDValue UNDEF = DAG.getUNDEF(VT);
18763     SDValue LHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
18764                               N->getOperand(0), UNDEF);
18765     SDValue RHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
18766                               N->getOperand(1), UNDEF);
18767     Results.push_back(DAG.getNode(N->getOpcode(), dl, MVT::v4f32, LHS, RHS));
18768     return;
18769   }
18770   case ISD::SIGN_EXTEND_INREG:
18771   case ISD::ADDC:
18772   case ISD::ADDE:
18773   case ISD::SUBC:
18774   case ISD::SUBE:
18775     // We don't want to expand or promote these.
18776     return;
18777   case ISD::SDIV:
18778   case ISD::UDIV:
18779   case ISD::SREM:
18780   case ISD::UREM:
18781   case ISD::SDIVREM:
18782   case ISD::UDIVREM: {
18783     SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
18784     Results.push_back(V);
18785     return;
18786   }
18787   case ISD::FP_TO_SINT:
18788     // FP_TO_INT*_IN_MEM is not legal for f16 inputs.  Do not convert
18789     // (FP_TO_SINT (load f16)) to FP_TO_INT*.
18790     if (N->getOperand(0).getValueType() == MVT::f16)
18791       break;
18792     // fallthrough
18793   case ISD::FP_TO_UINT: {
18794     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
18795
18796     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
18797       return;
18798
18799     std::pair<SDValue,SDValue> Vals =
18800         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
18801     SDValue FIST = Vals.first, StackSlot = Vals.second;
18802     if (FIST.getNode()) {
18803       EVT VT = N->getValueType(0);
18804       // Return a load from the stack slot.
18805       if (StackSlot.getNode())
18806         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
18807                                       MachinePointerInfo(),
18808                                       false, false, false, 0));
18809       else
18810         Results.push_back(FIST);
18811     }
18812     return;
18813   }
18814   case ISD::UINT_TO_FP: {
18815     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
18816     if (N->getOperand(0).getValueType() != MVT::v2i32 ||
18817         N->getValueType(0) != MVT::v2f32)
18818       return;
18819     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
18820                                  N->getOperand(0));
18821     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
18822                                      MVT::f64);
18823     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
18824     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
18825                              DAG.getBitcast(MVT::v2i64, VBias));
18826     Or = DAG.getBitcast(MVT::v2f64, Or);
18827     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
18828     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
18829     return;
18830   }
18831   case ISD::FP_ROUND: {
18832     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
18833         return;
18834     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
18835     Results.push_back(V);
18836     return;
18837   }
18838   case ISD::FP_EXTEND: {
18839     // Right now, only MVT::v2f32 has OperationAction for FP_EXTEND.
18840     // No other ValueType for FP_EXTEND should reach this point.
18841     assert(N->getValueType(0) == MVT::v2f32 &&
18842            "Do not know how to legalize this Node");
18843     return;
18844   }
18845   case ISD::INTRINSIC_W_CHAIN: {
18846     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
18847     switch (IntNo) {
18848     default : llvm_unreachable("Do not know how to custom type "
18849                                "legalize this intrinsic operation!");
18850     case Intrinsic::x86_rdtsc:
18851       return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
18852                                      Results);
18853     case Intrinsic::x86_rdtscp:
18854       return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
18855                                      Results);
18856     case Intrinsic::x86_rdpmc:
18857       return getReadPerformanceCounter(N, dl, DAG, Subtarget, Results);
18858     }
18859   }
18860   case ISD::READCYCLECOUNTER: {
18861     return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
18862                                    Results);
18863   }
18864   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
18865     EVT T = N->getValueType(0);
18866     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
18867     bool Regs64bit = T == MVT::i128;
18868     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
18869     SDValue cpInL, cpInH;
18870     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
18871                         DAG.getConstant(0, dl, HalfT));
18872     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
18873                         DAG.getConstant(1, dl, HalfT));
18874     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
18875                              Regs64bit ? X86::RAX : X86::EAX,
18876                              cpInL, SDValue());
18877     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
18878                              Regs64bit ? X86::RDX : X86::EDX,
18879                              cpInH, cpInL.getValue(1));
18880     SDValue swapInL, swapInH;
18881     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
18882                           DAG.getConstant(0, dl, HalfT));
18883     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
18884                           DAG.getConstant(1, dl, HalfT));
18885     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
18886                                Regs64bit ? X86::RBX : X86::EBX,
18887                                swapInL, cpInH.getValue(1));
18888     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
18889                                Regs64bit ? X86::RCX : X86::ECX,
18890                                swapInH, swapInL.getValue(1));
18891     SDValue Ops[] = { swapInH.getValue(0),
18892                       N->getOperand(1),
18893                       swapInH.getValue(1) };
18894     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
18895     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
18896     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
18897                                   X86ISD::LCMPXCHG8_DAG;
18898     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
18899     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
18900                                         Regs64bit ? X86::RAX : X86::EAX,
18901                                         HalfT, Result.getValue(1));
18902     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
18903                                         Regs64bit ? X86::RDX : X86::EDX,
18904                                         HalfT, cpOutL.getValue(2));
18905     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
18906
18907     SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
18908                                         MVT::i32, cpOutH.getValue(2));
18909     SDValue Success =
18910         DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
18911                     DAG.getConstant(X86::COND_E, dl, MVT::i8), EFLAGS);
18912     Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
18913
18914     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
18915     Results.push_back(Success);
18916     Results.push_back(EFLAGS.getValue(1));
18917     return;
18918   }
18919   case ISD::ATOMIC_SWAP:
18920   case ISD::ATOMIC_LOAD_ADD:
18921   case ISD::ATOMIC_LOAD_SUB:
18922   case ISD::ATOMIC_LOAD_AND:
18923   case ISD::ATOMIC_LOAD_OR:
18924   case ISD::ATOMIC_LOAD_XOR:
18925   case ISD::ATOMIC_LOAD_NAND:
18926   case ISD::ATOMIC_LOAD_MIN:
18927   case ISD::ATOMIC_LOAD_MAX:
18928   case ISD::ATOMIC_LOAD_UMIN:
18929   case ISD::ATOMIC_LOAD_UMAX:
18930   case ISD::ATOMIC_LOAD: {
18931     // Delegate to generic TypeLegalization. Situations we can really handle
18932     // should have already been dealt with by AtomicExpandPass.cpp.
18933     break;
18934   }
18935   case ISD::BITCAST: {
18936     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
18937     EVT DstVT = N->getValueType(0);
18938     EVT SrcVT = N->getOperand(0)->getValueType(0);
18939
18940     if (SrcVT != MVT::f64 ||
18941         (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
18942       return;
18943
18944     unsigned NumElts = DstVT.getVectorNumElements();
18945     EVT SVT = DstVT.getVectorElementType();
18946     EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
18947     SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
18948                                    MVT::v2f64, N->getOperand(0));
18949     SDValue ToVecInt = DAG.getBitcast(WiderVT, Expanded);
18950
18951     if (ExperimentalVectorWideningLegalization) {
18952       // If we are legalizing vectors by widening, we already have the desired
18953       // legal vector type, just return it.
18954       Results.push_back(ToVecInt);
18955       return;
18956     }
18957
18958     SmallVector<SDValue, 8> Elts;
18959     for (unsigned i = 0, e = NumElts; i != e; ++i)
18960       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
18961                                    ToVecInt, DAG.getIntPtrConstant(i, dl)));
18962
18963     Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
18964   }
18965   }
18966 }
18967
18968 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
18969   switch ((X86ISD::NodeType)Opcode) {
18970   case X86ISD::FIRST_NUMBER:       break;
18971   case X86ISD::BSF:                return "X86ISD::BSF";
18972   case X86ISD::BSR:                return "X86ISD::BSR";
18973   case X86ISD::SHLD:               return "X86ISD::SHLD";
18974   case X86ISD::SHRD:               return "X86ISD::SHRD";
18975   case X86ISD::FAND:               return "X86ISD::FAND";
18976   case X86ISD::FANDN:              return "X86ISD::FANDN";
18977   case X86ISD::FOR:                return "X86ISD::FOR";
18978   case X86ISD::FXOR:               return "X86ISD::FXOR";
18979   case X86ISD::FILD:               return "X86ISD::FILD";
18980   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
18981   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
18982   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
18983   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
18984   case X86ISD::FLD:                return "X86ISD::FLD";
18985   case X86ISD::FST:                return "X86ISD::FST";
18986   case X86ISD::CALL:               return "X86ISD::CALL";
18987   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
18988   case X86ISD::RDTSCP_DAG:         return "X86ISD::RDTSCP_DAG";
18989   case X86ISD::RDPMC_DAG:          return "X86ISD::RDPMC_DAG";
18990   case X86ISD::BT:                 return "X86ISD::BT";
18991   case X86ISD::CMP:                return "X86ISD::CMP";
18992   case X86ISD::COMI:               return "X86ISD::COMI";
18993   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
18994   case X86ISD::CMPM:               return "X86ISD::CMPM";
18995   case X86ISD::CMPMU:              return "X86ISD::CMPMU";
18996   case X86ISD::CMPM_RND:           return "X86ISD::CMPM_RND";
18997   case X86ISD::SETCC:              return "X86ISD::SETCC";
18998   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
18999   case X86ISD::FSETCC:             return "X86ISD::FSETCC";
19000   case X86ISD::FGETSIGNx86:        return "X86ISD::FGETSIGNx86";
19001   case X86ISD::CMOV:               return "X86ISD::CMOV";
19002   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
19003   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
19004   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
19005   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
19006   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
19007   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
19008   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
19009   case X86ISD::MOVDQ2Q:            return "X86ISD::MOVDQ2Q";
19010   case X86ISD::MMX_MOVD2W:         return "X86ISD::MMX_MOVD2W";
19011   case X86ISD::MMX_MOVW2D:         return "X86ISD::MMX_MOVW2D";
19012   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
19013   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
19014   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
19015   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
19016   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
19017   case X86ISD::MMX_PINSRW:         return "X86ISD::MMX_PINSRW";
19018   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
19019   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
19020   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
19021   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
19022   case X86ISD::SHRUNKBLEND:        return "X86ISD::SHRUNKBLEND";
19023   case X86ISD::ADDUS:              return "X86ISD::ADDUS";
19024   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
19025   case X86ISD::HADD:               return "X86ISD::HADD";
19026   case X86ISD::HSUB:               return "X86ISD::HSUB";
19027   case X86ISD::FHADD:              return "X86ISD::FHADD";
19028   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
19029   case X86ISD::ABS:                return "X86ISD::ABS";
19030   case X86ISD::FMAX:               return "X86ISD::FMAX";
19031   case X86ISD::FMAX_RND:           return "X86ISD::FMAX_RND";
19032   case X86ISD::FMIN:               return "X86ISD::FMIN";
19033   case X86ISD::FMIN_RND:           return "X86ISD::FMIN_RND";
19034   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
19035   case X86ISD::FMINC:              return "X86ISD::FMINC";
19036   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
19037   case X86ISD::FRCP:               return "X86ISD::FRCP";
19038   case X86ISD::EXTRQI:             return "X86ISD::EXTRQI";
19039   case X86ISD::INSERTQI:           return "X86ISD::INSERTQI";
19040   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
19041   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
19042   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
19043   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
19044   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
19045   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
19046   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
19047   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
19048   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
19049   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
19050   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
19051   case X86ISD::LCMPXCHG16_DAG:     return "X86ISD::LCMPXCHG16_DAG";
19052   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
19053   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
19054   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
19055   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
19056   case X86ISD::VTRUNC:             return "X86ISD::VTRUNC";
19057   case X86ISD::VTRUNCS:            return "X86ISD::VTRUNCS";
19058   case X86ISD::VTRUNCUS:           return "X86ISD::VTRUNCUS";
19059   case X86ISD::VINSERT:            return "X86ISD::VINSERT";
19060   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
19061   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
19062   case X86ISD::CVTDQ2PD:           return "X86ISD::CVTDQ2PD";
19063   case X86ISD::CVTUDQ2PD:          return "X86ISD::CVTUDQ2PD";
19064   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
19065   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
19066   case X86ISD::VSHL:               return "X86ISD::VSHL";
19067   case X86ISD::VSRL:               return "X86ISD::VSRL";
19068   case X86ISD::VSRA:               return "X86ISD::VSRA";
19069   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
19070   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
19071   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
19072   case X86ISD::CMPP:               return "X86ISD::CMPP";
19073   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
19074   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
19075   case X86ISD::PCMPEQM:            return "X86ISD::PCMPEQM";
19076   case X86ISD::PCMPGTM:            return "X86ISD::PCMPGTM";
19077   case X86ISD::ADD:                return "X86ISD::ADD";
19078   case X86ISD::SUB:                return "X86ISD::SUB";
19079   case X86ISD::ADC:                return "X86ISD::ADC";
19080   case X86ISD::SBB:                return "X86ISD::SBB";
19081   case X86ISD::SMUL:               return "X86ISD::SMUL";
19082   case X86ISD::UMUL:               return "X86ISD::UMUL";
19083   case X86ISD::SMUL8:              return "X86ISD::SMUL8";
19084   case X86ISD::UMUL8:              return "X86ISD::UMUL8";
19085   case X86ISD::SDIVREM8_SEXT_HREG: return "X86ISD::SDIVREM8_SEXT_HREG";
19086   case X86ISD::UDIVREM8_ZEXT_HREG: return "X86ISD::UDIVREM8_ZEXT_HREG";
19087   case X86ISD::INC:                return "X86ISD::INC";
19088   case X86ISD::DEC:                return "X86ISD::DEC";
19089   case X86ISD::OR:                 return "X86ISD::OR";
19090   case X86ISD::XOR:                return "X86ISD::XOR";
19091   case X86ISD::AND:                return "X86ISD::AND";
19092   case X86ISD::BEXTR:              return "X86ISD::BEXTR";
19093   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
19094   case X86ISD::PTEST:              return "X86ISD::PTEST";
19095   case X86ISD::TESTP:              return "X86ISD::TESTP";
19096   case X86ISD::TESTM:              return "X86ISD::TESTM";
19097   case X86ISD::TESTNM:             return "X86ISD::TESTNM";
19098   case X86ISD::KORTEST:            return "X86ISD::KORTEST";
19099   case X86ISD::PACKSS:             return "X86ISD::PACKSS";
19100   case X86ISD::PACKUS:             return "X86ISD::PACKUS";
19101   case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
19102   case X86ISD::VALIGN:             return "X86ISD::VALIGN";
19103   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
19104   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
19105   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
19106   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
19107   case X86ISD::SHUF128:            return "X86ISD::SHUF128";
19108   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
19109   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
19110   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
19111   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
19112   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
19113   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
19114   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
19115   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
19116   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
19117   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
19118   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
19119   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
19120   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
19121   case X86ISD::SUBV_BROADCAST:     return "X86ISD::SUBV_BROADCAST";
19122   case X86ISD::VEXTRACT:           return "X86ISD::VEXTRACT";
19123   case X86ISD::VPERMILPV:          return "X86ISD::VPERMILPV";
19124   case X86ISD::VPERMILPI:          return "X86ISD::VPERMILPI";
19125   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
19126   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
19127   case X86ISD::VPERMV3:            return "X86ISD::VPERMV3";
19128   case X86ISD::VPERMIV3:           return "X86ISD::VPERMIV3";
19129   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
19130   case X86ISD::VFIXUPIMM:          return "X86ISD::VFIXUPIMM";
19131   case X86ISD::VRANGE:             return "X86ISD::VRANGE";
19132   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
19133   case X86ISD::PMULDQ:             return "X86ISD::PMULDQ";
19134   case X86ISD::PSADBW:             return "X86ISD::PSADBW";
19135   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
19136   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
19137   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
19138   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
19139   case X86ISD::MFENCE:             return "X86ISD::MFENCE";
19140   case X86ISD::SFENCE:             return "X86ISD::SFENCE";
19141   case X86ISD::LFENCE:             return "X86ISD::LFENCE";
19142   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
19143   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
19144   case X86ISD::SAHF:               return "X86ISD::SAHF";
19145   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
19146   case X86ISD::RDSEED:             return "X86ISD::RDSEED";
19147   case X86ISD::VPMADDUBSW:         return "X86ISD::VPMADDUBSW";
19148   case X86ISD::VPMADDWD:           return "X86ISD::VPMADDWD";
19149   case X86ISD::FMADD:              return "X86ISD::FMADD";
19150   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
19151   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
19152   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
19153   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
19154   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
19155   case X86ISD::FMADD_RND:          return "X86ISD::FMADD_RND";
19156   case X86ISD::FNMADD_RND:         return "X86ISD::FNMADD_RND";
19157   case X86ISD::FMSUB_RND:          return "X86ISD::FMSUB_RND";
19158   case X86ISD::FNMSUB_RND:         return "X86ISD::FNMSUB_RND";
19159   case X86ISD::FMADDSUB_RND:       return "X86ISD::FMADDSUB_RND";
19160   case X86ISD::FMSUBADD_RND:       return "X86ISD::FMSUBADD_RND";
19161   case X86ISD::VRNDSCALE:          return "X86ISD::VRNDSCALE";
19162   case X86ISD::VREDUCE:            return "X86ISD::VREDUCE";
19163   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
19164   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
19165   case X86ISD::XTEST:              return "X86ISD::XTEST";
19166   case X86ISD::COMPRESS:           return "X86ISD::COMPRESS";
19167   case X86ISD::EXPAND:             return "X86ISD::EXPAND";
19168   case X86ISD::SELECT:             return "X86ISD::SELECT";
19169   case X86ISD::ADDSUB:             return "X86ISD::ADDSUB";
19170   case X86ISD::RCP28:              return "X86ISD::RCP28";
19171   case X86ISD::EXP2:               return "X86ISD::EXP2";
19172   case X86ISD::RSQRT28:            return "X86ISD::RSQRT28";
19173   case X86ISD::FADD_RND:           return "X86ISD::FADD_RND";
19174   case X86ISD::FSUB_RND:           return "X86ISD::FSUB_RND";
19175   case X86ISD::FMUL_RND:           return "X86ISD::FMUL_RND";
19176   case X86ISD::FDIV_RND:           return "X86ISD::FDIV_RND";
19177   case X86ISD::FSQRT_RND:          return "X86ISD::FSQRT_RND";
19178   case X86ISD::FGETEXP_RND:        return "X86ISD::FGETEXP_RND";
19179   case X86ISD::SCALEF:             return "X86ISD::SCALEF";
19180   case X86ISD::ADDS:               return "X86ISD::ADDS";
19181   case X86ISD::SUBS:               return "X86ISD::SUBS";
19182   case X86ISD::AVG:                return "X86ISD::AVG";
19183   case X86ISD::MULHRS:             return "X86ISD::MULHRS";
19184   case X86ISD::SINT_TO_FP_RND:     return "X86ISD::SINT_TO_FP_RND";
19185   case X86ISD::UINT_TO_FP_RND:     return "X86ISD::UINT_TO_FP_RND";
19186   case X86ISD::FP_TO_SINT_RND:     return "X86ISD::FP_TO_SINT_RND";
19187   case X86ISD::FP_TO_UINT_RND:     return "X86ISD::FP_TO_UINT_RND";
19188   }
19189   return nullptr;
19190 }
19191
19192 // isLegalAddressingMode - Return true if the addressing mode represented
19193 // by AM is legal for this target, for a load/store of the specified type.
19194 bool X86TargetLowering::isLegalAddressingMode(const DataLayout &DL,
19195                                               const AddrMode &AM, Type *Ty,
19196                                               unsigned AS) const {
19197   // X86 supports extremely general addressing modes.
19198   CodeModel::Model M = getTargetMachine().getCodeModel();
19199   Reloc::Model R = getTargetMachine().getRelocationModel();
19200
19201   // X86 allows a sign-extended 32-bit immediate field as a displacement.
19202   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
19203     return false;
19204
19205   if (AM.BaseGV) {
19206     unsigned GVFlags =
19207       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
19208
19209     // If a reference to this global requires an extra load, we can't fold it.
19210     if (isGlobalStubReference(GVFlags))
19211       return false;
19212
19213     // If BaseGV requires a register for the PIC base, we cannot also have a
19214     // BaseReg specified.
19215     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
19216       return false;
19217
19218     // If lower 4G is not available, then we must use rip-relative addressing.
19219     if ((M != CodeModel::Small || R != Reloc::Static) &&
19220         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
19221       return false;
19222   }
19223
19224   switch (AM.Scale) {
19225   case 0:
19226   case 1:
19227   case 2:
19228   case 4:
19229   case 8:
19230     // These scales always work.
19231     break;
19232   case 3:
19233   case 5:
19234   case 9:
19235     // These scales are formed with basereg+scalereg.  Only accept if there is
19236     // no basereg yet.
19237     if (AM.HasBaseReg)
19238       return false;
19239     break;
19240   default:  // Other stuff never works.
19241     return false;
19242   }
19243
19244   return true;
19245 }
19246
19247 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
19248   unsigned Bits = Ty->getScalarSizeInBits();
19249
19250   // 8-bit shifts are always expensive, but versions with a scalar amount aren't
19251   // particularly cheaper than those without.
19252   if (Bits == 8)
19253     return false;
19254
19255   // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
19256   // variable shifts just as cheap as scalar ones.
19257   if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
19258     return false;
19259
19260   // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
19261   // fully general vector.
19262   return true;
19263 }
19264
19265 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
19266   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
19267     return false;
19268   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
19269   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
19270   return NumBits1 > NumBits2;
19271 }
19272
19273 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
19274   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
19275     return false;
19276
19277   if (!isTypeLegal(EVT::getEVT(Ty1)))
19278     return false;
19279
19280   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
19281
19282   // Assuming the caller doesn't have a zeroext or signext return parameter,
19283   // truncation all the way down to i1 is valid.
19284   return true;
19285 }
19286
19287 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
19288   return isInt<32>(Imm);
19289 }
19290
19291 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
19292   // Can also use sub to handle negated immediates.
19293   return isInt<32>(Imm);
19294 }
19295
19296 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
19297   if (!VT1.isInteger() || !VT2.isInteger())
19298     return false;
19299   unsigned NumBits1 = VT1.getSizeInBits();
19300   unsigned NumBits2 = VT2.getSizeInBits();
19301   return NumBits1 > NumBits2;
19302 }
19303
19304 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
19305   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
19306   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
19307 }
19308
19309 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
19310   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
19311   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
19312 }
19313
19314 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
19315   EVT VT1 = Val.getValueType();
19316   if (isZExtFree(VT1, VT2))
19317     return true;
19318
19319   if (Val.getOpcode() != ISD::LOAD)
19320     return false;
19321
19322   if (!VT1.isSimple() || !VT1.isInteger() ||
19323       !VT2.isSimple() || !VT2.isInteger())
19324     return false;
19325
19326   switch (VT1.getSimpleVT().SimpleTy) {
19327   default: break;
19328   case MVT::i8:
19329   case MVT::i16:
19330   case MVT::i32:
19331     // X86 has 8, 16, and 32-bit zero-extending loads.
19332     return true;
19333   }
19334
19335   return false;
19336 }
19337
19338 bool X86TargetLowering::isVectorLoadExtDesirable(SDValue) const { return true; }
19339
19340 bool
19341 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
19342   if (!(Subtarget->hasFMA() || Subtarget->hasFMA4() || Subtarget->hasAVX512()))
19343     return false;
19344
19345   VT = VT.getScalarType();
19346
19347   if (!VT.isSimple())
19348     return false;
19349
19350   switch (VT.getSimpleVT().SimpleTy) {
19351   case MVT::f32:
19352   case MVT::f64:
19353     return true;
19354   default:
19355     break;
19356   }
19357
19358   return false;
19359 }
19360
19361 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
19362   // i16 instructions are longer (0x66 prefix) and potentially slower.
19363   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
19364 }
19365
19366 /// isShuffleMaskLegal - Targets can use this to indicate that they only
19367 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
19368 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
19369 /// are assumed to be legal.
19370 bool
19371 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
19372                                       EVT VT) const {
19373   if (!VT.isSimple())
19374     return false;
19375
19376   // Not for i1 vectors
19377   if (VT.getScalarType() == MVT::i1)
19378     return false;
19379
19380   // Very little shuffling can be done for 64-bit vectors right now.
19381   if (VT.getSizeInBits() == 64)
19382     return false;
19383
19384   // We only care that the types being shuffled are legal. The lowering can
19385   // handle any possible shuffle mask that results.
19386   return isTypeLegal(VT.getSimpleVT());
19387 }
19388
19389 bool
19390 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
19391                                           EVT VT) const {
19392   // Just delegate to the generic legality, clear masks aren't special.
19393   return isShuffleMaskLegal(Mask, VT);
19394 }
19395
19396 //===----------------------------------------------------------------------===//
19397 //                           X86 Scheduler Hooks
19398 //===----------------------------------------------------------------------===//
19399
19400 /// Utility function to emit xbegin specifying the start of an RTM region.
19401 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
19402                                      const TargetInstrInfo *TII) {
19403   DebugLoc DL = MI->getDebugLoc();
19404
19405   const BasicBlock *BB = MBB->getBasicBlock();
19406   MachineFunction::iterator I = MBB;
19407   ++I;
19408
19409   // For the v = xbegin(), we generate
19410   //
19411   // thisMBB:
19412   //  xbegin sinkMBB
19413   //
19414   // mainMBB:
19415   //  eax = -1
19416   //
19417   // sinkMBB:
19418   //  v = eax
19419
19420   MachineBasicBlock *thisMBB = MBB;
19421   MachineFunction *MF = MBB->getParent();
19422   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
19423   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
19424   MF->insert(I, mainMBB);
19425   MF->insert(I, sinkMBB);
19426
19427   // Transfer the remainder of BB and its successor edges to sinkMBB.
19428   sinkMBB->splice(sinkMBB->begin(), MBB,
19429                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
19430   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
19431
19432   // thisMBB:
19433   //  xbegin sinkMBB
19434   //  # fallthrough to mainMBB
19435   //  # abortion to sinkMBB
19436   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
19437   thisMBB->addSuccessor(mainMBB);
19438   thisMBB->addSuccessor(sinkMBB);
19439
19440   // mainMBB:
19441   //  EAX = -1
19442   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
19443   mainMBB->addSuccessor(sinkMBB);
19444
19445   // sinkMBB:
19446   // EAX is live into the sinkMBB
19447   sinkMBB->addLiveIn(X86::EAX);
19448   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
19449           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
19450     .addReg(X86::EAX);
19451
19452   MI->eraseFromParent();
19453   return sinkMBB;
19454 }
19455
19456 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
19457 // or XMM0_V32I8 in AVX all of this code can be replaced with that
19458 // in the .td file.
19459 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
19460                                        const TargetInstrInfo *TII) {
19461   unsigned Opc;
19462   switch (MI->getOpcode()) {
19463   default: llvm_unreachable("illegal opcode!");
19464   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
19465   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
19466   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
19467   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
19468   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
19469   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
19470   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
19471   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
19472   }
19473
19474   DebugLoc dl = MI->getDebugLoc();
19475   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
19476
19477   unsigned NumArgs = MI->getNumOperands();
19478   for (unsigned i = 1; i < NumArgs; ++i) {
19479     MachineOperand &Op = MI->getOperand(i);
19480     if (!(Op.isReg() && Op.isImplicit()))
19481       MIB.addOperand(Op);
19482   }
19483   if (MI->hasOneMemOperand())
19484     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
19485
19486   BuildMI(*BB, MI, dl,
19487     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
19488     .addReg(X86::XMM0);
19489
19490   MI->eraseFromParent();
19491   return BB;
19492 }
19493
19494 // FIXME: Custom handling because TableGen doesn't support multiple implicit
19495 // defs in an instruction pattern
19496 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
19497                                        const TargetInstrInfo *TII) {
19498   unsigned Opc;
19499   switch (MI->getOpcode()) {
19500   default: llvm_unreachable("illegal opcode!");
19501   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
19502   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
19503   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
19504   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
19505   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
19506   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
19507   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
19508   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
19509   }
19510
19511   DebugLoc dl = MI->getDebugLoc();
19512   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
19513
19514   unsigned NumArgs = MI->getNumOperands(); // remove the results
19515   for (unsigned i = 1; i < NumArgs; ++i) {
19516     MachineOperand &Op = MI->getOperand(i);
19517     if (!(Op.isReg() && Op.isImplicit()))
19518       MIB.addOperand(Op);
19519   }
19520   if (MI->hasOneMemOperand())
19521     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
19522
19523   BuildMI(*BB, MI, dl,
19524     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
19525     .addReg(X86::ECX);
19526
19527   MI->eraseFromParent();
19528   return BB;
19529 }
19530
19531 static MachineBasicBlock *EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
19532                                       const X86Subtarget *Subtarget) {
19533   DebugLoc dl = MI->getDebugLoc();
19534   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19535   // Address into RAX/EAX, other two args into ECX, EDX.
19536   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
19537   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
19538   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
19539   for (int i = 0; i < X86::AddrNumOperands; ++i)
19540     MIB.addOperand(MI->getOperand(i));
19541
19542   unsigned ValOps = X86::AddrNumOperands;
19543   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
19544     .addReg(MI->getOperand(ValOps).getReg());
19545   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
19546     .addReg(MI->getOperand(ValOps+1).getReg());
19547
19548   // The instruction doesn't actually take any operands though.
19549   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
19550
19551   MI->eraseFromParent(); // The pseudo is gone now.
19552   return BB;
19553 }
19554
19555 MachineBasicBlock *
19556 X86TargetLowering::EmitVAARG64WithCustomInserter(MachineInstr *MI,
19557                                                  MachineBasicBlock *MBB) const {
19558   // Emit va_arg instruction on X86-64.
19559
19560   // Operands to this pseudo-instruction:
19561   // 0  ) Output        : destination address (reg)
19562   // 1-5) Input         : va_list address (addr, i64mem)
19563   // 6  ) ArgSize       : Size (in bytes) of vararg type
19564   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
19565   // 8  ) Align         : Alignment of type
19566   // 9  ) EFLAGS (implicit-def)
19567
19568   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
19569   static_assert(X86::AddrNumOperands == 5,
19570                 "VAARG_64 assumes 5 address operands");
19571
19572   unsigned DestReg = MI->getOperand(0).getReg();
19573   MachineOperand &Base = MI->getOperand(1);
19574   MachineOperand &Scale = MI->getOperand(2);
19575   MachineOperand &Index = MI->getOperand(3);
19576   MachineOperand &Disp = MI->getOperand(4);
19577   MachineOperand &Segment = MI->getOperand(5);
19578   unsigned ArgSize = MI->getOperand(6).getImm();
19579   unsigned ArgMode = MI->getOperand(7).getImm();
19580   unsigned Align = MI->getOperand(8).getImm();
19581
19582   // Memory Reference
19583   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
19584   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
19585   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
19586
19587   // Machine Information
19588   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19589   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
19590   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
19591   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
19592   DebugLoc DL = MI->getDebugLoc();
19593
19594   // struct va_list {
19595   //   i32   gp_offset
19596   //   i32   fp_offset
19597   //   i64   overflow_area (address)
19598   //   i64   reg_save_area (address)
19599   // }
19600   // sizeof(va_list) = 24
19601   // alignment(va_list) = 8
19602
19603   unsigned TotalNumIntRegs = 6;
19604   unsigned TotalNumXMMRegs = 8;
19605   bool UseGPOffset = (ArgMode == 1);
19606   bool UseFPOffset = (ArgMode == 2);
19607   unsigned MaxOffset = TotalNumIntRegs * 8 +
19608                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
19609
19610   /* Align ArgSize to a multiple of 8 */
19611   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
19612   bool NeedsAlign = (Align > 8);
19613
19614   MachineBasicBlock *thisMBB = MBB;
19615   MachineBasicBlock *overflowMBB;
19616   MachineBasicBlock *offsetMBB;
19617   MachineBasicBlock *endMBB;
19618
19619   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
19620   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
19621   unsigned OffsetReg = 0;
19622
19623   if (!UseGPOffset && !UseFPOffset) {
19624     // If we only pull from the overflow region, we don't create a branch.
19625     // We don't need to alter control flow.
19626     OffsetDestReg = 0; // unused
19627     OverflowDestReg = DestReg;
19628
19629     offsetMBB = nullptr;
19630     overflowMBB = thisMBB;
19631     endMBB = thisMBB;
19632   } else {
19633     // First emit code to check if gp_offset (or fp_offset) is below the bound.
19634     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
19635     // If not, pull from overflow_area. (branch to overflowMBB)
19636     //
19637     //       thisMBB
19638     //         |     .
19639     //         |        .
19640     //     offsetMBB   overflowMBB
19641     //         |        .
19642     //         |     .
19643     //        endMBB
19644
19645     // Registers for the PHI in endMBB
19646     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
19647     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
19648
19649     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
19650     MachineFunction *MF = MBB->getParent();
19651     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
19652     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
19653     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
19654
19655     MachineFunction::iterator MBBIter = MBB;
19656     ++MBBIter;
19657
19658     // Insert the new basic blocks
19659     MF->insert(MBBIter, offsetMBB);
19660     MF->insert(MBBIter, overflowMBB);
19661     MF->insert(MBBIter, endMBB);
19662
19663     // Transfer the remainder of MBB and its successor edges to endMBB.
19664     endMBB->splice(endMBB->begin(), thisMBB,
19665                    std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
19666     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
19667
19668     // Make offsetMBB and overflowMBB successors of thisMBB
19669     thisMBB->addSuccessor(offsetMBB);
19670     thisMBB->addSuccessor(overflowMBB);
19671
19672     // endMBB is a successor of both offsetMBB and overflowMBB
19673     offsetMBB->addSuccessor(endMBB);
19674     overflowMBB->addSuccessor(endMBB);
19675
19676     // Load the offset value into a register
19677     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
19678     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
19679       .addOperand(Base)
19680       .addOperand(Scale)
19681       .addOperand(Index)
19682       .addDisp(Disp, UseFPOffset ? 4 : 0)
19683       .addOperand(Segment)
19684       .setMemRefs(MMOBegin, MMOEnd);
19685
19686     // Check if there is enough room left to pull this argument.
19687     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
19688       .addReg(OffsetReg)
19689       .addImm(MaxOffset + 8 - ArgSizeA8);
19690
19691     // Branch to "overflowMBB" if offset >= max
19692     // Fall through to "offsetMBB" otherwise
19693     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
19694       .addMBB(overflowMBB);
19695   }
19696
19697   // In offsetMBB, emit code to use the reg_save_area.
19698   if (offsetMBB) {
19699     assert(OffsetReg != 0);
19700
19701     // Read the reg_save_area address.
19702     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
19703     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
19704       .addOperand(Base)
19705       .addOperand(Scale)
19706       .addOperand(Index)
19707       .addDisp(Disp, 16)
19708       .addOperand(Segment)
19709       .setMemRefs(MMOBegin, MMOEnd);
19710
19711     // Zero-extend the offset
19712     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
19713       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
19714         .addImm(0)
19715         .addReg(OffsetReg)
19716         .addImm(X86::sub_32bit);
19717
19718     // Add the offset to the reg_save_area to get the final address.
19719     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
19720       .addReg(OffsetReg64)
19721       .addReg(RegSaveReg);
19722
19723     // Compute the offset for the next argument
19724     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
19725     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
19726       .addReg(OffsetReg)
19727       .addImm(UseFPOffset ? 16 : 8);
19728
19729     // Store it back into the va_list.
19730     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
19731       .addOperand(Base)
19732       .addOperand(Scale)
19733       .addOperand(Index)
19734       .addDisp(Disp, UseFPOffset ? 4 : 0)
19735       .addOperand(Segment)
19736       .addReg(NextOffsetReg)
19737       .setMemRefs(MMOBegin, MMOEnd);
19738
19739     // Jump to endMBB
19740     BuildMI(offsetMBB, DL, TII->get(X86::JMP_1))
19741       .addMBB(endMBB);
19742   }
19743
19744   //
19745   // Emit code to use overflow area
19746   //
19747
19748   // Load the overflow_area address into a register.
19749   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
19750   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
19751     .addOperand(Base)
19752     .addOperand(Scale)
19753     .addOperand(Index)
19754     .addDisp(Disp, 8)
19755     .addOperand(Segment)
19756     .setMemRefs(MMOBegin, MMOEnd);
19757
19758   // If we need to align it, do so. Otherwise, just copy the address
19759   // to OverflowDestReg.
19760   if (NeedsAlign) {
19761     // Align the overflow address
19762     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
19763     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
19764
19765     // aligned_addr = (addr + (align-1)) & ~(align-1)
19766     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
19767       .addReg(OverflowAddrReg)
19768       .addImm(Align-1);
19769
19770     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
19771       .addReg(TmpReg)
19772       .addImm(~(uint64_t)(Align-1));
19773   } else {
19774     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
19775       .addReg(OverflowAddrReg);
19776   }
19777
19778   // Compute the next overflow address after this argument.
19779   // (the overflow address should be kept 8-byte aligned)
19780   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
19781   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
19782     .addReg(OverflowDestReg)
19783     .addImm(ArgSizeA8);
19784
19785   // Store the new overflow address.
19786   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
19787     .addOperand(Base)
19788     .addOperand(Scale)
19789     .addOperand(Index)
19790     .addDisp(Disp, 8)
19791     .addOperand(Segment)
19792     .addReg(NextAddrReg)
19793     .setMemRefs(MMOBegin, MMOEnd);
19794
19795   // If we branched, emit the PHI to the front of endMBB.
19796   if (offsetMBB) {
19797     BuildMI(*endMBB, endMBB->begin(), DL,
19798             TII->get(X86::PHI), DestReg)
19799       .addReg(OffsetDestReg).addMBB(offsetMBB)
19800       .addReg(OverflowDestReg).addMBB(overflowMBB);
19801   }
19802
19803   // Erase the pseudo instruction
19804   MI->eraseFromParent();
19805
19806   return endMBB;
19807 }
19808
19809 MachineBasicBlock *
19810 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
19811                                                  MachineInstr *MI,
19812                                                  MachineBasicBlock *MBB) const {
19813   // Emit code to save XMM registers to the stack. The ABI says that the
19814   // number of registers to save is given in %al, so it's theoretically
19815   // possible to do an indirect jump trick to avoid saving all of them,
19816   // however this code takes a simpler approach and just executes all
19817   // of the stores if %al is non-zero. It's less code, and it's probably
19818   // easier on the hardware branch predictor, and stores aren't all that
19819   // expensive anyway.
19820
19821   // Create the new basic blocks. One block contains all the XMM stores,
19822   // and one block is the final destination regardless of whether any
19823   // stores were performed.
19824   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
19825   MachineFunction *F = MBB->getParent();
19826   MachineFunction::iterator MBBIter = MBB;
19827   ++MBBIter;
19828   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
19829   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
19830   F->insert(MBBIter, XMMSaveMBB);
19831   F->insert(MBBIter, EndMBB);
19832
19833   // Transfer the remainder of MBB and its successor edges to EndMBB.
19834   EndMBB->splice(EndMBB->begin(), MBB,
19835                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
19836   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
19837
19838   // The original block will now fall through to the XMM save block.
19839   MBB->addSuccessor(XMMSaveMBB);
19840   // The XMMSaveMBB will fall through to the end block.
19841   XMMSaveMBB->addSuccessor(EndMBB);
19842
19843   // Now add the instructions.
19844   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19845   DebugLoc DL = MI->getDebugLoc();
19846
19847   unsigned CountReg = MI->getOperand(0).getReg();
19848   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
19849   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
19850
19851   if (!Subtarget->isTargetWin64()) {
19852     // If %al is 0, branch around the XMM save block.
19853     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
19854     BuildMI(MBB, DL, TII->get(X86::JE_1)).addMBB(EndMBB);
19855     MBB->addSuccessor(EndMBB);
19856   }
19857
19858   // Make sure the last operand is EFLAGS, which gets clobbered by the branch
19859   // that was just emitted, but clearly shouldn't be "saved".
19860   assert((MI->getNumOperands() <= 3 ||
19861           !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
19862           MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
19863          && "Expected last argument to be EFLAGS");
19864   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
19865   // In the XMM save block, save all the XMM argument registers.
19866   for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
19867     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
19868     MachineMemOperand *MMO =
19869       F->getMachineMemOperand(
19870           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
19871         MachineMemOperand::MOStore,
19872         /*Size=*/16, /*Align=*/16);
19873     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
19874       .addFrameIndex(RegSaveFrameIndex)
19875       .addImm(/*Scale=*/1)
19876       .addReg(/*IndexReg=*/0)
19877       .addImm(/*Disp=*/Offset)
19878       .addReg(/*Segment=*/0)
19879       .addReg(MI->getOperand(i).getReg())
19880       .addMemOperand(MMO);
19881   }
19882
19883   MI->eraseFromParent();   // The pseudo instruction is gone now.
19884
19885   return EndMBB;
19886 }
19887
19888 // The EFLAGS operand of SelectItr might be missing a kill marker
19889 // because there were multiple uses of EFLAGS, and ISel didn't know
19890 // which to mark. Figure out whether SelectItr should have had a
19891 // kill marker, and set it if it should. Returns the correct kill
19892 // marker value.
19893 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
19894                                      MachineBasicBlock* BB,
19895                                      const TargetRegisterInfo* TRI) {
19896   // Scan forward through BB for a use/def of EFLAGS.
19897   MachineBasicBlock::iterator miI(std::next(SelectItr));
19898   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
19899     const MachineInstr& mi = *miI;
19900     if (mi.readsRegister(X86::EFLAGS))
19901       return false;
19902     if (mi.definesRegister(X86::EFLAGS))
19903       break; // Should have kill-flag - update below.
19904   }
19905
19906   // If we hit the end of the block, check whether EFLAGS is live into a
19907   // successor.
19908   if (miI == BB->end()) {
19909     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
19910                                           sEnd = BB->succ_end();
19911          sItr != sEnd; ++sItr) {
19912       MachineBasicBlock* succ = *sItr;
19913       if (succ->isLiveIn(X86::EFLAGS))
19914         return false;
19915     }
19916   }
19917
19918   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
19919   // out. SelectMI should have a kill flag on EFLAGS.
19920   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
19921   return true;
19922 }
19923
19924 MachineBasicBlock *
19925 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
19926                                      MachineBasicBlock *BB) const {
19927   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19928   DebugLoc DL = MI->getDebugLoc();
19929
19930   // To "insert" a SELECT_CC instruction, we actually have to insert the
19931   // diamond control-flow pattern.  The incoming instruction knows the
19932   // destination vreg to set, the condition code register to branch on, the
19933   // true/false values to select between, and a branch opcode to use.
19934   const BasicBlock *LLVM_BB = BB->getBasicBlock();
19935   MachineFunction::iterator It = BB;
19936   ++It;
19937
19938   //  thisMBB:
19939   //  ...
19940   //   TrueVal = ...
19941   //   cmpTY ccX, r1, r2
19942   //   bCC copy1MBB
19943   //   fallthrough --> copy0MBB
19944   MachineBasicBlock *thisMBB = BB;
19945   MachineFunction *F = BB->getParent();
19946
19947   // We also lower double CMOVs:
19948   //   (CMOV (CMOV F, T, cc1), T, cc2)
19949   // to two successives branches.  For that, we look for another CMOV as the
19950   // following instruction.
19951   //
19952   // Without this, we would add a PHI between the two jumps, which ends up
19953   // creating a few copies all around. For instance, for
19954   //
19955   //    (sitofp (zext (fcmp une)))
19956   //
19957   // we would generate:
19958   //
19959   //         ucomiss %xmm1, %xmm0
19960   //         movss  <1.0f>, %xmm0
19961   //         movaps  %xmm0, %xmm1
19962   //         jne     .LBB5_2
19963   //         xorps   %xmm1, %xmm1
19964   // .LBB5_2:
19965   //         jp      .LBB5_4
19966   //         movaps  %xmm1, %xmm0
19967   // .LBB5_4:
19968   //         retq
19969   //
19970   // because this custom-inserter would have generated:
19971   //
19972   //   A
19973   //   | \
19974   //   |  B
19975   //   | /
19976   //   C
19977   //   | \
19978   //   |  D
19979   //   | /
19980   //   E
19981   //
19982   // A: X = ...; Y = ...
19983   // B: empty
19984   // C: Z = PHI [X, A], [Y, B]
19985   // D: empty
19986   // E: PHI [X, C], [Z, D]
19987   //
19988   // If we lower both CMOVs in a single step, we can instead generate:
19989   //
19990   //   A
19991   //   | \
19992   //   |  C
19993   //   | /|
19994   //   |/ |
19995   //   |  |
19996   //   |  D
19997   //   | /
19998   //   E
19999   //
20000   // A: X = ...; Y = ...
20001   // D: empty
20002   // E: PHI [X, A], [X, C], [Y, D]
20003   //
20004   // Which, in our sitofp/fcmp example, gives us something like:
20005   //
20006   //         ucomiss %xmm1, %xmm0
20007   //         movss  <1.0f>, %xmm0
20008   //         jne     .LBB5_4
20009   //         jp      .LBB5_4
20010   //         xorps   %xmm0, %xmm0
20011   // .LBB5_4:
20012   //         retq
20013   //
20014   MachineInstr *NextCMOV = nullptr;
20015   MachineBasicBlock::iterator NextMIIt =
20016       std::next(MachineBasicBlock::iterator(MI));
20017   if (NextMIIt != BB->end() && NextMIIt->getOpcode() == MI->getOpcode() &&
20018       NextMIIt->getOperand(2).getReg() == MI->getOperand(2).getReg() &&
20019       NextMIIt->getOperand(1).getReg() == MI->getOperand(0).getReg())
20020     NextCMOV = &*NextMIIt;
20021
20022   MachineBasicBlock *jcc1MBB = nullptr;
20023
20024   // If we have a double CMOV, we lower it to two successive branches to
20025   // the same block.  EFLAGS is used by both, so mark it as live in the second.
20026   if (NextCMOV) {
20027     jcc1MBB = F->CreateMachineBasicBlock(LLVM_BB);
20028     F->insert(It, jcc1MBB);
20029     jcc1MBB->addLiveIn(X86::EFLAGS);
20030   }
20031
20032   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
20033   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
20034   F->insert(It, copy0MBB);
20035   F->insert(It, sinkMBB);
20036
20037   // If the EFLAGS register isn't dead in the terminator, then claim that it's
20038   // live into the sink and copy blocks.
20039   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
20040
20041   MachineInstr *LastEFLAGSUser = NextCMOV ? NextCMOV : MI;
20042   if (!LastEFLAGSUser->killsRegister(X86::EFLAGS) &&
20043       !checkAndUpdateEFLAGSKill(LastEFLAGSUser, BB, TRI)) {
20044     copy0MBB->addLiveIn(X86::EFLAGS);
20045     sinkMBB->addLiveIn(X86::EFLAGS);
20046   }
20047
20048   // Transfer the remainder of BB and its successor edges to sinkMBB.
20049   sinkMBB->splice(sinkMBB->begin(), BB,
20050                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
20051   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
20052
20053   // Add the true and fallthrough blocks as its successors.
20054   if (NextCMOV) {
20055     // The fallthrough block may be jcc1MBB, if we have a double CMOV.
20056     BB->addSuccessor(jcc1MBB);
20057
20058     // In that case, jcc1MBB will itself fallthrough the copy0MBB, and
20059     // jump to the sinkMBB.
20060     jcc1MBB->addSuccessor(copy0MBB);
20061     jcc1MBB->addSuccessor(sinkMBB);
20062   } else {
20063     BB->addSuccessor(copy0MBB);
20064   }
20065
20066   // The true block target of the first (or only) branch is always sinkMBB.
20067   BB->addSuccessor(sinkMBB);
20068
20069   // Create the conditional branch instruction.
20070   unsigned Opc =
20071     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
20072   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
20073
20074   if (NextCMOV) {
20075     unsigned Opc2 = X86::GetCondBranchFromCond(
20076         (X86::CondCode)NextCMOV->getOperand(3).getImm());
20077     BuildMI(jcc1MBB, DL, TII->get(Opc2)).addMBB(sinkMBB);
20078   }
20079
20080   //  copy0MBB:
20081   //   %FalseValue = ...
20082   //   # fallthrough to sinkMBB
20083   copy0MBB->addSuccessor(sinkMBB);
20084
20085   //  sinkMBB:
20086   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
20087   //  ...
20088   MachineInstrBuilder MIB =
20089       BuildMI(*sinkMBB, sinkMBB->begin(), DL, TII->get(X86::PHI),
20090               MI->getOperand(0).getReg())
20091           .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
20092           .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
20093
20094   // If we have a double CMOV, the second Jcc provides the same incoming
20095   // value as the first Jcc (the True operand of the SELECT_CC/CMOV nodes).
20096   if (NextCMOV) {
20097     MIB.addReg(MI->getOperand(2).getReg()).addMBB(jcc1MBB);
20098     // Copy the PHI result to the register defined by the second CMOV.
20099     BuildMI(*sinkMBB, std::next(MachineBasicBlock::iterator(MIB.getInstr())),
20100             DL, TII->get(TargetOpcode::COPY), NextCMOV->getOperand(0).getReg())
20101         .addReg(MI->getOperand(0).getReg());
20102     NextCMOV->eraseFromParent();
20103   }
20104
20105   MI->eraseFromParent();   // The pseudo instruction is gone now.
20106   return sinkMBB;
20107 }
20108
20109 MachineBasicBlock *
20110 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI,
20111                                         MachineBasicBlock *BB) const {
20112   MachineFunction *MF = BB->getParent();
20113   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20114   DebugLoc DL = MI->getDebugLoc();
20115   const BasicBlock *LLVM_BB = BB->getBasicBlock();
20116
20117   assert(MF->shouldSplitStack());
20118
20119   const bool Is64Bit = Subtarget->is64Bit();
20120   const bool IsLP64 = Subtarget->isTarget64BitLP64();
20121
20122   const unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
20123   const unsigned TlsOffset = IsLP64 ? 0x70 : Is64Bit ? 0x40 : 0x30;
20124
20125   // BB:
20126   //  ... [Till the alloca]
20127   // If stacklet is not large enough, jump to mallocMBB
20128   //
20129   // bumpMBB:
20130   //  Allocate by subtracting from RSP
20131   //  Jump to continueMBB
20132   //
20133   // mallocMBB:
20134   //  Allocate by call to runtime
20135   //
20136   // continueMBB:
20137   //  ...
20138   //  [rest of original BB]
20139   //
20140
20141   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20142   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20143   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20144
20145   MachineRegisterInfo &MRI = MF->getRegInfo();
20146   const TargetRegisterClass *AddrRegClass =
20147       getRegClassFor(getPointerTy(MF->getDataLayout()));
20148
20149   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
20150     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
20151     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
20152     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
20153     sizeVReg = MI->getOperand(1).getReg(),
20154     physSPReg = IsLP64 || Subtarget->isTargetNaCl64() ? X86::RSP : X86::ESP;
20155
20156   MachineFunction::iterator MBBIter = BB;
20157   ++MBBIter;
20158
20159   MF->insert(MBBIter, bumpMBB);
20160   MF->insert(MBBIter, mallocMBB);
20161   MF->insert(MBBIter, continueMBB);
20162
20163   continueMBB->splice(continueMBB->begin(), BB,
20164                       std::next(MachineBasicBlock::iterator(MI)), BB->end());
20165   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
20166
20167   // Add code to the main basic block to check if the stack limit has been hit,
20168   // and if so, jump to mallocMBB otherwise to bumpMBB.
20169   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
20170   BuildMI(BB, DL, TII->get(IsLP64 ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
20171     .addReg(tmpSPVReg).addReg(sizeVReg);
20172   BuildMI(BB, DL, TII->get(IsLP64 ? X86::CMP64mr:X86::CMP32mr))
20173     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
20174     .addReg(SPLimitVReg);
20175   BuildMI(BB, DL, TII->get(X86::JG_1)).addMBB(mallocMBB);
20176
20177   // bumpMBB simply decreases the stack pointer, since we know the current
20178   // stacklet has enough space.
20179   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
20180     .addReg(SPLimitVReg);
20181   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
20182     .addReg(SPLimitVReg);
20183   BuildMI(bumpMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
20184
20185   // Calls into a routine in libgcc to allocate more space from the heap.
20186   const uint32_t *RegMask =
20187       Subtarget->getRegisterInfo()->getCallPreservedMask(*MF, CallingConv::C);
20188   if (IsLP64) {
20189     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
20190       .addReg(sizeVReg);
20191     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
20192       .addExternalSymbol("__morestack_allocate_stack_space")
20193       .addRegMask(RegMask)
20194       .addReg(X86::RDI, RegState::Implicit)
20195       .addReg(X86::RAX, RegState::ImplicitDefine);
20196   } else if (Is64Bit) {
20197     BuildMI(mallocMBB, DL, TII->get(X86::MOV32rr), X86::EDI)
20198       .addReg(sizeVReg);
20199     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
20200       .addExternalSymbol("__morestack_allocate_stack_space")
20201       .addRegMask(RegMask)
20202       .addReg(X86::EDI, RegState::Implicit)
20203       .addReg(X86::EAX, RegState::ImplicitDefine);
20204   } else {
20205     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
20206       .addImm(12);
20207     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
20208     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
20209       .addExternalSymbol("__morestack_allocate_stack_space")
20210       .addRegMask(RegMask)
20211       .addReg(X86::EAX, RegState::ImplicitDefine);
20212   }
20213
20214   if (!Is64Bit)
20215     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
20216       .addImm(16);
20217
20218   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
20219     .addReg(IsLP64 ? X86::RAX : X86::EAX);
20220   BuildMI(mallocMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
20221
20222   // Set up the CFG correctly.
20223   BB->addSuccessor(bumpMBB);
20224   BB->addSuccessor(mallocMBB);
20225   mallocMBB->addSuccessor(continueMBB);
20226   bumpMBB->addSuccessor(continueMBB);
20227
20228   // Take care of the PHI nodes.
20229   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
20230           MI->getOperand(0).getReg())
20231     .addReg(mallocPtrVReg).addMBB(mallocMBB)
20232     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
20233
20234   // Delete the original pseudo instruction.
20235   MI->eraseFromParent();
20236
20237   // And we're done.
20238   return continueMBB;
20239 }
20240
20241 MachineBasicBlock *
20242 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
20243                                         MachineBasicBlock *BB) const {
20244   DebugLoc DL = MI->getDebugLoc();
20245
20246   assert(!Subtarget->isTargetMachO());
20247
20248   Subtarget->getFrameLowering()->emitStackProbeCall(*BB->getParent(), *BB, MI,
20249                                                     DL);
20250
20251   MI->eraseFromParent();   // The pseudo instruction is gone now.
20252   return BB;
20253 }
20254
20255 MachineBasicBlock *
20256 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
20257                                       MachineBasicBlock *BB) const {
20258   // This is pretty easy.  We're taking the value that we received from
20259   // our load from the relocation, sticking it in either RDI (x86-64)
20260   // or EAX and doing an indirect call.  The return value will then
20261   // be in the normal return register.
20262   MachineFunction *F = BB->getParent();
20263   const X86InstrInfo *TII = Subtarget->getInstrInfo();
20264   DebugLoc DL = MI->getDebugLoc();
20265
20266   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
20267   assert(MI->getOperand(3).isGlobal() && "This should be a global");
20268
20269   // Get a register mask for the lowered call.
20270   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
20271   // proper register mask.
20272   const uint32_t *RegMask =
20273       Subtarget->getRegisterInfo()->getCallPreservedMask(*F, CallingConv::C);
20274   if (Subtarget->is64Bit()) {
20275     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
20276                                       TII->get(X86::MOV64rm), X86::RDI)
20277     .addReg(X86::RIP)
20278     .addImm(0).addReg(0)
20279     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
20280                       MI->getOperand(3).getTargetFlags())
20281     .addReg(0);
20282     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
20283     addDirectMem(MIB, X86::RDI);
20284     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
20285   } else if (F->getTarget().getRelocationModel() != Reloc::PIC_) {
20286     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
20287                                       TII->get(X86::MOV32rm), X86::EAX)
20288     .addReg(0)
20289     .addImm(0).addReg(0)
20290     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
20291                       MI->getOperand(3).getTargetFlags())
20292     .addReg(0);
20293     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
20294     addDirectMem(MIB, X86::EAX);
20295     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
20296   } else {
20297     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
20298                                       TII->get(X86::MOV32rm), X86::EAX)
20299     .addReg(TII->getGlobalBaseReg(F))
20300     .addImm(0).addReg(0)
20301     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
20302                       MI->getOperand(3).getTargetFlags())
20303     .addReg(0);
20304     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
20305     addDirectMem(MIB, X86::EAX);
20306     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
20307   }
20308
20309   MI->eraseFromParent(); // The pseudo instruction is gone now.
20310   return BB;
20311 }
20312
20313 MachineBasicBlock *
20314 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
20315                                     MachineBasicBlock *MBB) const {
20316   DebugLoc DL = MI->getDebugLoc();
20317   MachineFunction *MF = MBB->getParent();
20318   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20319   MachineRegisterInfo &MRI = MF->getRegInfo();
20320
20321   const BasicBlock *BB = MBB->getBasicBlock();
20322   MachineFunction::iterator I = MBB;
20323   ++I;
20324
20325   // Memory Reference
20326   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
20327   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
20328
20329   unsigned DstReg;
20330   unsigned MemOpndSlot = 0;
20331
20332   unsigned CurOp = 0;
20333
20334   DstReg = MI->getOperand(CurOp++).getReg();
20335   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
20336   assert(RC->hasType(MVT::i32) && "Invalid destination!");
20337   unsigned mainDstReg = MRI.createVirtualRegister(RC);
20338   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
20339
20340   MemOpndSlot = CurOp;
20341
20342   MVT PVT = getPointerTy(MF->getDataLayout());
20343   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
20344          "Invalid Pointer Size!");
20345
20346   // For v = setjmp(buf), we generate
20347   //
20348   // thisMBB:
20349   //  buf[LabelOffset] = restoreMBB
20350   //  SjLjSetup restoreMBB
20351   //
20352   // mainMBB:
20353   //  v_main = 0
20354   //
20355   // sinkMBB:
20356   //  v = phi(main, restore)
20357   //
20358   // restoreMBB:
20359   //  if base pointer being used, load it from frame
20360   //  v_restore = 1
20361
20362   MachineBasicBlock *thisMBB = MBB;
20363   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
20364   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
20365   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
20366   MF->insert(I, mainMBB);
20367   MF->insert(I, sinkMBB);
20368   MF->push_back(restoreMBB);
20369
20370   MachineInstrBuilder MIB;
20371
20372   // Transfer the remainder of BB and its successor edges to sinkMBB.
20373   sinkMBB->splice(sinkMBB->begin(), MBB,
20374                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
20375   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
20376
20377   // thisMBB:
20378   unsigned PtrStoreOpc = 0;
20379   unsigned LabelReg = 0;
20380   const int64_t LabelOffset = 1 * PVT.getStoreSize();
20381   Reloc::Model RM = MF->getTarget().getRelocationModel();
20382   bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
20383                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
20384
20385   // Prepare IP either in reg or imm.
20386   if (!UseImmLabel) {
20387     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
20388     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
20389     LabelReg = MRI.createVirtualRegister(PtrRC);
20390     if (Subtarget->is64Bit()) {
20391       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
20392               .addReg(X86::RIP)
20393               .addImm(0)
20394               .addReg(0)
20395               .addMBB(restoreMBB)
20396               .addReg(0);
20397     } else {
20398       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
20399       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
20400               .addReg(XII->getGlobalBaseReg(MF))
20401               .addImm(0)
20402               .addReg(0)
20403               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
20404               .addReg(0);
20405     }
20406   } else
20407     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
20408   // Store IP
20409   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
20410   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
20411     if (i == X86::AddrDisp)
20412       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
20413     else
20414       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
20415   }
20416   if (!UseImmLabel)
20417     MIB.addReg(LabelReg);
20418   else
20419     MIB.addMBB(restoreMBB);
20420   MIB.setMemRefs(MMOBegin, MMOEnd);
20421   // Setup
20422   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
20423           .addMBB(restoreMBB);
20424
20425   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
20426   MIB.addRegMask(RegInfo->getNoPreservedMask());
20427   thisMBB->addSuccessor(mainMBB);
20428   thisMBB->addSuccessor(restoreMBB);
20429
20430   // mainMBB:
20431   //  EAX = 0
20432   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
20433   mainMBB->addSuccessor(sinkMBB);
20434
20435   // sinkMBB:
20436   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
20437           TII->get(X86::PHI), DstReg)
20438     .addReg(mainDstReg).addMBB(mainMBB)
20439     .addReg(restoreDstReg).addMBB(restoreMBB);
20440
20441   // restoreMBB:
20442   if (RegInfo->hasBasePointer(*MF)) {
20443     const bool Uses64BitFramePtr =
20444         Subtarget->isTarget64BitLP64() || Subtarget->isTargetNaCl64();
20445     X86MachineFunctionInfo *X86FI = MF->getInfo<X86MachineFunctionInfo>();
20446     X86FI->setRestoreBasePointer(MF);
20447     unsigned FramePtr = RegInfo->getFrameRegister(*MF);
20448     unsigned BasePtr = RegInfo->getBaseRegister();
20449     unsigned Opm = Uses64BitFramePtr ? X86::MOV64rm : X86::MOV32rm;
20450     addRegOffset(BuildMI(restoreMBB, DL, TII->get(Opm), BasePtr),
20451                  FramePtr, true, X86FI->getRestoreBasePointerOffset())
20452       .setMIFlag(MachineInstr::FrameSetup);
20453   }
20454   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
20455   BuildMI(restoreMBB, DL, TII->get(X86::JMP_1)).addMBB(sinkMBB);
20456   restoreMBB->addSuccessor(sinkMBB);
20457
20458   MI->eraseFromParent();
20459   return sinkMBB;
20460 }
20461
20462 MachineBasicBlock *
20463 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
20464                                      MachineBasicBlock *MBB) const {
20465   DebugLoc DL = MI->getDebugLoc();
20466   MachineFunction *MF = MBB->getParent();
20467   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20468   MachineRegisterInfo &MRI = MF->getRegInfo();
20469
20470   // Memory Reference
20471   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
20472   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
20473
20474   MVT PVT = getPointerTy(MF->getDataLayout());
20475   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
20476          "Invalid Pointer Size!");
20477
20478   const TargetRegisterClass *RC =
20479     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
20480   unsigned Tmp = MRI.createVirtualRegister(RC);
20481   // Since FP is only updated here but NOT referenced, it's treated as GPR.
20482   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
20483   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
20484   unsigned SP = RegInfo->getStackRegister();
20485
20486   MachineInstrBuilder MIB;
20487
20488   const int64_t LabelOffset = 1 * PVT.getStoreSize();
20489   const int64_t SPOffset = 2 * PVT.getStoreSize();
20490
20491   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
20492   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
20493
20494   // Reload FP
20495   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
20496   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
20497     MIB.addOperand(MI->getOperand(i));
20498   MIB.setMemRefs(MMOBegin, MMOEnd);
20499   // Reload IP
20500   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
20501   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
20502     if (i == X86::AddrDisp)
20503       MIB.addDisp(MI->getOperand(i), LabelOffset);
20504     else
20505       MIB.addOperand(MI->getOperand(i));
20506   }
20507   MIB.setMemRefs(MMOBegin, MMOEnd);
20508   // Reload SP
20509   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
20510   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
20511     if (i == X86::AddrDisp)
20512       MIB.addDisp(MI->getOperand(i), SPOffset);
20513     else
20514       MIB.addOperand(MI->getOperand(i));
20515   }
20516   MIB.setMemRefs(MMOBegin, MMOEnd);
20517   // Jump
20518   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
20519
20520   MI->eraseFromParent();
20521   return MBB;
20522 }
20523
20524 // Replace 213-type (isel default) FMA3 instructions with 231-type for
20525 // accumulator loops. Writing back to the accumulator allows the coalescer
20526 // to remove extra copies in the loop.
20527 // FIXME: Do this on AVX512.  We don't support 231 variants yet (PR23937).
20528 MachineBasicBlock *
20529 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
20530                                  MachineBasicBlock *MBB) const {
20531   MachineOperand &AddendOp = MI->getOperand(3);
20532
20533   // Bail out early if the addend isn't a register - we can't switch these.
20534   if (!AddendOp.isReg())
20535     return MBB;
20536
20537   MachineFunction &MF = *MBB->getParent();
20538   MachineRegisterInfo &MRI = MF.getRegInfo();
20539
20540   // Check whether the addend is defined by a PHI:
20541   assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
20542   MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
20543   if (!AddendDef.isPHI())
20544     return MBB;
20545
20546   // Look for the following pattern:
20547   // loop:
20548   //   %addend = phi [%entry, 0], [%loop, %result]
20549   //   ...
20550   //   %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
20551
20552   // Replace with:
20553   //   loop:
20554   //   %addend = phi [%entry, 0], [%loop, %result]
20555   //   ...
20556   //   %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
20557
20558   for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
20559     assert(AddendDef.getOperand(i).isReg());
20560     MachineOperand PHISrcOp = AddendDef.getOperand(i);
20561     MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
20562     if (&PHISrcInst == MI) {
20563       // Found a matching instruction.
20564       unsigned NewFMAOpc = 0;
20565       switch (MI->getOpcode()) {
20566         case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
20567         case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
20568         case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
20569         case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
20570         case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
20571         case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
20572         case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
20573         case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
20574         case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
20575         case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
20576         case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
20577         case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
20578         case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
20579         case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
20580         case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
20581         case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
20582         case X86::VFMADDSUBPDr213r: NewFMAOpc = X86::VFMADDSUBPDr231r; break;
20583         case X86::VFMADDSUBPSr213r: NewFMAOpc = X86::VFMADDSUBPSr231r; break;
20584         case X86::VFMSUBADDPDr213r: NewFMAOpc = X86::VFMSUBADDPDr231r; break;
20585         case X86::VFMSUBADDPSr213r: NewFMAOpc = X86::VFMSUBADDPSr231r; break;
20586
20587         case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
20588         case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
20589         case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
20590         case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
20591         case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
20592         case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
20593         case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
20594         case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
20595         case X86::VFMADDSUBPDr213rY: NewFMAOpc = X86::VFMADDSUBPDr231rY; break;
20596         case X86::VFMADDSUBPSr213rY: NewFMAOpc = X86::VFMADDSUBPSr231rY; break;
20597         case X86::VFMSUBADDPDr213rY: NewFMAOpc = X86::VFMSUBADDPDr231rY; break;
20598         case X86::VFMSUBADDPSr213rY: NewFMAOpc = X86::VFMSUBADDPSr231rY; break;
20599         default: llvm_unreachable("Unrecognized FMA variant.");
20600       }
20601
20602       const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
20603       MachineInstrBuilder MIB =
20604         BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
20605         .addOperand(MI->getOperand(0))
20606         .addOperand(MI->getOperand(3))
20607         .addOperand(MI->getOperand(2))
20608         .addOperand(MI->getOperand(1));
20609       MBB->insert(MachineBasicBlock::iterator(MI), MIB);
20610       MI->eraseFromParent();
20611     }
20612   }
20613
20614   return MBB;
20615 }
20616
20617 MachineBasicBlock *
20618 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
20619                                                MachineBasicBlock *BB) const {
20620   switch (MI->getOpcode()) {
20621   default: llvm_unreachable("Unexpected instr type to insert");
20622   case X86::TAILJMPd64:
20623   case X86::TAILJMPr64:
20624   case X86::TAILJMPm64:
20625   case X86::TAILJMPd64_REX:
20626   case X86::TAILJMPr64_REX:
20627   case X86::TAILJMPm64_REX:
20628     llvm_unreachable("TAILJMP64 would not be touched here.");
20629   case X86::TCRETURNdi64:
20630   case X86::TCRETURNri64:
20631   case X86::TCRETURNmi64:
20632     return BB;
20633   case X86::WIN_ALLOCA:
20634     return EmitLoweredWinAlloca(MI, BB);
20635   case X86::SEG_ALLOCA_32:
20636   case X86::SEG_ALLOCA_64:
20637     return EmitLoweredSegAlloca(MI, BB);
20638   case X86::TLSCall_32:
20639   case X86::TLSCall_64:
20640     return EmitLoweredTLSCall(MI, BB);
20641   case X86::CMOV_GR8:
20642   case X86::CMOV_FR32:
20643   case X86::CMOV_FR64:
20644   case X86::CMOV_V4F32:
20645   case X86::CMOV_V2F64:
20646   case X86::CMOV_V2I64:
20647   case X86::CMOV_V8F32:
20648   case X86::CMOV_V4F64:
20649   case X86::CMOV_V4I64:
20650   case X86::CMOV_V16F32:
20651   case X86::CMOV_V8F64:
20652   case X86::CMOV_V8I64:
20653   case X86::CMOV_GR16:
20654   case X86::CMOV_GR32:
20655   case X86::CMOV_RFP32:
20656   case X86::CMOV_RFP64:
20657   case X86::CMOV_RFP80:
20658   case X86::CMOV_V8I1:
20659   case X86::CMOV_V16I1:
20660   case X86::CMOV_V32I1:
20661   case X86::CMOV_V64I1:
20662     return EmitLoweredSelect(MI, BB);
20663
20664   case X86::FP32_TO_INT16_IN_MEM:
20665   case X86::FP32_TO_INT32_IN_MEM:
20666   case X86::FP32_TO_INT64_IN_MEM:
20667   case X86::FP64_TO_INT16_IN_MEM:
20668   case X86::FP64_TO_INT32_IN_MEM:
20669   case X86::FP64_TO_INT64_IN_MEM:
20670   case X86::FP80_TO_INT16_IN_MEM:
20671   case X86::FP80_TO_INT32_IN_MEM:
20672   case X86::FP80_TO_INT64_IN_MEM: {
20673     MachineFunction *F = BB->getParent();
20674     const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20675     DebugLoc DL = MI->getDebugLoc();
20676
20677     // Change the floating point control register to use "round towards zero"
20678     // mode when truncating to an integer value.
20679     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
20680     addFrameReference(BuildMI(*BB, MI, DL,
20681                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
20682
20683     // Load the old value of the high byte of the control word...
20684     unsigned OldCW =
20685       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
20686     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
20687                       CWFrameIdx);
20688
20689     // Set the high part to be round to zero...
20690     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
20691       .addImm(0xC7F);
20692
20693     // Reload the modified control word now...
20694     addFrameReference(BuildMI(*BB, MI, DL,
20695                               TII->get(X86::FLDCW16m)), CWFrameIdx);
20696
20697     // Restore the memory image of control word to original value
20698     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
20699       .addReg(OldCW);
20700
20701     // Get the X86 opcode to use.
20702     unsigned Opc;
20703     switch (MI->getOpcode()) {
20704     default: llvm_unreachable("illegal opcode!");
20705     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
20706     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
20707     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
20708     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
20709     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
20710     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
20711     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
20712     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
20713     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
20714     }
20715
20716     X86AddressMode AM;
20717     MachineOperand &Op = MI->getOperand(0);
20718     if (Op.isReg()) {
20719       AM.BaseType = X86AddressMode::RegBase;
20720       AM.Base.Reg = Op.getReg();
20721     } else {
20722       AM.BaseType = X86AddressMode::FrameIndexBase;
20723       AM.Base.FrameIndex = Op.getIndex();
20724     }
20725     Op = MI->getOperand(1);
20726     if (Op.isImm())
20727       AM.Scale = Op.getImm();
20728     Op = MI->getOperand(2);
20729     if (Op.isImm())
20730       AM.IndexReg = Op.getImm();
20731     Op = MI->getOperand(3);
20732     if (Op.isGlobal()) {
20733       AM.GV = Op.getGlobal();
20734     } else {
20735       AM.Disp = Op.getImm();
20736     }
20737     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
20738                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
20739
20740     // Reload the original control word now.
20741     addFrameReference(BuildMI(*BB, MI, DL,
20742                               TII->get(X86::FLDCW16m)), CWFrameIdx);
20743
20744     MI->eraseFromParent();   // The pseudo instruction is gone now.
20745     return BB;
20746   }
20747     // String/text processing lowering.
20748   case X86::PCMPISTRM128REG:
20749   case X86::VPCMPISTRM128REG:
20750   case X86::PCMPISTRM128MEM:
20751   case X86::VPCMPISTRM128MEM:
20752   case X86::PCMPESTRM128REG:
20753   case X86::VPCMPESTRM128REG:
20754   case X86::PCMPESTRM128MEM:
20755   case X86::VPCMPESTRM128MEM:
20756     assert(Subtarget->hasSSE42() &&
20757            "Target must have SSE4.2 or AVX features enabled");
20758     return EmitPCMPSTRM(MI, BB, Subtarget->getInstrInfo());
20759
20760   // String/text processing lowering.
20761   case X86::PCMPISTRIREG:
20762   case X86::VPCMPISTRIREG:
20763   case X86::PCMPISTRIMEM:
20764   case X86::VPCMPISTRIMEM:
20765   case X86::PCMPESTRIREG:
20766   case X86::VPCMPESTRIREG:
20767   case X86::PCMPESTRIMEM:
20768   case X86::VPCMPESTRIMEM:
20769     assert(Subtarget->hasSSE42() &&
20770            "Target must have SSE4.2 or AVX features enabled");
20771     return EmitPCMPSTRI(MI, BB, Subtarget->getInstrInfo());
20772
20773   // Thread synchronization.
20774   case X86::MONITOR:
20775     return EmitMonitor(MI, BB, Subtarget);
20776
20777   // xbegin
20778   case X86::XBEGIN:
20779     return EmitXBegin(MI, BB, Subtarget->getInstrInfo());
20780
20781   case X86::VASTART_SAVE_XMM_REGS:
20782     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
20783
20784   case X86::VAARG_64:
20785     return EmitVAARG64WithCustomInserter(MI, BB);
20786
20787   case X86::EH_SjLj_SetJmp32:
20788   case X86::EH_SjLj_SetJmp64:
20789     return emitEHSjLjSetJmp(MI, BB);
20790
20791   case X86::EH_SjLj_LongJmp32:
20792   case X86::EH_SjLj_LongJmp64:
20793     return emitEHSjLjLongJmp(MI, BB);
20794
20795   case TargetOpcode::STATEPOINT:
20796     // As an implementation detail, STATEPOINT shares the STACKMAP format at
20797     // this point in the process.  We diverge later.
20798     return emitPatchPoint(MI, BB);
20799
20800   case TargetOpcode::STACKMAP:
20801   case TargetOpcode::PATCHPOINT:
20802     return emitPatchPoint(MI, BB);
20803
20804   case X86::VFMADDPDr213r:
20805   case X86::VFMADDPSr213r:
20806   case X86::VFMADDSDr213r:
20807   case X86::VFMADDSSr213r:
20808   case X86::VFMSUBPDr213r:
20809   case X86::VFMSUBPSr213r:
20810   case X86::VFMSUBSDr213r:
20811   case X86::VFMSUBSSr213r:
20812   case X86::VFNMADDPDr213r:
20813   case X86::VFNMADDPSr213r:
20814   case X86::VFNMADDSDr213r:
20815   case X86::VFNMADDSSr213r:
20816   case X86::VFNMSUBPDr213r:
20817   case X86::VFNMSUBPSr213r:
20818   case X86::VFNMSUBSDr213r:
20819   case X86::VFNMSUBSSr213r:
20820   case X86::VFMADDSUBPDr213r:
20821   case X86::VFMADDSUBPSr213r:
20822   case X86::VFMSUBADDPDr213r:
20823   case X86::VFMSUBADDPSr213r:
20824   case X86::VFMADDPDr213rY:
20825   case X86::VFMADDPSr213rY:
20826   case X86::VFMSUBPDr213rY:
20827   case X86::VFMSUBPSr213rY:
20828   case X86::VFNMADDPDr213rY:
20829   case X86::VFNMADDPSr213rY:
20830   case X86::VFNMSUBPDr213rY:
20831   case X86::VFNMSUBPSr213rY:
20832   case X86::VFMADDSUBPDr213rY:
20833   case X86::VFMADDSUBPSr213rY:
20834   case X86::VFMSUBADDPDr213rY:
20835   case X86::VFMSUBADDPSr213rY:
20836     return emitFMA3Instr(MI, BB);
20837   }
20838 }
20839
20840 //===----------------------------------------------------------------------===//
20841 //                           X86 Optimization Hooks
20842 //===----------------------------------------------------------------------===//
20843
20844 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
20845                                                       APInt &KnownZero,
20846                                                       APInt &KnownOne,
20847                                                       const SelectionDAG &DAG,
20848                                                       unsigned Depth) const {
20849   unsigned BitWidth = KnownZero.getBitWidth();
20850   unsigned Opc = Op.getOpcode();
20851   assert((Opc >= ISD::BUILTIN_OP_END ||
20852           Opc == ISD::INTRINSIC_WO_CHAIN ||
20853           Opc == ISD::INTRINSIC_W_CHAIN ||
20854           Opc == ISD::INTRINSIC_VOID) &&
20855          "Should use MaskedValueIsZero if you don't know whether Op"
20856          " is a target node!");
20857
20858   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
20859   switch (Opc) {
20860   default: break;
20861   case X86ISD::ADD:
20862   case X86ISD::SUB:
20863   case X86ISD::ADC:
20864   case X86ISD::SBB:
20865   case X86ISD::SMUL:
20866   case X86ISD::UMUL:
20867   case X86ISD::INC:
20868   case X86ISD::DEC:
20869   case X86ISD::OR:
20870   case X86ISD::XOR:
20871   case X86ISD::AND:
20872     // These nodes' second result is a boolean.
20873     if (Op.getResNo() == 0)
20874       break;
20875     // Fallthrough
20876   case X86ISD::SETCC:
20877     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
20878     break;
20879   case ISD::INTRINSIC_WO_CHAIN: {
20880     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
20881     unsigned NumLoBits = 0;
20882     switch (IntId) {
20883     default: break;
20884     case Intrinsic::x86_sse_movmsk_ps:
20885     case Intrinsic::x86_avx_movmsk_ps_256:
20886     case Intrinsic::x86_sse2_movmsk_pd:
20887     case Intrinsic::x86_avx_movmsk_pd_256:
20888     case Intrinsic::x86_mmx_pmovmskb:
20889     case Intrinsic::x86_sse2_pmovmskb_128:
20890     case Intrinsic::x86_avx2_pmovmskb: {
20891       // High bits of movmskp{s|d}, pmovmskb are known zero.
20892       switch (IntId) {
20893         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
20894         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
20895         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
20896         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
20897         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
20898         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
20899         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
20900         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
20901       }
20902       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
20903       break;
20904     }
20905     }
20906     break;
20907   }
20908   }
20909 }
20910
20911 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
20912   SDValue Op,
20913   const SelectionDAG &,
20914   unsigned Depth) const {
20915   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
20916   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
20917     return Op.getValueType().getScalarType().getSizeInBits();
20918
20919   // Fallback case.
20920   return 1;
20921 }
20922
20923 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
20924 /// node is a GlobalAddress + offset.
20925 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
20926                                        const GlobalValue* &GA,
20927                                        int64_t &Offset) const {
20928   if (N->getOpcode() == X86ISD::Wrapper) {
20929     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
20930       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
20931       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
20932       return true;
20933     }
20934   }
20935   return TargetLowering::isGAPlusOffset(N, GA, Offset);
20936 }
20937
20938 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
20939 /// same as extracting the high 128-bit part of 256-bit vector and then
20940 /// inserting the result into the low part of a new 256-bit vector
20941 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
20942   EVT VT = SVOp->getValueType(0);
20943   unsigned NumElems = VT.getVectorNumElements();
20944
20945   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
20946   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
20947     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
20948         SVOp->getMaskElt(j) >= 0)
20949       return false;
20950
20951   return true;
20952 }
20953
20954 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
20955 /// same as extracting the low 128-bit part of 256-bit vector and then
20956 /// inserting the result into the high part of a new 256-bit vector
20957 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
20958   EVT VT = SVOp->getValueType(0);
20959   unsigned NumElems = VT.getVectorNumElements();
20960
20961   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
20962   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
20963     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
20964         SVOp->getMaskElt(j) >= 0)
20965       return false;
20966
20967   return true;
20968 }
20969
20970 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
20971 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
20972                                         TargetLowering::DAGCombinerInfo &DCI,
20973                                         const X86Subtarget* Subtarget) {
20974   SDLoc dl(N);
20975   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
20976   SDValue V1 = SVOp->getOperand(0);
20977   SDValue V2 = SVOp->getOperand(1);
20978   EVT VT = SVOp->getValueType(0);
20979   unsigned NumElems = VT.getVectorNumElements();
20980
20981   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
20982       V2.getOpcode() == ISD::CONCAT_VECTORS) {
20983     //
20984     //                   0,0,0,...
20985     //                      |
20986     //    V      UNDEF    BUILD_VECTOR    UNDEF
20987     //     \      /           \           /
20988     //  CONCAT_VECTOR         CONCAT_VECTOR
20989     //         \                  /
20990     //          \                /
20991     //          RESULT: V + zero extended
20992     //
20993     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
20994         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
20995         V1.getOperand(1).getOpcode() != ISD::UNDEF)
20996       return SDValue();
20997
20998     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
20999       return SDValue();
21000
21001     // To match the shuffle mask, the first half of the mask should
21002     // be exactly the first vector, and all the rest a splat with the
21003     // first element of the second one.
21004     for (unsigned i = 0; i != NumElems/2; ++i)
21005       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
21006           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
21007         return SDValue();
21008
21009     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
21010     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
21011       if (Ld->hasNUsesOfValue(1, 0)) {
21012         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
21013         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
21014         SDValue ResNode =
21015           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
21016                                   Ld->getMemoryVT(),
21017                                   Ld->getPointerInfo(),
21018                                   Ld->getAlignment(),
21019                                   false/*isVolatile*/, true/*ReadMem*/,
21020                                   false/*WriteMem*/);
21021
21022         // Make sure the newly-created LOAD is in the same position as Ld in
21023         // terms of dependency. We create a TokenFactor for Ld and ResNode,
21024         // and update uses of Ld's output chain to use the TokenFactor.
21025         if (Ld->hasAnyUseOfValue(1)) {
21026           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
21027                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
21028           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
21029           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
21030                                  SDValue(ResNode.getNode(), 1));
21031         }
21032
21033         return DAG.getBitcast(VT, ResNode);
21034       }
21035     }
21036
21037     // Emit a zeroed vector and insert the desired subvector on its
21038     // first half.
21039     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
21040     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
21041     return DCI.CombineTo(N, InsV);
21042   }
21043
21044   //===--------------------------------------------------------------------===//
21045   // Combine some shuffles into subvector extracts and inserts:
21046   //
21047
21048   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
21049   if (isShuffleHigh128VectorInsertLow(SVOp)) {
21050     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
21051     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
21052     return DCI.CombineTo(N, InsV);
21053   }
21054
21055   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
21056   if (isShuffleLow128VectorInsertHigh(SVOp)) {
21057     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
21058     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
21059     return DCI.CombineTo(N, InsV);
21060   }
21061
21062   return SDValue();
21063 }
21064
21065 /// \brief Combine an arbitrary chain of shuffles into a single instruction if
21066 /// possible.
21067 ///
21068 /// This is the leaf of the recursive combinine below. When we have found some
21069 /// chain of single-use x86 shuffle instructions and accumulated the combined
21070 /// shuffle mask represented by them, this will try to pattern match that mask
21071 /// into either a single instruction if there is a special purpose instruction
21072 /// for this operation, or into a PSHUFB instruction which is a fully general
21073 /// instruction but should only be used to replace chains over a certain depth.
21074 static bool combineX86ShuffleChain(SDValue Op, SDValue Root, ArrayRef<int> Mask,
21075                                    int Depth, bool HasPSHUFB, SelectionDAG &DAG,
21076                                    TargetLowering::DAGCombinerInfo &DCI,
21077                                    const X86Subtarget *Subtarget) {
21078   assert(!Mask.empty() && "Cannot combine an empty shuffle mask!");
21079
21080   // Find the operand that enters the chain. Note that multiple uses are OK
21081   // here, we're not going to remove the operand we find.
21082   SDValue Input = Op.getOperand(0);
21083   while (Input.getOpcode() == ISD::BITCAST)
21084     Input = Input.getOperand(0);
21085
21086   MVT VT = Input.getSimpleValueType();
21087   MVT RootVT = Root.getSimpleValueType();
21088   SDLoc DL(Root);
21089
21090   // Just remove no-op shuffle masks.
21091   if (Mask.size() == 1) {
21092     DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Input),
21093                   /*AddTo*/ true);
21094     return true;
21095   }
21096
21097   // Use the float domain if the operand type is a floating point type.
21098   bool FloatDomain = VT.isFloatingPoint();
21099
21100   // For floating point shuffles, we don't have free copies in the shuffle
21101   // instructions or the ability to load as part of the instruction, so
21102   // canonicalize their shuffles to UNPCK or MOV variants.
21103   //
21104   // Note that even with AVX we prefer the PSHUFD form of shuffle for integer
21105   // vectors because it can have a load folded into it that UNPCK cannot. This
21106   // doesn't preclude something switching to the shorter encoding post-RA.
21107   //
21108   // FIXME: Should teach these routines about AVX vector widths.
21109   if (FloatDomain && VT.getSizeInBits() == 128) {
21110     if (Mask.equals({0, 0}) || Mask.equals({1, 1})) {
21111       bool Lo = Mask.equals({0, 0});
21112       unsigned Shuffle;
21113       MVT ShuffleVT;
21114       // Check if we have SSE3 which will let us use MOVDDUP. That instruction
21115       // is no slower than UNPCKLPD but has the option to fold the input operand
21116       // into even an unaligned memory load.
21117       if (Lo && Subtarget->hasSSE3()) {
21118         Shuffle = X86ISD::MOVDDUP;
21119         ShuffleVT = MVT::v2f64;
21120       } else {
21121         // We have MOVLHPS and MOVHLPS throughout SSE and they encode smaller
21122         // than the UNPCK variants.
21123         Shuffle = Lo ? X86ISD::MOVLHPS : X86ISD::MOVHLPS;
21124         ShuffleVT = MVT::v4f32;
21125       }
21126       if (Depth == 1 && Root->getOpcode() == Shuffle)
21127         return false; // Nothing to do!
21128       Op = DAG.getBitcast(ShuffleVT, Input);
21129       DCI.AddToWorklist(Op.getNode());
21130       if (Shuffle == X86ISD::MOVDDUP)
21131         Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
21132       else
21133         Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
21134       DCI.AddToWorklist(Op.getNode());
21135       DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21136                     /*AddTo*/ true);
21137       return true;
21138     }
21139     if (Subtarget->hasSSE3() &&
21140         (Mask.equals({0, 0, 2, 2}) || Mask.equals({1, 1, 3, 3}))) {
21141       bool Lo = Mask.equals({0, 0, 2, 2});
21142       unsigned Shuffle = Lo ? X86ISD::MOVSLDUP : X86ISD::MOVSHDUP;
21143       MVT ShuffleVT = MVT::v4f32;
21144       if (Depth == 1 && Root->getOpcode() == Shuffle)
21145         return false; // Nothing to do!
21146       Op = DAG.getBitcast(ShuffleVT, Input);
21147       DCI.AddToWorklist(Op.getNode());
21148       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
21149       DCI.AddToWorklist(Op.getNode());
21150       DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21151                     /*AddTo*/ true);
21152       return true;
21153     }
21154     if (Mask.equals({0, 0, 1, 1}) || Mask.equals({2, 2, 3, 3})) {
21155       bool Lo = Mask.equals({0, 0, 1, 1});
21156       unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
21157       MVT ShuffleVT = MVT::v4f32;
21158       if (Depth == 1 && Root->getOpcode() == Shuffle)
21159         return false; // Nothing to do!
21160       Op = DAG.getBitcast(ShuffleVT, Input);
21161       DCI.AddToWorklist(Op.getNode());
21162       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
21163       DCI.AddToWorklist(Op.getNode());
21164       DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21165                     /*AddTo*/ true);
21166       return true;
21167     }
21168   }
21169
21170   // We always canonicalize the 8 x i16 and 16 x i8 shuffles into their UNPCK
21171   // variants as none of these have single-instruction variants that are
21172   // superior to the UNPCK formulation.
21173   if (!FloatDomain && VT.getSizeInBits() == 128 &&
21174       (Mask.equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
21175        Mask.equals({4, 4, 5, 5, 6, 6, 7, 7}) ||
21176        Mask.equals({0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7}) ||
21177        Mask.equals(
21178            {8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15, 15}))) {
21179     bool Lo = Mask[0] == 0;
21180     unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
21181     if (Depth == 1 && Root->getOpcode() == Shuffle)
21182       return false; // Nothing to do!
21183     MVT ShuffleVT;
21184     switch (Mask.size()) {
21185     case 8:
21186       ShuffleVT = MVT::v8i16;
21187       break;
21188     case 16:
21189       ShuffleVT = MVT::v16i8;
21190       break;
21191     default:
21192       llvm_unreachable("Impossible mask size!");
21193     };
21194     Op = DAG.getBitcast(ShuffleVT, Input);
21195     DCI.AddToWorklist(Op.getNode());
21196     Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
21197     DCI.AddToWorklist(Op.getNode());
21198     DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21199                   /*AddTo*/ true);
21200     return true;
21201   }
21202
21203   // Don't try to re-form single instruction chains under any circumstances now
21204   // that we've done encoding canonicalization for them.
21205   if (Depth < 2)
21206     return false;
21207
21208   // If we have 3 or more shuffle instructions or a chain involving PSHUFB, we
21209   // can replace them with a single PSHUFB instruction profitably. Intel's
21210   // manuals suggest only using PSHUFB if doing so replacing 5 instructions, but
21211   // in practice PSHUFB tends to be *very* fast so we're more aggressive.
21212   if ((Depth >= 3 || HasPSHUFB) && Subtarget->hasSSSE3()) {
21213     SmallVector<SDValue, 16> PSHUFBMask;
21214     int NumBytes = VT.getSizeInBits() / 8;
21215     int Ratio = NumBytes / Mask.size();
21216     for (int i = 0; i < NumBytes; ++i) {
21217       if (Mask[i / Ratio] == SM_SentinelUndef) {
21218         PSHUFBMask.push_back(DAG.getUNDEF(MVT::i8));
21219         continue;
21220       }
21221       int M = Mask[i / Ratio] != SM_SentinelZero
21222                   ? Ratio * Mask[i / Ratio] + i % Ratio
21223                   : 255;
21224       PSHUFBMask.push_back(DAG.getConstant(M, DL, MVT::i8));
21225     }
21226     MVT ByteVT = MVT::getVectorVT(MVT::i8, NumBytes);
21227     Op = DAG.getBitcast(ByteVT, Input);
21228     DCI.AddToWorklist(Op.getNode());
21229     SDValue PSHUFBMaskOp =
21230         DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVT, PSHUFBMask);
21231     DCI.AddToWorklist(PSHUFBMaskOp.getNode());
21232     Op = DAG.getNode(X86ISD::PSHUFB, DL, ByteVT, Op, PSHUFBMaskOp);
21233     DCI.AddToWorklist(Op.getNode());
21234     DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21235                   /*AddTo*/ true);
21236     return true;
21237   }
21238
21239   // Failed to find any combines.
21240   return false;
21241 }
21242
21243 /// \brief Fully generic combining of x86 shuffle instructions.
21244 ///
21245 /// This should be the last combine run over the x86 shuffle instructions. Once
21246 /// they have been fully optimized, this will recursively consider all chains
21247 /// of single-use shuffle instructions, build a generic model of the cumulative
21248 /// shuffle operation, and check for simpler instructions which implement this
21249 /// operation. We use this primarily for two purposes:
21250 ///
21251 /// 1) Collapse generic shuffles to specialized single instructions when
21252 ///    equivalent. In most cases, this is just an encoding size win, but
21253 ///    sometimes we will collapse multiple generic shuffles into a single
21254 ///    special-purpose shuffle.
21255 /// 2) Look for sequences of shuffle instructions with 3 or more total
21256 ///    instructions, and replace them with the slightly more expensive SSSE3
21257 ///    PSHUFB instruction if available. We do this as the last combining step
21258 ///    to ensure we avoid using PSHUFB if we can implement the shuffle with
21259 ///    a suitable short sequence of other instructions. The PHUFB will either
21260 ///    use a register or have to read from memory and so is slightly (but only
21261 ///    slightly) more expensive than the other shuffle instructions.
21262 ///
21263 /// Because this is inherently a quadratic operation (for each shuffle in
21264 /// a chain, we recurse up the chain), the depth is limited to 8 instructions.
21265 /// This should never be an issue in practice as the shuffle lowering doesn't
21266 /// produce sequences of more than 8 instructions.
21267 ///
21268 /// FIXME: We will currently miss some cases where the redundant shuffling
21269 /// would simplify under the threshold for PSHUFB formation because of
21270 /// combine-ordering. To fix this, we should do the redundant instruction
21271 /// combining in this recursive walk.
21272 static bool combineX86ShufflesRecursively(SDValue Op, SDValue Root,
21273                                           ArrayRef<int> RootMask,
21274                                           int Depth, bool HasPSHUFB,
21275                                           SelectionDAG &DAG,
21276                                           TargetLowering::DAGCombinerInfo &DCI,
21277                                           const X86Subtarget *Subtarget) {
21278   // Bound the depth of our recursive combine because this is ultimately
21279   // quadratic in nature.
21280   if (Depth > 8)
21281     return false;
21282
21283   // Directly rip through bitcasts to find the underlying operand.
21284   while (Op.getOpcode() == ISD::BITCAST && Op.getOperand(0).hasOneUse())
21285     Op = Op.getOperand(0);
21286
21287   MVT VT = Op.getSimpleValueType();
21288   if (!VT.isVector())
21289     return false; // Bail if we hit a non-vector.
21290
21291   assert(Root.getSimpleValueType().isVector() &&
21292          "Shuffles operate on vector types!");
21293   assert(VT.getSizeInBits() == Root.getSimpleValueType().getSizeInBits() &&
21294          "Can only combine shuffles of the same vector register size.");
21295
21296   if (!isTargetShuffle(Op.getOpcode()))
21297     return false;
21298   SmallVector<int, 16> OpMask;
21299   bool IsUnary;
21300   bool HaveMask = getTargetShuffleMask(Op.getNode(), VT, OpMask, IsUnary);
21301   // We only can combine unary shuffles which we can decode the mask for.
21302   if (!HaveMask || !IsUnary)
21303     return false;
21304
21305   assert(VT.getVectorNumElements() == OpMask.size() &&
21306          "Different mask size from vector size!");
21307   assert(((RootMask.size() > OpMask.size() &&
21308            RootMask.size() % OpMask.size() == 0) ||
21309           (OpMask.size() > RootMask.size() &&
21310            OpMask.size() % RootMask.size() == 0) ||
21311           OpMask.size() == RootMask.size()) &&
21312          "The smaller number of elements must divide the larger.");
21313   int RootRatio = std::max<int>(1, OpMask.size() / RootMask.size());
21314   int OpRatio = std::max<int>(1, RootMask.size() / OpMask.size());
21315   assert(((RootRatio == 1 && OpRatio == 1) ||
21316           (RootRatio == 1) != (OpRatio == 1)) &&
21317          "Must not have a ratio for both incoming and op masks!");
21318
21319   SmallVector<int, 16> Mask;
21320   Mask.reserve(std::max(OpMask.size(), RootMask.size()));
21321
21322   // Merge this shuffle operation's mask into our accumulated mask. Note that
21323   // this shuffle's mask will be the first applied to the input, followed by the
21324   // root mask to get us all the way to the root value arrangement. The reason
21325   // for this order is that we are recursing up the operation chain.
21326   for (int i = 0, e = std::max(OpMask.size(), RootMask.size()); i < e; ++i) {
21327     int RootIdx = i / RootRatio;
21328     if (RootMask[RootIdx] < 0) {
21329       // This is a zero or undef lane, we're done.
21330       Mask.push_back(RootMask[RootIdx]);
21331       continue;
21332     }
21333
21334     int RootMaskedIdx = RootMask[RootIdx] * RootRatio + i % RootRatio;
21335     int OpIdx = RootMaskedIdx / OpRatio;
21336     if (OpMask[OpIdx] < 0) {
21337       // The incoming lanes are zero or undef, it doesn't matter which ones we
21338       // are using.
21339       Mask.push_back(OpMask[OpIdx]);
21340       continue;
21341     }
21342
21343     // Ok, we have non-zero lanes, map them through.
21344     Mask.push_back(OpMask[OpIdx] * OpRatio +
21345                    RootMaskedIdx % OpRatio);
21346   }
21347
21348   // See if we can recurse into the operand to combine more things.
21349   switch (Op.getOpcode()) {
21350     case X86ISD::PSHUFB:
21351       HasPSHUFB = true;
21352     case X86ISD::PSHUFD:
21353     case X86ISD::PSHUFHW:
21354     case X86ISD::PSHUFLW:
21355       if (Op.getOperand(0).hasOneUse() &&
21356           combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
21357                                         HasPSHUFB, DAG, DCI, Subtarget))
21358         return true;
21359       break;
21360
21361     case X86ISD::UNPCKL:
21362     case X86ISD::UNPCKH:
21363       assert(Op.getOperand(0) == Op.getOperand(1) && "We only combine unary shuffles!");
21364       // We can't check for single use, we have to check that this shuffle is the only user.
21365       if (Op->isOnlyUserOf(Op.getOperand(0).getNode()) &&
21366           combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
21367                                         HasPSHUFB, DAG, DCI, Subtarget))
21368           return true;
21369       break;
21370   }
21371
21372   // Minor canonicalization of the accumulated shuffle mask to make it easier
21373   // to match below. All this does is detect masks with squential pairs of
21374   // elements, and shrink them to the half-width mask. It does this in a loop
21375   // so it will reduce the size of the mask to the minimal width mask which
21376   // performs an equivalent shuffle.
21377   SmallVector<int, 16> WidenedMask;
21378   while (Mask.size() > 1 && canWidenShuffleElements(Mask, WidenedMask)) {
21379     Mask = std::move(WidenedMask);
21380     WidenedMask.clear();
21381   }
21382
21383   return combineX86ShuffleChain(Op, Root, Mask, Depth, HasPSHUFB, DAG, DCI,
21384                                 Subtarget);
21385 }
21386
21387 /// \brief Get the PSHUF-style mask from PSHUF node.
21388 ///
21389 /// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
21390 /// PSHUF-style masks that can be reused with such instructions.
21391 static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
21392   MVT VT = N.getSimpleValueType();
21393   SmallVector<int, 4> Mask;
21394   bool IsUnary;
21395   bool HaveMask = getTargetShuffleMask(N.getNode(), VT, Mask, IsUnary);
21396   (void)HaveMask;
21397   assert(HaveMask);
21398
21399   // If we have more than 128-bits, only the low 128-bits of shuffle mask
21400   // matter. Check that the upper masks are repeats and remove them.
21401   if (VT.getSizeInBits() > 128) {
21402     int LaneElts = 128 / VT.getScalarSizeInBits();
21403 #ifndef NDEBUG
21404     for (int i = 1, NumLanes = VT.getSizeInBits() / 128; i < NumLanes; ++i)
21405       for (int j = 0; j < LaneElts; ++j)
21406         assert(Mask[j] == Mask[i * LaneElts + j] - (LaneElts * i) &&
21407                "Mask doesn't repeat in high 128-bit lanes!");
21408 #endif
21409     Mask.resize(LaneElts);
21410   }
21411
21412   switch (N.getOpcode()) {
21413   case X86ISD::PSHUFD:
21414     return Mask;
21415   case X86ISD::PSHUFLW:
21416     Mask.resize(4);
21417     return Mask;
21418   case X86ISD::PSHUFHW:
21419     Mask.erase(Mask.begin(), Mask.begin() + 4);
21420     for (int &M : Mask)
21421       M -= 4;
21422     return Mask;
21423   default:
21424     llvm_unreachable("No valid shuffle instruction found!");
21425   }
21426 }
21427
21428 /// \brief Search for a combinable shuffle across a chain ending in pshufd.
21429 ///
21430 /// We walk up the chain and look for a combinable shuffle, skipping over
21431 /// shuffles that we could hoist this shuffle's transformation past without
21432 /// altering anything.
21433 static SDValue
21434 combineRedundantDWordShuffle(SDValue N, MutableArrayRef<int> Mask,
21435                              SelectionDAG &DAG,
21436                              TargetLowering::DAGCombinerInfo &DCI) {
21437   assert(N.getOpcode() == X86ISD::PSHUFD &&
21438          "Called with something other than an x86 128-bit half shuffle!");
21439   SDLoc DL(N);
21440
21441   // Walk up a single-use chain looking for a combinable shuffle. Keep a stack
21442   // of the shuffles in the chain so that we can form a fresh chain to replace
21443   // this one.
21444   SmallVector<SDValue, 8> Chain;
21445   SDValue V = N.getOperand(0);
21446   for (; V.hasOneUse(); V = V.getOperand(0)) {
21447     switch (V.getOpcode()) {
21448     default:
21449       return SDValue(); // Nothing combined!
21450
21451     case ISD::BITCAST:
21452       // Skip bitcasts as we always know the type for the target specific
21453       // instructions.
21454       continue;
21455
21456     case X86ISD::PSHUFD:
21457       // Found another dword shuffle.
21458       break;
21459
21460     case X86ISD::PSHUFLW:
21461       // Check that the low words (being shuffled) are the identity in the
21462       // dword shuffle, and the high words are self-contained.
21463       if (Mask[0] != 0 || Mask[1] != 1 ||
21464           !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
21465         return SDValue();
21466
21467       Chain.push_back(V);
21468       continue;
21469
21470     case X86ISD::PSHUFHW:
21471       // Check that the high words (being shuffled) are the identity in the
21472       // dword shuffle, and the low words are self-contained.
21473       if (Mask[2] != 2 || Mask[3] != 3 ||
21474           !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
21475         return SDValue();
21476
21477       Chain.push_back(V);
21478       continue;
21479
21480     case X86ISD::UNPCKL:
21481     case X86ISD::UNPCKH:
21482       // For either i8 -> i16 or i16 -> i32 unpacks, we can combine a dword
21483       // shuffle into a preceding word shuffle.
21484       if (V.getSimpleValueType().getScalarType() != MVT::i8 &&
21485           V.getSimpleValueType().getScalarType() != MVT::i16)
21486         return SDValue();
21487
21488       // Search for a half-shuffle which we can combine with.
21489       unsigned CombineOp =
21490           V.getOpcode() == X86ISD::UNPCKL ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
21491       if (V.getOperand(0) != V.getOperand(1) ||
21492           !V->isOnlyUserOf(V.getOperand(0).getNode()))
21493         return SDValue();
21494       Chain.push_back(V);
21495       V = V.getOperand(0);
21496       do {
21497         switch (V.getOpcode()) {
21498         default:
21499           return SDValue(); // Nothing to combine.
21500
21501         case X86ISD::PSHUFLW:
21502         case X86ISD::PSHUFHW:
21503           if (V.getOpcode() == CombineOp)
21504             break;
21505
21506           Chain.push_back(V);
21507
21508           // Fallthrough!
21509         case ISD::BITCAST:
21510           V = V.getOperand(0);
21511           continue;
21512         }
21513         break;
21514       } while (V.hasOneUse());
21515       break;
21516     }
21517     // Break out of the loop if we break out of the switch.
21518     break;
21519   }
21520
21521   if (!V.hasOneUse())
21522     // We fell out of the loop without finding a viable combining instruction.
21523     return SDValue();
21524
21525   // Merge this node's mask and our incoming mask.
21526   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
21527   for (int &M : Mask)
21528     M = VMask[M];
21529   V = DAG.getNode(V.getOpcode(), DL, V.getValueType(), V.getOperand(0),
21530                   getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
21531
21532   // Rebuild the chain around this new shuffle.
21533   while (!Chain.empty()) {
21534     SDValue W = Chain.pop_back_val();
21535
21536     if (V.getValueType() != W.getOperand(0).getValueType())
21537       V = DAG.getBitcast(W.getOperand(0).getValueType(), V);
21538
21539     switch (W.getOpcode()) {
21540     default:
21541       llvm_unreachable("Only PSHUF and UNPCK instructions get here!");
21542
21543     case X86ISD::UNPCKL:
21544     case X86ISD::UNPCKH:
21545       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, V);
21546       break;
21547
21548     case X86ISD::PSHUFD:
21549     case X86ISD::PSHUFLW:
21550     case X86ISD::PSHUFHW:
21551       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, W.getOperand(1));
21552       break;
21553     }
21554   }
21555   if (V.getValueType() != N.getValueType())
21556     V = DAG.getBitcast(N.getValueType(), V);
21557
21558   // Return the new chain to replace N.
21559   return V;
21560 }
21561
21562 /// \brief Search for a combinable shuffle across a chain ending in pshuflw or pshufhw.
21563 ///
21564 /// We walk up the chain, skipping shuffles of the other half and looking
21565 /// through shuffles which switch halves trying to find a shuffle of the same
21566 /// pair of dwords.
21567 static bool combineRedundantHalfShuffle(SDValue N, MutableArrayRef<int> Mask,
21568                                         SelectionDAG &DAG,
21569                                         TargetLowering::DAGCombinerInfo &DCI) {
21570   assert(
21571       (N.getOpcode() == X86ISD::PSHUFLW || N.getOpcode() == X86ISD::PSHUFHW) &&
21572       "Called with something other than an x86 128-bit half shuffle!");
21573   SDLoc DL(N);
21574   unsigned CombineOpcode = N.getOpcode();
21575
21576   // Walk up a single-use chain looking for a combinable shuffle.
21577   SDValue V = N.getOperand(0);
21578   for (; V.hasOneUse(); V = V.getOperand(0)) {
21579     switch (V.getOpcode()) {
21580     default:
21581       return false; // Nothing combined!
21582
21583     case ISD::BITCAST:
21584       // Skip bitcasts as we always know the type for the target specific
21585       // instructions.
21586       continue;
21587
21588     case X86ISD::PSHUFLW:
21589     case X86ISD::PSHUFHW:
21590       if (V.getOpcode() == CombineOpcode)
21591         break;
21592
21593       // Other-half shuffles are no-ops.
21594       continue;
21595     }
21596     // Break out of the loop if we break out of the switch.
21597     break;
21598   }
21599
21600   if (!V.hasOneUse())
21601     // We fell out of the loop without finding a viable combining instruction.
21602     return false;
21603
21604   // Combine away the bottom node as its shuffle will be accumulated into
21605   // a preceding shuffle.
21606   DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
21607
21608   // Record the old value.
21609   SDValue Old = V;
21610
21611   // Merge this node's mask and our incoming mask (adjusted to account for all
21612   // the pshufd instructions encountered).
21613   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
21614   for (int &M : Mask)
21615     M = VMask[M];
21616   V = DAG.getNode(V.getOpcode(), DL, MVT::v8i16, V.getOperand(0),
21617                   getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
21618
21619   // Check that the shuffles didn't cancel each other out. If not, we need to
21620   // combine to the new one.
21621   if (Old != V)
21622     // Replace the combinable shuffle with the combined one, updating all users
21623     // so that we re-evaluate the chain here.
21624     DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
21625
21626   return true;
21627 }
21628
21629 /// \brief Try to combine x86 target specific shuffles.
21630 static SDValue PerformTargetShuffleCombine(SDValue N, SelectionDAG &DAG,
21631                                            TargetLowering::DAGCombinerInfo &DCI,
21632                                            const X86Subtarget *Subtarget) {
21633   SDLoc DL(N);
21634   MVT VT = N.getSimpleValueType();
21635   SmallVector<int, 4> Mask;
21636
21637   switch (N.getOpcode()) {
21638   case X86ISD::PSHUFD:
21639   case X86ISD::PSHUFLW:
21640   case X86ISD::PSHUFHW:
21641     Mask = getPSHUFShuffleMask(N);
21642     assert(Mask.size() == 4);
21643     break;
21644   default:
21645     return SDValue();
21646   }
21647
21648   // Nuke no-op shuffles that show up after combining.
21649   if (isNoopShuffleMask(Mask))
21650     return DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
21651
21652   // Look for simplifications involving one or two shuffle instructions.
21653   SDValue V = N.getOperand(0);
21654   switch (N.getOpcode()) {
21655   default:
21656     break;
21657   case X86ISD::PSHUFLW:
21658   case X86ISD::PSHUFHW:
21659     assert(VT.getScalarType() == MVT::i16 && "Bad word shuffle type!");
21660
21661     if (combineRedundantHalfShuffle(N, Mask, DAG, DCI))
21662       return SDValue(); // We combined away this shuffle, so we're done.
21663
21664     // See if this reduces to a PSHUFD which is no more expensive and can
21665     // combine with more operations. Note that it has to at least flip the
21666     // dwords as otherwise it would have been removed as a no-op.
21667     if (makeArrayRef(Mask).equals({2, 3, 0, 1})) {
21668       int DMask[] = {0, 1, 2, 3};
21669       int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
21670       DMask[DOffset + 0] = DOffset + 1;
21671       DMask[DOffset + 1] = DOffset + 0;
21672       MVT DVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
21673       V = DAG.getBitcast(DVT, V);
21674       DCI.AddToWorklist(V.getNode());
21675       V = DAG.getNode(X86ISD::PSHUFD, DL, DVT, V,
21676                       getV4X86ShuffleImm8ForMask(DMask, DL, DAG));
21677       DCI.AddToWorklist(V.getNode());
21678       return DAG.getBitcast(VT, V);
21679     }
21680
21681     // Look for shuffle patterns which can be implemented as a single unpack.
21682     // FIXME: This doesn't handle the location of the PSHUFD generically, and
21683     // only works when we have a PSHUFD followed by two half-shuffles.
21684     if (Mask[0] == Mask[1] && Mask[2] == Mask[3] &&
21685         (V.getOpcode() == X86ISD::PSHUFLW ||
21686          V.getOpcode() == X86ISD::PSHUFHW) &&
21687         V.getOpcode() != N.getOpcode() &&
21688         V.hasOneUse()) {
21689       SDValue D = V.getOperand(0);
21690       while (D.getOpcode() == ISD::BITCAST && D.hasOneUse())
21691         D = D.getOperand(0);
21692       if (D.getOpcode() == X86ISD::PSHUFD && D.hasOneUse()) {
21693         SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
21694         SmallVector<int, 4> DMask = getPSHUFShuffleMask(D);
21695         int NOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
21696         int VOffset = V.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
21697         int WordMask[8];
21698         for (int i = 0; i < 4; ++i) {
21699           WordMask[i + NOffset] = Mask[i] + NOffset;
21700           WordMask[i + VOffset] = VMask[i] + VOffset;
21701         }
21702         // Map the word mask through the DWord mask.
21703         int MappedMask[8];
21704         for (int i = 0; i < 8; ++i)
21705           MappedMask[i] = 2 * DMask[WordMask[i] / 2] + WordMask[i] % 2;
21706         if (makeArrayRef(MappedMask).equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
21707             makeArrayRef(MappedMask).equals({4, 4, 5, 5, 6, 6, 7, 7})) {
21708           // We can replace all three shuffles with an unpack.
21709           V = DAG.getBitcast(VT, D.getOperand(0));
21710           DCI.AddToWorklist(V.getNode());
21711           return DAG.getNode(MappedMask[0] == 0 ? X86ISD::UNPCKL
21712                                                 : X86ISD::UNPCKH,
21713                              DL, VT, V, V);
21714         }
21715       }
21716     }
21717
21718     break;
21719
21720   case X86ISD::PSHUFD:
21721     if (SDValue NewN = combineRedundantDWordShuffle(N, Mask, DAG, DCI))
21722       return NewN;
21723
21724     break;
21725   }
21726
21727   return SDValue();
21728 }
21729
21730 /// \brief Try to combine a shuffle into a target-specific add-sub node.
21731 ///
21732 /// We combine this directly on the abstract vector shuffle nodes so it is
21733 /// easier to generically match. We also insert dummy vector shuffle nodes for
21734 /// the operands which explicitly discard the lanes which are unused by this
21735 /// operation to try to flow through the rest of the combiner the fact that
21736 /// they're unused.
21737 static SDValue combineShuffleToAddSub(SDNode *N, SelectionDAG &DAG) {
21738   SDLoc DL(N);
21739   EVT VT = N->getValueType(0);
21740
21741   // We only handle target-independent shuffles.
21742   // FIXME: It would be easy and harmless to use the target shuffle mask
21743   // extraction tool to support more.
21744   if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
21745     return SDValue();
21746
21747   auto *SVN = cast<ShuffleVectorSDNode>(N);
21748   ArrayRef<int> Mask = SVN->getMask();
21749   SDValue V1 = N->getOperand(0);
21750   SDValue V2 = N->getOperand(1);
21751
21752   // We require the first shuffle operand to be the SUB node, and the second to
21753   // be the ADD node.
21754   // FIXME: We should support the commuted patterns.
21755   if (V1->getOpcode() != ISD::FSUB || V2->getOpcode() != ISD::FADD)
21756     return SDValue();
21757
21758   // If there are other uses of these operations we can't fold them.
21759   if (!V1->hasOneUse() || !V2->hasOneUse())
21760     return SDValue();
21761
21762   // Ensure that both operations have the same operands. Note that we can
21763   // commute the FADD operands.
21764   SDValue LHS = V1->getOperand(0), RHS = V1->getOperand(1);
21765   if ((V2->getOperand(0) != LHS || V2->getOperand(1) != RHS) &&
21766       (V2->getOperand(0) != RHS || V2->getOperand(1) != LHS))
21767     return SDValue();
21768
21769   // We're looking for blends between FADD and FSUB nodes. We insist on these
21770   // nodes being lined up in a specific expected pattern.
21771   if (!(isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
21772         isShuffleEquivalent(V1, V2, Mask, {0, 5, 2, 7}) ||
21773         isShuffleEquivalent(V1, V2, Mask, {0, 9, 2, 11, 4, 13, 6, 15})))
21774     return SDValue();
21775
21776   // Only specific types are legal at this point, assert so we notice if and
21777   // when these change.
21778   assert((VT == MVT::v4f32 || VT == MVT::v2f64 || VT == MVT::v8f32 ||
21779           VT == MVT::v4f64) &&
21780          "Unknown vector type encountered!");
21781
21782   return DAG.getNode(X86ISD::ADDSUB, DL, VT, LHS, RHS);
21783 }
21784
21785 /// PerformShuffleCombine - Performs several different shuffle combines.
21786 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
21787                                      TargetLowering::DAGCombinerInfo &DCI,
21788                                      const X86Subtarget *Subtarget) {
21789   SDLoc dl(N);
21790   SDValue N0 = N->getOperand(0);
21791   SDValue N1 = N->getOperand(1);
21792   EVT VT = N->getValueType(0);
21793
21794   // Don't create instructions with illegal types after legalize types has run.
21795   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21796   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
21797     return SDValue();
21798
21799   // If we have legalized the vector types, look for blends of FADD and FSUB
21800   // nodes that we can fuse into an ADDSUB node.
21801   if (TLI.isTypeLegal(VT) && Subtarget->hasSSE3())
21802     if (SDValue AddSub = combineShuffleToAddSub(N, DAG))
21803       return AddSub;
21804
21805   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
21806   if (Subtarget->hasFp256() && VT.is256BitVector() &&
21807       N->getOpcode() == ISD::VECTOR_SHUFFLE)
21808     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
21809
21810   // During Type Legalization, when promoting illegal vector types,
21811   // the backend might introduce new shuffle dag nodes and bitcasts.
21812   //
21813   // This code performs the following transformation:
21814   // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
21815   //       (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
21816   //
21817   // We do this only if both the bitcast and the BINOP dag nodes have
21818   // one use. Also, perform this transformation only if the new binary
21819   // operation is legal. This is to avoid introducing dag nodes that
21820   // potentially need to be further expanded (or custom lowered) into a
21821   // less optimal sequence of dag nodes.
21822   if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
21823       N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
21824       N0.getOpcode() == ISD::BITCAST) {
21825     SDValue BC0 = N0.getOperand(0);
21826     EVT SVT = BC0.getValueType();
21827     unsigned Opcode = BC0.getOpcode();
21828     unsigned NumElts = VT.getVectorNumElements();
21829
21830     if (BC0.hasOneUse() && SVT.isVector() &&
21831         SVT.getVectorNumElements() * 2 == NumElts &&
21832         TLI.isOperationLegal(Opcode, VT)) {
21833       bool CanFold = false;
21834       switch (Opcode) {
21835       default : break;
21836       case ISD::ADD :
21837       case ISD::FADD :
21838       case ISD::SUB :
21839       case ISD::FSUB :
21840       case ISD::MUL :
21841       case ISD::FMUL :
21842         CanFold = true;
21843       }
21844
21845       unsigned SVTNumElts = SVT.getVectorNumElements();
21846       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
21847       for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
21848         CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
21849       for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
21850         CanFold = SVOp->getMaskElt(i) < 0;
21851
21852       if (CanFold) {
21853         SDValue BC00 = DAG.getBitcast(VT, BC0.getOperand(0));
21854         SDValue BC01 = DAG.getBitcast(VT, BC0.getOperand(1));
21855         SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
21856         return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
21857       }
21858     }
21859   }
21860
21861   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
21862   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
21863   // consecutive, non-overlapping, and in the right order.
21864   SmallVector<SDValue, 16> Elts;
21865   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
21866     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
21867
21868   if (SDValue LD = EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true))
21869     return LD;
21870
21871   if (isTargetShuffle(N->getOpcode())) {
21872     SDValue Shuffle =
21873         PerformTargetShuffleCombine(SDValue(N, 0), DAG, DCI, Subtarget);
21874     if (Shuffle.getNode())
21875       return Shuffle;
21876
21877     // Try recursively combining arbitrary sequences of x86 shuffle
21878     // instructions into higher-order shuffles. We do this after combining
21879     // specific PSHUF instruction sequences into their minimal form so that we
21880     // can evaluate how many specialized shuffle instructions are involved in
21881     // a particular chain.
21882     SmallVector<int, 1> NonceMask; // Just a placeholder.
21883     NonceMask.push_back(0);
21884     if (combineX86ShufflesRecursively(SDValue(N, 0), SDValue(N, 0), NonceMask,
21885                                       /*Depth*/ 1, /*HasPSHUFB*/ false, DAG,
21886                                       DCI, Subtarget))
21887       return SDValue(); // This routine will use CombineTo to replace N.
21888   }
21889
21890   return SDValue();
21891 }
21892
21893 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
21894 /// specific shuffle of a load can be folded into a single element load.
21895 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
21896 /// shuffles have been custom lowered so we need to handle those here.
21897 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
21898                                          TargetLowering::DAGCombinerInfo &DCI) {
21899   if (DCI.isBeforeLegalizeOps())
21900     return SDValue();
21901
21902   SDValue InVec = N->getOperand(0);
21903   SDValue EltNo = N->getOperand(1);
21904
21905   if (!isa<ConstantSDNode>(EltNo))
21906     return SDValue();
21907
21908   EVT OriginalVT = InVec.getValueType();
21909
21910   if (InVec.getOpcode() == ISD::BITCAST) {
21911     // Don't duplicate a load with other uses.
21912     if (!InVec.hasOneUse())
21913       return SDValue();
21914     EVT BCVT = InVec.getOperand(0).getValueType();
21915     if (!BCVT.isVector() ||
21916         BCVT.getVectorNumElements() != OriginalVT.getVectorNumElements())
21917       return SDValue();
21918     InVec = InVec.getOperand(0);
21919   }
21920
21921   EVT CurrentVT = InVec.getValueType();
21922
21923   if (!isTargetShuffle(InVec.getOpcode()))
21924     return SDValue();
21925
21926   // Don't duplicate a load with other uses.
21927   if (!InVec.hasOneUse())
21928     return SDValue();
21929
21930   SmallVector<int, 16> ShuffleMask;
21931   bool UnaryShuffle;
21932   if (!getTargetShuffleMask(InVec.getNode(), CurrentVT.getSimpleVT(),
21933                             ShuffleMask, UnaryShuffle))
21934     return SDValue();
21935
21936   // Select the input vector, guarding against out of range extract vector.
21937   unsigned NumElems = CurrentVT.getVectorNumElements();
21938   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
21939   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
21940   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
21941                                          : InVec.getOperand(1);
21942
21943   // If inputs to shuffle are the same for both ops, then allow 2 uses
21944   unsigned AllowedUses = InVec.getNumOperands() > 1 &&
21945                          InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
21946
21947   if (LdNode.getOpcode() == ISD::BITCAST) {
21948     // Don't duplicate a load with other uses.
21949     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
21950       return SDValue();
21951
21952     AllowedUses = 1; // only allow 1 load use if we have a bitcast
21953     LdNode = LdNode.getOperand(0);
21954   }
21955
21956   if (!ISD::isNormalLoad(LdNode.getNode()))
21957     return SDValue();
21958
21959   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
21960
21961   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
21962     return SDValue();
21963
21964   EVT EltVT = N->getValueType(0);
21965   // If there's a bitcast before the shuffle, check if the load type and
21966   // alignment is valid.
21967   unsigned Align = LN0->getAlignment();
21968   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21969   unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
21970       EltVT.getTypeForEVT(*DAG.getContext()));
21971
21972   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, EltVT))
21973     return SDValue();
21974
21975   // All checks match so transform back to vector_shuffle so that DAG combiner
21976   // can finish the job
21977   SDLoc dl(N);
21978
21979   // Create shuffle node taking into account the case that its a unary shuffle
21980   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(CurrentVT)
21981                                    : InVec.getOperand(1);
21982   Shuffle = DAG.getVectorShuffle(CurrentVT, dl,
21983                                  InVec.getOperand(0), Shuffle,
21984                                  &ShuffleMask[0]);
21985   Shuffle = DAG.getBitcast(OriginalVT, Shuffle);
21986   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
21987                      EltNo);
21988 }
21989
21990 /// \brief Detect bitcasts between i32 to x86mmx low word. Since MMX types are
21991 /// special and don't usually play with other vector types, it's better to
21992 /// handle them early to be sure we emit efficient code by avoiding
21993 /// store-load conversions.
21994 static SDValue PerformBITCASTCombine(SDNode *N, SelectionDAG &DAG) {
21995   if (N->getValueType(0) != MVT::x86mmx ||
21996       N->getOperand(0)->getOpcode() != ISD::BUILD_VECTOR ||
21997       N->getOperand(0)->getValueType(0) != MVT::v2i32)
21998     return SDValue();
21999
22000   SDValue V = N->getOperand(0);
22001   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V.getOperand(1));
22002   if (C && C->getZExtValue() == 0 && V.getOperand(0).getValueType() == MVT::i32)
22003     return DAG.getNode(X86ISD::MMX_MOVW2D, SDLoc(V.getOperand(0)),
22004                        N->getValueType(0), V.getOperand(0));
22005
22006   return SDValue();
22007 }
22008
22009 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
22010 /// generation and convert it from being a bunch of shuffles and extracts
22011 /// into a somewhat faster sequence. For i686, the best sequence is apparently
22012 /// storing the value and loading scalars back, while for x64 we should
22013 /// use 64-bit extracts and shifts.
22014 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
22015                                          TargetLowering::DAGCombinerInfo &DCI) {
22016   if (SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI))
22017     return NewOp;
22018
22019   SDValue InputVector = N->getOperand(0);
22020   SDLoc dl(InputVector);
22021   // Detect mmx to i32 conversion through a v2i32 elt extract.
22022   if (InputVector.getOpcode() == ISD::BITCAST && InputVector.hasOneUse() &&
22023       N->getValueType(0) == MVT::i32 &&
22024       InputVector.getValueType() == MVT::v2i32) {
22025
22026     // The bitcast source is a direct mmx result.
22027     SDValue MMXSrc = InputVector.getNode()->getOperand(0);
22028     if (MMXSrc.getValueType() == MVT::x86mmx)
22029       return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
22030                          N->getValueType(0),
22031                          InputVector.getNode()->getOperand(0));
22032
22033     // The mmx is indirect: (i64 extract_elt (v1i64 bitcast (x86mmx ...))).
22034     SDValue MMXSrcOp = MMXSrc.getOperand(0);
22035     if (MMXSrc.getOpcode() == ISD::EXTRACT_VECTOR_ELT && MMXSrc.hasOneUse() &&
22036         MMXSrc.getValueType() == MVT::i64 && MMXSrcOp.hasOneUse() &&
22037         MMXSrcOp.getOpcode() == ISD::BITCAST &&
22038         MMXSrcOp.getValueType() == MVT::v1i64 &&
22039         MMXSrcOp.getOperand(0).getValueType() == MVT::x86mmx)
22040       return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
22041                          N->getValueType(0),
22042                          MMXSrcOp.getOperand(0));
22043   }
22044
22045   EVT VT = N->getValueType(0);
22046
22047   if (VT == MVT::i1 && dyn_cast<ConstantSDNode>(N->getOperand(1)) &&
22048       InputVector.getOpcode() == ISD::BITCAST &&
22049       dyn_cast<ConstantSDNode>(InputVector.getOperand(0))) {
22050     uint64_t ExtractedElt =
22051           cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
22052     uint64_t InputValue =
22053           cast<ConstantSDNode>(InputVector.getOperand(0))->getZExtValue();
22054     uint64_t Res = (InputValue >> ExtractedElt) & 1;
22055     return DAG.getConstant(Res, dl, MVT::i1);
22056   }
22057   // Only operate on vectors of 4 elements, where the alternative shuffling
22058   // gets to be more expensive.
22059   if (InputVector.getValueType() != MVT::v4i32)
22060     return SDValue();
22061
22062   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
22063   // single use which is a sign-extend or zero-extend, and all elements are
22064   // used.
22065   SmallVector<SDNode *, 4> Uses;
22066   unsigned ExtractedElements = 0;
22067   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
22068        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
22069     if (UI.getUse().getResNo() != InputVector.getResNo())
22070       return SDValue();
22071
22072     SDNode *Extract = *UI;
22073     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
22074       return SDValue();
22075
22076     if (Extract->getValueType(0) != MVT::i32)
22077       return SDValue();
22078     if (!Extract->hasOneUse())
22079       return SDValue();
22080     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
22081         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
22082       return SDValue();
22083     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
22084       return SDValue();
22085
22086     // Record which element was extracted.
22087     ExtractedElements |=
22088       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
22089
22090     Uses.push_back(Extract);
22091   }
22092
22093   // If not all the elements were used, this may not be worthwhile.
22094   if (ExtractedElements != 15)
22095     return SDValue();
22096
22097   // Ok, we've now decided to do the transformation.
22098   // If 64-bit shifts are legal, use the extract-shift sequence,
22099   // otherwise bounce the vector off the cache.
22100   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22101   SDValue Vals[4];
22102
22103   if (TLI.isOperationLegal(ISD::SRA, MVT::i64)) {
22104     SDValue Cst = DAG.getBitcast(MVT::v2i64, InputVector);
22105     auto &DL = DAG.getDataLayout();
22106     EVT VecIdxTy = DAG.getTargetLoweringInfo().getVectorIdxTy(DL);
22107     SDValue BottomHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
22108       DAG.getConstant(0, dl, VecIdxTy));
22109     SDValue TopHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
22110       DAG.getConstant(1, dl, VecIdxTy));
22111
22112     SDValue ShAmt = DAG.getConstant(
22113         32, dl, DAG.getTargetLoweringInfo().getShiftAmountTy(MVT::i64, DL));
22114     Vals[0] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BottomHalf);
22115     Vals[1] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
22116       DAG.getNode(ISD::SRA, dl, MVT::i64, BottomHalf, ShAmt));
22117     Vals[2] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, TopHalf);
22118     Vals[3] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
22119       DAG.getNode(ISD::SRA, dl, MVT::i64, TopHalf, ShAmt));
22120   } else {
22121     // Store the value to a temporary stack slot.
22122     SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
22123     SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
22124       MachinePointerInfo(), false, false, 0);
22125
22126     EVT ElementType = InputVector.getValueType().getVectorElementType();
22127     unsigned EltSize = ElementType.getSizeInBits() / 8;
22128
22129     // Replace each use (extract) with a load of the appropriate element.
22130     for (unsigned i = 0; i < 4; ++i) {
22131       uint64_t Offset = EltSize * i;
22132       auto PtrVT = TLI.getPointerTy(DAG.getDataLayout());
22133       SDValue OffsetVal = DAG.getConstant(Offset, dl, PtrVT);
22134
22135       SDValue ScalarAddr =
22136           DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, OffsetVal);
22137
22138       // Load the scalar.
22139       Vals[i] = DAG.getLoad(ElementType, dl, Ch,
22140                             ScalarAddr, MachinePointerInfo(),
22141                             false, false, false, 0);
22142
22143     }
22144   }
22145
22146   // Replace the extracts
22147   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
22148     UE = Uses.end(); UI != UE; ++UI) {
22149     SDNode *Extract = *UI;
22150
22151     SDValue Idx = Extract->getOperand(1);
22152     uint64_t IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
22153     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), Vals[IdxVal]);
22154   }
22155
22156   // The replacement was made in place; don't return anything.
22157   return SDValue();
22158 }
22159
22160 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
22161 static std::pair<unsigned, bool>
22162 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
22163                    SelectionDAG &DAG, const X86Subtarget *Subtarget) {
22164   if (!VT.isVector())
22165     return std::make_pair(0, false);
22166
22167   bool NeedSplit = false;
22168   switch (VT.getSimpleVT().SimpleTy) {
22169   default: return std::make_pair(0, false);
22170   case MVT::v4i64:
22171   case MVT::v2i64:
22172     if (!Subtarget->hasVLX())
22173       return std::make_pair(0, false);
22174     break;
22175   case MVT::v64i8:
22176   case MVT::v32i16:
22177     if (!Subtarget->hasBWI())
22178       return std::make_pair(0, false);
22179     break;
22180   case MVT::v16i32:
22181   case MVT::v8i64:
22182     if (!Subtarget->hasAVX512())
22183       return std::make_pair(0, false);
22184     break;
22185   case MVT::v32i8:
22186   case MVT::v16i16:
22187   case MVT::v8i32:
22188     if (!Subtarget->hasAVX2())
22189       NeedSplit = true;
22190     if (!Subtarget->hasAVX())
22191       return std::make_pair(0, false);
22192     break;
22193   case MVT::v16i8:
22194   case MVT::v8i16:
22195   case MVT::v4i32:
22196     if (!Subtarget->hasSSE2())
22197       return std::make_pair(0, false);
22198   }
22199
22200   // SSE2 has only a small subset of the operations.
22201   bool hasUnsigned = Subtarget->hasSSE41() ||
22202                      (Subtarget->hasSSE2() && VT == MVT::v16i8);
22203   bool hasSigned = Subtarget->hasSSE41() ||
22204                    (Subtarget->hasSSE2() && VT == MVT::v8i16);
22205
22206   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
22207
22208   unsigned Opc = 0;
22209   // Check for x CC y ? x : y.
22210   if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
22211       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
22212     switch (CC) {
22213     default: break;
22214     case ISD::SETULT:
22215     case ISD::SETULE:
22216       Opc = hasUnsigned ? ISD::UMIN : 0; break;
22217     case ISD::SETUGT:
22218     case ISD::SETUGE:
22219       Opc = hasUnsigned ? ISD::UMAX : 0; break;
22220     case ISD::SETLT:
22221     case ISD::SETLE:
22222       Opc = hasSigned ? ISD::SMIN : 0; break;
22223     case ISD::SETGT:
22224     case ISD::SETGE:
22225       Opc = hasSigned ? ISD::SMAX : 0; break;
22226     }
22227   // Check for x CC y ? y : x -- a min/max with reversed arms.
22228   } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
22229              DAG.isEqualTo(RHS, Cond.getOperand(0))) {
22230     switch (CC) {
22231     default: break;
22232     case ISD::SETULT:
22233     case ISD::SETULE:
22234       Opc = hasUnsigned ? ISD::UMAX : 0; break;
22235     case ISD::SETUGT:
22236     case ISD::SETUGE:
22237       Opc = hasUnsigned ? ISD::UMIN : 0; break;
22238     case ISD::SETLT:
22239     case ISD::SETLE:
22240       Opc = hasSigned ? ISD::SMAX : 0; break;
22241     case ISD::SETGT:
22242     case ISD::SETGE:
22243       Opc = hasSigned ? ISD::SMIN : 0; break;
22244     }
22245   }
22246
22247   return std::make_pair(Opc, NeedSplit);
22248 }
22249
22250 static SDValue
22251 transformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
22252                                       const X86Subtarget *Subtarget) {
22253   SDLoc dl(N);
22254   SDValue Cond = N->getOperand(0);
22255   SDValue LHS = N->getOperand(1);
22256   SDValue RHS = N->getOperand(2);
22257
22258   if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
22259     SDValue CondSrc = Cond->getOperand(0);
22260     if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
22261       Cond = CondSrc->getOperand(0);
22262   }
22263
22264   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
22265     return SDValue();
22266
22267   // A vselect where all conditions and data are constants can be optimized into
22268   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
22269   if (ISD::isBuildVectorOfConstantSDNodes(LHS.getNode()) &&
22270       ISD::isBuildVectorOfConstantSDNodes(RHS.getNode()))
22271     return SDValue();
22272
22273   unsigned MaskValue = 0;
22274   if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
22275     return SDValue();
22276
22277   MVT VT = N->getSimpleValueType(0);
22278   unsigned NumElems = VT.getVectorNumElements();
22279   SmallVector<int, 8> ShuffleMask(NumElems, -1);
22280   for (unsigned i = 0; i < NumElems; ++i) {
22281     // Be sure we emit undef where we can.
22282     if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
22283       ShuffleMask[i] = -1;
22284     else
22285       ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
22286   }
22287
22288   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22289   if (!TLI.isShuffleMaskLegal(ShuffleMask, VT))
22290     return SDValue();
22291   return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
22292 }
22293
22294 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
22295 /// nodes.
22296 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
22297                                     TargetLowering::DAGCombinerInfo &DCI,
22298                                     const X86Subtarget *Subtarget) {
22299   SDLoc DL(N);
22300   SDValue Cond = N->getOperand(0);
22301   // Get the LHS/RHS of the select.
22302   SDValue LHS = N->getOperand(1);
22303   SDValue RHS = N->getOperand(2);
22304   EVT VT = LHS.getValueType();
22305   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22306
22307   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
22308   // instructions match the semantics of the common C idiom x<y?x:y but not
22309   // x<=y?x:y, because of how they handle negative zero (which can be
22310   // ignored in unsafe-math mode).
22311   // We also try to create v2f32 min/max nodes, which we later widen to v4f32.
22312   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
22313       VT != MVT::f80 && (TLI.isTypeLegal(VT) || VT == MVT::v2f32) &&
22314       (Subtarget->hasSSE2() ||
22315        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
22316     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
22317
22318     unsigned Opcode = 0;
22319     // Check for x CC y ? x : y.
22320     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
22321         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
22322       switch (CC) {
22323       default: break;
22324       case ISD::SETULT:
22325         // Converting this to a min would handle NaNs incorrectly, and swapping
22326         // the operands would cause it to handle comparisons between positive
22327         // and negative zero incorrectly.
22328         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
22329           if (!DAG.getTarget().Options.UnsafeFPMath &&
22330               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
22331             break;
22332           std::swap(LHS, RHS);
22333         }
22334         Opcode = X86ISD::FMIN;
22335         break;
22336       case ISD::SETOLE:
22337         // Converting this to a min would handle comparisons between positive
22338         // and negative zero incorrectly.
22339         if (!DAG.getTarget().Options.UnsafeFPMath &&
22340             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
22341           break;
22342         Opcode = X86ISD::FMIN;
22343         break;
22344       case ISD::SETULE:
22345         // Converting this to a min would handle both negative zeros and NaNs
22346         // incorrectly, but we can swap the operands to fix both.
22347         std::swap(LHS, RHS);
22348       case ISD::SETOLT:
22349       case ISD::SETLT:
22350       case ISD::SETLE:
22351         Opcode = X86ISD::FMIN;
22352         break;
22353
22354       case ISD::SETOGE:
22355         // Converting this to a max would handle comparisons between positive
22356         // and negative zero incorrectly.
22357         if (!DAG.getTarget().Options.UnsafeFPMath &&
22358             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
22359           break;
22360         Opcode = X86ISD::FMAX;
22361         break;
22362       case ISD::SETUGT:
22363         // Converting this to a max would handle NaNs incorrectly, and swapping
22364         // the operands would cause it to handle comparisons between positive
22365         // and negative zero incorrectly.
22366         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
22367           if (!DAG.getTarget().Options.UnsafeFPMath &&
22368               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
22369             break;
22370           std::swap(LHS, RHS);
22371         }
22372         Opcode = X86ISD::FMAX;
22373         break;
22374       case ISD::SETUGE:
22375         // Converting this to a max would handle both negative zeros and NaNs
22376         // incorrectly, but we can swap the operands to fix both.
22377         std::swap(LHS, RHS);
22378       case ISD::SETOGT:
22379       case ISD::SETGT:
22380       case ISD::SETGE:
22381         Opcode = X86ISD::FMAX;
22382         break;
22383       }
22384     // Check for x CC y ? y : x -- a min/max with reversed arms.
22385     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
22386                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
22387       switch (CC) {
22388       default: break;
22389       case ISD::SETOGE:
22390         // Converting this to a min would handle comparisons between positive
22391         // and negative zero incorrectly, and swapping the operands would
22392         // cause it to handle NaNs incorrectly.
22393         if (!DAG.getTarget().Options.UnsafeFPMath &&
22394             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
22395           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
22396             break;
22397           std::swap(LHS, RHS);
22398         }
22399         Opcode = X86ISD::FMIN;
22400         break;
22401       case ISD::SETUGT:
22402         // Converting this to a min would handle NaNs incorrectly.
22403         if (!DAG.getTarget().Options.UnsafeFPMath &&
22404             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
22405           break;
22406         Opcode = X86ISD::FMIN;
22407         break;
22408       case ISD::SETUGE:
22409         // Converting this to a min would handle both negative zeros and NaNs
22410         // incorrectly, but we can swap the operands to fix both.
22411         std::swap(LHS, RHS);
22412       case ISD::SETOGT:
22413       case ISD::SETGT:
22414       case ISD::SETGE:
22415         Opcode = X86ISD::FMIN;
22416         break;
22417
22418       case ISD::SETULT:
22419         // Converting this to a max would handle NaNs incorrectly.
22420         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
22421           break;
22422         Opcode = X86ISD::FMAX;
22423         break;
22424       case ISD::SETOLE:
22425         // Converting this to a max would handle comparisons between positive
22426         // and negative zero incorrectly, and swapping the operands would
22427         // cause it to handle NaNs incorrectly.
22428         if (!DAG.getTarget().Options.UnsafeFPMath &&
22429             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
22430           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
22431             break;
22432           std::swap(LHS, RHS);
22433         }
22434         Opcode = X86ISD::FMAX;
22435         break;
22436       case ISD::SETULE:
22437         // Converting this to a max would handle both negative zeros and NaNs
22438         // incorrectly, but we can swap the operands to fix both.
22439         std::swap(LHS, RHS);
22440       case ISD::SETOLT:
22441       case ISD::SETLT:
22442       case ISD::SETLE:
22443         Opcode = X86ISD::FMAX;
22444         break;
22445       }
22446     }
22447
22448     if (Opcode)
22449       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
22450   }
22451
22452   EVT CondVT = Cond.getValueType();
22453   if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
22454       CondVT.getVectorElementType() == MVT::i1) {
22455     // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
22456     // lowering on KNL. In this case we convert it to
22457     // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
22458     // The same situation for all 128 and 256-bit vectors of i8 and i16.
22459     // Since SKX these selects have a proper lowering.
22460     EVT OpVT = LHS.getValueType();
22461     if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
22462         (OpVT.getVectorElementType() == MVT::i8 ||
22463          OpVT.getVectorElementType() == MVT::i16) &&
22464         !(Subtarget->hasBWI() && Subtarget->hasVLX())) {
22465       Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
22466       DCI.AddToWorklist(Cond.getNode());
22467       return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
22468     }
22469   }
22470   // If this is a select between two integer constants, try to do some
22471   // optimizations.
22472   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
22473     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
22474       // Don't do this for crazy integer types.
22475       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
22476         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
22477         // so that TrueC (the true value) is larger than FalseC.
22478         bool NeedsCondInvert = false;
22479
22480         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
22481             // Efficiently invertible.
22482             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
22483              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
22484               isa<ConstantSDNode>(Cond.getOperand(1))))) {
22485           NeedsCondInvert = true;
22486           std::swap(TrueC, FalseC);
22487         }
22488
22489         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
22490         if (FalseC->getAPIntValue() == 0 &&
22491             TrueC->getAPIntValue().isPowerOf2()) {
22492           if (NeedsCondInvert) // Invert the condition if needed.
22493             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
22494                                DAG.getConstant(1, DL, Cond.getValueType()));
22495
22496           // Zero extend the condition if needed.
22497           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
22498
22499           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
22500           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
22501                              DAG.getConstant(ShAmt, DL, MVT::i8));
22502         }
22503
22504         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
22505         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
22506           if (NeedsCondInvert) // Invert the condition if needed.
22507             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
22508                                DAG.getConstant(1, DL, Cond.getValueType()));
22509
22510           // Zero extend the condition if needed.
22511           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
22512                              FalseC->getValueType(0), Cond);
22513           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
22514                              SDValue(FalseC, 0));
22515         }
22516
22517         // Optimize cases that will turn into an LEA instruction.  This requires
22518         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
22519         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
22520           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
22521           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
22522
22523           bool isFastMultiplier = false;
22524           if (Diff < 10) {
22525             switch ((unsigned char)Diff) {
22526               default: break;
22527               case 1:  // result = add base, cond
22528               case 2:  // result = lea base(    , cond*2)
22529               case 3:  // result = lea base(cond, cond*2)
22530               case 4:  // result = lea base(    , cond*4)
22531               case 5:  // result = lea base(cond, cond*4)
22532               case 8:  // result = lea base(    , cond*8)
22533               case 9:  // result = lea base(cond, cond*8)
22534                 isFastMultiplier = true;
22535                 break;
22536             }
22537           }
22538
22539           if (isFastMultiplier) {
22540             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
22541             if (NeedsCondInvert) // Invert the condition if needed.
22542               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
22543                                  DAG.getConstant(1, DL, Cond.getValueType()));
22544
22545             // Zero extend the condition if needed.
22546             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
22547                                Cond);
22548             // Scale the condition by the difference.
22549             if (Diff != 1)
22550               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
22551                                  DAG.getConstant(Diff, DL,
22552                                                  Cond.getValueType()));
22553
22554             // Add the base if non-zero.
22555             if (FalseC->getAPIntValue() != 0)
22556               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
22557                                  SDValue(FalseC, 0));
22558             return Cond;
22559           }
22560         }
22561       }
22562   }
22563
22564   // Canonicalize max and min:
22565   // (x > y) ? x : y -> (x >= y) ? x : y
22566   // (x < y) ? x : y -> (x <= y) ? x : y
22567   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
22568   // the need for an extra compare
22569   // against zero. e.g.
22570   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
22571   // subl   %esi, %edi
22572   // testl  %edi, %edi
22573   // movl   $0, %eax
22574   // cmovgl %edi, %eax
22575   // =>
22576   // xorl   %eax, %eax
22577   // subl   %esi, $edi
22578   // cmovsl %eax, %edi
22579   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
22580       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
22581       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
22582     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
22583     switch (CC) {
22584     default: break;
22585     case ISD::SETLT:
22586     case ISD::SETGT: {
22587       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
22588       Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
22589                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
22590       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
22591     }
22592     }
22593   }
22594
22595   // Early exit check
22596   if (!TLI.isTypeLegal(VT))
22597     return SDValue();
22598
22599   // Match VSELECTs into subs with unsigned saturation.
22600   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
22601       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
22602       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
22603        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
22604     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
22605
22606     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
22607     // left side invert the predicate to simplify logic below.
22608     SDValue Other;
22609     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
22610       Other = RHS;
22611       CC = ISD::getSetCCInverse(CC, true);
22612     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
22613       Other = LHS;
22614     }
22615
22616     if (Other.getNode() && Other->getNumOperands() == 2 &&
22617         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
22618       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
22619       SDValue CondRHS = Cond->getOperand(1);
22620
22621       // Look for a general sub with unsigned saturation first.
22622       // x >= y ? x-y : 0 --> subus x, y
22623       // x >  y ? x-y : 0 --> subus x, y
22624       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
22625           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
22626         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
22627
22628       if (auto *OpRHSBV = dyn_cast<BuildVectorSDNode>(OpRHS))
22629         if (auto *OpRHSConst = OpRHSBV->getConstantSplatNode()) {
22630           if (auto *CondRHSBV = dyn_cast<BuildVectorSDNode>(CondRHS))
22631             if (auto *CondRHSConst = CondRHSBV->getConstantSplatNode())
22632               // If the RHS is a constant we have to reverse the const
22633               // canonicalization.
22634               // x > C-1 ? x+-C : 0 --> subus x, C
22635               if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
22636                   CondRHSConst->getAPIntValue() ==
22637                       (-OpRHSConst->getAPIntValue() - 1))
22638                 return DAG.getNode(
22639                     X86ISD::SUBUS, DL, VT, OpLHS,
22640                     DAG.getConstant(-OpRHSConst->getAPIntValue(), DL, VT));
22641
22642           // Another special case: If C was a sign bit, the sub has been
22643           // canonicalized into a xor.
22644           // FIXME: Would it be better to use computeKnownBits to determine
22645           //        whether it's safe to decanonicalize the xor?
22646           // x s< 0 ? x^C : 0 --> subus x, C
22647           if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
22648               ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
22649               OpRHSConst->getAPIntValue().isSignBit())
22650             // Note that we have to rebuild the RHS constant here to ensure we
22651             // don't rely on particular values of undef lanes.
22652             return DAG.getNode(
22653                 X86ISD::SUBUS, DL, VT, OpLHS,
22654                 DAG.getConstant(OpRHSConst->getAPIntValue(), DL, VT));
22655         }
22656     }
22657   }
22658
22659   // Try to match a min/max vector operation.
22660   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
22661     std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
22662     unsigned Opc = ret.first;
22663     bool NeedSplit = ret.second;
22664
22665     if (Opc && NeedSplit) {
22666       unsigned NumElems = VT.getVectorNumElements();
22667       // Extract the LHS vectors
22668       SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
22669       SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
22670
22671       // Extract the RHS vectors
22672       SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
22673       SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
22674
22675       // Create min/max for each subvector
22676       LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
22677       RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
22678
22679       // Merge the result
22680       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
22681     } else if (Opc)
22682       return DAG.getNode(Opc, DL, VT, LHS, RHS);
22683   }
22684
22685   // Simplify vector selection if condition value type matches vselect
22686   // operand type
22687   if (N->getOpcode() == ISD::VSELECT && CondVT == VT) {
22688     assert(Cond.getValueType().isVector() &&
22689            "vector select expects a vector selector!");
22690
22691     bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
22692     bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
22693
22694     // Try invert the condition if true value is not all 1s and false value
22695     // is not all 0s.
22696     if (!TValIsAllOnes && !FValIsAllZeros &&
22697         // Check if the selector will be produced by CMPP*/PCMP*
22698         Cond.getOpcode() == ISD::SETCC &&
22699         // Check if SETCC has already been promoted
22700         TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT) ==
22701             CondVT) {
22702       bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
22703       bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
22704
22705       if (TValIsAllZeros || FValIsAllOnes) {
22706         SDValue CC = Cond.getOperand(2);
22707         ISD::CondCode NewCC =
22708           ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
22709                                Cond.getOperand(0).getValueType().isInteger());
22710         Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
22711         std::swap(LHS, RHS);
22712         TValIsAllOnes = FValIsAllOnes;
22713         FValIsAllZeros = TValIsAllZeros;
22714       }
22715     }
22716
22717     if (TValIsAllOnes || FValIsAllZeros) {
22718       SDValue Ret;
22719
22720       if (TValIsAllOnes && FValIsAllZeros)
22721         Ret = Cond;
22722       else if (TValIsAllOnes)
22723         Ret =
22724             DAG.getNode(ISD::OR, DL, CondVT, Cond, DAG.getBitcast(CondVT, RHS));
22725       else if (FValIsAllZeros)
22726         Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
22727                           DAG.getBitcast(CondVT, LHS));
22728
22729       return DAG.getBitcast(VT, Ret);
22730     }
22731   }
22732
22733   // We should generate an X86ISD::BLENDI from a vselect if its argument
22734   // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
22735   // constants. This specific pattern gets generated when we split a
22736   // selector for a 512 bit vector in a machine without AVX512 (but with
22737   // 256-bit vectors), during legalization:
22738   //
22739   // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
22740   //
22741   // Iff we find this pattern and the build_vectors are built from
22742   // constants, we translate the vselect into a shuffle_vector that we
22743   // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
22744   if ((N->getOpcode() == ISD::VSELECT ||
22745        N->getOpcode() == X86ISD::SHRUNKBLEND) &&
22746       !DCI.isBeforeLegalize() && !VT.is512BitVector()) {
22747     SDValue Shuffle = transformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
22748     if (Shuffle.getNode())
22749       return Shuffle;
22750   }
22751
22752   // If this is a *dynamic* select (non-constant condition) and we can match
22753   // this node with one of the variable blend instructions, restructure the
22754   // condition so that the blends can use the high bit of each element and use
22755   // SimplifyDemandedBits to simplify the condition operand.
22756   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
22757       !DCI.isBeforeLegalize() &&
22758       !ISD::isBuildVectorOfConstantSDNodes(Cond.getNode())) {
22759     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
22760
22761     // Don't optimize vector selects that map to mask-registers.
22762     if (BitWidth == 1)
22763       return SDValue();
22764
22765     // We can only handle the cases where VSELECT is directly legal on the
22766     // subtarget. We custom lower VSELECT nodes with constant conditions and
22767     // this makes it hard to see whether a dynamic VSELECT will correctly
22768     // lower, so we both check the operation's status and explicitly handle the
22769     // cases where a *dynamic* blend will fail even though a constant-condition
22770     // blend could be custom lowered.
22771     // FIXME: We should find a better way to handle this class of problems.
22772     // Potentially, we should combine constant-condition vselect nodes
22773     // pre-legalization into shuffles and not mark as many types as custom
22774     // lowered.
22775     if (!TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
22776       return SDValue();
22777     // FIXME: We don't support i16-element blends currently. We could and
22778     // should support them by making *all* the bits in the condition be set
22779     // rather than just the high bit and using an i8-element blend.
22780     if (VT.getScalarType() == MVT::i16)
22781       return SDValue();
22782     // Dynamic blending was only available from SSE4.1 onward.
22783     if (VT.getSizeInBits() == 128 && !Subtarget->hasSSE41())
22784       return SDValue();
22785     // Byte blends are only available in AVX2
22786     if (VT.getSizeInBits() == 256 && VT.getScalarType() == MVT::i8 &&
22787         !Subtarget->hasAVX2())
22788       return SDValue();
22789
22790     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
22791     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
22792
22793     APInt KnownZero, KnownOne;
22794     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
22795                                           DCI.isBeforeLegalizeOps());
22796     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
22797         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne,
22798                                  TLO)) {
22799       // If we changed the computation somewhere in the DAG, this change
22800       // will affect all users of Cond.
22801       // Make sure it is fine and update all the nodes so that we do not
22802       // use the generic VSELECT anymore. Otherwise, we may perform
22803       // wrong optimizations as we messed up with the actual expectation
22804       // for the vector boolean values.
22805       if (Cond != TLO.Old) {
22806         // Check all uses of that condition operand to check whether it will be
22807         // consumed by non-BLEND instructions, which may depend on all bits are
22808         // set properly.
22809         for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
22810              I != E; ++I)
22811           if (I->getOpcode() != ISD::VSELECT)
22812             // TODO: Add other opcodes eventually lowered into BLEND.
22813             return SDValue();
22814
22815         // Update all the users of the condition, before committing the change,
22816         // so that the VSELECT optimizations that expect the correct vector
22817         // boolean value will not be triggered.
22818         for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
22819              I != E; ++I)
22820           DAG.ReplaceAllUsesOfValueWith(
22821               SDValue(*I, 0),
22822               DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(*I), I->getValueType(0),
22823                           Cond, I->getOperand(1), I->getOperand(2)));
22824         DCI.CommitTargetLoweringOpt(TLO);
22825         return SDValue();
22826       }
22827       // At this point, only Cond is changed. Change the condition
22828       // just for N to keep the opportunity to optimize all other
22829       // users their own way.
22830       DAG.ReplaceAllUsesOfValueWith(
22831           SDValue(N, 0),
22832           DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(N), N->getValueType(0),
22833                       TLO.New, N->getOperand(1), N->getOperand(2)));
22834       return SDValue();
22835     }
22836   }
22837
22838   return SDValue();
22839 }
22840
22841 // Check whether a boolean test is testing a boolean value generated by
22842 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
22843 // code.
22844 //
22845 // Simplify the following patterns:
22846 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
22847 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
22848 // to (Op EFLAGS Cond)
22849 //
22850 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
22851 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
22852 // to (Op EFLAGS !Cond)
22853 //
22854 // where Op could be BRCOND or CMOV.
22855 //
22856 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
22857   // Quit if not CMP and SUB with its value result used.
22858   if (Cmp.getOpcode() != X86ISD::CMP &&
22859       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
22860       return SDValue();
22861
22862   // Quit if not used as a boolean value.
22863   if (CC != X86::COND_E && CC != X86::COND_NE)
22864     return SDValue();
22865
22866   // Check CMP operands. One of them should be 0 or 1 and the other should be
22867   // an SetCC or extended from it.
22868   SDValue Op1 = Cmp.getOperand(0);
22869   SDValue Op2 = Cmp.getOperand(1);
22870
22871   SDValue SetCC;
22872   const ConstantSDNode* C = nullptr;
22873   bool needOppositeCond = (CC == X86::COND_E);
22874   bool checkAgainstTrue = false; // Is it a comparison against 1?
22875
22876   if ((C = dyn_cast<ConstantSDNode>(Op1)))
22877     SetCC = Op2;
22878   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
22879     SetCC = Op1;
22880   else // Quit if all operands are not constants.
22881     return SDValue();
22882
22883   if (C->getZExtValue() == 1) {
22884     needOppositeCond = !needOppositeCond;
22885     checkAgainstTrue = true;
22886   } else if (C->getZExtValue() != 0)
22887     // Quit if the constant is neither 0 or 1.
22888     return SDValue();
22889
22890   bool truncatedToBoolWithAnd = false;
22891   // Skip (zext $x), (trunc $x), or (and $x, 1) node.
22892   while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
22893          SetCC.getOpcode() == ISD::TRUNCATE ||
22894          SetCC.getOpcode() == ISD::AND) {
22895     if (SetCC.getOpcode() == ISD::AND) {
22896       int OpIdx = -1;
22897       ConstantSDNode *CS;
22898       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
22899           CS->getZExtValue() == 1)
22900         OpIdx = 1;
22901       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
22902           CS->getZExtValue() == 1)
22903         OpIdx = 0;
22904       if (OpIdx == -1)
22905         break;
22906       SetCC = SetCC.getOperand(OpIdx);
22907       truncatedToBoolWithAnd = true;
22908     } else
22909       SetCC = SetCC.getOperand(0);
22910   }
22911
22912   switch (SetCC.getOpcode()) {
22913   case X86ISD::SETCC_CARRY:
22914     // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
22915     // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
22916     // i.e. it's a comparison against true but the result of SETCC_CARRY is not
22917     // truncated to i1 using 'and'.
22918     if (checkAgainstTrue && !truncatedToBoolWithAnd)
22919       break;
22920     assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
22921            "Invalid use of SETCC_CARRY!");
22922     // FALL THROUGH
22923   case X86ISD::SETCC:
22924     // Set the condition code or opposite one if necessary.
22925     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
22926     if (needOppositeCond)
22927       CC = X86::GetOppositeBranchCondition(CC);
22928     return SetCC.getOperand(1);
22929   case X86ISD::CMOV: {
22930     // Check whether false/true value has canonical one, i.e. 0 or 1.
22931     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
22932     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
22933     // Quit if true value is not a constant.
22934     if (!TVal)
22935       return SDValue();
22936     // Quit if false value is not a constant.
22937     if (!FVal) {
22938       SDValue Op = SetCC.getOperand(0);
22939       // Skip 'zext' or 'trunc' node.
22940       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
22941           Op.getOpcode() == ISD::TRUNCATE)
22942         Op = Op.getOperand(0);
22943       // A special case for rdrand/rdseed, where 0 is set if false cond is
22944       // found.
22945       if ((Op.getOpcode() != X86ISD::RDRAND &&
22946            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
22947         return SDValue();
22948     }
22949     // Quit if false value is not the constant 0 or 1.
22950     bool FValIsFalse = true;
22951     if (FVal && FVal->getZExtValue() != 0) {
22952       if (FVal->getZExtValue() != 1)
22953         return SDValue();
22954       // If FVal is 1, opposite cond is needed.
22955       needOppositeCond = !needOppositeCond;
22956       FValIsFalse = false;
22957     }
22958     // Quit if TVal is not the constant opposite of FVal.
22959     if (FValIsFalse && TVal->getZExtValue() != 1)
22960       return SDValue();
22961     if (!FValIsFalse && TVal->getZExtValue() != 0)
22962       return SDValue();
22963     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
22964     if (needOppositeCond)
22965       CC = X86::GetOppositeBranchCondition(CC);
22966     return SetCC.getOperand(3);
22967   }
22968   }
22969
22970   return SDValue();
22971 }
22972
22973 /// Check whether Cond is an AND/OR of SETCCs off of the same EFLAGS.
22974 /// Match:
22975 ///   (X86or (X86setcc) (X86setcc))
22976 ///   (X86cmp (and (X86setcc) (X86setcc)), 0)
22977 static bool checkBoolTestAndOrSetCCCombine(SDValue Cond, X86::CondCode &CC0,
22978                                            X86::CondCode &CC1, SDValue &Flags,
22979                                            bool &isAnd) {
22980   if (Cond->getOpcode() == X86ISD::CMP) {
22981     ConstantSDNode *CondOp1C = dyn_cast<ConstantSDNode>(Cond->getOperand(1));
22982     if (!CondOp1C || !CondOp1C->isNullValue())
22983       return false;
22984
22985     Cond = Cond->getOperand(0);
22986   }
22987
22988   isAnd = false;
22989
22990   SDValue SetCC0, SetCC1;
22991   switch (Cond->getOpcode()) {
22992   default: return false;
22993   case ISD::AND:
22994   case X86ISD::AND:
22995     isAnd = true;
22996     // fallthru
22997   case ISD::OR:
22998   case X86ISD::OR:
22999     SetCC0 = Cond->getOperand(0);
23000     SetCC1 = Cond->getOperand(1);
23001     break;
23002   };
23003
23004   // Make sure we have SETCC nodes, using the same flags value.
23005   if (SetCC0.getOpcode() != X86ISD::SETCC ||
23006       SetCC1.getOpcode() != X86ISD::SETCC ||
23007       SetCC0->getOperand(1) != SetCC1->getOperand(1))
23008     return false;
23009
23010   CC0 = (X86::CondCode)SetCC0->getConstantOperandVal(0);
23011   CC1 = (X86::CondCode)SetCC1->getConstantOperandVal(0);
23012   Flags = SetCC0->getOperand(1);
23013   return true;
23014 }
23015
23016 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
23017 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
23018                                   TargetLowering::DAGCombinerInfo &DCI,
23019                                   const X86Subtarget *Subtarget) {
23020   SDLoc DL(N);
23021
23022   // If the flag operand isn't dead, don't touch this CMOV.
23023   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
23024     return SDValue();
23025
23026   SDValue FalseOp = N->getOperand(0);
23027   SDValue TrueOp = N->getOperand(1);
23028   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
23029   SDValue Cond = N->getOperand(3);
23030
23031   if (CC == X86::COND_E || CC == X86::COND_NE) {
23032     switch (Cond.getOpcode()) {
23033     default: break;
23034     case X86ISD::BSR:
23035     case X86ISD::BSF:
23036       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
23037       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
23038         return (CC == X86::COND_E) ? FalseOp : TrueOp;
23039     }
23040   }
23041
23042   SDValue Flags;
23043
23044   Flags = checkBoolTestSetCCCombine(Cond, CC);
23045   if (Flags.getNode() &&
23046       // Extra check as FCMOV only supports a subset of X86 cond.
23047       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
23048     SDValue Ops[] = { FalseOp, TrueOp,
23049                       DAG.getConstant(CC, DL, MVT::i8), Flags };
23050     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
23051   }
23052
23053   // If this is a select between two integer constants, try to do some
23054   // optimizations.  Note that the operands are ordered the opposite of SELECT
23055   // operands.
23056   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
23057     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
23058       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
23059       // larger than FalseC (the false value).
23060       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
23061         CC = X86::GetOppositeBranchCondition(CC);
23062         std::swap(TrueC, FalseC);
23063         std::swap(TrueOp, FalseOp);
23064       }
23065
23066       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
23067       // This is efficient for any integer data type (including i8/i16) and
23068       // shift amount.
23069       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
23070         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
23071                            DAG.getConstant(CC, DL, MVT::i8), Cond);
23072
23073         // Zero extend the condition if needed.
23074         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
23075
23076         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
23077         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
23078                            DAG.getConstant(ShAmt, DL, MVT::i8));
23079         if (N->getNumValues() == 2)  // Dead flag value?
23080           return DCI.CombineTo(N, Cond, SDValue());
23081         return Cond;
23082       }
23083
23084       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
23085       // for any integer data type, including i8/i16.
23086       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
23087         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
23088                            DAG.getConstant(CC, DL, MVT::i8), Cond);
23089
23090         // Zero extend the condition if needed.
23091         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
23092                            FalseC->getValueType(0), Cond);
23093         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
23094                            SDValue(FalseC, 0));
23095
23096         if (N->getNumValues() == 2)  // Dead flag value?
23097           return DCI.CombineTo(N, Cond, SDValue());
23098         return Cond;
23099       }
23100
23101       // Optimize cases that will turn into an LEA instruction.  This requires
23102       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
23103       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
23104         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
23105         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
23106
23107         bool isFastMultiplier = false;
23108         if (Diff < 10) {
23109           switch ((unsigned char)Diff) {
23110           default: break;
23111           case 1:  // result = add base, cond
23112           case 2:  // result = lea base(    , cond*2)
23113           case 3:  // result = lea base(cond, cond*2)
23114           case 4:  // result = lea base(    , cond*4)
23115           case 5:  // result = lea base(cond, cond*4)
23116           case 8:  // result = lea base(    , cond*8)
23117           case 9:  // result = lea base(cond, cond*8)
23118             isFastMultiplier = true;
23119             break;
23120           }
23121         }
23122
23123         if (isFastMultiplier) {
23124           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
23125           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
23126                              DAG.getConstant(CC, DL, MVT::i8), Cond);
23127           // Zero extend the condition if needed.
23128           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
23129                              Cond);
23130           // Scale the condition by the difference.
23131           if (Diff != 1)
23132             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
23133                                DAG.getConstant(Diff, DL, Cond.getValueType()));
23134
23135           // Add the base if non-zero.
23136           if (FalseC->getAPIntValue() != 0)
23137             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
23138                                SDValue(FalseC, 0));
23139           if (N->getNumValues() == 2)  // Dead flag value?
23140             return DCI.CombineTo(N, Cond, SDValue());
23141           return Cond;
23142         }
23143       }
23144     }
23145   }
23146
23147   // Handle these cases:
23148   //   (select (x != c), e, c) -> select (x != c), e, x),
23149   //   (select (x == c), c, e) -> select (x == c), x, e)
23150   // where the c is an integer constant, and the "select" is the combination
23151   // of CMOV and CMP.
23152   //
23153   // The rationale for this change is that the conditional-move from a constant
23154   // needs two instructions, however, conditional-move from a register needs
23155   // only one instruction.
23156   //
23157   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
23158   //  some instruction-combining opportunities. This opt needs to be
23159   //  postponed as late as possible.
23160   //
23161   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
23162     // the DCI.xxxx conditions are provided to postpone the optimization as
23163     // late as possible.
23164
23165     ConstantSDNode *CmpAgainst = nullptr;
23166     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
23167         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
23168         !isa<ConstantSDNode>(Cond.getOperand(0))) {
23169
23170       if (CC == X86::COND_NE &&
23171           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
23172         CC = X86::GetOppositeBranchCondition(CC);
23173         std::swap(TrueOp, FalseOp);
23174       }
23175
23176       if (CC == X86::COND_E &&
23177           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
23178         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
23179                           DAG.getConstant(CC, DL, MVT::i8), Cond };
23180         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
23181       }
23182     }
23183   }
23184
23185   // Fold and/or of setcc's to double CMOV:
23186   //   (CMOV F, T, ((cc1 | cc2) != 0)) -> (CMOV (CMOV F, T, cc1), T, cc2)
23187   //   (CMOV F, T, ((cc1 & cc2) != 0)) -> (CMOV (CMOV T, F, !cc1), F, !cc2)
23188   //
23189   // This combine lets us generate:
23190   //   cmovcc1 (jcc1 if we don't have CMOV)
23191   //   cmovcc2 (same)
23192   // instead of:
23193   //   setcc1
23194   //   setcc2
23195   //   and/or
23196   //   cmovne (jne if we don't have CMOV)
23197   // When we can't use the CMOV instruction, it might increase branch
23198   // mispredicts.
23199   // When we can use CMOV, or when there is no mispredict, this improves
23200   // throughput and reduces register pressure.
23201   //
23202   if (CC == X86::COND_NE) {
23203     SDValue Flags;
23204     X86::CondCode CC0, CC1;
23205     bool isAndSetCC;
23206     if (checkBoolTestAndOrSetCCCombine(Cond, CC0, CC1, Flags, isAndSetCC)) {
23207       if (isAndSetCC) {
23208         std::swap(FalseOp, TrueOp);
23209         CC0 = X86::GetOppositeBranchCondition(CC0);
23210         CC1 = X86::GetOppositeBranchCondition(CC1);
23211       }
23212
23213       SDValue LOps[] = {FalseOp, TrueOp, DAG.getConstant(CC0, DL, MVT::i8),
23214         Flags};
23215       SDValue LCMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), LOps);
23216       SDValue Ops[] = {LCMOV, TrueOp, DAG.getConstant(CC1, DL, MVT::i8), Flags};
23217       SDValue CMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
23218       DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SDValue(CMOV.getNode(), 1));
23219       return CMOV;
23220     }
23221   }
23222
23223   return SDValue();
23224 }
23225
23226 static SDValue PerformINTRINSIC_WO_CHAINCombine(SDNode *N, SelectionDAG &DAG,
23227                                                 const X86Subtarget *Subtarget) {
23228   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
23229   switch (IntNo) {
23230   default: return SDValue();
23231   // SSE/AVX/AVX2 blend intrinsics.
23232   case Intrinsic::x86_avx2_pblendvb:
23233     // Don't try to simplify this intrinsic if we don't have AVX2.
23234     if (!Subtarget->hasAVX2())
23235       return SDValue();
23236     // FALL-THROUGH
23237   case Intrinsic::x86_avx_blendv_pd_256:
23238   case Intrinsic::x86_avx_blendv_ps_256:
23239     // Don't try to simplify this intrinsic if we don't have AVX.
23240     if (!Subtarget->hasAVX())
23241       return SDValue();
23242     // FALL-THROUGH
23243   case Intrinsic::x86_sse41_blendvps:
23244   case Intrinsic::x86_sse41_blendvpd:
23245   case Intrinsic::x86_sse41_pblendvb: {
23246     SDValue Op0 = N->getOperand(1);
23247     SDValue Op1 = N->getOperand(2);
23248     SDValue Mask = N->getOperand(3);
23249
23250     // Don't try to simplify this intrinsic if we don't have SSE4.1.
23251     if (!Subtarget->hasSSE41())
23252       return SDValue();
23253
23254     // fold (blend A, A, Mask) -> A
23255     if (Op0 == Op1)
23256       return Op0;
23257     // fold (blend A, B, allZeros) -> A
23258     if (ISD::isBuildVectorAllZeros(Mask.getNode()))
23259       return Op0;
23260     // fold (blend A, B, allOnes) -> B
23261     if (ISD::isBuildVectorAllOnes(Mask.getNode()))
23262       return Op1;
23263
23264     // Simplify the case where the mask is a constant i32 value.
23265     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Mask)) {
23266       if (C->isNullValue())
23267         return Op0;
23268       if (C->isAllOnesValue())
23269         return Op1;
23270     }
23271
23272     return SDValue();
23273   }
23274
23275   // Packed SSE2/AVX2 arithmetic shift immediate intrinsics.
23276   case Intrinsic::x86_sse2_psrai_w:
23277   case Intrinsic::x86_sse2_psrai_d:
23278   case Intrinsic::x86_avx2_psrai_w:
23279   case Intrinsic::x86_avx2_psrai_d:
23280   case Intrinsic::x86_sse2_psra_w:
23281   case Intrinsic::x86_sse2_psra_d:
23282   case Intrinsic::x86_avx2_psra_w:
23283   case Intrinsic::x86_avx2_psra_d: {
23284     SDValue Op0 = N->getOperand(1);
23285     SDValue Op1 = N->getOperand(2);
23286     EVT VT = Op0.getValueType();
23287     assert(VT.isVector() && "Expected a vector type!");
23288
23289     if (isa<BuildVectorSDNode>(Op1))
23290       Op1 = Op1.getOperand(0);
23291
23292     if (!isa<ConstantSDNode>(Op1))
23293       return SDValue();
23294
23295     EVT SVT = VT.getVectorElementType();
23296     unsigned SVTBits = SVT.getSizeInBits();
23297
23298     ConstantSDNode *CND = cast<ConstantSDNode>(Op1);
23299     const APInt &C = APInt(SVTBits, CND->getAPIntValue().getZExtValue());
23300     uint64_t ShAmt = C.getZExtValue();
23301
23302     // Don't try to convert this shift into a ISD::SRA if the shift
23303     // count is bigger than or equal to the element size.
23304     if (ShAmt >= SVTBits)
23305       return SDValue();
23306
23307     // Trivial case: if the shift count is zero, then fold this
23308     // into the first operand.
23309     if (ShAmt == 0)
23310       return Op0;
23311
23312     // Replace this packed shift intrinsic with a target independent
23313     // shift dag node.
23314     SDLoc DL(N);
23315     SDValue Splat = DAG.getConstant(C, DL, VT);
23316     return DAG.getNode(ISD::SRA, DL, VT, Op0, Splat);
23317   }
23318   }
23319 }
23320
23321 /// PerformMulCombine - Optimize a single multiply with constant into two
23322 /// in order to implement it with two cheaper instructions, e.g.
23323 /// LEA + SHL, LEA + LEA.
23324 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
23325                                  TargetLowering::DAGCombinerInfo &DCI) {
23326   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
23327     return SDValue();
23328
23329   EVT VT = N->getValueType(0);
23330   if (VT != MVT::i64 && VT != MVT::i32)
23331     return SDValue();
23332
23333   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
23334   if (!C)
23335     return SDValue();
23336   uint64_t MulAmt = C->getZExtValue();
23337   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
23338     return SDValue();
23339
23340   uint64_t MulAmt1 = 0;
23341   uint64_t MulAmt2 = 0;
23342   if ((MulAmt % 9) == 0) {
23343     MulAmt1 = 9;
23344     MulAmt2 = MulAmt / 9;
23345   } else if ((MulAmt % 5) == 0) {
23346     MulAmt1 = 5;
23347     MulAmt2 = MulAmt / 5;
23348   } else if ((MulAmt % 3) == 0) {
23349     MulAmt1 = 3;
23350     MulAmt2 = MulAmt / 3;
23351   }
23352   if (MulAmt2 &&
23353       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
23354     SDLoc DL(N);
23355
23356     if (isPowerOf2_64(MulAmt2) &&
23357         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
23358       // If second multiplifer is pow2, issue it first. We want the multiply by
23359       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
23360       // is an add.
23361       std::swap(MulAmt1, MulAmt2);
23362
23363     SDValue NewMul;
23364     if (isPowerOf2_64(MulAmt1))
23365       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
23366                            DAG.getConstant(Log2_64(MulAmt1), DL, MVT::i8));
23367     else
23368       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
23369                            DAG.getConstant(MulAmt1, DL, VT));
23370
23371     if (isPowerOf2_64(MulAmt2))
23372       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
23373                            DAG.getConstant(Log2_64(MulAmt2), DL, MVT::i8));
23374     else
23375       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
23376                            DAG.getConstant(MulAmt2, DL, VT));
23377
23378     // Do not add new nodes to DAG combiner worklist.
23379     DCI.CombineTo(N, NewMul, false);
23380   }
23381   return SDValue();
23382 }
23383
23384 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
23385   SDValue N0 = N->getOperand(0);
23386   SDValue N1 = N->getOperand(1);
23387   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
23388   EVT VT = N0.getValueType();
23389
23390   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
23391   // since the result of setcc_c is all zero's or all ones.
23392   if (VT.isInteger() && !VT.isVector() &&
23393       N1C && N0.getOpcode() == ISD::AND &&
23394       N0.getOperand(1).getOpcode() == ISD::Constant) {
23395     SDValue N00 = N0.getOperand(0);
23396     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
23397         ((N00.getOpcode() == ISD::ANY_EXTEND ||
23398           N00.getOpcode() == ISD::ZERO_EXTEND) &&
23399          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
23400       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
23401       APInt ShAmt = N1C->getAPIntValue();
23402       Mask = Mask.shl(ShAmt);
23403       if (Mask != 0) {
23404         SDLoc DL(N);
23405         return DAG.getNode(ISD::AND, DL, VT,
23406                            N00, DAG.getConstant(Mask, DL, VT));
23407       }
23408     }
23409   }
23410
23411   // Hardware support for vector shifts is sparse which makes us scalarize the
23412   // vector operations in many cases. Also, on sandybridge ADD is faster than
23413   // shl.
23414   // (shl V, 1) -> add V,V
23415   if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
23416     if (auto *N1SplatC = N1BV->getConstantSplatNode()) {
23417       assert(N0.getValueType().isVector() && "Invalid vector shift type");
23418       // We shift all of the values by one. In many cases we do not have
23419       // hardware support for this operation. This is better expressed as an ADD
23420       // of two values.
23421       if (N1SplatC->getAPIntValue() == 1)
23422         return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
23423     }
23424
23425   return SDValue();
23426 }
23427
23428 /// \brief Returns a vector of 0s if the node in input is a vector logical
23429 /// shift by a constant amount which is known to be bigger than or equal
23430 /// to the vector element size in bits.
23431 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
23432                                       const X86Subtarget *Subtarget) {
23433   EVT VT = N->getValueType(0);
23434
23435   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
23436       (!Subtarget->hasInt256() ||
23437        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
23438     return SDValue();
23439
23440   SDValue Amt = N->getOperand(1);
23441   SDLoc DL(N);
23442   if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Amt))
23443     if (auto *AmtSplat = AmtBV->getConstantSplatNode()) {
23444       APInt ShiftAmt = AmtSplat->getAPIntValue();
23445       unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
23446
23447       // SSE2/AVX2 logical shifts always return a vector of 0s
23448       // if the shift amount is bigger than or equal to
23449       // the element size. The constant shift amount will be
23450       // encoded as a 8-bit immediate.
23451       if (ShiftAmt.trunc(8).uge(MaxAmount))
23452         return getZeroVector(VT, Subtarget, DAG, DL);
23453     }
23454
23455   return SDValue();
23456 }
23457
23458 /// PerformShiftCombine - Combine shifts.
23459 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
23460                                    TargetLowering::DAGCombinerInfo &DCI,
23461                                    const X86Subtarget *Subtarget) {
23462   if (N->getOpcode() == ISD::SHL)
23463     if (SDValue V = PerformSHLCombine(N, DAG))
23464       return V;
23465
23466   // Try to fold this logical shift into a zero vector.
23467   if (N->getOpcode() != ISD::SRA)
23468     if (SDValue V = performShiftToAllZeros(N, DAG, Subtarget))
23469       return V;
23470
23471   return SDValue();
23472 }
23473
23474 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
23475 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
23476 // and friends.  Likewise for OR -> CMPNEQSS.
23477 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
23478                             TargetLowering::DAGCombinerInfo &DCI,
23479                             const X86Subtarget *Subtarget) {
23480   unsigned opcode;
23481
23482   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
23483   // we're requiring SSE2 for both.
23484   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
23485     SDValue N0 = N->getOperand(0);
23486     SDValue N1 = N->getOperand(1);
23487     SDValue CMP0 = N0->getOperand(1);
23488     SDValue CMP1 = N1->getOperand(1);
23489     SDLoc DL(N);
23490
23491     // The SETCCs should both refer to the same CMP.
23492     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
23493       return SDValue();
23494
23495     SDValue CMP00 = CMP0->getOperand(0);
23496     SDValue CMP01 = CMP0->getOperand(1);
23497     EVT     VT    = CMP00.getValueType();
23498
23499     if (VT == MVT::f32 || VT == MVT::f64) {
23500       bool ExpectingFlags = false;
23501       // Check for any users that want flags:
23502       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
23503            !ExpectingFlags && UI != UE; ++UI)
23504         switch (UI->getOpcode()) {
23505         default:
23506         case ISD::BR_CC:
23507         case ISD::BRCOND:
23508         case ISD::SELECT:
23509           ExpectingFlags = true;
23510           break;
23511         case ISD::CopyToReg:
23512         case ISD::SIGN_EXTEND:
23513         case ISD::ZERO_EXTEND:
23514         case ISD::ANY_EXTEND:
23515           break;
23516         }
23517
23518       if (!ExpectingFlags) {
23519         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
23520         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
23521
23522         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
23523           X86::CondCode tmp = cc0;
23524           cc0 = cc1;
23525           cc1 = tmp;
23526         }
23527
23528         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
23529             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
23530           // FIXME: need symbolic constants for these magic numbers.
23531           // See X86ATTInstPrinter.cpp:printSSECC().
23532           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
23533           if (Subtarget->hasAVX512()) {
23534             SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
23535                                          CMP01,
23536                                          DAG.getConstant(x86cc, DL, MVT::i8));
23537             if (N->getValueType(0) != MVT::i1)
23538               return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
23539                                  FSetCC);
23540             return FSetCC;
23541           }
23542           SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
23543                                               CMP00.getValueType(), CMP00, CMP01,
23544                                               DAG.getConstant(x86cc, DL,
23545                                                               MVT::i8));
23546
23547           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
23548           MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
23549
23550           if (is64BitFP && !Subtarget->is64Bit()) {
23551             // On a 32-bit target, we cannot bitcast the 64-bit float to a
23552             // 64-bit integer, since that's not a legal type. Since
23553             // OnesOrZeroesF is all ones of all zeroes, we don't need all the
23554             // bits, but can do this little dance to extract the lowest 32 bits
23555             // and work with those going forward.
23556             SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
23557                                            OnesOrZeroesF);
23558             SDValue Vector32 = DAG.getBitcast(MVT::v4f32, Vector64);
23559             OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
23560                                         Vector32, DAG.getIntPtrConstant(0, DL));
23561             IntVT = MVT::i32;
23562           }
23563
23564           SDValue OnesOrZeroesI = DAG.getBitcast(IntVT, OnesOrZeroesF);
23565           SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
23566                                       DAG.getConstant(1, DL, IntVT));
23567           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8,
23568                                               ANDed);
23569           return OneBitOfTruth;
23570         }
23571       }
23572     }
23573   }
23574   return SDValue();
23575 }
23576
23577 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
23578 /// so it can be folded inside ANDNP.
23579 static bool CanFoldXORWithAllOnes(const SDNode *N) {
23580   EVT VT = N->getValueType(0);
23581
23582   // Match direct AllOnes for 128 and 256-bit vectors
23583   if (ISD::isBuildVectorAllOnes(N))
23584     return true;
23585
23586   // Look through a bit convert.
23587   if (N->getOpcode() == ISD::BITCAST)
23588     N = N->getOperand(0).getNode();
23589
23590   // Sometimes the operand may come from a insert_subvector building a 256-bit
23591   // allones vector
23592   if (VT.is256BitVector() &&
23593       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
23594     SDValue V1 = N->getOperand(0);
23595     SDValue V2 = N->getOperand(1);
23596
23597     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
23598         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
23599         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
23600         ISD::isBuildVectorAllOnes(V2.getNode()))
23601       return true;
23602   }
23603
23604   return false;
23605 }
23606
23607 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
23608 // register. In most cases we actually compare or select YMM-sized registers
23609 // and mixing the two types creates horrible code. This method optimizes
23610 // some of the transition sequences.
23611 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
23612                                  TargetLowering::DAGCombinerInfo &DCI,
23613                                  const X86Subtarget *Subtarget) {
23614   EVT VT = N->getValueType(0);
23615   if (!VT.is256BitVector())
23616     return SDValue();
23617
23618   assert((N->getOpcode() == ISD::ANY_EXTEND ||
23619           N->getOpcode() == ISD::ZERO_EXTEND ||
23620           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
23621
23622   SDValue Narrow = N->getOperand(0);
23623   EVT NarrowVT = Narrow->getValueType(0);
23624   if (!NarrowVT.is128BitVector())
23625     return SDValue();
23626
23627   if (Narrow->getOpcode() != ISD::XOR &&
23628       Narrow->getOpcode() != ISD::AND &&
23629       Narrow->getOpcode() != ISD::OR)
23630     return SDValue();
23631
23632   SDValue N0  = Narrow->getOperand(0);
23633   SDValue N1  = Narrow->getOperand(1);
23634   SDLoc DL(Narrow);
23635
23636   // The Left side has to be a trunc.
23637   if (N0.getOpcode() != ISD::TRUNCATE)
23638     return SDValue();
23639
23640   // The type of the truncated inputs.
23641   EVT WideVT = N0->getOperand(0)->getValueType(0);
23642   if (WideVT != VT)
23643     return SDValue();
23644
23645   // The right side has to be a 'trunc' or a constant vector.
23646   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
23647   ConstantSDNode *RHSConstSplat = nullptr;
23648   if (auto *RHSBV = dyn_cast<BuildVectorSDNode>(N1))
23649     RHSConstSplat = RHSBV->getConstantSplatNode();
23650   if (!RHSTrunc && !RHSConstSplat)
23651     return SDValue();
23652
23653   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23654
23655   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
23656     return SDValue();
23657
23658   // Set N0 and N1 to hold the inputs to the new wide operation.
23659   N0 = N0->getOperand(0);
23660   if (RHSConstSplat) {
23661     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
23662                      SDValue(RHSConstSplat, 0));
23663     SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
23664     N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
23665   } else if (RHSTrunc) {
23666     N1 = N1->getOperand(0);
23667   }
23668
23669   // Generate the wide operation.
23670   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
23671   unsigned Opcode = N->getOpcode();
23672   switch (Opcode) {
23673   case ISD::ANY_EXTEND:
23674     return Op;
23675   case ISD::ZERO_EXTEND: {
23676     unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
23677     APInt Mask = APInt::getAllOnesValue(InBits);
23678     Mask = Mask.zext(VT.getScalarType().getSizeInBits());
23679     return DAG.getNode(ISD::AND, DL, VT,
23680                        Op, DAG.getConstant(Mask, DL, VT));
23681   }
23682   case ISD::SIGN_EXTEND:
23683     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
23684                        Op, DAG.getValueType(NarrowVT));
23685   default:
23686     llvm_unreachable("Unexpected opcode");
23687   }
23688 }
23689
23690 static SDValue VectorZextCombine(SDNode *N, SelectionDAG &DAG,
23691                                  TargetLowering::DAGCombinerInfo &DCI,
23692                                  const X86Subtarget *Subtarget) {
23693   SDValue N0 = N->getOperand(0);
23694   SDValue N1 = N->getOperand(1);
23695   SDLoc DL(N);
23696
23697   // A vector zext_in_reg may be represented as a shuffle,
23698   // feeding into a bitcast (this represents anyext) feeding into
23699   // an and with a mask.
23700   // We'd like to try to combine that into a shuffle with zero
23701   // plus a bitcast, removing the and.
23702   if (N0.getOpcode() != ISD::BITCAST ||
23703       N0.getOperand(0).getOpcode() != ISD::VECTOR_SHUFFLE)
23704     return SDValue();
23705
23706   // The other side of the AND should be a splat of 2^C, where C
23707   // is the number of bits in the source type.
23708   if (N1.getOpcode() == ISD::BITCAST)
23709     N1 = N1.getOperand(0);
23710   if (N1.getOpcode() != ISD::BUILD_VECTOR)
23711     return SDValue();
23712   BuildVectorSDNode *Vector = cast<BuildVectorSDNode>(N1);
23713
23714   ShuffleVectorSDNode *Shuffle = cast<ShuffleVectorSDNode>(N0.getOperand(0));
23715   EVT SrcType = Shuffle->getValueType(0);
23716
23717   // We expect a single-source shuffle
23718   if (Shuffle->getOperand(1)->getOpcode() != ISD::UNDEF)
23719     return SDValue();
23720
23721   unsigned SrcSize = SrcType.getScalarSizeInBits();
23722
23723   APInt SplatValue, SplatUndef;
23724   unsigned SplatBitSize;
23725   bool HasAnyUndefs;
23726   if (!Vector->isConstantSplat(SplatValue, SplatUndef,
23727                                 SplatBitSize, HasAnyUndefs))
23728     return SDValue();
23729
23730   unsigned ResSize = N1.getValueType().getScalarSizeInBits();
23731   // Make sure the splat matches the mask we expect
23732   if (SplatBitSize > ResSize ||
23733       (SplatValue + 1).exactLogBase2() != (int)SrcSize)
23734     return SDValue();
23735
23736   // Make sure the input and output size make sense
23737   if (SrcSize >= ResSize || ResSize % SrcSize)
23738     return SDValue();
23739
23740   // We expect a shuffle of the form <0, u, u, u, 1, u, u, u...>
23741   // The number of u's between each two values depends on the ratio between
23742   // the source and dest type.
23743   unsigned ZextRatio = ResSize / SrcSize;
23744   bool IsZext = true;
23745   for (unsigned i = 0; i < SrcType.getVectorNumElements(); ++i) {
23746     if (i % ZextRatio) {
23747       if (Shuffle->getMaskElt(i) > 0) {
23748         // Expected undef
23749         IsZext = false;
23750         break;
23751       }
23752     } else {
23753       if (Shuffle->getMaskElt(i) != (int)(i / ZextRatio)) {
23754         // Expected element number
23755         IsZext = false;
23756         break;
23757       }
23758     }
23759   }
23760
23761   if (!IsZext)
23762     return SDValue();
23763
23764   // Ok, perform the transformation - replace the shuffle with
23765   // a shuffle of the form <0, k, k, k, 1, k, k, k> with zero
23766   // (instead of undef) where the k elements come from the zero vector.
23767   SmallVector<int, 8> Mask;
23768   unsigned NumElems = SrcType.getVectorNumElements();
23769   for (unsigned i = 0; i < NumElems; ++i)
23770     if (i % ZextRatio)
23771       Mask.push_back(NumElems);
23772     else
23773       Mask.push_back(i / ZextRatio);
23774
23775   SDValue NewShuffle = DAG.getVectorShuffle(Shuffle->getValueType(0), DL,
23776     Shuffle->getOperand(0), DAG.getConstant(0, DL, SrcType), Mask);
23777   return DAG.getBitcast(N0.getValueType(), NewShuffle);
23778 }
23779
23780 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
23781                                  TargetLowering::DAGCombinerInfo &DCI,
23782                                  const X86Subtarget *Subtarget) {
23783   if (DCI.isBeforeLegalizeOps())
23784     return SDValue();
23785
23786   if (SDValue Zext = VectorZextCombine(N, DAG, DCI, Subtarget))
23787     return Zext;
23788
23789   if (SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget))
23790     return R;
23791
23792   EVT VT = N->getValueType(0);
23793   SDValue N0 = N->getOperand(0);
23794   SDValue N1 = N->getOperand(1);
23795   SDLoc DL(N);
23796
23797   // Create BEXTR instructions
23798   // BEXTR is ((X >> imm) & (2**size-1))
23799   if (VT == MVT::i32 || VT == MVT::i64) {
23800     // Check for BEXTR.
23801     if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
23802         (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
23803       ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
23804       ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
23805       if (MaskNode && ShiftNode) {
23806         uint64_t Mask = MaskNode->getZExtValue();
23807         uint64_t Shift = ShiftNode->getZExtValue();
23808         if (isMask_64(Mask)) {
23809           uint64_t MaskSize = countPopulation(Mask);
23810           if (Shift + MaskSize <= VT.getSizeInBits())
23811             return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
23812                                DAG.getConstant(Shift | (MaskSize << 8), DL,
23813                                                VT));
23814         }
23815       }
23816     } // BEXTR
23817
23818     return SDValue();
23819   }
23820
23821   // Want to form ANDNP nodes:
23822   // 1) In the hopes of then easily combining them with OR and AND nodes
23823   //    to form PBLEND/PSIGN.
23824   // 2) To match ANDN packed intrinsics
23825   if (VT != MVT::v2i64 && VT != MVT::v4i64)
23826     return SDValue();
23827
23828   // Check LHS for vnot
23829   if (N0.getOpcode() == ISD::XOR &&
23830       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
23831       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
23832     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
23833
23834   // Check RHS for vnot
23835   if (N1.getOpcode() == ISD::XOR &&
23836       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
23837       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
23838     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
23839
23840   return SDValue();
23841 }
23842
23843 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
23844                                 TargetLowering::DAGCombinerInfo &DCI,
23845                                 const X86Subtarget *Subtarget) {
23846   if (DCI.isBeforeLegalizeOps())
23847     return SDValue();
23848
23849   if (SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget))
23850     return R;
23851
23852   SDValue N0 = N->getOperand(0);
23853   SDValue N1 = N->getOperand(1);
23854   EVT VT = N->getValueType(0);
23855
23856   // look for psign/blend
23857   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
23858     if (!Subtarget->hasSSSE3() ||
23859         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
23860       return SDValue();
23861
23862     // Canonicalize pandn to RHS
23863     if (N0.getOpcode() == X86ISD::ANDNP)
23864       std::swap(N0, N1);
23865     // or (and (m, y), (pandn m, x))
23866     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
23867       SDValue Mask = N1.getOperand(0);
23868       SDValue X    = N1.getOperand(1);
23869       SDValue Y;
23870       if (N0.getOperand(0) == Mask)
23871         Y = N0.getOperand(1);
23872       if (N0.getOperand(1) == Mask)
23873         Y = N0.getOperand(0);
23874
23875       // Check to see if the mask appeared in both the AND and ANDNP and
23876       if (!Y.getNode())
23877         return SDValue();
23878
23879       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
23880       // Look through mask bitcast.
23881       if (Mask.getOpcode() == ISD::BITCAST)
23882         Mask = Mask.getOperand(0);
23883       if (X.getOpcode() == ISD::BITCAST)
23884         X = X.getOperand(0);
23885       if (Y.getOpcode() == ISD::BITCAST)
23886         Y = Y.getOperand(0);
23887
23888       EVT MaskVT = Mask.getValueType();
23889
23890       // Validate that the Mask operand is a vector sra node.
23891       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
23892       // there is no psrai.b
23893       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
23894       unsigned SraAmt = ~0;
23895       if (Mask.getOpcode() == ISD::SRA) {
23896         if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Mask.getOperand(1)))
23897           if (auto *AmtConst = AmtBV->getConstantSplatNode())
23898             SraAmt = AmtConst->getZExtValue();
23899       } else if (Mask.getOpcode() == X86ISD::VSRAI) {
23900         SDValue SraC = Mask.getOperand(1);
23901         SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
23902       }
23903       if ((SraAmt + 1) != EltBits)
23904         return SDValue();
23905
23906       SDLoc DL(N);
23907
23908       // Now we know we at least have a plendvb with the mask val.  See if
23909       // we can form a psignb/w/d.
23910       // psign = x.type == y.type == mask.type && y = sub(0, x);
23911       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
23912           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
23913           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
23914         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
23915                "Unsupported VT for PSIGN");
23916         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
23917         return DAG.getBitcast(VT, Mask);
23918       }
23919       // PBLENDVB only available on SSE 4.1
23920       if (!Subtarget->hasSSE41())
23921         return SDValue();
23922
23923       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
23924
23925       X = DAG.getBitcast(BlendVT, X);
23926       Y = DAG.getBitcast(BlendVT, Y);
23927       Mask = DAG.getBitcast(BlendVT, Mask);
23928       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
23929       return DAG.getBitcast(VT, Mask);
23930     }
23931   }
23932
23933   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
23934     return SDValue();
23935
23936   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
23937   MachineFunction &MF = DAG.getMachineFunction();
23938   bool OptForSize =
23939       MF.getFunction()->hasFnAttribute(Attribute::OptimizeForSize);
23940
23941   // SHLD/SHRD instructions have lower register pressure, but on some
23942   // platforms they have higher latency than the equivalent
23943   // series of shifts/or that would otherwise be generated.
23944   // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
23945   // have higher latencies and we are not optimizing for size.
23946   if (!OptForSize && Subtarget->isSHLDSlow())
23947     return SDValue();
23948
23949   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
23950     std::swap(N0, N1);
23951   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
23952     return SDValue();
23953   if (!N0.hasOneUse() || !N1.hasOneUse())
23954     return SDValue();
23955
23956   SDValue ShAmt0 = N0.getOperand(1);
23957   if (ShAmt0.getValueType() != MVT::i8)
23958     return SDValue();
23959   SDValue ShAmt1 = N1.getOperand(1);
23960   if (ShAmt1.getValueType() != MVT::i8)
23961     return SDValue();
23962   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
23963     ShAmt0 = ShAmt0.getOperand(0);
23964   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
23965     ShAmt1 = ShAmt1.getOperand(0);
23966
23967   SDLoc DL(N);
23968   unsigned Opc = X86ISD::SHLD;
23969   SDValue Op0 = N0.getOperand(0);
23970   SDValue Op1 = N1.getOperand(0);
23971   if (ShAmt0.getOpcode() == ISD::SUB) {
23972     Opc = X86ISD::SHRD;
23973     std::swap(Op0, Op1);
23974     std::swap(ShAmt0, ShAmt1);
23975   }
23976
23977   unsigned Bits = VT.getSizeInBits();
23978   if (ShAmt1.getOpcode() == ISD::SUB) {
23979     SDValue Sum = ShAmt1.getOperand(0);
23980     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
23981       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
23982       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
23983         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
23984       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
23985         return DAG.getNode(Opc, DL, VT,
23986                            Op0, Op1,
23987                            DAG.getNode(ISD::TRUNCATE, DL,
23988                                        MVT::i8, ShAmt0));
23989     }
23990   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
23991     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
23992     if (ShAmt0C &&
23993         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
23994       return DAG.getNode(Opc, DL, VT,
23995                          N0.getOperand(0), N1.getOperand(0),
23996                          DAG.getNode(ISD::TRUNCATE, DL,
23997                                        MVT::i8, ShAmt0));
23998   }
23999
24000   return SDValue();
24001 }
24002
24003 // Generate NEG and CMOV for integer abs.
24004 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
24005   EVT VT = N->getValueType(0);
24006
24007   // Since X86 does not have CMOV for 8-bit integer, we don't convert
24008   // 8-bit integer abs to NEG and CMOV.
24009   if (VT.isInteger() && VT.getSizeInBits() == 8)
24010     return SDValue();
24011
24012   SDValue N0 = N->getOperand(0);
24013   SDValue N1 = N->getOperand(1);
24014   SDLoc DL(N);
24015
24016   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
24017   // and change it to SUB and CMOV.
24018   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
24019       N0.getOpcode() == ISD::ADD &&
24020       N0.getOperand(1) == N1 &&
24021       N1.getOpcode() == ISD::SRA &&
24022       N1.getOperand(0) == N0.getOperand(0))
24023     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
24024       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
24025         // Generate SUB & CMOV.
24026         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
24027                                   DAG.getConstant(0, DL, VT), N0.getOperand(0));
24028
24029         SDValue Ops[] = { N0.getOperand(0), Neg,
24030                           DAG.getConstant(X86::COND_GE, DL, MVT::i8),
24031                           SDValue(Neg.getNode(), 1) };
24032         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
24033       }
24034   return SDValue();
24035 }
24036
24037 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
24038 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
24039                                  TargetLowering::DAGCombinerInfo &DCI,
24040                                  const X86Subtarget *Subtarget) {
24041   if (DCI.isBeforeLegalizeOps())
24042     return SDValue();
24043
24044   if (Subtarget->hasCMov())
24045     if (SDValue RV = performIntegerAbsCombine(N, DAG))
24046       return RV;
24047
24048   return SDValue();
24049 }
24050
24051 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
24052 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
24053                                   TargetLowering::DAGCombinerInfo &DCI,
24054                                   const X86Subtarget *Subtarget) {
24055   LoadSDNode *Ld = cast<LoadSDNode>(N);
24056   EVT RegVT = Ld->getValueType(0);
24057   EVT MemVT = Ld->getMemoryVT();
24058   SDLoc dl(Ld);
24059   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24060
24061   // For chips with slow 32-byte unaligned loads, break the 32-byte operation
24062   // into two 16-byte operations.
24063   ISD::LoadExtType Ext = Ld->getExtensionType();
24064   unsigned Alignment = Ld->getAlignment();
24065   bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
24066   if (RegVT.is256BitVector() && Subtarget->isUnalignedMem32Slow() &&
24067       !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
24068     unsigned NumElems = RegVT.getVectorNumElements();
24069     if (NumElems < 2)
24070       return SDValue();
24071
24072     SDValue Ptr = Ld->getBasePtr();
24073     SDValue Increment =
24074         DAG.getConstant(16, dl, TLI.getPointerTy(DAG.getDataLayout()));
24075
24076     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
24077                                   NumElems/2);
24078     SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
24079                                 Ld->getPointerInfo(), Ld->isVolatile(),
24080                                 Ld->isNonTemporal(), Ld->isInvariant(),
24081                                 Alignment);
24082     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
24083     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
24084                                 Ld->getPointerInfo(), Ld->isVolatile(),
24085                                 Ld->isNonTemporal(), Ld->isInvariant(),
24086                                 std::min(16U, Alignment));
24087     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
24088                              Load1.getValue(1),
24089                              Load2.getValue(1));
24090
24091     SDValue NewVec = DAG.getUNDEF(RegVT);
24092     NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
24093     NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
24094     return DCI.CombineTo(N, NewVec, TF, true);
24095   }
24096
24097   return SDValue();
24098 }
24099
24100 /// PerformMLOADCombine - Resolve extending loads
24101 static SDValue PerformMLOADCombine(SDNode *N, SelectionDAG &DAG,
24102                                    TargetLowering::DAGCombinerInfo &DCI,
24103                                    const X86Subtarget *Subtarget) {
24104   MaskedLoadSDNode *Mld = cast<MaskedLoadSDNode>(N);
24105   if (Mld->getExtensionType() != ISD::SEXTLOAD)
24106     return SDValue();
24107
24108   EVT VT = Mld->getValueType(0);
24109   unsigned NumElems = VT.getVectorNumElements();
24110   EVT LdVT = Mld->getMemoryVT();
24111   SDLoc dl(Mld);
24112
24113   assert(LdVT != VT && "Cannot extend to the same type");
24114   unsigned ToSz = VT.getVectorElementType().getSizeInBits();
24115   unsigned FromSz = LdVT.getVectorElementType().getSizeInBits();
24116   // From, To sizes and ElemCount must be pow of two
24117   assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
24118     "Unexpected size for extending masked load");
24119
24120   unsigned SizeRatio  = ToSz / FromSz;
24121   assert(SizeRatio * NumElems * FromSz == VT.getSizeInBits());
24122
24123   // Create a type on which we perform the shuffle
24124   EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
24125           LdVT.getScalarType(), NumElems*SizeRatio);
24126   assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
24127
24128   // Convert Src0 value
24129   SDValue WideSrc0 = DAG.getBitcast(WideVecVT, Mld->getSrc0());
24130   if (Mld->getSrc0().getOpcode() != ISD::UNDEF) {
24131     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
24132     for (unsigned i = 0; i != NumElems; ++i)
24133       ShuffleVec[i] = i * SizeRatio;
24134
24135     // Can't shuffle using an illegal type.
24136     assert (DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT)
24137             && "WideVecVT should be legal");
24138     WideSrc0 = DAG.getVectorShuffle(WideVecVT, dl, WideSrc0,
24139                                     DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
24140   }
24141   // Prepare the new mask
24142   SDValue NewMask;
24143   SDValue Mask = Mld->getMask();
24144   if (Mask.getValueType() == VT) {
24145     // Mask and original value have the same type
24146     NewMask = DAG.getBitcast(WideVecVT, Mask);
24147     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
24148     for (unsigned i = 0; i != NumElems; ++i)
24149       ShuffleVec[i] = i * SizeRatio;
24150     for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
24151       ShuffleVec[i] = NumElems*SizeRatio;
24152     NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
24153                                    DAG.getConstant(0, dl, WideVecVT),
24154                                    &ShuffleVec[0]);
24155   }
24156   else {
24157     assert(Mask.getValueType().getVectorElementType() == MVT::i1);
24158     unsigned WidenNumElts = NumElems*SizeRatio;
24159     unsigned MaskNumElts = VT.getVectorNumElements();
24160     EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(),  MVT::i1,
24161                                      WidenNumElts);
24162
24163     unsigned NumConcat = WidenNumElts / MaskNumElts;
24164     SmallVector<SDValue, 16> Ops(NumConcat);
24165     SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
24166     Ops[0] = Mask;
24167     for (unsigned i = 1; i != NumConcat; ++i)
24168       Ops[i] = ZeroVal;
24169
24170     NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
24171   }
24172
24173   SDValue WideLd = DAG.getMaskedLoad(WideVecVT, dl, Mld->getChain(),
24174                                      Mld->getBasePtr(), NewMask, WideSrc0,
24175                                      Mld->getMemoryVT(), Mld->getMemOperand(),
24176                                      ISD::NON_EXTLOAD);
24177   SDValue NewVec = DAG.getNode(X86ISD::VSEXT, dl, VT, WideLd);
24178   return DCI.CombineTo(N, NewVec, WideLd.getValue(1), true);
24179
24180 }
24181 /// PerformMSTORECombine - Resolve truncating stores
24182 static SDValue PerformMSTORECombine(SDNode *N, SelectionDAG &DAG,
24183                                     const X86Subtarget *Subtarget) {
24184   MaskedStoreSDNode *Mst = cast<MaskedStoreSDNode>(N);
24185   if (!Mst->isTruncatingStore())
24186     return SDValue();
24187
24188   EVT VT = Mst->getValue().getValueType();
24189   unsigned NumElems = VT.getVectorNumElements();
24190   EVT StVT = Mst->getMemoryVT();
24191   SDLoc dl(Mst);
24192
24193   assert(StVT != VT && "Cannot truncate to the same type");
24194   unsigned FromSz = VT.getVectorElementType().getSizeInBits();
24195   unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
24196
24197   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24198
24199   // The truncating store is legal in some cases. For example
24200   // vpmovqb, vpmovqw, vpmovqd, vpmovdb, vpmovdw
24201   // are designated for truncate store.
24202   // In this case we don't need any further transformations.
24203   if (TLI.isTruncStoreLegal(VT, StVT))
24204     return SDValue();
24205
24206   // From, To sizes and ElemCount must be pow of two
24207   assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
24208     "Unexpected size for truncating masked store");
24209   // We are going to use the original vector elt for storing.
24210   // Accumulated smaller vector elements must be a multiple of the store size.
24211   assert (((NumElems * FromSz) % ToSz) == 0 &&
24212           "Unexpected ratio for truncating masked store");
24213
24214   unsigned SizeRatio  = FromSz / ToSz;
24215   assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
24216
24217   // Create a type on which we perform the shuffle
24218   EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
24219           StVT.getScalarType(), NumElems*SizeRatio);
24220
24221   assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
24222
24223   SDValue WideVec = DAG.getBitcast(WideVecVT, Mst->getValue());
24224   SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
24225   for (unsigned i = 0; i != NumElems; ++i)
24226     ShuffleVec[i] = i * SizeRatio;
24227
24228   // Can't shuffle using an illegal type.
24229   assert (DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT)
24230           && "WideVecVT should be legal");
24231
24232   SDValue TruncatedVal = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
24233                                         DAG.getUNDEF(WideVecVT),
24234                                         &ShuffleVec[0]);
24235
24236   SDValue NewMask;
24237   SDValue Mask = Mst->getMask();
24238   if (Mask.getValueType() == VT) {
24239     // Mask and original value have the same type
24240     NewMask = DAG.getBitcast(WideVecVT, Mask);
24241     for (unsigned i = 0; i != NumElems; ++i)
24242       ShuffleVec[i] = i * SizeRatio;
24243     for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
24244       ShuffleVec[i] = NumElems*SizeRatio;
24245     NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
24246                                    DAG.getConstant(0, dl, WideVecVT),
24247                                    &ShuffleVec[0]);
24248   }
24249   else {
24250     assert(Mask.getValueType().getVectorElementType() == MVT::i1);
24251     unsigned WidenNumElts = NumElems*SizeRatio;
24252     unsigned MaskNumElts = VT.getVectorNumElements();
24253     EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(),  MVT::i1,
24254                                      WidenNumElts);
24255
24256     unsigned NumConcat = WidenNumElts / MaskNumElts;
24257     SmallVector<SDValue, 16> Ops(NumConcat);
24258     SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
24259     Ops[0] = Mask;
24260     for (unsigned i = 1; i != NumConcat; ++i)
24261       Ops[i] = ZeroVal;
24262
24263     NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
24264   }
24265
24266   return DAG.getMaskedStore(Mst->getChain(), dl, TruncatedVal, Mst->getBasePtr(),
24267                             NewMask, StVT, Mst->getMemOperand(), false);
24268 }
24269 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
24270 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
24271                                    const X86Subtarget *Subtarget) {
24272   StoreSDNode *St = cast<StoreSDNode>(N);
24273   EVT VT = St->getValue().getValueType();
24274   EVT StVT = St->getMemoryVT();
24275   SDLoc dl(St);
24276   SDValue StoredVal = St->getOperand(1);
24277   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24278
24279   // If we are saving a concatenation of two XMM registers and 32-byte stores
24280   // are slow, such as on Sandy Bridge, perform two 16-byte stores.
24281   unsigned Alignment = St->getAlignment();
24282   bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
24283   if (VT.is256BitVector() && Subtarget->isUnalignedMem32Slow() &&
24284       StVT == VT && !IsAligned) {
24285     unsigned NumElems = VT.getVectorNumElements();
24286     if (NumElems < 2)
24287       return SDValue();
24288
24289     SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
24290     SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
24291
24292     SDValue Stride =
24293         DAG.getConstant(16, dl, TLI.getPointerTy(DAG.getDataLayout()));
24294     SDValue Ptr0 = St->getBasePtr();
24295     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
24296
24297     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
24298                                 St->getPointerInfo(), St->isVolatile(),
24299                                 St->isNonTemporal(), Alignment);
24300     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
24301                                 St->getPointerInfo(), St->isVolatile(),
24302                                 St->isNonTemporal(),
24303                                 std::min(16U, Alignment));
24304     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
24305   }
24306
24307   // Optimize trunc store (of multiple scalars) to shuffle and store.
24308   // First, pack all of the elements in one place. Next, store to memory
24309   // in fewer chunks.
24310   if (St->isTruncatingStore() && VT.isVector()) {
24311     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24312     unsigned NumElems = VT.getVectorNumElements();
24313     assert(StVT != VT && "Cannot truncate to the same type");
24314     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
24315     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
24316
24317     // The truncating store is legal in some cases. For example
24318     // vpmovqb, vpmovqw, vpmovqd, vpmovdb, vpmovdw
24319     // are designated for truncate store.
24320     // In this case we don't need any further transformations.
24321     if (TLI.isTruncStoreLegal(VT, StVT))
24322       return SDValue();
24323
24324     // From, To sizes and ElemCount must be pow of two
24325     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
24326     // We are going to use the original vector elt for storing.
24327     // Accumulated smaller vector elements must be a multiple of the store size.
24328     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
24329
24330     unsigned SizeRatio  = FromSz / ToSz;
24331
24332     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
24333
24334     // Create a type on which we perform the shuffle
24335     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
24336             StVT.getScalarType(), NumElems*SizeRatio);
24337
24338     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
24339
24340     SDValue WideVec = DAG.getBitcast(WideVecVT, St->getValue());
24341     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
24342     for (unsigned i = 0; i != NumElems; ++i)
24343       ShuffleVec[i] = i * SizeRatio;
24344
24345     // Can't shuffle using an illegal type.
24346     if (!TLI.isTypeLegal(WideVecVT))
24347       return SDValue();
24348
24349     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
24350                                          DAG.getUNDEF(WideVecVT),
24351                                          &ShuffleVec[0]);
24352     // At this point all of the data is stored at the bottom of the
24353     // register. We now need to save it to mem.
24354
24355     // Find the largest store unit
24356     MVT StoreType = MVT::i8;
24357     for (MVT Tp : MVT::integer_valuetypes()) {
24358       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
24359         StoreType = Tp;
24360     }
24361
24362     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
24363     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
24364         (64 <= NumElems * ToSz))
24365       StoreType = MVT::f64;
24366
24367     // Bitcast the original vector into a vector of store-size units
24368     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
24369             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
24370     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
24371     SDValue ShuffWide = DAG.getBitcast(StoreVecVT, Shuff);
24372     SmallVector<SDValue, 8> Chains;
24373     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, dl,
24374                                         TLI.getPointerTy(DAG.getDataLayout()));
24375     SDValue Ptr = St->getBasePtr();
24376
24377     // Perform one or more big stores into memory.
24378     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
24379       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
24380                                    StoreType, ShuffWide,
24381                                    DAG.getIntPtrConstant(i, dl));
24382       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
24383                                 St->getPointerInfo(), St->isVolatile(),
24384                                 St->isNonTemporal(), St->getAlignment());
24385       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
24386       Chains.push_back(Ch);
24387     }
24388
24389     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
24390   }
24391
24392   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
24393   // the FP state in cases where an emms may be missing.
24394   // A preferable solution to the general problem is to figure out the right
24395   // places to insert EMMS.  This qualifies as a quick hack.
24396
24397   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
24398   if (VT.getSizeInBits() != 64)
24399     return SDValue();
24400
24401   const Function *F = DAG.getMachineFunction().getFunction();
24402   bool NoImplicitFloatOps = F->hasFnAttribute(Attribute::NoImplicitFloat);
24403   bool F64IsLegal =
24404       !Subtarget->useSoftFloat() && !NoImplicitFloatOps && Subtarget->hasSSE2();
24405   if ((VT.isVector() ||
24406        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
24407       isa<LoadSDNode>(St->getValue()) &&
24408       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
24409       St->getChain().hasOneUse() && !St->isVolatile()) {
24410     SDNode* LdVal = St->getValue().getNode();
24411     LoadSDNode *Ld = nullptr;
24412     int TokenFactorIndex = -1;
24413     SmallVector<SDValue, 8> Ops;
24414     SDNode* ChainVal = St->getChain().getNode();
24415     // Must be a store of a load.  We currently handle two cases:  the load
24416     // is a direct child, and it's under an intervening TokenFactor.  It is
24417     // possible to dig deeper under nested TokenFactors.
24418     if (ChainVal == LdVal)
24419       Ld = cast<LoadSDNode>(St->getChain());
24420     else if (St->getValue().hasOneUse() &&
24421              ChainVal->getOpcode() == ISD::TokenFactor) {
24422       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
24423         if (ChainVal->getOperand(i).getNode() == LdVal) {
24424           TokenFactorIndex = i;
24425           Ld = cast<LoadSDNode>(St->getValue());
24426         } else
24427           Ops.push_back(ChainVal->getOperand(i));
24428       }
24429     }
24430
24431     if (!Ld || !ISD::isNormalLoad(Ld))
24432       return SDValue();
24433
24434     // If this is not the MMX case, i.e. we are just turning i64 load/store
24435     // into f64 load/store, avoid the transformation if there are multiple
24436     // uses of the loaded value.
24437     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
24438       return SDValue();
24439
24440     SDLoc LdDL(Ld);
24441     SDLoc StDL(N);
24442     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
24443     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
24444     // pair instead.
24445     if (Subtarget->is64Bit() || F64IsLegal) {
24446       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
24447       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
24448                                   Ld->getPointerInfo(), Ld->isVolatile(),
24449                                   Ld->isNonTemporal(), Ld->isInvariant(),
24450                                   Ld->getAlignment());
24451       SDValue NewChain = NewLd.getValue(1);
24452       if (TokenFactorIndex != -1) {
24453         Ops.push_back(NewChain);
24454         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
24455       }
24456       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
24457                           St->getPointerInfo(),
24458                           St->isVolatile(), St->isNonTemporal(),
24459                           St->getAlignment());
24460     }
24461
24462     // Otherwise, lower to two pairs of 32-bit loads / stores.
24463     SDValue LoAddr = Ld->getBasePtr();
24464     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
24465                                  DAG.getConstant(4, LdDL, MVT::i32));
24466
24467     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
24468                                Ld->getPointerInfo(),
24469                                Ld->isVolatile(), Ld->isNonTemporal(),
24470                                Ld->isInvariant(), Ld->getAlignment());
24471     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
24472                                Ld->getPointerInfo().getWithOffset(4),
24473                                Ld->isVolatile(), Ld->isNonTemporal(),
24474                                Ld->isInvariant(),
24475                                MinAlign(Ld->getAlignment(), 4));
24476
24477     SDValue NewChain = LoLd.getValue(1);
24478     if (TokenFactorIndex != -1) {
24479       Ops.push_back(LoLd);
24480       Ops.push_back(HiLd);
24481       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
24482     }
24483
24484     LoAddr = St->getBasePtr();
24485     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
24486                          DAG.getConstant(4, StDL, MVT::i32));
24487
24488     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
24489                                 St->getPointerInfo(),
24490                                 St->isVolatile(), St->isNonTemporal(),
24491                                 St->getAlignment());
24492     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
24493                                 St->getPointerInfo().getWithOffset(4),
24494                                 St->isVolatile(),
24495                                 St->isNonTemporal(),
24496                                 MinAlign(St->getAlignment(), 4));
24497     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
24498   }
24499
24500   // This is similar to the above case, but here we handle a scalar 64-bit
24501   // integer store that is extracted from a vector on a 32-bit target.
24502   // If we have SSE2, then we can treat it like a floating-point double
24503   // to get past legalization. The execution dependencies fixup pass will
24504   // choose the optimal machine instruction for the store if this really is
24505   // an integer or v2f32 rather than an f64.
24506   if (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit() &&
24507       St->getOperand(1).getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
24508     SDValue OldExtract = St->getOperand(1);
24509     SDValue ExtOp0 = OldExtract.getOperand(0);
24510     unsigned VecSize = ExtOp0.getValueSizeInBits();
24511     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, VecSize / 64);
24512     SDValue BitCast = DAG.getBitcast(VecVT, ExtOp0);
24513     SDValue NewExtract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
24514                                      BitCast, OldExtract.getOperand(1));
24515     return DAG.getStore(St->getChain(), dl, NewExtract, St->getBasePtr(),
24516                         St->getPointerInfo(), St->isVolatile(),
24517                         St->isNonTemporal(), St->getAlignment());
24518   }
24519
24520   return SDValue();
24521 }
24522
24523 /// Return 'true' if this vector operation is "horizontal"
24524 /// and return the operands for the horizontal operation in LHS and RHS.  A
24525 /// horizontal operation performs the binary operation on successive elements
24526 /// of its first operand, then on successive elements of its second operand,
24527 /// returning the resulting values in a vector.  For example, if
24528 ///   A = < float a0, float a1, float a2, float a3 >
24529 /// and
24530 ///   B = < float b0, float b1, float b2, float b3 >
24531 /// then the result of doing a horizontal operation on A and B is
24532 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
24533 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
24534 /// A horizontal-op B, for some already available A and B, and if so then LHS is
24535 /// set to A, RHS to B, and the routine returns 'true'.
24536 /// Note that the binary operation should have the property that if one of the
24537 /// operands is UNDEF then the result is UNDEF.
24538 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
24539   // Look for the following pattern: if
24540   //   A = < float a0, float a1, float a2, float a3 >
24541   //   B = < float b0, float b1, float b2, float b3 >
24542   // and
24543   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
24544   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
24545   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
24546   // which is A horizontal-op B.
24547
24548   // At least one of the operands should be a vector shuffle.
24549   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
24550       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
24551     return false;
24552
24553   MVT VT = LHS.getSimpleValueType();
24554
24555   assert((VT.is128BitVector() || VT.is256BitVector()) &&
24556          "Unsupported vector type for horizontal add/sub");
24557
24558   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
24559   // operate independently on 128-bit lanes.
24560   unsigned NumElts = VT.getVectorNumElements();
24561   unsigned NumLanes = VT.getSizeInBits()/128;
24562   unsigned NumLaneElts = NumElts / NumLanes;
24563   assert((NumLaneElts % 2 == 0) &&
24564          "Vector type should have an even number of elements in each lane");
24565   unsigned HalfLaneElts = NumLaneElts/2;
24566
24567   // View LHS in the form
24568   //   LHS = VECTOR_SHUFFLE A, B, LMask
24569   // If LHS is not a shuffle then pretend it is the shuffle
24570   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
24571   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
24572   // type VT.
24573   SDValue A, B;
24574   SmallVector<int, 16> LMask(NumElts);
24575   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
24576     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
24577       A = LHS.getOperand(0);
24578     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
24579       B = LHS.getOperand(1);
24580     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
24581     std::copy(Mask.begin(), Mask.end(), LMask.begin());
24582   } else {
24583     if (LHS.getOpcode() != ISD::UNDEF)
24584       A = LHS;
24585     for (unsigned i = 0; i != NumElts; ++i)
24586       LMask[i] = i;
24587   }
24588
24589   // Likewise, view RHS in the form
24590   //   RHS = VECTOR_SHUFFLE C, D, RMask
24591   SDValue C, D;
24592   SmallVector<int, 16> RMask(NumElts);
24593   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
24594     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
24595       C = RHS.getOperand(0);
24596     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
24597       D = RHS.getOperand(1);
24598     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
24599     std::copy(Mask.begin(), Mask.end(), RMask.begin());
24600   } else {
24601     if (RHS.getOpcode() != ISD::UNDEF)
24602       C = RHS;
24603     for (unsigned i = 0; i != NumElts; ++i)
24604       RMask[i] = i;
24605   }
24606
24607   // Check that the shuffles are both shuffling the same vectors.
24608   if (!(A == C && B == D) && !(A == D && B == C))
24609     return false;
24610
24611   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
24612   if (!A.getNode() && !B.getNode())
24613     return false;
24614
24615   // If A and B occur in reverse order in RHS, then "swap" them (which means
24616   // rewriting the mask).
24617   if (A != C)
24618     ShuffleVectorSDNode::commuteMask(RMask);
24619
24620   // At this point LHS and RHS are equivalent to
24621   //   LHS = VECTOR_SHUFFLE A, B, LMask
24622   //   RHS = VECTOR_SHUFFLE A, B, RMask
24623   // Check that the masks correspond to performing a horizontal operation.
24624   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
24625     for (unsigned i = 0; i != NumLaneElts; ++i) {
24626       int LIdx = LMask[i+l], RIdx = RMask[i+l];
24627
24628       // Ignore any UNDEF components.
24629       if (LIdx < 0 || RIdx < 0 ||
24630           (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
24631           (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
24632         continue;
24633
24634       // Check that successive elements are being operated on.  If not, this is
24635       // not a horizontal operation.
24636       unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
24637       int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
24638       if (!(LIdx == Index && RIdx == Index + 1) &&
24639           !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
24640         return false;
24641     }
24642   }
24643
24644   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
24645   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
24646   return true;
24647 }
24648
24649 /// Do target-specific dag combines on floating point adds.
24650 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
24651                                   const X86Subtarget *Subtarget) {
24652   EVT VT = N->getValueType(0);
24653   SDValue LHS = N->getOperand(0);
24654   SDValue RHS = N->getOperand(1);
24655
24656   // Try to synthesize horizontal adds from adds of shuffles.
24657   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
24658        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
24659       isHorizontalBinOp(LHS, RHS, true))
24660     return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
24661   return SDValue();
24662 }
24663
24664 /// Do target-specific dag combines on floating point subs.
24665 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
24666                                   const X86Subtarget *Subtarget) {
24667   EVT VT = N->getValueType(0);
24668   SDValue LHS = N->getOperand(0);
24669   SDValue RHS = N->getOperand(1);
24670
24671   // Try to synthesize horizontal subs from subs of shuffles.
24672   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
24673        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
24674       isHorizontalBinOp(LHS, RHS, false))
24675     return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
24676   return SDValue();
24677 }
24678
24679 /// Do target-specific dag combines on X86ISD::FOR and X86ISD::FXOR nodes.
24680 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
24681   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
24682
24683   // F[X]OR(0.0, x) -> x
24684   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
24685     if (C->getValueAPF().isPosZero())
24686       return N->getOperand(1);
24687
24688   // F[X]OR(x, 0.0) -> x
24689   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
24690     if (C->getValueAPF().isPosZero())
24691       return N->getOperand(0);
24692   return SDValue();
24693 }
24694
24695 /// Do target-specific dag combines on X86ISD::FMIN and X86ISD::FMAX nodes.
24696 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
24697   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
24698
24699   // Only perform optimizations if UnsafeMath is used.
24700   if (!DAG.getTarget().Options.UnsafeFPMath)
24701     return SDValue();
24702
24703   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
24704   // into FMINC and FMAXC, which are Commutative operations.
24705   unsigned NewOp = 0;
24706   switch (N->getOpcode()) {
24707     default: llvm_unreachable("unknown opcode");
24708     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
24709     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
24710   }
24711
24712   return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
24713                      N->getOperand(0), N->getOperand(1));
24714 }
24715
24716 /// Do target-specific dag combines on X86ISD::FAND nodes.
24717 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
24718   // FAND(0.0, x) -> 0.0
24719   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
24720     if (C->getValueAPF().isPosZero())
24721       return N->getOperand(0);
24722
24723   // FAND(x, 0.0) -> 0.0
24724   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
24725     if (C->getValueAPF().isPosZero())
24726       return N->getOperand(1);
24727
24728   return SDValue();
24729 }
24730
24731 /// Do target-specific dag combines on X86ISD::FANDN nodes
24732 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
24733   // FANDN(0.0, x) -> x
24734   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
24735     if (C->getValueAPF().isPosZero())
24736       return N->getOperand(1);
24737
24738   // FANDN(x, 0.0) -> 0.0
24739   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
24740     if (C->getValueAPF().isPosZero())
24741       return N->getOperand(1);
24742
24743   return SDValue();
24744 }
24745
24746 static SDValue PerformBTCombine(SDNode *N,
24747                                 SelectionDAG &DAG,
24748                                 TargetLowering::DAGCombinerInfo &DCI) {
24749   // BT ignores high bits in the bit index operand.
24750   SDValue Op1 = N->getOperand(1);
24751   if (Op1.hasOneUse()) {
24752     unsigned BitWidth = Op1.getValueSizeInBits();
24753     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
24754     APInt KnownZero, KnownOne;
24755     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
24756                                           !DCI.isBeforeLegalizeOps());
24757     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24758     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
24759         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
24760       DCI.CommitTargetLoweringOpt(TLO);
24761   }
24762   return SDValue();
24763 }
24764
24765 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
24766   SDValue Op = N->getOperand(0);
24767   if (Op.getOpcode() == ISD::BITCAST)
24768     Op = Op.getOperand(0);
24769   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
24770   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
24771       VT.getVectorElementType().getSizeInBits() ==
24772       OpVT.getVectorElementType().getSizeInBits()) {
24773     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
24774   }
24775   return SDValue();
24776 }
24777
24778 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
24779                                                const X86Subtarget *Subtarget) {
24780   EVT VT = N->getValueType(0);
24781   if (!VT.isVector())
24782     return SDValue();
24783
24784   SDValue N0 = N->getOperand(0);
24785   SDValue N1 = N->getOperand(1);
24786   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
24787   SDLoc dl(N);
24788
24789   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
24790   // both SSE and AVX2 since there is no sign-extended shift right
24791   // operation on a vector with 64-bit elements.
24792   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
24793   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
24794   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
24795       N0.getOpcode() == ISD::SIGN_EXTEND)) {
24796     SDValue N00 = N0.getOperand(0);
24797
24798     // EXTLOAD has a better solution on AVX2,
24799     // it may be replaced with X86ISD::VSEXT node.
24800     if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
24801       if (!ISD::isNormalLoad(N00.getNode()))
24802         return SDValue();
24803
24804     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
24805         SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
24806                                   N00, N1);
24807       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
24808     }
24809   }
24810   return SDValue();
24811 }
24812
24813 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
24814                                   TargetLowering::DAGCombinerInfo &DCI,
24815                                   const X86Subtarget *Subtarget) {
24816   SDValue N0 = N->getOperand(0);
24817   EVT VT = N->getValueType(0);
24818   EVT SVT = VT.getScalarType();
24819   EVT InVT = N0.getValueType();
24820   EVT InSVT = InVT.getScalarType();
24821   SDLoc DL(N);
24822
24823   // (i8,i32 sext (sdivrem (i8 x, i8 y)) ->
24824   // (i8,i32 (sdivrem_sext_hreg (i8 x, i8 y)
24825   // This exposes the sext to the sdivrem lowering, so that it directly extends
24826   // from AH (which we otherwise need to do contortions to access).
24827   if (N0.getOpcode() == ISD::SDIVREM && N0.getResNo() == 1 &&
24828       InVT == MVT::i8 && VT == MVT::i32) {
24829     SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
24830     SDValue R = DAG.getNode(X86ISD::SDIVREM8_SEXT_HREG, DL, NodeTys,
24831                             N0.getOperand(0), N0.getOperand(1));
24832     DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
24833     return R.getValue(1);
24834   }
24835
24836   if (!DCI.isBeforeLegalizeOps()) {
24837     if (InVT == MVT::i1) {
24838       SDValue Zero = DAG.getConstant(0, DL, VT);
24839       SDValue AllOnes =
24840         DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), DL, VT);
24841       return DAG.getNode(ISD::SELECT, DL, VT, N0, AllOnes, Zero);
24842     }
24843     return SDValue();
24844   }
24845
24846   if (VT.isVector() && Subtarget->hasSSE2()) {
24847     auto ExtendVecSize = [&DAG](SDLoc DL, SDValue N, unsigned Size) {
24848       EVT InVT = N.getValueType();
24849       EVT OutVT = EVT::getVectorVT(*DAG.getContext(), InVT.getScalarType(),
24850                                    Size / InVT.getScalarSizeInBits());
24851       SmallVector<SDValue, 8> Opnds(Size / InVT.getSizeInBits(),
24852                                     DAG.getUNDEF(InVT));
24853       Opnds[0] = N;
24854       return DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, Opnds);
24855     };
24856
24857     // If target-size is less than 128-bits, extend to a type that would extend
24858     // to 128 bits, extend that and extract the original target vector.
24859     if (VT.getSizeInBits() < 128 && !(128 % VT.getSizeInBits()) &&
24860         (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
24861         (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
24862       unsigned Scale = 128 / VT.getSizeInBits();
24863       EVT ExVT =
24864           EVT::getVectorVT(*DAG.getContext(), SVT, 128 / SVT.getSizeInBits());
24865       SDValue Ex = ExtendVecSize(DL, N0, Scale * InVT.getSizeInBits());
24866       SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND, DL, ExVT, Ex);
24867       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, SExt,
24868                          DAG.getIntPtrConstant(0, DL));
24869     }
24870
24871     // If target-size is 128-bits, then convert to ISD::SIGN_EXTEND_VECTOR_INREG
24872     // which ensures lowering to X86ISD::VSEXT (pmovsx*).
24873     if (VT.getSizeInBits() == 128 &&
24874         (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
24875         (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
24876       SDValue ExOp = ExtendVecSize(DL, N0, 128);
24877       return DAG.getSignExtendVectorInReg(ExOp, DL, VT);
24878     }
24879
24880     // On pre-AVX2 targets, split into 128-bit nodes of
24881     // ISD::SIGN_EXTEND_VECTOR_INREG.
24882     if (!Subtarget->hasInt256() && !(VT.getSizeInBits() % 128) &&
24883         (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
24884         (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
24885       unsigned NumVecs = VT.getSizeInBits() / 128;
24886       unsigned NumSubElts = 128 / SVT.getSizeInBits();
24887       EVT SubVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumSubElts);
24888       EVT InSubVT = EVT::getVectorVT(*DAG.getContext(), InSVT, NumSubElts);
24889
24890       SmallVector<SDValue, 8> Opnds;
24891       for (unsigned i = 0, Offset = 0; i != NumVecs;
24892            ++i, Offset += NumSubElts) {
24893         SDValue SrcVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InSubVT, N0,
24894                                      DAG.getIntPtrConstant(Offset, DL));
24895         SrcVec = ExtendVecSize(DL, SrcVec, 128);
24896         SrcVec = DAG.getSignExtendVectorInReg(SrcVec, DL, SubVT);
24897         Opnds.push_back(SrcVec);
24898       }
24899       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Opnds);
24900     }
24901   }
24902
24903   if (!Subtarget->hasFp256())
24904     return SDValue();
24905
24906   if (VT.isVector() && VT.getSizeInBits() == 256)
24907     if (SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget))
24908       return R;
24909
24910   return SDValue();
24911 }
24912
24913 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
24914                                  const X86Subtarget* Subtarget) {
24915   SDLoc dl(N);
24916   EVT VT = N->getValueType(0);
24917
24918   // Let legalize expand this if it isn't a legal type yet.
24919   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
24920     return SDValue();
24921
24922   EVT ScalarVT = VT.getScalarType();
24923   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
24924       (!Subtarget->hasFMA() && !Subtarget->hasFMA4() &&
24925        !Subtarget->hasAVX512()))
24926     return SDValue();
24927
24928   SDValue A = N->getOperand(0);
24929   SDValue B = N->getOperand(1);
24930   SDValue C = N->getOperand(2);
24931
24932   bool NegA = (A.getOpcode() == ISD::FNEG);
24933   bool NegB = (B.getOpcode() == ISD::FNEG);
24934   bool NegC = (C.getOpcode() == ISD::FNEG);
24935
24936   // Negative multiplication when NegA xor NegB
24937   bool NegMul = (NegA != NegB);
24938   if (NegA)
24939     A = A.getOperand(0);
24940   if (NegB)
24941     B = B.getOperand(0);
24942   if (NegC)
24943     C = C.getOperand(0);
24944
24945   unsigned Opcode;
24946   if (!NegMul)
24947     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
24948   else
24949     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
24950
24951   return DAG.getNode(Opcode, dl, VT, A, B, C);
24952 }
24953
24954 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
24955                                   TargetLowering::DAGCombinerInfo &DCI,
24956                                   const X86Subtarget *Subtarget) {
24957   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
24958   //           (and (i32 x86isd::setcc_carry), 1)
24959   // This eliminates the zext. This transformation is necessary because
24960   // ISD::SETCC is always legalized to i8.
24961   SDLoc dl(N);
24962   SDValue N0 = N->getOperand(0);
24963   EVT VT = N->getValueType(0);
24964
24965   if (N0.getOpcode() == ISD::AND &&
24966       N0.hasOneUse() &&
24967       N0.getOperand(0).hasOneUse()) {
24968     SDValue N00 = N0.getOperand(0);
24969     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
24970       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
24971       if (!C || C->getZExtValue() != 1)
24972         return SDValue();
24973       return DAG.getNode(ISD::AND, dl, VT,
24974                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
24975                                      N00.getOperand(0), N00.getOperand(1)),
24976                          DAG.getConstant(1, dl, VT));
24977     }
24978   }
24979
24980   if (N0.getOpcode() == ISD::TRUNCATE &&
24981       N0.hasOneUse() &&
24982       N0.getOperand(0).hasOneUse()) {
24983     SDValue N00 = N0.getOperand(0);
24984     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
24985       return DAG.getNode(ISD::AND, dl, VT,
24986                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
24987                                      N00.getOperand(0), N00.getOperand(1)),
24988                          DAG.getConstant(1, dl, VT));
24989     }
24990   }
24991
24992   if (VT.is256BitVector())
24993     if (SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget))
24994       return R;
24995
24996   // (i8,i32 zext (udivrem (i8 x, i8 y)) ->
24997   // (i8,i32 (udivrem_zext_hreg (i8 x, i8 y)
24998   // This exposes the zext to the udivrem lowering, so that it directly extends
24999   // from AH (which we otherwise need to do contortions to access).
25000   if (N0.getOpcode() == ISD::UDIVREM &&
25001       N0.getResNo() == 1 && N0.getValueType() == MVT::i8 &&
25002       (VT == MVT::i32 || VT == MVT::i64)) {
25003     SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
25004     SDValue R = DAG.getNode(X86ISD::UDIVREM8_ZEXT_HREG, dl, NodeTys,
25005                             N0.getOperand(0), N0.getOperand(1));
25006     DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
25007     return R.getValue(1);
25008   }
25009
25010   return SDValue();
25011 }
25012
25013 // Optimize x == -y --> x+y == 0
25014 //          x != -y --> x+y != 0
25015 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
25016                                       const X86Subtarget* Subtarget) {
25017   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
25018   SDValue LHS = N->getOperand(0);
25019   SDValue RHS = N->getOperand(1);
25020   EVT VT = N->getValueType(0);
25021   SDLoc DL(N);
25022
25023   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
25024     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
25025       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
25026         SDValue addV = DAG.getNode(ISD::ADD, DL, LHS.getValueType(), RHS,
25027                                    LHS.getOperand(1));
25028         return DAG.getSetCC(DL, N->getValueType(0), addV,
25029                             DAG.getConstant(0, DL, addV.getValueType()), CC);
25030       }
25031   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
25032     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
25033       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
25034         SDValue addV = DAG.getNode(ISD::ADD, DL, RHS.getValueType(), LHS,
25035                                    RHS.getOperand(1));
25036         return DAG.getSetCC(DL, N->getValueType(0), addV,
25037                             DAG.getConstant(0, DL, addV.getValueType()), CC);
25038       }
25039
25040   if (VT.getScalarType() == MVT::i1 &&
25041       (CC == ISD::SETNE || CC == ISD::SETEQ || ISD::isSignedIntSetCC(CC))) {
25042     bool IsSEXT0 =
25043         (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
25044         (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
25045     bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
25046
25047     if (!IsSEXT0 || !IsVZero1) {
25048       // Swap the operands and update the condition code.
25049       std::swap(LHS, RHS);
25050       CC = ISD::getSetCCSwappedOperands(CC);
25051
25052       IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
25053                 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
25054       IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
25055     }
25056
25057     if (IsSEXT0 && IsVZero1) {
25058       assert(VT == LHS.getOperand(0).getValueType() &&
25059              "Uexpected operand type");
25060       if (CC == ISD::SETGT)
25061         return DAG.getConstant(0, DL, VT);
25062       if (CC == ISD::SETLE)
25063         return DAG.getConstant(1, DL, VT);
25064       if (CC == ISD::SETEQ || CC == ISD::SETGE)
25065         return DAG.getNOT(DL, LHS.getOperand(0), VT);
25066
25067       assert((CC == ISD::SETNE || CC == ISD::SETLT) &&
25068              "Unexpected condition code!");
25069       return LHS.getOperand(0);
25070     }
25071   }
25072
25073   return SDValue();
25074 }
25075
25076 static SDValue NarrowVectorLoadToElement(LoadSDNode *Load, unsigned Index,
25077                                          SelectionDAG &DAG) {
25078   SDLoc dl(Load);
25079   MVT VT = Load->getSimpleValueType(0);
25080   MVT EVT = VT.getVectorElementType();
25081   SDValue Addr = Load->getOperand(1);
25082   SDValue NewAddr = DAG.getNode(
25083       ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
25084       DAG.getConstant(Index * EVT.getStoreSize(), dl,
25085                       Addr.getSimpleValueType()));
25086
25087   SDValue NewLoad =
25088       DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
25089                   DAG.getMachineFunction().getMachineMemOperand(
25090                       Load->getMemOperand(), 0, EVT.getStoreSize()));
25091   return NewLoad;
25092 }
25093
25094 static SDValue PerformINSERTPSCombine(SDNode *N, SelectionDAG &DAG,
25095                                       const X86Subtarget *Subtarget) {
25096   SDLoc dl(N);
25097   MVT VT = N->getOperand(1)->getSimpleValueType(0);
25098   assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
25099          "X86insertps is only defined for v4x32");
25100
25101   SDValue Ld = N->getOperand(1);
25102   if (MayFoldLoad(Ld)) {
25103     // Extract the countS bits from the immediate so we can get the proper
25104     // address when narrowing the vector load to a specific element.
25105     // When the second source op is a memory address, insertps doesn't use
25106     // countS and just gets an f32 from that address.
25107     unsigned DestIndex =
25108         cast<ConstantSDNode>(N->getOperand(2))->getZExtValue() >> 6;
25109
25110     Ld = NarrowVectorLoadToElement(cast<LoadSDNode>(Ld), DestIndex, DAG);
25111
25112     // Create this as a scalar to vector to match the instruction pattern.
25113     SDValue LoadScalarToVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Ld);
25114     // countS bits are ignored when loading from memory on insertps, which
25115     // means we don't need to explicitly set them to 0.
25116     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N->getOperand(0),
25117                        LoadScalarToVector, N->getOperand(2));
25118   }
25119   return SDValue();
25120 }
25121
25122 static SDValue PerformBLENDICombine(SDNode *N, SelectionDAG &DAG) {
25123   SDValue V0 = N->getOperand(0);
25124   SDValue V1 = N->getOperand(1);
25125   SDLoc DL(N);
25126   EVT VT = N->getValueType(0);
25127
25128   // Canonicalize a v2f64 blend with a mask of 2 by swapping the vector
25129   // operands and changing the mask to 1. This saves us a bunch of
25130   // pattern-matching possibilities related to scalar math ops in SSE/AVX.
25131   // x86InstrInfo knows how to commute this back after instruction selection
25132   // if it would help register allocation.
25133
25134   // TODO: If optimizing for size or a processor that doesn't suffer from
25135   // partial register update stalls, this should be transformed into a MOVSD
25136   // instruction because a MOVSD is 1-2 bytes smaller than a BLENDPD.
25137
25138   if (VT == MVT::v2f64)
25139     if (auto *Mask = dyn_cast<ConstantSDNode>(N->getOperand(2)))
25140       if (Mask->getZExtValue() == 2 && !isShuffleFoldableLoad(V0)) {
25141         SDValue NewMask = DAG.getConstant(1, DL, MVT::i8);
25142         return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V0, NewMask);
25143       }
25144
25145   return SDValue();
25146 }
25147
25148 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
25149 // as "sbb reg,reg", since it can be extended without zext and produces
25150 // an all-ones bit which is more useful than 0/1 in some cases.
25151 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
25152                                MVT VT) {
25153   if (VT == MVT::i8)
25154     return DAG.getNode(ISD::AND, DL, VT,
25155                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
25156                                    DAG.getConstant(X86::COND_B, DL, MVT::i8),
25157                                    EFLAGS),
25158                        DAG.getConstant(1, DL, VT));
25159   assert (VT == MVT::i1 && "Unexpected type for SECCC node");
25160   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
25161                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
25162                                  DAG.getConstant(X86::COND_B, DL, MVT::i8),
25163                                  EFLAGS));
25164 }
25165
25166 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
25167 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
25168                                    TargetLowering::DAGCombinerInfo &DCI,
25169                                    const X86Subtarget *Subtarget) {
25170   SDLoc DL(N);
25171   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
25172   SDValue EFLAGS = N->getOperand(1);
25173
25174   if (CC == X86::COND_A) {
25175     // Try to convert COND_A into COND_B in an attempt to facilitate
25176     // materializing "setb reg".
25177     //
25178     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
25179     // cannot take an immediate as its first operand.
25180     //
25181     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
25182         EFLAGS.getValueType().isInteger() &&
25183         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
25184       SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
25185                                    EFLAGS.getNode()->getVTList(),
25186                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
25187       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
25188       return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
25189     }
25190   }
25191
25192   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
25193   // a zext and produces an all-ones bit which is more useful than 0/1 in some
25194   // cases.
25195   if (CC == X86::COND_B)
25196     return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
25197
25198   if (SDValue Flags = checkBoolTestSetCCCombine(EFLAGS, CC)) {
25199     SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
25200     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
25201   }
25202
25203   return SDValue();
25204 }
25205
25206 // Optimize branch condition evaluation.
25207 //
25208 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
25209                                     TargetLowering::DAGCombinerInfo &DCI,
25210                                     const X86Subtarget *Subtarget) {
25211   SDLoc DL(N);
25212   SDValue Chain = N->getOperand(0);
25213   SDValue Dest = N->getOperand(1);
25214   SDValue EFLAGS = N->getOperand(3);
25215   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
25216
25217   if (SDValue Flags = checkBoolTestSetCCCombine(EFLAGS, CC)) {
25218     SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
25219     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
25220                        Flags);
25221   }
25222
25223   return SDValue();
25224 }
25225
25226 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
25227                                                          SelectionDAG &DAG) {
25228   // Take advantage of vector comparisons producing 0 or -1 in each lane to
25229   // optimize away operation when it's from a constant.
25230   //
25231   // The general transformation is:
25232   //    UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
25233   //       AND(VECTOR_CMP(x,y), constant2)
25234   //    constant2 = UNARYOP(constant)
25235
25236   // Early exit if this isn't a vector operation, the operand of the
25237   // unary operation isn't a bitwise AND, or if the sizes of the operations
25238   // aren't the same.
25239   EVT VT = N->getValueType(0);
25240   if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
25241       N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
25242       VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
25243     return SDValue();
25244
25245   // Now check that the other operand of the AND is a constant. We could
25246   // make the transformation for non-constant splats as well, but it's unclear
25247   // that would be a benefit as it would not eliminate any operations, just
25248   // perform one more step in scalar code before moving to the vector unit.
25249   if (BuildVectorSDNode *BV =
25250           dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
25251     // Bail out if the vector isn't a constant.
25252     if (!BV->isConstant())
25253       return SDValue();
25254
25255     // Everything checks out. Build up the new and improved node.
25256     SDLoc DL(N);
25257     EVT IntVT = BV->getValueType(0);
25258     // Create a new constant of the appropriate type for the transformed
25259     // DAG.
25260     SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
25261     // The AND node needs bitcasts to/from an integer vector type around it.
25262     SDValue MaskConst = DAG.getBitcast(IntVT, SourceConst);
25263     SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
25264                                  N->getOperand(0)->getOperand(0), MaskConst);
25265     SDValue Res = DAG.getBitcast(VT, NewAnd);
25266     return Res;
25267   }
25268
25269   return SDValue();
25270 }
25271
25272 static SDValue PerformUINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
25273                                         const X86Subtarget *Subtarget) {
25274   SDValue Op0 = N->getOperand(0);
25275   EVT VT = N->getValueType(0);
25276   EVT InVT = Op0.getValueType();
25277   EVT InSVT = InVT.getScalarType();
25278   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
25279
25280   // UINT_TO_FP(vXi8) -> SINT_TO_FP(ZEXT(vXi8 to vXi32))
25281   // UINT_TO_FP(vXi16) -> SINT_TO_FP(ZEXT(vXi16 to vXi32))
25282   if (InVT.isVector() && (InSVT == MVT::i8 || InSVT == MVT::i16)) {
25283     SDLoc dl(N);
25284     EVT DstVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
25285                                  InVT.getVectorNumElements());
25286     SDValue P = DAG.getNode(ISD::ZERO_EXTEND, dl, DstVT, Op0);
25287
25288     if (TLI.isOperationLegal(ISD::UINT_TO_FP, DstVT))
25289       return DAG.getNode(ISD::UINT_TO_FP, dl, VT, P);
25290
25291     return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
25292   }
25293
25294   return SDValue();
25295 }
25296
25297 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
25298                                         const X86Subtarget *Subtarget) {
25299   // First try to optimize away the conversion entirely when it's
25300   // conditionally from a constant. Vectors only.
25301   if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG))
25302     return Res;
25303
25304   // Now move on to more general possibilities.
25305   SDValue Op0 = N->getOperand(0);
25306   EVT VT = N->getValueType(0);
25307   EVT InVT = Op0.getValueType();
25308   EVT InSVT = InVT.getScalarType();
25309
25310   // SINT_TO_FP(vXi8) -> SINT_TO_FP(SEXT(vXi8 to vXi32))
25311   // SINT_TO_FP(vXi16) -> SINT_TO_FP(SEXT(vXi16 to vXi32))
25312   if (InVT.isVector() && (InSVT == MVT::i8 || InSVT == MVT::i16)) {
25313     SDLoc dl(N);
25314     EVT DstVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
25315                                  InVT.getVectorNumElements());
25316     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
25317     return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
25318   }
25319
25320   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
25321   // a 32-bit target where SSE doesn't support i64->FP operations.
25322   if (Op0.getOpcode() == ISD::LOAD) {
25323     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
25324     EVT LdVT = Ld->getValueType(0);
25325
25326     // This transformation is not supported if the result type is f16
25327     if (VT == MVT::f16)
25328       return SDValue();
25329
25330     if (!Ld->isVolatile() && !VT.isVector() &&
25331         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
25332         !Subtarget->is64Bit() && LdVT == MVT::i64) {
25333       SDValue FILDChain = Subtarget->getTargetLowering()->BuildFILD(
25334           SDValue(N, 0), LdVT, Ld->getChain(), Op0, DAG);
25335       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
25336       return FILDChain;
25337     }
25338   }
25339   return SDValue();
25340 }
25341
25342 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
25343 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
25344                                  X86TargetLowering::DAGCombinerInfo &DCI) {
25345   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
25346   // the result is either zero or one (depending on the input carry bit).
25347   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
25348   if (X86::isZeroNode(N->getOperand(0)) &&
25349       X86::isZeroNode(N->getOperand(1)) &&
25350       // We don't have a good way to replace an EFLAGS use, so only do this when
25351       // dead right now.
25352       SDValue(N, 1).use_empty()) {
25353     SDLoc DL(N);
25354     EVT VT = N->getValueType(0);
25355     SDValue CarryOut = DAG.getConstant(0, DL, N->getValueType(1));
25356     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
25357                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
25358                                            DAG.getConstant(X86::COND_B, DL,
25359                                                            MVT::i8),
25360                                            N->getOperand(2)),
25361                                DAG.getConstant(1, DL, VT));
25362     return DCI.CombineTo(N, Res1, CarryOut);
25363   }
25364
25365   return SDValue();
25366 }
25367
25368 // fold (add Y, (sete  X, 0)) -> adc  0, Y
25369 //      (add Y, (setne X, 0)) -> sbb -1, Y
25370 //      (sub (sete  X, 0), Y) -> sbb  0, Y
25371 //      (sub (setne X, 0), Y) -> adc -1, Y
25372 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
25373   SDLoc DL(N);
25374
25375   // Look through ZExts.
25376   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
25377   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
25378     return SDValue();
25379
25380   SDValue SetCC = Ext.getOperand(0);
25381   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
25382     return SDValue();
25383
25384   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
25385   if (CC != X86::COND_E && CC != X86::COND_NE)
25386     return SDValue();
25387
25388   SDValue Cmp = SetCC.getOperand(1);
25389   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
25390       !X86::isZeroNode(Cmp.getOperand(1)) ||
25391       !Cmp.getOperand(0).getValueType().isInteger())
25392     return SDValue();
25393
25394   SDValue CmpOp0 = Cmp.getOperand(0);
25395   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
25396                                DAG.getConstant(1, DL, CmpOp0.getValueType()));
25397
25398   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
25399   if (CC == X86::COND_NE)
25400     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
25401                        DL, OtherVal.getValueType(), OtherVal,
25402                        DAG.getConstant(-1ULL, DL, OtherVal.getValueType()),
25403                        NewCmp);
25404   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
25405                      DL, OtherVal.getValueType(), OtherVal,
25406                      DAG.getConstant(0, DL, OtherVal.getValueType()), NewCmp);
25407 }
25408
25409 /// PerformADDCombine - Do target-specific dag combines on integer adds.
25410 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
25411                                  const X86Subtarget *Subtarget) {
25412   EVT VT = N->getValueType(0);
25413   SDValue Op0 = N->getOperand(0);
25414   SDValue Op1 = N->getOperand(1);
25415
25416   // Try to synthesize horizontal adds from adds of shuffles.
25417   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
25418        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
25419       isHorizontalBinOp(Op0, Op1, true))
25420     return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
25421
25422   return OptimizeConditionalInDecrement(N, DAG);
25423 }
25424
25425 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
25426                                  const X86Subtarget *Subtarget) {
25427   SDValue Op0 = N->getOperand(0);
25428   SDValue Op1 = N->getOperand(1);
25429
25430   // X86 can't encode an immediate LHS of a sub. See if we can push the
25431   // negation into a preceding instruction.
25432   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
25433     // If the RHS of the sub is a XOR with one use and a constant, invert the
25434     // immediate. Then add one to the LHS of the sub so we can turn
25435     // X-Y -> X+~Y+1, saving one register.
25436     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
25437         isa<ConstantSDNode>(Op1.getOperand(1))) {
25438       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
25439       EVT VT = Op0.getValueType();
25440       SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
25441                                    Op1.getOperand(0),
25442                                    DAG.getConstant(~XorC, SDLoc(Op1), VT));
25443       return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
25444                          DAG.getConstant(C->getAPIntValue() + 1, SDLoc(N), VT));
25445     }
25446   }
25447
25448   // Try to synthesize horizontal adds from adds of shuffles.
25449   EVT VT = N->getValueType(0);
25450   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
25451        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
25452       isHorizontalBinOp(Op0, Op1, true))
25453     return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
25454
25455   return OptimizeConditionalInDecrement(N, DAG);
25456 }
25457
25458 /// performVZEXTCombine - Performs build vector combines
25459 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
25460                                    TargetLowering::DAGCombinerInfo &DCI,
25461                                    const X86Subtarget *Subtarget) {
25462   SDLoc DL(N);
25463   MVT VT = N->getSimpleValueType(0);
25464   SDValue Op = N->getOperand(0);
25465   MVT OpVT = Op.getSimpleValueType();
25466   MVT OpEltVT = OpVT.getVectorElementType();
25467   unsigned InputBits = OpEltVT.getSizeInBits() * VT.getVectorNumElements();
25468
25469   // (vzext (bitcast (vzext (x)) -> (vzext x)
25470   SDValue V = Op;
25471   while (V.getOpcode() == ISD::BITCAST)
25472     V = V.getOperand(0);
25473
25474   if (V != Op && V.getOpcode() == X86ISD::VZEXT) {
25475     MVT InnerVT = V.getSimpleValueType();
25476     MVT InnerEltVT = InnerVT.getVectorElementType();
25477
25478     // If the element sizes match exactly, we can just do one larger vzext. This
25479     // is always an exact type match as vzext operates on integer types.
25480     if (OpEltVT == InnerEltVT) {
25481       assert(OpVT == InnerVT && "Types must match for vzext!");
25482       return DAG.getNode(X86ISD::VZEXT, DL, VT, V.getOperand(0));
25483     }
25484
25485     // The only other way we can combine them is if only a single element of the
25486     // inner vzext is used in the input to the outer vzext.
25487     if (InnerEltVT.getSizeInBits() < InputBits)
25488       return SDValue();
25489
25490     // In this case, the inner vzext is completely dead because we're going to
25491     // only look at bits inside of the low element. Just do the outer vzext on
25492     // a bitcast of the input to the inner.
25493     return DAG.getNode(X86ISD::VZEXT, DL, VT, DAG.getBitcast(OpVT, V));
25494   }
25495
25496   // Check if we can bypass extracting and re-inserting an element of an input
25497   // vector. Essentialy:
25498   // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
25499   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR &&
25500       V.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
25501       V.getOperand(0).getSimpleValueType().getSizeInBits() == InputBits) {
25502     SDValue ExtractedV = V.getOperand(0);
25503     SDValue OrigV = ExtractedV.getOperand(0);
25504     if (auto *ExtractIdx = dyn_cast<ConstantSDNode>(ExtractedV.getOperand(1)))
25505       if (ExtractIdx->getZExtValue() == 0) {
25506         MVT OrigVT = OrigV.getSimpleValueType();
25507         // Extract a subvector if necessary...
25508         if (OrigVT.getSizeInBits() > OpVT.getSizeInBits()) {
25509           int Ratio = OrigVT.getSizeInBits() / OpVT.getSizeInBits();
25510           OrigVT = MVT::getVectorVT(OrigVT.getVectorElementType(),
25511                                     OrigVT.getVectorNumElements() / Ratio);
25512           OrigV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigVT, OrigV,
25513                               DAG.getIntPtrConstant(0, DL));
25514         }
25515         Op = DAG.getBitcast(OpVT, OrigV);
25516         return DAG.getNode(X86ISD::VZEXT, DL, VT, Op);
25517       }
25518   }
25519
25520   return SDValue();
25521 }
25522
25523 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
25524                                              DAGCombinerInfo &DCI) const {
25525   SelectionDAG &DAG = DCI.DAG;
25526   switch (N->getOpcode()) {
25527   default: break;
25528   case ISD::EXTRACT_VECTOR_ELT:
25529     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
25530   case ISD::VSELECT:
25531   case ISD::SELECT:
25532   case X86ISD::SHRUNKBLEND:
25533     return PerformSELECTCombine(N, DAG, DCI, Subtarget);
25534   case ISD::BITCAST:        return PerformBITCASTCombine(N, DAG);
25535   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
25536   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
25537   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
25538   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
25539   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
25540   case ISD::SHL:
25541   case ISD::SRA:
25542   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
25543   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
25544   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
25545   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
25546   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
25547   case ISD::MLOAD:          return PerformMLOADCombine(N, DAG, DCI, Subtarget);
25548   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
25549   case ISD::MSTORE:         return PerformMSTORECombine(N, DAG, Subtarget);
25550   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, Subtarget);
25551   case ISD::UINT_TO_FP:     return PerformUINT_TO_FPCombine(N, DAG, Subtarget);
25552   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
25553   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
25554   case X86ISD::FXOR:
25555   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
25556   case X86ISD::FMIN:
25557   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
25558   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
25559   case X86ISD::FANDN:       return PerformFANDNCombine(N, DAG);
25560   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
25561   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
25562   case ISD::ANY_EXTEND:
25563   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
25564   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
25565   case ISD::SIGN_EXTEND_INREG:
25566     return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
25567   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG, Subtarget);
25568   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
25569   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
25570   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
25571   case X86ISD::SHUFP:       // Handle all target specific shuffles
25572   case X86ISD::PALIGNR:
25573   case X86ISD::UNPCKH:
25574   case X86ISD::UNPCKL:
25575   case X86ISD::MOVHLPS:
25576   case X86ISD::MOVLHPS:
25577   case X86ISD::PSHUFB:
25578   case X86ISD::PSHUFD:
25579   case X86ISD::PSHUFHW:
25580   case X86ISD::PSHUFLW:
25581   case X86ISD::MOVSS:
25582   case X86ISD::MOVSD:
25583   case X86ISD::VPERMILPI:
25584   case X86ISD::VPERM2X128:
25585   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
25586   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
25587   case ISD::INTRINSIC_WO_CHAIN:
25588     return PerformINTRINSIC_WO_CHAINCombine(N, DAG, Subtarget);
25589   case X86ISD::INSERTPS: {
25590     if (getTargetMachine().getOptLevel() > CodeGenOpt::None)
25591       return PerformINSERTPSCombine(N, DAG, Subtarget);
25592     break;
25593   }
25594   case X86ISD::BLENDI:    return PerformBLENDICombine(N, DAG);
25595   }
25596
25597   return SDValue();
25598 }
25599
25600 /// isTypeDesirableForOp - Return true if the target has native support for
25601 /// the specified value type and it is 'desirable' to use the type for the
25602 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
25603 /// instruction encodings are longer and some i16 instructions are slow.
25604 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
25605   if (!isTypeLegal(VT))
25606     return false;
25607   if (VT != MVT::i16)
25608     return true;
25609
25610   switch (Opc) {
25611   default:
25612     return true;
25613   case ISD::LOAD:
25614   case ISD::SIGN_EXTEND:
25615   case ISD::ZERO_EXTEND:
25616   case ISD::ANY_EXTEND:
25617   case ISD::SHL:
25618   case ISD::SRL:
25619   case ISD::SUB:
25620   case ISD::ADD:
25621   case ISD::MUL:
25622   case ISD::AND:
25623   case ISD::OR:
25624   case ISD::XOR:
25625     return false;
25626   }
25627 }
25628
25629 /// IsDesirableToPromoteOp - This method query the target whether it is
25630 /// beneficial for dag combiner to promote the specified node. If true, it
25631 /// should return the desired promotion type by reference.
25632 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
25633   EVT VT = Op.getValueType();
25634   if (VT != MVT::i16)
25635     return false;
25636
25637   bool Promote = false;
25638   bool Commute = false;
25639   switch (Op.getOpcode()) {
25640   default: break;
25641   case ISD::LOAD: {
25642     LoadSDNode *LD = cast<LoadSDNode>(Op);
25643     // If the non-extending load has a single use and it's not live out, then it
25644     // might be folded.
25645     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
25646                                                      Op.hasOneUse()*/) {
25647       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
25648              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
25649         // The only case where we'd want to promote LOAD (rather then it being
25650         // promoted as an operand is when it's only use is liveout.
25651         if (UI->getOpcode() != ISD::CopyToReg)
25652           return false;
25653       }
25654     }
25655     Promote = true;
25656     break;
25657   }
25658   case ISD::SIGN_EXTEND:
25659   case ISD::ZERO_EXTEND:
25660   case ISD::ANY_EXTEND:
25661     Promote = true;
25662     break;
25663   case ISD::SHL:
25664   case ISD::SRL: {
25665     SDValue N0 = Op.getOperand(0);
25666     // Look out for (store (shl (load), x)).
25667     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
25668       return false;
25669     Promote = true;
25670     break;
25671   }
25672   case ISD::ADD:
25673   case ISD::MUL:
25674   case ISD::AND:
25675   case ISD::OR:
25676   case ISD::XOR:
25677     Commute = true;
25678     // fallthrough
25679   case ISD::SUB: {
25680     SDValue N0 = Op.getOperand(0);
25681     SDValue N1 = Op.getOperand(1);
25682     if (!Commute && MayFoldLoad(N1))
25683       return false;
25684     // Avoid disabling potential load folding opportunities.
25685     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
25686       return false;
25687     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
25688       return false;
25689     Promote = true;
25690   }
25691   }
25692
25693   PVT = MVT::i32;
25694   return Promote;
25695 }
25696
25697 //===----------------------------------------------------------------------===//
25698 //                           X86 Inline Assembly Support
25699 //===----------------------------------------------------------------------===//
25700
25701 // Helper to match a string separated by whitespace.
25702 static bool matchAsm(StringRef S, ArrayRef<const char *> Pieces) {
25703   S = S.substr(S.find_first_not_of(" \t")); // Skip leading whitespace.
25704
25705   for (StringRef Piece : Pieces) {
25706     if (!S.startswith(Piece)) // Check if the piece matches.
25707       return false;
25708
25709     S = S.substr(Piece.size());
25710     StringRef::size_type Pos = S.find_first_not_of(" \t");
25711     if (Pos == 0) // We matched a prefix.
25712       return false;
25713
25714     S = S.substr(Pos);
25715   }
25716
25717   return S.empty();
25718 }
25719
25720 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
25721
25722   if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
25723     if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
25724         std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
25725         std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
25726
25727       if (AsmPieces.size() == 3)
25728         return true;
25729       else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
25730         return true;
25731     }
25732   }
25733   return false;
25734 }
25735
25736 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
25737   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
25738
25739   std::string AsmStr = IA->getAsmString();
25740
25741   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
25742   if (!Ty || Ty->getBitWidth() % 16 != 0)
25743     return false;
25744
25745   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
25746   SmallVector<StringRef, 4> AsmPieces;
25747   SplitString(AsmStr, AsmPieces, ";\n");
25748
25749   switch (AsmPieces.size()) {
25750   default: return false;
25751   case 1:
25752     // FIXME: this should verify that we are targeting a 486 or better.  If not,
25753     // we will turn this bswap into something that will be lowered to logical
25754     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
25755     // lower so don't worry about this.
25756     // bswap $0
25757     if (matchAsm(AsmPieces[0], {"bswap", "$0"}) ||
25758         matchAsm(AsmPieces[0], {"bswapl", "$0"}) ||
25759         matchAsm(AsmPieces[0], {"bswapq", "$0"}) ||
25760         matchAsm(AsmPieces[0], {"bswap", "${0:q}"}) ||
25761         matchAsm(AsmPieces[0], {"bswapl", "${0:q}"}) ||
25762         matchAsm(AsmPieces[0], {"bswapq", "${0:q}"})) {
25763       // No need to check constraints, nothing other than the equivalent of
25764       // "=r,0" would be valid here.
25765       return IntrinsicLowering::LowerToByteSwap(CI);
25766     }
25767
25768     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
25769     if (CI->getType()->isIntegerTy(16) &&
25770         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
25771         (matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) ||
25772          matchAsm(AsmPieces[0], {"rolw", "$$8,", "${0:w}"}))) {
25773       AsmPieces.clear();
25774       StringRef ConstraintsStr = IA->getConstraintString();
25775       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
25776       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
25777       if (clobbersFlagRegisters(AsmPieces))
25778         return IntrinsicLowering::LowerToByteSwap(CI);
25779     }
25780     break;
25781   case 3:
25782     if (CI->getType()->isIntegerTy(32) &&
25783         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
25784         matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) &&
25785         matchAsm(AsmPieces[1], {"rorl", "$$16,", "$0"}) &&
25786         matchAsm(AsmPieces[2], {"rorw", "$$8,", "${0:w}"})) {
25787       AsmPieces.clear();
25788       StringRef ConstraintsStr = IA->getConstraintString();
25789       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
25790       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
25791       if (clobbersFlagRegisters(AsmPieces))
25792         return IntrinsicLowering::LowerToByteSwap(CI);
25793     }
25794
25795     if (CI->getType()->isIntegerTy(64)) {
25796       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
25797       if (Constraints.size() >= 2 &&
25798           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
25799           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
25800         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
25801         if (matchAsm(AsmPieces[0], {"bswap", "%eax"}) &&
25802             matchAsm(AsmPieces[1], {"bswap", "%edx"}) &&
25803             matchAsm(AsmPieces[2], {"xchgl", "%eax,", "%edx"}))
25804           return IntrinsicLowering::LowerToByteSwap(CI);
25805       }
25806     }
25807     break;
25808   }
25809   return false;
25810 }
25811
25812 /// getConstraintType - Given a constraint letter, return the type of
25813 /// constraint it is for this target.
25814 X86TargetLowering::ConstraintType
25815 X86TargetLowering::getConstraintType(StringRef Constraint) const {
25816   if (Constraint.size() == 1) {
25817     switch (Constraint[0]) {
25818     case 'R':
25819     case 'q':
25820     case 'Q':
25821     case 'f':
25822     case 't':
25823     case 'u':
25824     case 'y':
25825     case 'x':
25826     case 'Y':
25827     case 'l':
25828       return C_RegisterClass;
25829     case 'a':
25830     case 'b':
25831     case 'c':
25832     case 'd':
25833     case 'S':
25834     case 'D':
25835     case 'A':
25836       return C_Register;
25837     case 'I':
25838     case 'J':
25839     case 'K':
25840     case 'L':
25841     case 'M':
25842     case 'N':
25843     case 'G':
25844     case 'C':
25845     case 'e':
25846     case 'Z':
25847       return C_Other;
25848     default:
25849       break;
25850     }
25851   }
25852   return TargetLowering::getConstraintType(Constraint);
25853 }
25854
25855 /// Examine constraint type and operand type and determine a weight value.
25856 /// This object must already have been set up with the operand type
25857 /// and the current alternative constraint selected.
25858 TargetLowering::ConstraintWeight
25859   X86TargetLowering::getSingleConstraintMatchWeight(
25860     AsmOperandInfo &info, const char *constraint) const {
25861   ConstraintWeight weight = CW_Invalid;
25862   Value *CallOperandVal = info.CallOperandVal;
25863     // If we don't have a value, we can't do a match,
25864     // but allow it at the lowest weight.
25865   if (!CallOperandVal)
25866     return CW_Default;
25867   Type *type = CallOperandVal->getType();
25868   // Look at the constraint type.
25869   switch (*constraint) {
25870   default:
25871     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
25872   case 'R':
25873   case 'q':
25874   case 'Q':
25875   case 'a':
25876   case 'b':
25877   case 'c':
25878   case 'd':
25879   case 'S':
25880   case 'D':
25881   case 'A':
25882     if (CallOperandVal->getType()->isIntegerTy())
25883       weight = CW_SpecificReg;
25884     break;
25885   case 'f':
25886   case 't':
25887   case 'u':
25888     if (type->isFloatingPointTy())
25889       weight = CW_SpecificReg;
25890     break;
25891   case 'y':
25892     if (type->isX86_MMXTy() && Subtarget->hasMMX())
25893       weight = CW_SpecificReg;
25894     break;
25895   case 'x':
25896   case 'Y':
25897     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
25898         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
25899       weight = CW_Register;
25900     break;
25901   case 'I':
25902     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
25903       if (C->getZExtValue() <= 31)
25904         weight = CW_Constant;
25905     }
25906     break;
25907   case 'J':
25908     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25909       if (C->getZExtValue() <= 63)
25910         weight = CW_Constant;
25911     }
25912     break;
25913   case 'K':
25914     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25915       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
25916         weight = CW_Constant;
25917     }
25918     break;
25919   case 'L':
25920     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25921       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
25922         weight = CW_Constant;
25923     }
25924     break;
25925   case 'M':
25926     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25927       if (C->getZExtValue() <= 3)
25928         weight = CW_Constant;
25929     }
25930     break;
25931   case 'N':
25932     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25933       if (C->getZExtValue() <= 0xff)
25934         weight = CW_Constant;
25935     }
25936     break;
25937   case 'G':
25938   case 'C':
25939     if (isa<ConstantFP>(CallOperandVal)) {
25940       weight = CW_Constant;
25941     }
25942     break;
25943   case 'e':
25944     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25945       if ((C->getSExtValue() >= -0x80000000LL) &&
25946           (C->getSExtValue() <= 0x7fffffffLL))
25947         weight = CW_Constant;
25948     }
25949     break;
25950   case 'Z':
25951     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25952       if (C->getZExtValue() <= 0xffffffff)
25953         weight = CW_Constant;
25954     }
25955     break;
25956   }
25957   return weight;
25958 }
25959
25960 /// LowerXConstraint - try to replace an X constraint, which matches anything,
25961 /// with another that has more specific requirements based on the type of the
25962 /// corresponding operand.
25963 const char *X86TargetLowering::
25964 LowerXConstraint(EVT ConstraintVT) const {
25965   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
25966   // 'f' like normal targets.
25967   if (ConstraintVT.isFloatingPoint()) {
25968     if (Subtarget->hasSSE2())
25969       return "Y";
25970     if (Subtarget->hasSSE1())
25971       return "x";
25972   }
25973
25974   return TargetLowering::LowerXConstraint(ConstraintVT);
25975 }
25976
25977 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
25978 /// vector.  If it is invalid, don't add anything to Ops.
25979 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
25980                                                      std::string &Constraint,
25981                                                      std::vector<SDValue>&Ops,
25982                                                      SelectionDAG &DAG) const {
25983   SDValue Result;
25984
25985   // Only support length 1 constraints for now.
25986   if (Constraint.length() > 1) return;
25987
25988   char ConstraintLetter = Constraint[0];
25989   switch (ConstraintLetter) {
25990   default: break;
25991   case 'I':
25992     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
25993       if (C->getZExtValue() <= 31) {
25994         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
25995                                        Op.getValueType());
25996         break;
25997       }
25998     }
25999     return;
26000   case 'J':
26001     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26002       if (C->getZExtValue() <= 63) {
26003         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26004                                        Op.getValueType());
26005         break;
26006       }
26007     }
26008     return;
26009   case 'K':
26010     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26011       if (isInt<8>(C->getSExtValue())) {
26012         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26013                                        Op.getValueType());
26014         break;
26015       }
26016     }
26017     return;
26018   case 'L':
26019     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26020       if (C->getZExtValue() == 0xff || C->getZExtValue() == 0xffff ||
26021           (Subtarget->is64Bit() && C->getZExtValue() == 0xffffffff)) {
26022         Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op),
26023                                        Op.getValueType());
26024         break;
26025       }
26026     }
26027     return;
26028   case 'M':
26029     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26030       if (C->getZExtValue() <= 3) {
26031         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26032                                        Op.getValueType());
26033         break;
26034       }
26035     }
26036     return;
26037   case 'N':
26038     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26039       if (C->getZExtValue() <= 255) {
26040         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26041                                        Op.getValueType());
26042         break;
26043       }
26044     }
26045     return;
26046   case 'O':
26047     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26048       if (C->getZExtValue() <= 127) {
26049         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26050                                        Op.getValueType());
26051         break;
26052       }
26053     }
26054     return;
26055   case 'e': {
26056     // 32-bit signed value
26057     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26058       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
26059                                            C->getSExtValue())) {
26060         // Widen to 64 bits here to get it sign extended.
26061         Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op), MVT::i64);
26062         break;
26063       }
26064     // FIXME gcc accepts some relocatable values here too, but only in certain
26065     // memory models; it's complicated.
26066     }
26067     return;
26068   }
26069   case 'Z': {
26070     // 32-bit unsigned value
26071     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26072       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
26073                                            C->getZExtValue())) {
26074         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26075                                        Op.getValueType());
26076         break;
26077       }
26078     }
26079     // FIXME gcc accepts some relocatable values here too, but only in certain
26080     // memory models; it's complicated.
26081     return;
26082   }
26083   case 'i': {
26084     // Literal immediates are always ok.
26085     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
26086       // Widen to 64 bits here to get it sign extended.
26087       Result = DAG.getTargetConstant(CST->getSExtValue(), SDLoc(Op), MVT::i64);
26088       break;
26089     }
26090
26091     // In any sort of PIC mode addresses need to be computed at runtime by
26092     // adding in a register or some sort of table lookup.  These can't
26093     // be used as immediates.
26094     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
26095       return;
26096
26097     // If we are in non-pic codegen mode, we allow the address of a global (with
26098     // an optional displacement) to be used with 'i'.
26099     GlobalAddressSDNode *GA = nullptr;
26100     int64_t Offset = 0;
26101
26102     // Match either (GA), (GA+C), (GA+C1+C2), etc.
26103     while (1) {
26104       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
26105         Offset += GA->getOffset();
26106         break;
26107       } else if (Op.getOpcode() == ISD::ADD) {
26108         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
26109           Offset += C->getZExtValue();
26110           Op = Op.getOperand(0);
26111           continue;
26112         }
26113       } else if (Op.getOpcode() == ISD::SUB) {
26114         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
26115           Offset += -C->getZExtValue();
26116           Op = Op.getOperand(0);
26117           continue;
26118         }
26119       }
26120
26121       // Otherwise, this isn't something we can handle, reject it.
26122       return;
26123     }
26124
26125     const GlobalValue *GV = GA->getGlobal();
26126     // If we require an extra load to get this address, as in PIC mode, we
26127     // can't accept it.
26128     if (isGlobalStubReference(
26129             Subtarget->ClassifyGlobalReference(GV, DAG.getTarget())))
26130       return;
26131
26132     Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
26133                                         GA->getValueType(0), Offset);
26134     break;
26135   }
26136   }
26137
26138   if (Result.getNode()) {
26139     Ops.push_back(Result);
26140     return;
26141   }
26142   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
26143 }
26144
26145 std::pair<unsigned, const TargetRegisterClass *>
26146 X86TargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
26147                                                 StringRef Constraint,
26148                                                 MVT VT) const {
26149   // First, see if this is a constraint that directly corresponds to an LLVM
26150   // register class.
26151   if (Constraint.size() == 1) {
26152     // GCC Constraint Letters
26153     switch (Constraint[0]) {
26154     default: break;
26155       // TODO: Slight differences here in allocation order and leaving
26156       // RIP in the class. Do they matter any more here than they do
26157       // in the normal allocation?
26158     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
26159       if (Subtarget->is64Bit()) {
26160         if (VT == MVT::i32 || VT == MVT::f32)
26161           return std::make_pair(0U, &X86::GR32RegClass);
26162         if (VT == MVT::i16)
26163           return std::make_pair(0U, &X86::GR16RegClass);
26164         if (VT == MVT::i8 || VT == MVT::i1)
26165           return std::make_pair(0U, &X86::GR8RegClass);
26166         if (VT == MVT::i64 || VT == MVT::f64)
26167           return std::make_pair(0U, &X86::GR64RegClass);
26168         break;
26169       }
26170       // 32-bit fallthrough
26171     case 'Q':   // Q_REGS
26172       if (VT == MVT::i32 || VT == MVT::f32)
26173         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
26174       if (VT == MVT::i16)
26175         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
26176       if (VT == MVT::i8 || VT == MVT::i1)
26177         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
26178       if (VT == MVT::i64)
26179         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
26180       break;
26181     case 'r':   // GENERAL_REGS
26182     case 'l':   // INDEX_REGS
26183       if (VT == MVT::i8 || VT == MVT::i1)
26184         return std::make_pair(0U, &X86::GR8RegClass);
26185       if (VT == MVT::i16)
26186         return std::make_pair(0U, &X86::GR16RegClass);
26187       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
26188         return std::make_pair(0U, &X86::GR32RegClass);
26189       return std::make_pair(0U, &X86::GR64RegClass);
26190     case 'R':   // LEGACY_REGS
26191       if (VT == MVT::i8 || VT == MVT::i1)
26192         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
26193       if (VT == MVT::i16)
26194         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
26195       if (VT == MVT::i32 || !Subtarget->is64Bit())
26196         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
26197       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
26198     case 'f':  // FP Stack registers.
26199       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
26200       // value to the correct fpstack register class.
26201       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
26202         return std::make_pair(0U, &X86::RFP32RegClass);
26203       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
26204         return std::make_pair(0U, &X86::RFP64RegClass);
26205       return std::make_pair(0U, &X86::RFP80RegClass);
26206     case 'y':   // MMX_REGS if MMX allowed.
26207       if (!Subtarget->hasMMX()) break;
26208       return std::make_pair(0U, &X86::VR64RegClass);
26209     case 'Y':   // SSE_REGS if SSE2 allowed
26210       if (!Subtarget->hasSSE2()) break;
26211       // FALL THROUGH.
26212     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
26213       if (!Subtarget->hasSSE1()) break;
26214
26215       switch (VT.SimpleTy) {
26216       default: break;
26217       // Scalar SSE types.
26218       case MVT::f32:
26219       case MVT::i32:
26220         return std::make_pair(0U, &X86::FR32RegClass);
26221       case MVT::f64:
26222       case MVT::i64:
26223         return std::make_pair(0U, &X86::FR64RegClass);
26224       // Vector types.
26225       case MVT::v16i8:
26226       case MVT::v8i16:
26227       case MVT::v4i32:
26228       case MVT::v2i64:
26229       case MVT::v4f32:
26230       case MVT::v2f64:
26231         return std::make_pair(0U, &X86::VR128RegClass);
26232       // AVX types.
26233       case MVT::v32i8:
26234       case MVT::v16i16:
26235       case MVT::v8i32:
26236       case MVT::v4i64:
26237       case MVT::v8f32:
26238       case MVT::v4f64:
26239         return std::make_pair(0U, &X86::VR256RegClass);
26240       case MVT::v8f64:
26241       case MVT::v16f32:
26242       case MVT::v16i32:
26243       case MVT::v8i64:
26244         return std::make_pair(0U, &X86::VR512RegClass);
26245       }
26246       break;
26247     }
26248   }
26249
26250   // Use the default implementation in TargetLowering to convert the register
26251   // constraint into a member of a register class.
26252   std::pair<unsigned, const TargetRegisterClass*> Res;
26253   Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
26254
26255   // Not found as a standard register?
26256   if (!Res.second) {
26257     // Map st(0) -> st(7) -> ST0
26258     if (Constraint.size() == 7 && Constraint[0] == '{' &&
26259         tolower(Constraint[1]) == 's' &&
26260         tolower(Constraint[2]) == 't' &&
26261         Constraint[3] == '(' &&
26262         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
26263         Constraint[5] == ')' &&
26264         Constraint[6] == '}') {
26265
26266       Res.first = X86::FP0+Constraint[4]-'0';
26267       Res.second = &X86::RFP80RegClass;
26268       return Res;
26269     }
26270
26271     // GCC allows "st(0)" to be called just plain "st".
26272     if (StringRef("{st}").equals_lower(Constraint)) {
26273       Res.first = X86::FP0;
26274       Res.second = &X86::RFP80RegClass;
26275       return Res;
26276     }
26277
26278     // flags -> EFLAGS
26279     if (StringRef("{flags}").equals_lower(Constraint)) {
26280       Res.first = X86::EFLAGS;
26281       Res.second = &X86::CCRRegClass;
26282       return Res;
26283     }
26284
26285     // 'A' means EAX + EDX.
26286     if (Constraint == "A") {
26287       Res.first = X86::EAX;
26288       Res.second = &X86::GR32_ADRegClass;
26289       return Res;
26290     }
26291     return Res;
26292   }
26293
26294   // Otherwise, check to see if this is a register class of the wrong value
26295   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
26296   // turn into {ax},{dx}.
26297   // MVT::Other is used to specify clobber names.
26298   if (Res.second->hasType(VT) || VT == MVT::Other)
26299     return Res;   // Correct type already, nothing to do.
26300
26301   // Get a matching integer of the correct size. i.e. "ax" with MVT::32 should
26302   // return "eax". This should even work for things like getting 64bit integer
26303   // registers when given an f64 type.
26304   const TargetRegisterClass *Class = Res.second;
26305   if (Class == &X86::GR8RegClass || Class == &X86::GR16RegClass ||
26306       Class == &X86::GR32RegClass || Class == &X86::GR64RegClass) {
26307     unsigned Size = VT.getSizeInBits();
26308     MVT::SimpleValueType SimpleTy = Size == 1 || Size == 8 ? MVT::i8
26309                                   : Size == 16 ? MVT::i16
26310                                   : Size == 32 ? MVT::i32
26311                                   : Size == 64 ? MVT::i64
26312                                   : MVT::Other;
26313     unsigned DestReg = getX86SubSuperRegisterOrZero(Res.first, SimpleTy);
26314     if (DestReg > 0) {
26315       Res.first = DestReg;
26316       Res.second = SimpleTy == MVT::i8 ? &X86::GR8RegClass
26317                  : SimpleTy == MVT::i16 ? &X86::GR16RegClass
26318                  : SimpleTy == MVT::i32 ? &X86::GR32RegClass
26319                  : &X86::GR64RegClass;
26320       assert(Res.second->contains(Res.first) && "Register in register class");
26321     } else {
26322       // No register found/type mismatch.
26323       Res.first = 0;
26324       Res.second = nullptr;
26325     }
26326   } else if (Class == &X86::FR32RegClass || Class == &X86::FR64RegClass ||
26327              Class == &X86::VR128RegClass || Class == &X86::VR256RegClass ||
26328              Class == &X86::FR32XRegClass || Class == &X86::FR64XRegClass ||
26329              Class == &X86::VR128XRegClass || Class == &X86::VR256XRegClass ||
26330              Class == &X86::VR512RegClass) {
26331     // Handle references to XMM physical registers that got mapped into the
26332     // wrong class.  This can happen with constraints like {xmm0} where the
26333     // target independent register mapper will just pick the first match it can
26334     // find, ignoring the required type.
26335
26336     if (VT == MVT::f32 || VT == MVT::i32)
26337       Res.second = &X86::FR32RegClass;
26338     else if (VT == MVT::f64 || VT == MVT::i64)
26339       Res.second = &X86::FR64RegClass;
26340     else if (X86::VR128RegClass.hasType(VT))
26341       Res.second = &X86::VR128RegClass;
26342     else if (X86::VR256RegClass.hasType(VT))
26343       Res.second = &X86::VR256RegClass;
26344     else if (X86::VR512RegClass.hasType(VT))
26345       Res.second = &X86::VR512RegClass;
26346     else {
26347       // Type mismatch and not a clobber: Return an error;
26348       Res.first = 0;
26349       Res.second = nullptr;
26350     }
26351   }
26352
26353   return Res;
26354 }
26355
26356 int X86TargetLowering::getScalingFactorCost(const DataLayout &DL,
26357                                             const AddrMode &AM, Type *Ty,
26358                                             unsigned AS) const {
26359   // Scaling factors are not free at all.
26360   // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
26361   // will take 2 allocations in the out of order engine instead of 1
26362   // for plain addressing mode, i.e. inst (reg1).
26363   // E.g.,
26364   // vaddps (%rsi,%drx), %ymm0, %ymm1
26365   // Requires two allocations (one for the load, one for the computation)
26366   // whereas:
26367   // vaddps (%rsi), %ymm0, %ymm1
26368   // Requires just 1 allocation, i.e., freeing allocations for other operations
26369   // and having less micro operations to execute.
26370   //
26371   // For some X86 architectures, this is even worse because for instance for
26372   // stores, the complex addressing mode forces the instruction to use the
26373   // "load" ports instead of the dedicated "store" port.
26374   // E.g., on Haswell:
26375   // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
26376   // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.
26377   if (isLegalAddressingMode(DL, AM, Ty, AS))
26378     // Scale represents reg2 * scale, thus account for 1
26379     // as soon as we use a second register.
26380     return AM.Scale != 0;
26381   return -1;
26382 }
26383
26384 bool X86TargetLowering::isTargetFTOL() const {
26385   return Subtarget->isTargetKnownWindowsMSVC() && !Subtarget->is64Bit();
26386 }