a27c9f56ae4f1c77e81e3c61d9c8aae8a70b2c2a
[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->isTarget64BitLP64()) {
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       setOperationAction(ISD::SMAX,            MVT::v32i8,  Custom);
1203       setOperationAction(ISD::SMAX,            MVT::v16i16, Custom);
1204       setOperationAction(ISD::SMAX,            MVT::v8i32,  Custom);
1205       setOperationAction(ISD::UMAX,            MVT::v32i8,  Custom);
1206       setOperationAction(ISD::UMAX,            MVT::v16i16, Custom);
1207       setOperationAction(ISD::UMAX,            MVT::v8i32,  Custom);
1208       setOperationAction(ISD::SMIN,            MVT::v32i8,  Custom);
1209       setOperationAction(ISD::SMIN,            MVT::v16i16, Custom);
1210       setOperationAction(ISD::SMIN,            MVT::v8i32,  Custom);
1211       setOperationAction(ISD::UMIN,            MVT::v32i8,  Custom);
1212       setOperationAction(ISD::UMIN,            MVT::v16i16, Custom);
1213       setOperationAction(ISD::UMIN,            MVT::v8i32,  Custom);
1214     }
1215
1216     // In the customized shift lowering, the legal cases in AVX2 will be
1217     // recognized.
1218     setOperationAction(ISD::SRL,               MVT::v4i64, Custom);
1219     setOperationAction(ISD::SRL,               MVT::v8i32, Custom);
1220
1221     setOperationAction(ISD::SHL,               MVT::v4i64, Custom);
1222     setOperationAction(ISD::SHL,               MVT::v8i32, Custom);
1223
1224     setOperationAction(ISD::SRA,               MVT::v4i64, Custom);
1225     setOperationAction(ISD::SRA,               MVT::v8i32, Custom);
1226
1227     // Custom lower several nodes for 256-bit types.
1228     for (MVT VT : MVT::vector_valuetypes()) {
1229       if (VT.getScalarSizeInBits() >= 32) {
1230         setOperationAction(ISD::MLOAD,  VT, Legal);
1231         setOperationAction(ISD::MSTORE, VT, Legal);
1232       }
1233       // Extract subvector is special because the value type
1234       // (result) is 128-bit but the source is 256-bit wide.
1235       if (VT.is128BitVector()) {
1236         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1237       }
1238       // Do not attempt to custom lower other non-256-bit vectors
1239       if (!VT.is256BitVector())
1240         continue;
1241
1242       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1243       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1244       setOperationAction(ISD::VSELECT,            VT, Custom);
1245       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1246       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1247       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1248       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1249       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1250     }
1251
1252     if (Subtarget->hasInt256())
1253       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1254
1255
1256     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1257     for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1258       MVT VT = (MVT::SimpleValueType)i;
1259
1260       // Do not attempt to promote non-256-bit vectors
1261       if (!VT.is256BitVector())
1262         continue;
1263
1264       setOperationAction(ISD::AND,    VT, Promote);
1265       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1266       setOperationAction(ISD::OR,     VT, Promote);
1267       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1268       setOperationAction(ISD::XOR,    VT, Promote);
1269       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1270       setOperationAction(ISD::LOAD,   VT, Promote);
1271       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1272       setOperationAction(ISD::SELECT, VT, Promote);
1273       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1274     }
1275   }
1276
1277   if (!Subtarget->useSoftFloat() && Subtarget->hasAVX512()) {
1278     addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1279     addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1280     addRegisterClass(MVT::v8i64,  &X86::VR512RegClass);
1281     addRegisterClass(MVT::v8f64,  &X86::VR512RegClass);
1282
1283     addRegisterClass(MVT::i1,     &X86::VK1RegClass);
1284     addRegisterClass(MVT::v8i1,   &X86::VK8RegClass);
1285     addRegisterClass(MVT::v16i1,  &X86::VK16RegClass);
1286
1287     for (MVT VT : MVT::fp_vector_valuetypes())
1288       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8f32, Legal);
1289
1290     setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i32, MVT::v16i8, Legal);
1291     setLoadExtAction(ISD::SEXTLOAD, MVT::v16i32, MVT::v16i8, Legal);
1292     setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i32, MVT::v16i16, Legal);
1293     setLoadExtAction(ISD::SEXTLOAD, MVT::v16i32, MVT::v16i16, Legal);
1294     setLoadExtAction(ISD::ZEXTLOAD, MVT::v32i16, MVT::v32i8, Legal);
1295     setLoadExtAction(ISD::SEXTLOAD, MVT::v32i16, MVT::v32i8, Legal);
1296     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64,  MVT::v8i8,  Legal);
1297     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64,  MVT::v8i8,  Legal);
1298     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64,  MVT::v8i16,  Legal);
1299     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64,  MVT::v8i16,  Legal);
1300     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64,  MVT::v8i32,  Legal);
1301     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64,  MVT::v8i32,  Legal);
1302
1303     setOperationAction(ISD::BR_CC,              MVT::i1,    Expand);
1304     setOperationAction(ISD::SETCC,              MVT::i1,    Custom);
1305     setOperationAction(ISD::XOR,                MVT::i1,    Legal);
1306     setOperationAction(ISD::OR,                 MVT::i1,    Legal);
1307     setOperationAction(ISD::AND,                MVT::i1,    Legal);
1308     setOperationAction(ISD::SUB,                MVT::i1,    Custom);
1309     setOperationAction(ISD::ADD,                MVT::i1,    Custom);
1310     setOperationAction(ISD::MUL,                MVT::i1,    Custom);
1311     setOperationAction(ISD::LOAD,               MVT::v16f32, Legal);
1312     setOperationAction(ISD::LOAD,               MVT::v8f64, Legal);
1313     setOperationAction(ISD::LOAD,               MVT::v8i64, Legal);
1314     setOperationAction(ISD::LOAD,               MVT::v16i32, Legal);
1315     setOperationAction(ISD::LOAD,               MVT::v16i1, Legal);
1316
1317     setOperationAction(ISD::FADD,               MVT::v16f32, Legal);
1318     setOperationAction(ISD::FSUB,               MVT::v16f32, Legal);
1319     setOperationAction(ISD::FMUL,               MVT::v16f32, Legal);
1320     setOperationAction(ISD::FDIV,               MVT::v16f32, Legal);
1321     setOperationAction(ISD::FSQRT,              MVT::v16f32, Legal);
1322     setOperationAction(ISD::FNEG,               MVT::v16f32, Custom);
1323
1324     setOperationAction(ISD::FADD,               MVT::v8f64, Legal);
1325     setOperationAction(ISD::FSUB,               MVT::v8f64, Legal);
1326     setOperationAction(ISD::FMUL,               MVT::v8f64, Legal);
1327     setOperationAction(ISD::FDIV,               MVT::v8f64, Legal);
1328     setOperationAction(ISD::FSQRT,              MVT::v8f64, Legal);
1329     setOperationAction(ISD::FNEG,               MVT::v8f64, Custom);
1330     setOperationAction(ISD::FMA,                MVT::v8f64, Legal);
1331     setOperationAction(ISD::FMA,                MVT::v16f32, Legal);
1332
1333     setOperationAction(ISD::FP_TO_SINT,         MVT::i32, Legal);
1334     setOperationAction(ISD::FP_TO_UINT,         MVT::i32, Legal);
1335     setOperationAction(ISD::SINT_TO_FP,         MVT::i32, Legal);
1336     setOperationAction(ISD::UINT_TO_FP,         MVT::i32, Legal);
1337     if (Subtarget->is64Bit()) {
1338       setOperationAction(ISD::FP_TO_UINT,       MVT::i64, Legal);
1339       setOperationAction(ISD::FP_TO_SINT,       MVT::i64, Legal);
1340       setOperationAction(ISD::SINT_TO_FP,       MVT::i64, Legal);
1341       setOperationAction(ISD::UINT_TO_FP,       MVT::i64, Legal);
1342     }
1343     setOperationAction(ISD::FP_TO_SINT,         MVT::v16i32, Legal);
1344     setOperationAction(ISD::FP_TO_UINT,         MVT::v16i32, Legal);
1345     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i32, Legal);
1346     setOperationAction(ISD::FP_TO_UINT,         MVT::v4i32, Legal);
1347     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i32, Legal);
1348     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i1,   Custom);
1349     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i1,  Custom);
1350     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i8,  Promote);
1351     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i16, Promote);
1352     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i32, Legal);
1353     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i32, Legal);
1354     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Legal);
1355     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i8, Custom);
1356     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i16, Custom);
1357     setOperationAction(ISD::FP_ROUND,           MVT::v8f32, Legal);
1358     setOperationAction(ISD::FP_EXTEND,          MVT::v8f32, Legal);
1359
1360     setTruncStoreAction(MVT::v8i64,   MVT::v8i8,   Legal);
1361     setTruncStoreAction(MVT::v8i64,   MVT::v8i16,  Legal);
1362     setTruncStoreAction(MVT::v8i64,   MVT::v8i32,  Legal);
1363     setTruncStoreAction(MVT::v16i32,  MVT::v16i8,  Legal);
1364     setTruncStoreAction(MVT::v16i32,  MVT::v16i16, Legal);
1365     if (Subtarget->hasVLX()){
1366       setTruncStoreAction(MVT::v4i64, MVT::v4i8,  Legal);
1367       setTruncStoreAction(MVT::v4i64, MVT::v4i16, Legal);
1368       setTruncStoreAction(MVT::v4i64, MVT::v4i32, Legal);
1369       setTruncStoreAction(MVT::v8i32, MVT::v8i8,  Legal);
1370       setTruncStoreAction(MVT::v8i32, MVT::v8i16, Legal);
1371
1372       setTruncStoreAction(MVT::v2i64, MVT::v2i8,  Legal);
1373       setTruncStoreAction(MVT::v2i64, MVT::v2i16, Legal);
1374       setTruncStoreAction(MVT::v2i64, MVT::v2i32, Legal);
1375       setTruncStoreAction(MVT::v4i32, MVT::v4i8,  Legal);
1376       setTruncStoreAction(MVT::v4i32, MVT::v4i16, Legal);
1377     }
1378     setOperationAction(ISD::TRUNCATE,           MVT::i1, Custom);
1379     setOperationAction(ISD::TRUNCATE,           MVT::v16i8, Custom);
1380     setOperationAction(ISD::TRUNCATE,           MVT::v8i32, Custom);
1381     if (Subtarget->hasDQI()) {
1382       setOperationAction(ISD::TRUNCATE,         MVT::v2i1, Custom);
1383       setOperationAction(ISD::TRUNCATE,         MVT::v4i1, Custom);
1384
1385       setOperationAction(ISD::SINT_TO_FP,       MVT::v8i64, Legal);
1386       setOperationAction(ISD::UINT_TO_FP,       MVT::v8i64, Legal);
1387       setOperationAction(ISD::FP_TO_SINT,       MVT::v8i64, Legal);
1388       setOperationAction(ISD::FP_TO_UINT,       MVT::v8i64, Legal);
1389       if (Subtarget->hasVLX()) {
1390         setOperationAction(ISD::SINT_TO_FP,    MVT::v4i64, Legal);
1391         setOperationAction(ISD::SINT_TO_FP,    MVT::v2i64, Legal);
1392         setOperationAction(ISD::UINT_TO_FP,    MVT::v4i64, Legal);
1393         setOperationAction(ISD::UINT_TO_FP,    MVT::v2i64, Legal);
1394         setOperationAction(ISD::FP_TO_SINT,    MVT::v4i64, Legal);
1395         setOperationAction(ISD::FP_TO_SINT,    MVT::v2i64, Legal);
1396         setOperationAction(ISD::FP_TO_UINT,    MVT::v4i64, Legal);
1397         setOperationAction(ISD::FP_TO_UINT,    MVT::v2i64, Legal);
1398       }
1399     }
1400     if (Subtarget->hasVLX()) {
1401       setOperationAction(ISD::SINT_TO_FP,       MVT::v8i32, Legal);
1402       setOperationAction(ISD::UINT_TO_FP,       MVT::v8i32, Legal);
1403       setOperationAction(ISD::FP_TO_SINT,       MVT::v8i32, Legal);
1404       setOperationAction(ISD::FP_TO_UINT,       MVT::v8i32, Legal);
1405       setOperationAction(ISD::SINT_TO_FP,       MVT::v4i32, Legal);
1406       setOperationAction(ISD::UINT_TO_FP,       MVT::v4i32, Legal);
1407       setOperationAction(ISD::FP_TO_SINT,       MVT::v4i32, Legal);
1408       setOperationAction(ISD::FP_TO_UINT,       MVT::v4i32, Legal);
1409     }
1410     setOperationAction(ISD::TRUNCATE,           MVT::v8i1, Custom);
1411     setOperationAction(ISD::TRUNCATE,           MVT::v16i1, Custom);
1412     setOperationAction(ISD::TRUNCATE,           MVT::v16i16, Custom);
1413     setOperationAction(ISD::ZERO_EXTEND,        MVT::v16i32, Custom);
1414     setOperationAction(ISD::ZERO_EXTEND,        MVT::v8i64, Custom);
1415     setOperationAction(ISD::ANY_EXTEND,         MVT::v16i32, Custom);
1416     setOperationAction(ISD::ANY_EXTEND,         MVT::v8i64, Custom);
1417     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i32, Custom);
1418     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i64, Custom);
1419     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i8, Custom);
1420     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i16, Custom);
1421     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i16, Custom);
1422     if (Subtarget->hasDQI()) {
1423       setOperationAction(ISD::SIGN_EXTEND,        MVT::v4i32, Custom);
1424       setOperationAction(ISD::SIGN_EXTEND,        MVT::v2i64, Custom);
1425     }
1426     setOperationAction(ISD::FFLOOR,             MVT::v16f32, Legal);
1427     setOperationAction(ISD::FFLOOR,             MVT::v8f64, Legal);
1428     setOperationAction(ISD::FCEIL,              MVT::v16f32, Legal);
1429     setOperationAction(ISD::FCEIL,              MVT::v8f64, Legal);
1430     setOperationAction(ISD::FTRUNC,             MVT::v16f32, Legal);
1431     setOperationAction(ISD::FTRUNC,             MVT::v8f64, Legal);
1432     setOperationAction(ISD::FRINT,              MVT::v16f32, Legal);
1433     setOperationAction(ISD::FRINT,              MVT::v8f64, Legal);
1434     setOperationAction(ISD::FNEARBYINT,         MVT::v16f32, Legal);
1435     setOperationAction(ISD::FNEARBYINT,         MVT::v8f64, Legal);
1436
1437     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8f64,  Custom);
1438     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i64,  Custom);
1439     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16f32,  Custom);
1440     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i32,  Custom);
1441     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i1, Legal);
1442
1443     setOperationAction(ISD::SETCC,              MVT::v16i1, Custom);
1444     setOperationAction(ISD::SETCC,              MVT::v8i1, Custom);
1445
1446     setOperationAction(ISD::MUL,              MVT::v8i64, Custom);
1447
1448     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1,  Custom);
1449     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1450     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i1, Custom);
1451     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i1, Custom);
1452     setOperationAction(ISD::BUILD_VECTOR,       MVT::v8i1, Custom);
1453     setOperationAction(ISD::BUILD_VECTOR,       MVT::v16i1, Custom);
1454     setOperationAction(ISD::SELECT,             MVT::v8f64, Custom);
1455     setOperationAction(ISD::SELECT,             MVT::v8i64, Custom);
1456     setOperationAction(ISD::SELECT,             MVT::v16f32, Custom);
1457     setOperationAction(ISD::SELECT,             MVT::v16i1, Custom);
1458     setOperationAction(ISD::SELECT,             MVT::v8i1,  Custom);
1459
1460     setOperationAction(ISD::SMAX,               MVT::v16i32, Legal);
1461     setOperationAction(ISD::SMAX,               MVT::v8i64, Legal);
1462     setOperationAction(ISD::UMAX,               MVT::v16i32, Legal);
1463     setOperationAction(ISD::UMAX,               MVT::v8i64, Legal);
1464     setOperationAction(ISD::SMIN,               MVT::v16i32, Legal);
1465     setOperationAction(ISD::SMIN,               MVT::v8i64, Legal);
1466     setOperationAction(ISD::UMIN,               MVT::v16i32, Legal);
1467     setOperationAction(ISD::UMIN,               MVT::v8i64, Legal);
1468
1469     setOperationAction(ISD::ADD,                MVT::v8i64, Legal);
1470     setOperationAction(ISD::ADD,                MVT::v16i32, Legal);
1471
1472     setOperationAction(ISD::SUB,                MVT::v8i64, Legal);
1473     setOperationAction(ISD::SUB,                MVT::v16i32, Legal);
1474
1475     setOperationAction(ISD::MUL,                MVT::v16i32, Legal);
1476
1477     setOperationAction(ISD::SRL,                MVT::v8i64, Custom);
1478     setOperationAction(ISD::SRL,                MVT::v16i32, Custom);
1479
1480     setOperationAction(ISD::SHL,                MVT::v8i64, Custom);
1481     setOperationAction(ISD::SHL,                MVT::v16i32, Custom);
1482
1483     setOperationAction(ISD::SRA,                MVT::v8i64, Custom);
1484     setOperationAction(ISD::SRA,                MVT::v16i32, Custom);
1485
1486     setOperationAction(ISD::AND,                MVT::v8i64, Legal);
1487     setOperationAction(ISD::OR,                 MVT::v8i64, Legal);
1488     setOperationAction(ISD::XOR,                MVT::v8i64, Legal);
1489     setOperationAction(ISD::AND,                MVT::v16i32, Legal);
1490     setOperationAction(ISD::OR,                 MVT::v16i32, Legal);
1491     setOperationAction(ISD::XOR,                MVT::v16i32, Legal);
1492
1493     if (Subtarget->hasCDI()) {
1494       setOperationAction(ISD::CTLZ,             MVT::v8i64, Legal);
1495       setOperationAction(ISD::CTLZ,             MVT::v16i32, Legal);
1496     }
1497     if (Subtarget->hasDQI()) {
1498       setOperationAction(ISD::MUL,             MVT::v2i64, Legal);
1499       setOperationAction(ISD::MUL,             MVT::v4i64, Legal);
1500       setOperationAction(ISD::MUL,             MVT::v8i64, Legal);
1501     }
1502     // Custom lower several nodes.
1503     for (MVT VT : MVT::vector_valuetypes()) {
1504       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1505       if (EltSize == 1) {
1506         setOperationAction(ISD::AND, VT, Legal);
1507         setOperationAction(ISD::OR,  VT, Legal);
1508         setOperationAction(ISD::XOR,  VT, Legal);
1509       }
1510       if (EltSize >= 32 && VT.getSizeInBits() <= 512) {
1511         setOperationAction(ISD::MGATHER,  VT, Custom);
1512         setOperationAction(ISD::MSCATTER, VT, Custom);
1513       }
1514       // Extract subvector is special because the value type
1515       // (result) is 256/128-bit but the source is 512-bit wide.
1516       if (VT.is128BitVector() || VT.is256BitVector()) {
1517         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1518       }
1519       if (VT.getVectorElementType() == MVT::i1)
1520         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1521
1522       // Do not attempt to custom lower other non-512-bit vectors
1523       if (!VT.is512BitVector())
1524         continue;
1525
1526       if (EltSize >= 32) {
1527         setOperationAction(ISD::VECTOR_SHUFFLE,      VT, Custom);
1528         setOperationAction(ISD::INSERT_VECTOR_ELT,   VT, Custom);
1529         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1530         setOperationAction(ISD::VSELECT,             VT, Legal);
1531         setOperationAction(ISD::EXTRACT_VECTOR_ELT,  VT, Custom);
1532         setOperationAction(ISD::SCALAR_TO_VECTOR,    VT, Custom);
1533         setOperationAction(ISD::INSERT_SUBVECTOR,    VT, Custom);
1534         setOperationAction(ISD::MLOAD,               VT, Legal);
1535         setOperationAction(ISD::MSTORE,              VT, Legal);
1536       }
1537     }
1538     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1539       MVT VT = (MVT::SimpleValueType)i;
1540
1541       // Do not attempt to promote non-512-bit vectors.
1542       if (!VT.is512BitVector())
1543         continue;
1544
1545       setOperationAction(ISD::SELECT, VT, Promote);
1546       AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1547     }
1548   }// has  AVX-512
1549
1550   if (!Subtarget->useSoftFloat() && Subtarget->hasBWI()) {
1551     addRegisterClass(MVT::v32i16, &X86::VR512RegClass);
1552     addRegisterClass(MVT::v64i8,  &X86::VR512RegClass);
1553
1554     addRegisterClass(MVT::v32i1,  &X86::VK32RegClass);
1555     addRegisterClass(MVT::v64i1,  &X86::VK64RegClass);
1556
1557     setOperationAction(ISD::LOAD,               MVT::v32i16, Legal);
1558     setOperationAction(ISD::LOAD,               MVT::v64i8, Legal);
1559     setOperationAction(ISD::SETCC,              MVT::v32i1, Custom);
1560     setOperationAction(ISD::SETCC,              MVT::v64i1, Custom);
1561     setOperationAction(ISD::ADD,                MVT::v32i16, Legal);
1562     setOperationAction(ISD::ADD,                MVT::v64i8, Legal);
1563     setOperationAction(ISD::SUB,                MVT::v32i16, Legal);
1564     setOperationAction(ISD::SUB,                MVT::v64i8, Legal);
1565     setOperationAction(ISD::MUL,                MVT::v32i16, Legal);
1566     setOperationAction(ISD::MULHS,              MVT::v32i16, Legal);
1567     setOperationAction(ISD::MULHU,              MVT::v32i16, Legal);
1568     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v32i1, Custom);
1569     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v64i1, Custom);
1570     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v32i1, Custom);
1571     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v64i1, Custom);
1572     setOperationAction(ISD::SELECT,             MVT::v32i1, Custom);
1573     setOperationAction(ISD::SELECT,             MVT::v64i1, Custom);
1574     setOperationAction(ISD::SIGN_EXTEND,        MVT::v32i8, Custom);
1575     setOperationAction(ISD::ZERO_EXTEND,        MVT::v32i8, Custom);
1576     setOperationAction(ISD::SIGN_EXTEND,        MVT::v32i16, Custom);
1577     setOperationAction(ISD::ZERO_EXTEND,        MVT::v32i16, Custom);
1578     setOperationAction(ISD::SIGN_EXTEND,        MVT::v64i8, Custom);
1579     setOperationAction(ISD::ZERO_EXTEND,        MVT::v64i8, Custom);
1580     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v32i1, Custom);
1581     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v64i1, Custom);
1582     setOperationAction(ISD::VSELECT,            MVT::v32i16, Legal);
1583     setOperationAction(ISD::VSELECT,            MVT::v64i8, Legal);
1584     setOperationAction(ISD::TRUNCATE,           MVT::v32i1, Custom);
1585     setOperationAction(ISD::TRUNCATE,           MVT::v64i1, Custom);
1586     setOperationAction(ISD::TRUNCATE,           MVT::v32i8, Custom);
1587
1588     setOperationAction(ISD::SMAX,               MVT::v64i8, Legal);
1589     setOperationAction(ISD::SMAX,               MVT::v32i16, Legal);
1590     setOperationAction(ISD::UMAX,               MVT::v64i8, Legal);
1591     setOperationAction(ISD::UMAX,               MVT::v32i16, Legal);
1592     setOperationAction(ISD::SMIN,               MVT::v64i8, Legal);
1593     setOperationAction(ISD::SMIN,               MVT::v32i16, Legal);
1594     setOperationAction(ISD::UMIN,               MVT::v64i8, Legal);
1595     setOperationAction(ISD::UMIN,               MVT::v32i16, Legal);
1596
1597     setTruncStoreAction(MVT::v32i16,  MVT::v32i8, Legal);
1598     setTruncStoreAction(MVT::v16i16,  MVT::v16i8, Legal);
1599     if (Subtarget->hasVLX())
1600       setTruncStoreAction(MVT::v8i16,   MVT::v8i8,  Legal);
1601
1602     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1603       const MVT VT = (MVT::SimpleValueType)i;
1604
1605       const unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1606
1607       // Do not attempt to promote non-512-bit vectors.
1608       if (!VT.is512BitVector())
1609         continue;
1610
1611       if (EltSize < 32) {
1612         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1613         setOperationAction(ISD::VSELECT,             VT, Legal);
1614       }
1615     }
1616   }
1617
1618   if (!Subtarget->useSoftFloat() && Subtarget->hasVLX()) {
1619     addRegisterClass(MVT::v4i1,   &X86::VK4RegClass);
1620     addRegisterClass(MVT::v2i1,   &X86::VK2RegClass);
1621
1622     setOperationAction(ISD::SETCC,              MVT::v4i1, Custom);
1623     setOperationAction(ISD::SETCC,              MVT::v2i1, Custom);
1624     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4i1, Custom);
1625     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i1, Custom);
1626     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v8i1, Custom);
1627     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v4i1, Custom);
1628     setOperationAction(ISD::SELECT,             MVT::v4i1, Custom);
1629     setOperationAction(ISD::SELECT,             MVT::v2i1, Custom);
1630     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4i1, Custom);
1631     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i1, Custom);
1632
1633     setOperationAction(ISD::AND,                MVT::v8i32, Legal);
1634     setOperationAction(ISD::OR,                 MVT::v8i32, Legal);
1635     setOperationAction(ISD::XOR,                MVT::v8i32, Legal);
1636     setOperationAction(ISD::AND,                MVT::v4i32, Legal);
1637     setOperationAction(ISD::OR,                 MVT::v4i32, Legal);
1638     setOperationAction(ISD::XOR,                MVT::v4i32, Legal);
1639     setOperationAction(ISD::SRA,                MVT::v2i64, Custom);
1640     setOperationAction(ISD::SRA,                MVT::v4i64, Custom);
1641
1642     setOperationAction(ISD::SMAX,               MVT::v2i64, Legal);
1643     setOperationAction(ISD::SMAX,               MVT::v4i64, Legal);
1644     setOperationAction(ISD::UMAX,               MVT::v2i64, Legal);
1645     setOperationAction(ISD::UMAX,               MVT::v4i64, Legal);
1646     setOperationAction(ISD::SMIN,               MVT::v2i64, Legal);
1647     setOperationAction(ISD::SMIN,               MVT::v4i64, Legal);
1648     setOperationAction(ISD::UMIN,               MVT::v2i64, Legal);
1649     setOperationAction(ISD::UMIN,               MVT::v4i64, Legal);
1650   }
1651
1652   // We want to custom lower some of our intrinsics.
1653   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1654   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1655   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1656   if (!Subtarget->is64Bit())
1657     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1658
1659   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1660   // handle type legalization for these operations here.
1661   //
1662   // FIXME: We really should do custom legalization for addition and
1663   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1664   // than generic legalization for 64-bit multiplication-with-overflow, though.
1665   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1666     // Add/Sub/Mul with overflow operations are custom lowered.
1667     MVT VT = IntVTs[i];
1668     setOperationAction(ISD::SADDO, VT, Custom);
1669     setOperationAction(ISD::UADDO, VT, Custom);
1670     setOperationAction(ISD::SSUBO, VT, Custom);
1671     setOperationAction(ISD::USUBO, VT, Custom);
1672     setOperationAction(ISD::SMULO, VT, Custom);
1673     setOperationAction(ISD::UMULO, VT, Custom);
1674   }
1675
1676
1677   if (!Subtarget->is64Bit()) {
1678     // These libcalls are not available in 32-bit.
1679     setLibcallName(RTLIB::SHL_I128, nullptr);
1680     setLibcallName(RTLIB::SRL_I128, nullptr);
1681     setLibcallName(RTLIB::SRA_I128, nullptr);
1682   }
1683
1684   // Combine sin / cos into one node or libcall if possible.
1685   if (Subtarget->hasSinCos()) {
1686     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1687     setLibcallName(RTLIB::SINCOS_F64, "sincos");
1688     if (Subtarget->isTargetDarwin()) {
1689       // For MacOSX, we don't want the normal expansion of a libcall to sincos.
1690       // We want to issue a libcall to __sincos_stret to avoid memory traffic.
1691       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1692       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1693     }
1694   }
1695
1696   if (Subtarget->isTargetWin64()) {
1697     setOperationAction(ISD::SDIV, MVT::i128, Custom);
1698     setOperationAction(ISD::UDIV, MVT::i128, Custom);
1699     setOperationAction(ISD::SREM, MVT::i128, Custom);
1700     setOperationAction(ISD::UREM, MVT::i128, Custom);
1701     setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1702     setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1703   }
1704
1705   // We have target-specific dag combine patterns for the following nodes:
1706   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1707   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1708   setTargetDAGCombine(ISD::BITCAST);
1709   setTargetDAGCombine(ISD::VSELECT);
1710   setTargetDAGCombine(ISD::SELECT);
1711   setTargetDAGCombine(ISD::SHL);
1712   setTargetDAGCombine(ISD::SRA);
1713   setTargetDAGCombine(ISD::SRL);
1714   setTargetDAGCombine(ISD::OR);
1715   setTargetDAGCombine(ISD::AND);
1716   setTargetDAGCombine(ISD::ADD);
1717   setTargetDAGCombine(ISD::FADD);
1718   setTargetDAGCombine(ISD::FSUB);
1719   setTargetDAGCombine(ISD::FMA);
1720   setTargetDAGCombine(ISD::SUB);
1721   setTargetDAGCombine(ISD::LOAD);
1722   setTargetDAGCombine(ISD::MLOAD);
1723   setTargetDAGCombine(ISD::STORE);
1724   setTargetDAGCombine(ISD::MSTORE);
1725   setTargetDAGCombine(ISD::ZERO_EXTEND);
1726   setTargetDAGCombine(ISD::ANY_EXTEND);
1727   setTargetDAGCombine(ISD::SIGN_EXTEND);
1728   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1729   setTargetDAGCombine(ISD::SINT_TO_FP);
1730   setTargetDAGCombine(ISD::UINT_TO_FP);
1731   setTargetDAGCombine(ISD::SETCC);
1732   setTargetDAGCombine(ISD::BUILD_VECTOR);
1733   setTargetDAGCombine(ISD::MUL);
1734   setTargetDAGCombine(ISD::XOR);
1735
1736   computeRegisterProperties(Subtarget->getRegisterInfo());
1737
1738   MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1739   MaxStoresPerMemsetOptSize = 8;
1740   MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1741   MaxStoresPerMemcpyOptSize = 4;
1742   MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1743   MaxStoresPerMemmoveOptSize = 4;
1744   setPrefLoopAlignment(4); // 2^4 bytes.
1745
1746   // Predictable cmov don't hurt on atom because it's in-order.
1747   PredictableSelectIsExpensive = !Subtarget->isAtom();
1748   EnableExtLdPromotion = true;
1749   setPrefFunctionAlignment(4); // 2^4 bytes.
1750
1751   verifyIntrinsicTables();
1752 }
1753
1754 // This has so far only been implemented for 64-bit MachO.
1755 bool X86TargetLowering::useLoadStackGuardNode() const {
1756   return Subtarget->isTargetMachO() && Subtarget->is64Bit();
1757 }
1758
1759 TargetLoweringBase::LegalizeTypeAction
1760 X86TargetLowering::getPreferredVectorAction(EVT VT) const {
1761   if (ExperimentalVectorWideningLegalization &&
1762       VT.getVectorNumElements() != 1 &&
1763       VT.getVectorElementType().getSimpleVT() != MVT::i1)
1764     return TypeWidenVector;
1765
1766   return TargetLoweringBase::getPreferredVectorAction(VT);
1767 }
1768
1769 EVT X86TargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &,
1770                                           EVT VT) const {
1771   if (!VT.isVector())
1772     return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1773
1774   const unsigned NumElts = VT.getVectorNumElements();
1775   const EVT EltVT = VT.getVectorElementType();
1776   if (VT.is512BitVector()) {
1777     if (Subtarget->hasAVX512())
1778       if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1779           EltVT == MVT::f32 || EltVT == MVT::f64)
1780         switch(NumElts) {
1781         case  8: return MVT::v8i1;
1782         case 16: return MVT::v16i1;
1783       }
1784     if (Subtarget->hasBWI())
1785       if (EltVT == MVT::i8 || EltVT == MVT::i16)
1786         switch(NumElts) {
1787         case 32: return MVT::v32i1;
1788         case 64: return MVT::v64i1;
1789       }
1790   }
1791
1792   if (VT.is256BitVector() || VT.is128BitVector()) {
1793     if (Subtarget->hasVLX())
1794       if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1795           EltVT == MVT::f32 || EltVT == MVT::f64)
1796         switch(NumElts) {
1797         case 2: return MVT::v2i1;
1798         case 4: return MVT::v4i1;
1799         case 8: return MVT::v8i1;
1800       }
1801     if (Subtarget->hasBWI() && Subtarget->hasVLX())
1802       if (EltVT == MVT::i8 || EltVT == MVT::i16)
1803         switch(NumElts) {
1804         case  8: return MVT::v8i1;
1805         case 16: return MVT::v16i1;
1806         case 32: return MVT::v32i1;
1807       }
1808   }
1809
1810   return VT.changeVectorElementTypeToInteger();
1811 }
1812
1813 /// Helper for getByValTypeAlignment to determine
1814 /// the desired ByVal argument alignment.
1815 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1816   if (MaxAlign == 16)
1817     return;
1818   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1819     if (VTy->getBitWidth() == 128)
1820       MaxAlign = 16;
1821   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1822     unsigned EltAlign = 0;
1823     getMaxByValAlign(ATy->getElementType(), EltAlign);
1824     if (EltAlign > MaxAlign)
1825       MaxAlign = EltAlign;
1826   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1827     for (auto *EltTy : STy->elements()) {
1828       unsigned EltAlign = 0;
1829       getMaxByValAlign(EltTy, EltAlign);
1830       if (EltAlign > MaxAlign)
1831         MaxAlign = EltAlign;
1832       if (MaxAlign == 16)
1833         break;
1834     }
1835   }
1836 }
1837
1838 /// Return the desired alignment for ByVal aggregate
1839 /// function arguments in the caller parameter area. For X86, aggregates
1840 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1841 /// are at 4-byte boundaries.
1842 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty,
1843                                                   const DataLayout &DL) const {
1844   if (Subtarget->is64Bit()) {
1845     // Max of 8 and alignment of type.
1846     unsigned TyAlign = DL.getABITypeAlignment(Ty);
1847     if (TyAlign > 8)
1848       return TyAlign;
1849     return 8;
1850   }
1851
1852   unsigned Align = 4;
1853   if (Subtarget->hasSSE1())
1854     getMaxByValAlign(Ty, Align);
1855   return Align;
1856 }
1857
1858 /// Returns the target specific optimal type for load
1859 /// and store operations as a result of memset, memcpy, and memmove
1860 /// lowering. If DstAlign is zero that means it's safe to destination
1861 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1862 /// means there isn't a need to check it against alignment requirement,
1863 /// probably because the source does not need to be loaded. If 'IsMemset' is
1864 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1865 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1866 /// source is constant so it does not need to be loaded.
1867 /// It returns EVT::Other if the type should be determined using generic
1868 /// target-independent logic.
1869 EVT
1870 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1871                                        unsigned DstAlign, unsigned SrcAlign,
1872                                        bool IsMemset, bool ZeroMemset,
1873                                        bool MemcpyStrSrc,
1874                                        MachineFunction &MF) const {
1875   const Function *F = MF.getFunction();
1876   if ((!IsMemset || ZeroMemset) &&
1877       !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
1878     if (Size >= 16 &&
1879         (Subtarget->isUnalignedMemAccessFast() ||
1880          ((DstAlign == 0 || DstAlign >= 16) &&
1881           (SrcAlign == 0 || SrcAlign >= 16)))) {
1882       if (Size >= 32) {
1883         if (Subtarget->hasInt256())
1884           return MVT::v8i32;
1885         if (Subtarget->hasFp256())
1886           return MVT::v8f32;
1887       }
1888       if (Subtarget->hasSSE2())
1889         return MVT::v4i32;
1890       if (Subtarget->hasSSE1())
1891         return MVT::v4f32;
1892     } else if (!MemcpyStrSrc && Size >= 8 &&
1893                !Subtarget->is64Bit() &&
1894                Subtarget->hasSSE2()) {
1895       // Do not use f64 to lower memcpy if source is string constant. It's
1896       // better to use i32 to avoid the loads.
1897       return MVT::f64;
1898     }
1899   }
1900   if (Subtarget->is64Bit() && Size >= 8)
1901     return MVT::i64;
1902   return MVT::i32;
1903 }
1904
1905 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1906   if (VT == MVT::f32)
1907     return X86ScalarSSEf32;
1908   else if (VT == MVT::f64)
1909     return X86ScalarSSEf64;
1910   return true;
1911 }
1912
1913 bool
1914 X86TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
1915                                                   unsigned,
1916                                                   unsigned,
1917                                                   bool *Fast) const {
1918   if (Fast) {
1919     // FIXME: We should be checking 128-bit accesses separately from smaller
1920     // accesses.
1921     if (VT.getSizeInBits() == 256)
1922       *Fast = !Subtarget->isUnalignedMem32Slow();
1923     else
1924       *Fast = Subtarget->isUnalignedMemAccessFast();
1925   }
1926   return true;
1927 }
1928
1929 /// Return the entry encoding for a jump table in the
1930 /// current function.  The returned value is a member of the
1931 /// MachineJumpTableInfo::JTEntryKind enum.
1932 unsigned X86TargetLowering::getJumpTableEncoding() const {
1933   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1934   // symbol.
1935   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1936       Subtarget->isPICStyleGOT())
1937     return MachineJumpTableInfo::EK_Custom32;
1938
1939   // Otherwise, use the normal jump table encoding heuristics.
1940   return TargetLowering::getJumpTableEncoding();
1941 }
1942
1943 bool X86TargetLowering::useSoftFloat() const {
1944   return Subtarget->useSoftFloat();
1945 }
1946
1947 const MCExpr *
1948 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1949                                              const MachineBasicBlock *MBB,
1950                                              unsigned uid,MCContext &Ctx) const{
1951   assert(MBB->getParent()->getTarget().getRelocationModel() == Reloc::PIC_ &&
1952          Subtarget->isPICStyleGOT());
1953   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1954   // entries.
1955   return MCSymbolRefExpr::create(MBB->getSymbol(),
1956                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1957 }
1958
1959 /// Returns relocation base for the given PIC jumptable.
1960 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1961                                                     SelectionDAG &DAG) const {
1962   if (!Subtarget->is64Bit())
1963     // This doesn't have SDLoc associated with it, but is not really the
1964     // same as a Register.
1965     return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(),
1966                        getPointerTy(DAG.getDataLayout()));
1967   return Table;
1968 }
1969
1970 /// This returns the relocation base for the given PIC jumptable,
1971 /// the same as getPICJumpTableRelocBase, but as an MCExpr.
1972 const MCExpr *X86TargetLowering::
1973 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1974                              MCContext &Ctx) const {
1975   // X86-64 uses RIP relative addressing based on the jump table label.
1976   if (Subtarget->isPICStyleRIPRel())
1977     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1978
1979   // Otherwise, the reference is relative to the PIC base.
1980   return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx);
1981 }
1982
1983 std::pair<const TargetRegisterClass *, uint8_t>
1984 X86TargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
1985                                            MVT VT) const {
1986   const TargetRegisterClass *RRC = nullptr;
1987   uint8_t Cost = 1;
1988   switch (VT.SimpleTy) {
1989   default:
1990     return TargetLowering::findRepresentativeClass(TRI, VT);
1991   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1992     RRC = Subtarget->is64Bit() ? &X86::GR64RegClass : &X86::GR32RegClass;
1993     break;
1994   case MVT::x86mmx:
1995     RRC = &X86::VR64RegClass;
1996     break;
1997   case MVT::f32: case MVT::f64:
1998   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1999   case MVT::v4f32: case MVT::v2f64:
2000   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
2001   case MVT::v4f64:
2002     RRC = &X86::VR128RegClass;
2003     break;
2004   }
2005   return std::make_pair(RRC, Cost);
2006 }
2007
2008 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
2009                                                unsigned &Offset) const {
2010   if (!Subtarget->isTargetLinux())
2011     return false;
2012
2013   if (Subtarget->is64Bit()) {
2014     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
2015     Offset = 0x28;
2016     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
2017       AddressSpace = 256;
2018     else
2019       AddressSpace = 257;
2020   } else {
2021     // %gs:0x14 on i386
2022     Offset = 0x14;
2023     AddressSpace = 256;
2024   }
2025   return true;
2026 }
2027
2028 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
2029                                             unsigned DestAS) const {
2030   assert(SrcAS != DestAS && "Expected different address spaces!");
2031
2032   return SrcAS < 256 && DestAS < 256;
2033 }
2034
2035 //===----------------------------------------------------------------------===//
2036 //               Return Value Calling Convention Implementation
2037 //===----------------------------------------------------------------------===//
2038
2039 #include "X86GenCallingConv.inc"
2040
2041 bool
2042 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2043                                   MachineFunction &MF, bool isVarArg,
2044                         const SmallVectorImpl<ISD::OutputArg> &Outs,
2045                         LLVMContext &Context) const {
2046   SmallVector<CCValAssign, 16> RVLocs;
2047   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2048   return CCInfo.CheckReturn(Outs, RetCC_X86);
2049 }
2050
2051 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
2052   static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
2053   return ScratchRegs;
2054 }
2055
2056 SDValue
2057 X86TargetLowering::LowerReturn(SDValue Chain,
2058                                CallingConv::ID CallConv, bool isVarArg,
2059                                const SmallVectorImpl<ISD::OutputArg> &Outs,
2060                                const SmallVectorImpl<SDValue> &OutVals,
2061                                SDLoc dl, SelectionDAG &DAG) const {
2062   MachineFunction &MF = DAG.getMachineFunction();
2063   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2064
2065   SmallVector<CCValAssign, 16> RVLocs;
2066   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, *DAG.getContext());
2067   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
2068
2069   SDValue Flag;
2070   SmallVector<SDValue, 6> RetOps;
2071   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2072   // Operand #1 = Bytes To Pop
2073   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(), dl,
2074                    MVT::i16));
2075
2076   // Copy the result values into the output registers.
2077   for (unsigned i = 0; i != RVLocs.size(); ++i) {
2078     CCValAssign &VA = RVLocs[i];
2079     assert(VA.isRegLoc() && "Can only return in registers!");
2080     SDValue ValToCopy = OutVals[i];
2081     EVT ValVT = ValToCopy.getValueType();
2082
2083     // Promote values to the appropriate types.
2084     if (VA.getLocInfo() == CCValAssign::SExt)
2085       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2086     else if (VA.getLocInfo() == CCValAssign::ZExt)
2087       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
2088     else if (VA.getLocInfo() == CCValAssign::AExt) {
2089       if (ValVT.isVector() && ValVT.getScalarType() == MVT::i1)
2090         ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2091       else
2092         ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
2093     }
2094     else if (VA.getLocInfo() == CCValAssign::BCvt)
2095       ValToCopy = DAG.getBitcast(VA.getLocVT(), ValToCopy);
2096
2097     assert(VA.getLocInfo() != CCValAssign::FPExt &&
2098            "Unexpected FP-extend for return value.");
2099
2100     // If this is x86-64, and we disabled SSE, we can't return FP values,
2101     // or SSE or MMX vectors.
2102     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
2103          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
2104           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
2105       report_fatal_error("SSE register return with SSE disabled");
2106     }
2107     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
2108     // llvm-gcc has never done it right and no one has noticed, so this
2109     // should be OK for now.
2110     if (ValVT == MVT::f64 &&
2111         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
2112       report_fatal_error("SSE2 register return with SSE2 disabled");
2113
2114     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
2115     // the RET instruction and handled by the FP Stackifier.
2116     if (VA.getLocReg() == X86::FP0 ||
2117         VA.getLocReg() == X86::FP1) {
2118       // If this is a copy from an xmm register to ST(0), use an FPExtend to
2119       // change the value to the FP stack register class.
2120       if (isScalarFPTypeInSSEReg(VA.getValVT()))
2121         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
2122       RetOps.push_back(ValToCopy);
2123       // Don't emit a copytoreg.
2124       continue;
2125     }
2126
2127     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
2128     // which is returned in RAX / RDX.
2129     if (Subtarget->is64Bit()) {
2130       if (ValVT == MVT::x86mmx) {
2131         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
2132           ValToCopy = DAG.getBitcast(MVT::i64, ValToCopy);
2133           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
2134                                   ValToCopy);
2135           // If we don't have SSE2 available, convert to v4f32 so the generated
2136           // register is legal.
2137           if (!Subtarget->hasSSE2())
2138             ValToCopy = DAG.getBitcast(MVT::v4f32, ValToCopy);
2139         }
2140       }
2141     }
2142
2143     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
2144     Flag = Chain.getValue(1);
2145     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2146   }
2147
2148   // All x86 ABIs require that for returning structs by value we copy
2149   // the sret argument into %rax/%eax (depending on ABI) for the return.
2150   // We saved the argument into a virtual register in the entry block,
2151   // so now we copy the value out and into %rax/%eax.
2152   //
2153   // Checking Function.hasStructRetAttr() here is insufficient because the IR
2154   // may not have an explicit sret argument. If FuncInfo.CanLowerReturn is
2155   // false, then an sret argument may be implicitly inserted in the SelDAG. In
2156   // either case FuncInfo->setSRetReturnReg() will have been called.
2157   if (unsigned SRetReg = FuncInfo->getSRetReturnReg()) {
2158     SDValue Val = DAG.getCopyFromReg(Chain, dl, SRetReg,
2159                                      getPointerTy(MF.getDataLayout()));
2160
2161     unsigned RetValReg
2162         = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
2163           X86::RAX : X86::EAX;
2164     Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
2165     Flag = Chain.getValue(1);
2166
2167     // RAX/EAX now acts like a return value.
2168     RetOps.push_back(
2169         DAG.getRegister(RetValReg, getPointerTy(DAG.getDataLayout())));
2170   }
2171
2172   RetOps[0] = Chain;  // Update chain.
2173
2174   // Add the flag if we have it.
2175   if (Flag.getNode())
2176     RetOps.push_back(Flag);
2177
2178   return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
2179 }
2180
2181 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2182   if (N->getNumValues() != 1)
2183     return false;
2184   if (!N->hasNUsesOfValue(1, 0))
2185     return false;
2186
2187   SDValue TCChain = Chain;
2188   SDNode *Copy = *N->use_begin();
2189   if (Copy->getOpcode() == ISD::CopyToReg) {
2190     // If the copy has a glue operand, we conservatively assume it isn't safe to
2191     // perform a tail call.
2192     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2193       return false;
2194     TCChain = Copy->getOperand(0);
2195   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
2196     return false;
2197
2198   bool HasRet = false;
2199   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2200        UI != UE; ++UI) {
2201     if (UI->getOpcode() != X86ISD::RET_FLAG)
2202       return false;
2203     // If we are returning more than one value, we can definitely
2204     // not make a tail call see PR19530
2205     if (UI->getNumOperands() > 4)
2206       return false;
2207     if (UI->getNumOperands() == 4 &&
2208         UI->getOperand(UI->getNumOperands()-1).getValueType() != MVT::Glue)
2209       return false;
2210     HasRet = true;
2211   }
2212
2213   if (!HasRet)
2214     return false;
2215
2216   Chain = TCChain;
2217   return true;
2218 }
2219
2220 EVT
2221 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
2222                                             ISD::NodeType ExtendKind) const {
2223   MVT ReturnMVT;
2224   // TODO: Is this also valid on 32-bit?
2225   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
2226     ReturnMVT = MVT::i8;
2227   else
2228     ReturnMVT = MVT::i32;
2229
2230   EVT MinVT = getRegisterType(Context, ReturnMVT);
2231   return VT.bitsLT(MinVT) ? MinVT : VT;
2232 }
2233
2234 /// Lower the result values of a call into the
2235 /// appropriate copies out of appropriate physical registers.
2236 ///
2237 SDValue
2238 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2239                                    CallingConv::ID CallConv, bool isVarArg,
2240                                    const SmallVectorImpl<ISD::InputArg> &Ins,
2241                                    SDLoc dl, SelectionDAG &DAG,
2242                                    SmallVectorImpl<SDValue> &InVals) const {
2243
2244   // Assign locations to each value returned by this call.
2245   SmallVector<CCValAssign, 16> RVLocs;
2246   bool Is64Bit = Subtarget->is64Bit();
2247   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2248                  *DAG.getContext());
2249   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2250
2251   // Copy all of the result registers out of their specified physreg.
2252   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2253     CCValAssign &VA = RVLocs[i];
2254     EVT CopyVT = VA.getLocVT();
2255
2256     // If this is x86-64, and we disabled SSE, we can't return FP values
2257     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2258         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2259       report_fatal_error("SSE register return with SSE disabled");
2260     }
2261
2262     // If we prefer to use the value in xmm registers, copy it out as f80 and
2263     // use a truncate to move it from fp stack reg to xmm reg.
2264     bool RoundAfterCopy = false;
2265     if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
2266         isScalarFPTypeInSSEReg(VA.getValVT())) {
2267       CopyVT = MVT::f80;
2268       RoundAfterCopy = (CopyVT != VA.getLocVT());
2269     }
2270
2271     Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2272                                CopyVT, InFlag).getValue(1);
2273     SDValue Val = Chain.getValue(0);
2274
2275     if (RoundAfterCopy)
2276       Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2277                         // This truncation won't change the value.
2278                         DAG.getIntPtrConstant(1, dl));
2279
2280     if (VA.isExtInLoc() && VA.getValVT().getScalarType() == MVT::i1)
2281       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
2282
2283     InFlag = Chain.getValue(2);
2284     InVals.push_back(Val);
2285   }
2286
2287   return Chain;
2288 }
2289
2290 //===----------------------------------------------------------------------===//
2291 //                C & StdCall & Fast Calling Convention implementation
2292 //===----------------------------------------------------------------------===//
2293 //  StdCall calling convention seems to be standard for many Windows' API
2294 //  routines and around. It differs from C calling convention just a little:
2295 //  callee should clean up the stack, not caller. Symbols should be also
2296 //  decorated in some fancy way :) It doesn't support any vector arguments.
2297 //  For info on fast calling convention see Fast Calling Convention (tail call)
2298 //  implementation LowerX86_32FastCCCallTo.
2299
2300 /// CallIsStructReturn - Determines whether a call uses struct return
2301 /// semantics.
2302 enum StructReturnType {
2303   NotStructReturn,
2304   RegStructReturn,
2305   StackStructReturn
2306 };
2307 static StructReturnType
2308 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2309   if (Outs.empty())
2310     return NotStructReturn;
2311
2312   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2313   if (!Flags.isSRet())
2314     return NotStructReturn;
2315   if (Flags.isInReg())
2316     return RegStructReturn;
2317   return StackStructReturn;
2318 }
2319
2320 /// Determines whether a function uses struct return semantics.
2321 static StructReturnType
2322 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2323   if (Ins.empty())
2324     return NotStructReturn;
2325
2326   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2327   if (!Flags.isSRet())
2328     return NotStructReturn;
2329   if (Flags.isInReg())
2330     return RegStructReturn;
2331   return StackStructReturn;
2332 }
2333
2334 /// Make a copy of an aggregate at address specified by "Src" to address
2335 /// "Dst" with size and alignment information specified by the specific
2336 /// parameter attribute. The copy will be passed as a byval function parameter.
2337 static SDValue
2338 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2339                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2340                           SDLoc dl) {
2341   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
2342
2343   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2344                        /*isVolatile*/false, /*AlwaysInline=*/true,
2345                        /*isTailCall*/false,
2346                        MachinePointerInfo(), MachinePointerInfo());
2347 }
2348
2349 /// Return true if the calling convention is one that
2350 /// supports tail call optimization.
2351 static bool IsTailCallConvention(CallingConv::ID CC) {
2352   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2353           CC == CallingConv::HiPE);
2354 }
2355
2356 /// \brief Return true if the calling convention is a C calling convention.
2357 static bool IsCCallConvention(CallingConv::ID CC) {
2358   return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2359           CC == CallingConv::X86_64_SysV);
2360 }
2361
2362 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2363   auto Attr =
2364       CI->getParent()->getParent()->getFnAttribute("disable-tail-calls");
2365   if (!CI->isTailCall() || Attr.getValueAsString() == "true")
2366     return false;
2367
2368   CallSite CS(CI);
2369   CallingConv::ID CalleeCC = CS.getCallingConv();
2370   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2371     return false;
2372
2373   return true;
2374 }
2375
2376 /// Return true if the function is being made into
2377 /// a tailcall target by changing its ABI.
2378 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2379                                    bool GuaranteedTailCallOpt) {
2380   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2381 }
2382
2383 SDValue
2384 X86TargetLowering::LowerMemArgument(SDValue Chain,
2385                                     CallingConv::ID CallConv,
2386                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2387                                     SDLoc dl, SelectionDAG &DAG,
2388                                     const CCValAssign &VA,
2389                                     MachineFrameInfo *MFI,
2390                                     unsigned i) const {
2391   // Create the nodes corresponding to a load from this parameter slot.
2392   ISD::ArgFlagsTy Flags = Ins[i].Flags;
2393   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(
2394       CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2395   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2396   EVT ValVT;
2397
2398   // If value is passed by pointer we have address passed instead of the value
2399   // itself.
2400   bool ExtendedInMem = VA.isExtInLoc() &&
2401     VA.getValVT().getScalarType() == MVT::i1;
2402
2403   if (VA.getLocInfo() == CCValAssign::Indirect || ExtendedInMem)
2404     ValVT = VA.getLocVT();
2405   else
2406     ValVT = VA.getValVT();
2407
2408   // FIXME: For now, all byval parameter objects are marked mutable. This can be
2409   // changed with more analysis.
2410   // In case of tail call optimization mark all arguments mutable. Since they
2411   // could be overwritten by lowering of arguments in case of a tail call.
2412   if (Flags.isByVal()) {
2413     unsigned Bytes = Flags.getByValSize();
2414     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2415     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2416     return DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2417   } else {
2418     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2419                                     VA.getLocMemOffset(), isImmutable);
2420     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2421     SDValue Val = DAG.getLoad(
2422         ValVT, dl, Chain, FIN,
2423         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), false,
2424         false, false, 0);
2425     return ExtendedInMem ?
2426       DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val) : Val;
2427   }
2428 }
2429
2430 // FIXME: Get this from tablegen.
2431 static ArrayRef<MCPhysReg> get64BitArgumentGPRs(CallingConv::ID CallConv,
2432                                                 const X86Subtarget *Subtarget) {
2433   assert(Subtarget->is64Bit());
2434
2435   if (Subtarget->isCallingConvWin64(CallConv)) {
2436     static const MCPhysReg GPR64ArgRegsWin64[] = {
2437       X86::RCX, X86::RDX, X86::R8,  X86::R9
2438     };
2439     return makeArrayRef(std::begin(GPR64ArgRegsWin64), std::end(GPR64ArgRegsWin64));
2440   }
2441
2442   static const MCPhysReg GPR64ArgRegs64Bit[] = {
2443     X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2444   };
2445   return makeArrayRef(std::begin(GPR64ArgRegs64Bit), std::end(GPR64ArgRegs64Bit));
2446 }
2447
2448 // FIXME: Get this from tablegen.
2449 static ArrayRef<MCPhysReg> get64BitArgumentXMMs(MachineFunction &MF,
2450                                                 CallingConv::ID CallConv,
2451                                                 const X86Subtarget *Subtarget) {
2452   assert(Subtarget->is64Bit());
2453   if (Subtarget->isCallingConvWin64(CallConv)) {
2454     // The XMM registers which might contain var arg parameters are shadowed
2455     // in their paired GPR.  So we only need to save the GPR to their home
2456     // slots.
2457     // TODO: __vectorcall will change this.
2458     return None;
2459   }
2460
2461   const Function *Fn = MF.getFunction();
2462   bool NoImplicitFloatOps = Fn->hasFnAttribute(Attribute::NoImplicitFloat);
2463   bool isSoftFloat = Subtarget->useSoftFloat();
2464   assert(!(isSoftFloat && NoImplicitFloatOps) &&
2465          "SSE register cannot be used when SSE is disabled!");
2466   if (isSoftFloat || NoImplicitFloatOps || !Subtarget->hasSSE1())
2467     // Kernel mode asks for SSE to be disabled, so there are no XMM argument
2468     // registers.
2469     return None;
2470
2471   static const MCPhysReg XMMArgRegs64Bit[] = {
2472     X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2473     X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2474   };
2475   return makeArrayRef(std::begin(XMMArgRegs64Bit), std::end(XMMArgRegs64Bit));
2476 }
2477
2478 SDValue
2479 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2480                                         CallingConv::ID CallConv,
2481                                         bool isVarArg,
2482                                       const SmallVectorImpl<ISD::InputArg> &Ins,
2483                                         SDLoc dl,
2484                                         SelectionDAG &DAG,
2485                                         SmallVectorImpl<SDValue> &InVals)
2486                                           const {
2487   MachineFunction &MF = DAG.getMachineFunction();
2488   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2489   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
2490
2491   const Function* Fn = MF.getFunction();
2492   if (Fn->hasExternalLinkage() &&
2493       Subtarget->isTargetCygMing() &&
2494       Fn->getName() == "main")
2495     FuncInfo->setForceFramePointer(true);
2496
2497   MachineFrameInfo *MFI = MF.getFrameInfo();
2498   bool Is64Bit = Subtarget->is64Bit();
2499   bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2500
2501   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2502          "Var args not supported with calling convention fastcc, ghc or hipe");
2503
2504   // Assign locations to all of the incoming arguments.
2505   SmallVector<CCValAssign, 16> ArgLocs;
2506   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2507
2508   // Allocate shadow area for Win64
2509   if (IsWin64)
2510     CCInfo.AllocateStack(32, 8);
2511
2512   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2513
2514   unsigned LastVal = ~0U;
2515   SDValue ArgValue;
2516   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2517     CCValAssign &VA = ArgLocs[i];
2518     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2519     // places.
2520     assert(VA.getValNo() != LastVal &&
2521            "Don't support value assigned to multiple locs yet");
2522     (void)LastVal;
2523     LastVal = VA.getValNo();
2524
2525     if (VA.isRegLoc()) {
2526       EVT RegVT = VA.getLocVT();
2527       const TargetRegisterClass *RC;
2528       if (RegVT == MVT::i32)
2529         RC = &X86::GR32RegClass;
2530       else if (Is64Bit && RegVT == MVT::i64)
2531         RC = &X86::GR64RegClass;
2532       else if (RegVT == MVT::f32)
2533         RC = &X86::FR32RegClass;
2534       else if (RegVT == MVT::f64)
2535         RC = &X86::FR64RegClass;
2536       else if (RegVT.is512BitVector())
2537         RC = &X86::VR512RegClass;
2538       else if (RegVT.is256BitVector())
2539         RC = &X86::VR256RegClass;
2540       else if (RegVT.is128BitVector())
2541         RC = &X86::VR128RegClass;
2542       else if (RegVT == MVT::x86mmx)
2543         RC = &X86::VR64RegClass;
2544       else if (RegVT == MVT::i1)
2545         RC = &X86::VK1RegClass;
2546       else if (RegVT == MVT::v8i1)
2547         RC = &X86::VK8RegClass;
2548       else if (RegVT == MVT::v16i1)
2549         RC = &X86::VK16RegClass;
2550       else if (RegVT == MVT::v32i1)
2551         RC = &X86::VK32RegClass;
2552       else if (RegVT == MVT::v64i1)
2553         RC = &X86::VK64RegClass;
2554       else
2555         llvm_unreachable("Unknown argument type!");
2556
2557       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2558       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2559
2560       // If this is an 8 or 16-bit value, it is really passed promoted to 32
2561       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
2562       // right size.
2563       if (VA.getLocInfo() == CCValAssign::SExt)
2564         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2565                                DAG.getValueType(VA.getValVT()));
2566       else if (VA.getLocInfo() == CCValAssign::ZExt)
2567         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2568                                DAG.getValueType(VA.getValVT()));
2569       else if (VA.getLocInfo() == CCValAssign::BCvt)
2570         ArgValue = DAG.getBitcast(VA.getValVT(), ArgValue);
2571
2572       if (VA.isExtInLoc()) {
2573         // Handle MMX values passed in XMM regs.
2574         if (RegVT.isVector() && VA.getValVT().getScalarType() != MVT::i1)
2575           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2576         else
2577           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2578       }
2579     } else {
2580       assert(VA.isMemLoc());
2581       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2582     }
2583
2584     // If value is passed via pointer - do a load.
2585     if (VA.getLocInfo() == CCValAssign::Indirect)
2586       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2587                              MachinePointerInfo(), false, false, false, 0);
2588
2589     InVals.push_back(ArgValue);
2590   }
2591
2592   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2593     // All x86 ABIs require that for returning structs by value we copy the
2594     // sret argument into %rax/%eax (depending on ABI) for the return. Save
2595     // the argument into a virtual register so that we can access it from the
2596     // return points.
2597     if (Ins[i].Flags.isSRet()) {
2598       unsigned Reg = FuncInfo->getSRetReturnReg();
2599       if (!Reg) {
2600         MVT PtrTy = getPointerTy(DAG.getDataLayout());
2601         Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2602         FuncInfo->setSRetReturnReg(Reg);
2603       }
2604       SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2605       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2606       break;
2607     }
2608   }
2609
2610   unsigned StackSize = CCInfo.getNextStackOffset();
2611   // Align stack specially for tail calls.
2612   if (FuncIsMadeTailCallSafe(CallConv,
2613                              MF.getTarget().Options.GuaranteedTailCallOpt))
2614     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2615
2616   // If the function takes variable number of arguments, make a frame index for
2617   // the start of the first vararg value... for expansion of llvm.va_start. We
2618   // can skip this if there are no va_start calls.
2619   if (MFI->hasVAStart() &&
2620       (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2621                    CallConv != CallingConv::X86_ThisCall))) {
2622     FuncInfo->setVarArgsFrameIndex(
2623         MFI->CreateFixedObject(1, StackSize, true));
2624   }
2625
2626   MachineModuleInfo &MMI = MF.getMMI();
2627   const Function *WinEHParent = nullptr;
2628   if (MMI.hasWinEHFuncInfo(Fn))
2629     WinEHParent = MMI.getWinEHParent(Fn);
2630   bool IsWinEHOutlined = WinEHParent && WinEHParent != Fn;
2631   bool IsWinEHParent = WinEHParent && WinEHParent == Fn;
2632
2633   // Figure out if XMM registers are in use.
2634   assert(!(Subtarget->useSoftFloat() &&
2635            Fn->hasFnAttribute(Attribute::NoImplicitFloat)) &&
2636          "SSE register cannot be used when SSE is disabled!");
2637
2638   // 64-bit calling conventions support varargs and register parameters, so we
2639   // have to do extra work to spill them in the prologue.
2640   if (Is64Bit && isVarArg && MFI->hasVAStart()) {
2641     // Find the first unallocated argument registers.
2642     ArrayRef<MCPhysReg> ArgGPRs = get64BitArgumentGPRs(CallConv, Subtarget);
2643     ArrayRef<MCPhysReg> ArgXMMs = get64BitArgumentXMMs(MF, CallConv, Subtarget);
2644     unsigned NumIntRegs = CCInfo.getFirstUnallocated(ArgGPRs);
2645     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(ArgXMMs);
2646     assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2647            "SSE register cannot be used when SSE is disabled!");
2648
2649     // Gather all the live in physical registers.
2650     SmallVector<SDValue, 6> LiveGPRs;
2651     SmallVector<SDValue, 8> LiveXMMRegs;
2652     SDValue ALVal;
2653     for (MCPhysReg Reg : ArgGPRs.slice(NumIntRegs)) {
2654       unsigned GPR = MF.addLiveIn(Reg, &X86::GR64RegClass);
2655       LiveGPRs.push_back(
2656           DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64));
2657     }
2658     if (!ArgXMMs.empty()) {
2659       unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2660       ALVal = DAG.getCopyFromReg(Chain, dl, AL, MVT::i8);
2661       for (MCPhysReg Reg : ArgXMMs.slice(NumXMMRegs)) {
2662         unsigned XMMReg = MF.addLiveIn(Reg, &X86::VR128RegClass);
2663         LiveXMMRegs.push_back(
2664             DAG.getCopyFromReg(Chain, dl, XMMReg, MVT::v4f32));
2665       }
2666     }
2667
2668     if (IsWin64) {
2669       // Get to the caller-allocated home save location.  Add 8 to account
2670       // for the return address.
2671       int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2672       FuncInfo->setRegSaveFrameIndex(
2673           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2674       // Fixup to set vararg frame on shadow area (4 x i64).
2675       if (NumIntRegs < 4)
2676         FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2677     } else {
2678       // For X86-64, if there are vararg parameters that are passed via
2679       // registers, then we must store them to their spots on the stack so
2680       // they may be loaded by deferencing the result of va_next.
2681       FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2682       FuncInfo->setVarArgsFPOffset(ArgGPRs.size() * 8 + NumXMMRegs * 16);
2683       FuncInfo->setRegSaveFrameIndex(MFI->CreateStackObject(
2684           ArgGPRs.size() * 8 + ArgXMMs.size() * 16, 16, false));
2685     }
2686
2687     // Store the integer parameter registers.
2688     SmallVector<SDValue, 8> MemOps;
2689     SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2690                                       getPointerTy(DAG.getDataLayout()));
2691     unsigned Offset = FuncInfo->getVarArgsGPOffset();
2692     for (SDValue Val : LiveGPRs) {
2693       SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
2694                                 RSFIN, DAG.getIntPtrConstant(Offset, dl));
2695       SDValue Store =
2696           DAG.getStore(Val.getValue(1), dl, Val, FIN,
2697                        MachinePointerInfo::getFixedStack(
2698                            DAG.getMachineFunction(),
2699                            FuncInfo->getRegSaveFrameIndex(), Offset),
2700                        false, false, 0);
2701       MemOps.push_back(Store);
2702       Offset += 8;
2703     }
2704
2705     if (!ArgXMMs.empty() && NumXMMRegs != ArgXMMs.size()) {
2706       // Now store the XMM (fp + vector) parameter registers.
2707       SmallVector<SDValue, 12> SaveXMMOps;
2708       SaveXMMOps.push_back(Chain);
2709       SaveXMMOps.push_back(ALVal);
2710       SaveXMMOps.push_back(DAG.getIntPtrConstant(
2711                              FuncInfo->getRegSaveFrameIndex(), dl));
2712       SaveXMMOps.push_back(DAG.getIntPtrConstant(
2713                              FuncInfo->getVarArgsFPOffset(), dl));
2714       SaveXMMOps.insert(SaveXMMOps.end(), LiveXMMRegs.begin(),
2715                         LiveXMMRegs.end());
2716       MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2717                                    MVT::Other, SaveXMMOps));
2718     }
2719
2720     if (!MemOps.empty())
2721       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2722   } else if (IsWin64 && IsWinEHOutlined) {
2723     // Get to the caller-allocated home save location.  Add 8 to account
2724     // for the return address.
2725     int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2726     FuncInfo->setRegSaveFrameIndex(MFI->CreateFixedObject(
2727         /*Size=*/1, /*SPOffset=*/HomeOffset + 8, /*Immutable=*/false));
2728
2729     MMI.getWinEHFuncInfo(Fn)
2730         .CatchHandlerParentFrameObjIdx[const_cast<Function *>(Fn)] =
2731         FuncInfo->getRegSaveFrameIndex();
2732
2733     // Store the second integer parameter (rdx) into rsp+16 relative to the
2734     // stack pointer at the entry of the function.
2735     SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2736                                       getPointerTy(DAG.getDataLayout()));
2737     unsigned GPR = MF.addLiveIn(X86::RDX, &X86::GR64RegClass);
2738     SDValue Val = DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64);
2739     Chain = DAG.getStore(
2740         Val.getValue(1), dl, Val, RSFIN,
2741         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(),
2742                                           FuncInfo->getRegSaveFrameIndex()),
2743         /*isVolatile=*/true, /*isNonTemporal=*/false, /*Alignment=*/0);
2744   }
2745
2746   if (isVarArg && MFI->hasMustTailInVarArgFunc()) {
2747     // Find the largest legal vector type.
2748     MVT VecVT = MVT::Other;
2749     // FIXME: Only some x86_32 calling conventions support AVX512.
2750     if (Subtarget->hasAVX512() &&
2751         (Is64Bit || (CallConv == CallingConv::X86_VectorCall ||
2752                      CallConv == CallingConv::Intel_OCL_BI)))
2753       VecVT = MVT::v16f32;
2754     else if (Subtarget->hasAVX())
2755       VecVT = MVT::v8f32;
2756     else if (Subtarget->hasSSE2())
2757       VecVT = MVT::v4f32;
2758
2759     // We forward some GPRs and some vector types.
2760     SmallVector<MVT, 2> RegParmTypes;
2761     MVT IntVT = Is64Bit ? MVT::i64 : MVT::i32;
2762     RegParmTypes.push_back(IntVT);
2763     if (VecVT != MVT::Other)
2764       RegParmTypes.push_back(VecVT);
2765
2766     // Compute the set of forwarded registers. The rest are scratch.
2767     SmallVectorImpl<ForwardedRegister> &Forwards =
2768         FuncInfo->getForwardedMustTailRegParms();
2769     CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes, CC_X86);
2770
2771     // Conservatively forward AL on x86_64, since it might be used for varargs.
2772     if (Is64Bit && !CCInfo.isAllocated(X86::AL)) {
2773       unsigned ALVReg = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2774       Forwards.push_back(ForwardedRegister(ALVReg, X86::AL, MVT::i8));
2775     }
2776
2777     // Copy all forwards from physical to virtual registers.
2778     for (ForwardedRegister &F : Forwards) {
2779       // FIXME: Can we use a less constrained schedule?
2780       SDValue RegVal = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
2781       F.VReg = MF.getRegInfo().createVirtualRegister(getRegClassFor(F.VT));
2782       Chain = DAG.getCopyToReg(Chain, dl, F.VReg, RegVal);
2783     }
2784   }
2785
2786   // Some CCs need callee pop.
2787   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2788                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2789     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2790   } else {
2791     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2792     // If this is an sret function, the return should pop the hidden pointer.
2793     if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2794         !Subtarget->getTargetTriple().isOSMSVCRT() &&
2795         argsAreStructReturn(Ins) == StackStructReturn)
2796       FuncInfo->setBytesToPopOnReturn(4);
2797   }
2798
2799   if (!Is64Bit) {
2800     // RegSaveFrameIndex is X86-64 only.
2801     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2802     if (CallConv == CallingConv::X86_FastCall ||
2803         CallConv == CallingConv::X86_ThisCall)
2804       // fastcc functions can't have varargs.
2805       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2806   }
2807
2808   FuncInfo->setArgumentStackSize(StackSize);
2809
2810   if (IsWinEHParent) {
2811     if (Is64Bit) {
2812       int UnwindHelpFI = MFI->CreateStackObject(8, 8, /*isSS=*/false);
2813       SDValue StackSlot = DAG.getFrameIndex(UnwindHelpFI, MVT::i64);
2814       MMI.getWinEHFuncInfo(MF.getFunction()).UnwindHelpFrameIdx = UnwindHelpFI;
2815       SDValue Neg2 = DAG.getConstant(-2, dl, MVT::i64);
2816       Chain = DAG.getStore(Chain, dl, Neg2, StackSlot,
2817                            MachinePointerInfo::getFixedStack(
2818                                DAG.getMachineFunction(), UnwindHelpFI),
2819                            /*isVolatile=*/true,
2820                            /*isNonTemporal=*/false, /*Alignment=*/0);
2821     } else {
2822       // Functions using Win32 EH are considered to have opaque SP adjustments
2823       // to force local variables to be addressed from the frame or base
2824       // pointers.
2825       MFI->setHasOpaqueSPAdjustment(true);
2826     }
2827   }
2828
2829   return Chain;
2830 }
2831
2832 SDValue
2833 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2834                                     SDValue StackPtr, SDValue Arg,
2835                                     SDLoc dl, SelectionDAG &DAG,
2836                                     const CCValAssign &VA,
2837                                     ISD::ArgFlagsTy Flags) const {
2838   unsigned LocMemOffset = VA.getLocMemOffset();
2839   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
2840   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
2841                        StackPtr, PtrOff);
2842   if (Flags.isByVal())
2843     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2844
2845   return DAG.getStore(
2846       Chain, dl, Arg, PtrOff,
2847       MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset),
2848       false, false, 0);
2849 }
2850
2851 /// Emit a load of return address if tail call
2852 /// optimization is performed and it is required.
2853 SDValue
2854 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2855                                            SDValue &OutRetAddr, SDValue Chain,
2856                                            bool IsTailCall, bool Is64Bit,
2857                                            int FPDiff, SDLoc dl) const {
2858   // Adjust the Return address stack slot.
2859   EVT VT = getPointerTy(DAG.getDataLayout());
2860   OutRetAddr = getReturnAddressFrameIndex(DAG);
2861
2862   // Load the "old" Return address.
2863   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2864                            false, false, false, 0);
2865   return SDValue(OutRetAddr.getNode(), 1);
2866 }
2867
2868 /// Emit a store of the return address if tail call
2869 /// optimization is performed and it is required (FPDiff!=0).
2870 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2871                                         SDValue Chain, SDValue RetAddrFrIdx,
2872                                         EVT PtrVT, unsigned SlotSize,
2873                                         int FPDiff, SDLoc dl) {
2874   // Store the return address to the appropriate stack slot.
2875   if (!FPDiff) return Chain;
2876   // Calculate the new stack slot for the return address.
2877   int NewReturnAddrFI =
2878     MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2879                                          false);
2880   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2881   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2882                        MachinePointerInfo::getFixedStack(
2883                            DAG.getMachineFunction(), NewReturnAddrFI),
2884                        false, false, 0);
2885   return Chain;
2886 }
2887
2888 /// Returns a vector_shuffle mask for an movs{s|d}, movd
2889 /// operation of specified width.
2890 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
2891                        SDValue V2) {
2892   unsigned NumElems = VT.getVectorNumElements();
2893   SmallVector<int, 8> Mask;
2894   Mask.push_back(NumElems);
2895   for (unsigned i = 1; i != NumElems; ++i)
2896     Mask.push_back(i);
2897   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
2898 }
2899
2900 SDValue
2901 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2902                              SmallVectorImpl<SDValue> &InVals) const {
2903   SelectionDAG &DAG                     = CLI.DAG;
2904   SDLoc &dl                             = CLI.DL;
2905   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2906   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
2907   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
2908   SDValue Chain                         = CLI.Chain;
2909   SDValue Callee                        = CLI.Callee;
2910   CallingConv::ID CallConv              = CLI.CallConv;
2911   bool &isTailCall                      = CLI.IsTailCall;
2912   bool isVarArg                         = CLI.IsVarArg;
2913
2914   MachineFunction &MF = DAG.getMachineFunction();
2915   bool Is64Bit        = Subtarget->is64Bit();
2916   bool IsWin64        = Subtarget->isCallingConvWin64(CallConv);
2917   StructReturnType SR = callIsStructReturn(Outs);
2918   bool IsSibcall      = false;
2919   X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2920   auto Attr = MF.getFunction()->getFnAttribute("disable-tail-calls");
2921
2922   if (Attr.getValueAsString() == "true")
2923     isTailCall = false;
2924
2925   if (Subtarget->isPICStyleGOT() &&
2926       !MF.getTarget().Options.GuaranteedTailCallOpt) {
2927     // If we are using a GOT, disable tail calls to external symbols with
2928     // default visibility. Tail calling such a symbol requires using a GOT
2929     // relocation, which forces early binding of the symbol. This breaks code
2930     // that require lazy function symbol resolution. Using musttail or
2931     // GuaranteedTailCallOpt will override this.
2932     GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2933     if (!G || (!G->getGlobal()->hasLocalLinkage() &&
2934                G->getGlobal()->hasDefaultVisibility()))
2935       isTailCall = false;
2936   }
2937
2938   bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
2939   if (IsMustTail) {
2940     // Force this to be a tail call.  The verifier rules are enough to ensure
2941     // that we can lower this successfully without moving the return address
2942     // around.
2943     isTailCall = true;
2944   } else if (isTailCall) {
2945     // Check if it's really possible to do a tail call.
2946     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2947                     isVarArg, SR != NotStructReturn,
2948                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2949                     Outs, OutVals, Ins, DAG);
2950
2951     // Sibcalls are automatically detected tailcalls which do not require
2952     // ABI changes.
2953     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2954       IsSibcall = true;
2955
2956     if (isTailCall)
2957       ++NumTailCalls;
2958   }
2959
2960   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2961          "Var args not supported with calling convention fastcc, ghc or hipe");
2962
2963   // Analyze operands of the call, assigning locations to each operand.
2964   SmallVector<CCValAssign, 16> ArgLocs;
2965   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2966
2967   // Allocate shadow area for Win64
2968   if (IsWin64)
2969     CCInfo.AllocateStack(32, 8);
2970
2971   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2972
2973   // Get a count of how many bytes are to be pushed on the stack.
2974   unsigned NumBytes = CCInfo.getNextStackOffset();
2975   if (IsSibcall)
2976     // This is a sibcall. The memory operands are available in caller's
2977     // own caller's stack.
2978     NumBytes = 0;
2979   else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
2980            IsTailCallConvention(CallConv))
2981     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2982
2983   int FPDiff = 0;
2984   if (isTailCall && !IsSibcall && !IsMustTail) {
2985     // Lower arguments at fp - stackoffset + fpdiff.
2986     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2987
2988     FPDiff = NumBytesCallerPushed - NumBytes;
2989
2990     // Set the delta of movement of the returnaddr stackslot.
2991     // But only set if delta is greater than previous delta.
2992     if (FPDiff < X86Info->getTCReturnAddrDelta())
2993       X86Info->setTCReturnAddrDelta(FPDiff);
2994   }
2995
2996   unsigned NumBytesToPush = NumBytes;
2997   unsigned NumBytesToPop = NumBytes;
2998
2999   // If we have an inalloca argument, all stack space has already been allocated
3000   // for us and be right at the top of the stack.  We don't support multiple
3001   // arguments passed in memory when using inalloca.
3002   if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
3003     NumBytesToPush = 0;
3004     if (!ArgLocs.back().isMemLoc())
3005       report_fatal_error("cannot use inalloca attribute on a register "
3006                          "parameter");
3007     if (ArgLocs.back().getLocMemOffset() != 0)
3008       report_fatal_error("any parameter with the inalloca attribute must be "
3009                          "the only memory argument");
3010   }
3011
3012   if (!IsSibcall)
3013     Chain = DAG.getCALLSEQ_START(
3014         Chain, DAG.getIntPtrConstant(NumBytesToPush, dl, true), dl);
3015
3016   SDValue RetAddrFrIdx;
3017   // Load return address for tail calls.
3018   if (isTailCall && FPDiff)
3019     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
3020                                     Is64Bit, FPDiff, dl);
3021
3022   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3023   SmallVector<SDValue, 8> MemOpChains;
3024   SDValue StackPtr;
3025
3026   // Walk the register/memloc assignments, inserting copies/loads.  In the case
3027   // of tail call optimization arguments are handle later.
3028   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3029   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3030     // Skip inalloca arguments, they have already been written.
3031     ISD::ArgFlagsTy Flags = Outs[i].Flags;
3032     if (Flags.isInAlloca())
3033       continue;
3034
3035     CCValAssign &VA = ArgLocs[i];
3036     EVT RegVT = VA.getLocVT();
3037     SDValue Arg = OutVals[i];
3038     bool isByVal = Flags.isByVal();
3039
3040     // Promote the value if needed.
3041     switch (VA.getLocInfo()) {
3042     default: llvm_unreachable("Unknown loc info!");
3043     case CCValAssign::Full: break;
3044     case CCValAssign::SExt:
3045       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
3046       break;
3047     case CCValAssign::ZExt:
3048       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
3049       break;
3050     case CCValAssign::AExt:
3051       if (Arg.getValueType().isVector() &&
3052           Arg.getValueType().getScalarType() == MVT::i1)
3053         Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
3054       else if (RegVT.is128BitVector()) {
3055         // Special case: passing MMX values in XMM registers.
3056         Arg = DAG.getBitcast(MVT::i64, Arg);
3057         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
3058         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
3059       } else
3060         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
3061       break;
3062     case CCValAssign::BCvt:
3063       Arg = DAG.getBitcast(RegVT, Arg);
3064       break;
3065     case CCValAssign::Indirect: {
3066       // Store the argument.
3067       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
3068       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
3069       Chain = DAG.getStore(
3070           Chain, dl, Arg, SpillSlot,
3071           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3072           false, false, 0);
3073       Arg = SpillSlot;
3074       break;
3075     }
3076     }
3077
3078     if (VA.isRegLoc()) {
3079       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3080       if (isVarArg && IsWin64) {
3081         // Win64 ABI requires argument XMM reg to be copied to the corresponding
3082         // shadow reg if callee is a varargs function.
3083         unsigned ShadowReg = 0;
3084         switch (VA.getLocReg()) {
3085         case X86::XMM0: ShadowReg = X86::RCX; break;
3086         case X86::XMM1: ShadowReg = X86::RDX; break;
3087         case X86::XMM2: ShadowReg = X86::R8; break;
3088         case X86::XMM3: ShadowReg = X86::R9; break;
3089         }
3090         if (ShadowReg)
3091           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
3092       }
3093     } else if (!IsSibcall && (!isTailCall || isByVal)) {
3094       assert(VA.isMemLoc());
3095       if (!StackPtr.getNode())
3096         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
3097                                       getPointerTy(DAG.getDataLayout()));
3098       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
3099                                              dl, DAG, VA, Flags));
3100     }
3101   }
3102
3103   if (!MemOpChains.empty())
3104     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
3105
3106   if (Subtarget->isPICStyleGOT()) {
3107     // ELF / PIC requires GOT in the EBX register before function calls via PLT
3108     // GOT pointer.
3109     if (!isTailCall) {
3110       RegsToPass.push_back(std::make_pair(
3111           unsigned(X86::EBX), DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(),
3112                                           getPointerTy(DAG.getDataLayout()))));
3113     } else {
3114       // If we are tail calling and generating PIC/GOT style code load the
3115       // address of the callee into ECX. The value in ecx is used as target of
3116       // the tail jump. This is done to circumvent the ebx/callee-saved problem
3117       // for tail calls on PIC/GOT architectures. Normally we would just put the
3118       // address of GOT into ebx and then call target@PLT. But for tail calls
3119       // ebx would be restored (since ebx is callee saved) before jumping to the
3120       // target@PLT.
3121
3122       // Note: The actual moving to ECX is done further down.
3123       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
3124       if (G && !G->getGlobal()->hasLocalLinkage() &&
3125           G->getGlobal()->hasDefaultVisibility())
3126         Callee = LowerGlobalAddress(Callee, DAG);
3127       else if (isa<ExternalSymbolSDNode>(Callee))
3128         Callee = LowerExternalSymbol(Callee, DAG);
3129     }
3130   }
3131
3132   if (Is64Bit && isVarArg && !IsWin64 && !IsMustTail) {
3133     // From AMD64 ABI document:
3134     // For calls that may call functions that use varargs or stdargs
3135     // (prototype-less calls or calls to functions containing ellipsis (...) in
3136     // the declaration) %al is used as hidden argument to specify the number
3137     // of SSE registers used. The contents of %al do not need to match exactly
3138     // the number of registers, but must be an ubound on the number of SSE
3139     // registers used and is in the range 0 - 8 inclusive.
3140
3141     // Count the number of XMM registers allocated.
3142     static const MCPhysReg XMMArgRegs[] = {
3143       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
3144       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
3145     };
3146     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs);
3147     assert((Subtarget->hasSSE1() || !NumXMMRegs)
3148            && "SSE registers cannot be used when SSE is disabled");
3149
3150     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
3151                                         DAG.getConstant(NumXMMRegs, dl,
3152                                                         MVT::i8)));
3153   }
3154
3155   if (isVarArg && IsMustTail) {
3156     const auto &Forwards = X86Info->getForwardedMustTailRegParms();
3157     for (const auto &F : Forwards) {
3158       SDValue Val = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
3159       RegsToPass.push_back(std::make_pair(unsigned(F.PReg), Val));
3160     }
3161   }
3162
3163   // For tail calls lower the arguments to the 'real' stack slots.  Sibcalls
3164   // don't need this because the eligibility check rejects calls that require
3165   // shuffling arguments passed in memory.
3166   if (!IsSibcall && isTailCall) {
3167     // Force all the incoming stack arguments to be loaded from the stack
3168     // before any new outgoing arguments are stored to the stack, because the
3169     // outgoing stack slots may alias the incoming argument stack slots, and
3170     // the alias isn't otherwise explicit. This is slightly more conservative
3171     // than necessary, because it means that each store effectively depends
3172     // on every argument instead of just those arguments it would clobber.
3173     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
3174
3175     SmallVector<SDValue, 8> MemOpChains2;
3176     SDValue FIN;
3177     int FI = 0;
3178     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3179       CCValAssign &VA = ArgLocs[i];
3180       if (VA.isRegLoc())
3181         continue;
3182       assert(VA.isMemLoc());
3183       SDValue Arg = OutVals[i];
3184       ISD::ArgFlagsTy Flags = Outs[i].Flags;
3185       // Skip inalloca arguments.  They don't require any work.
3186       if (Flags.isInAlloca())
3187         continue;
3188       // Create frame index.
3189       int32_t Offset = VA.getLocMemOffset()+FPDiff;
3190       uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
3191       FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3192       FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
3193
3194       if (Flags.isByVal()) {
3195         // Copy relative to framepointer.
3196         SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset(), dl);
3197         if (!StackPtr.getNode())
3198           StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
3199                                         getPointerTy(DAG.getDataLayout()));
3200         Source = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
3201                              StackPtr, Source);
3202
3203         MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
3204                                                          ArgChain,
3205                                                          Flags, DAG, dl));
3206       } else {
3207         // Store relative to framepointer.
3208         MemOpChains2.push_back(DAG.getStore(
3209             ArgChain, dl, Arg, FIN,
3210             MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3211             false, false, 0));
3212       }
3213     }
3214
3215     if (!MemOpChains2.empty())
3216       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
3217
3218     // Store the return address to the appropriate stack slot.
3219     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
3220                                      getPointerTy(DAG.getDataLayout()),
3221                                      RegInfo->getSlotSize(), FPDiff, dl);
3222   }
3223
3224   // Build a sequence of copy-to-reg nodes chained together with token chain
3225   // and flag operands which copy the outgoing args into registers.
3226   SDValue InFlag;
3227   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
3228     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
3229                              RegsToPass[i].second, InFlag);
3230     InFlag = Chain.getValue(1);
3231   }
3232
3233   if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
3234     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
3235     // In the 64-bit large code model, we have to make all calls
3236     // through a register, since the call instruction's 32-bit
3237     // pc-relative offset may not be large enough to hold the whole
3238     // address.
3239   } else if (Callee->getOpcode() == ISD::GlobalAddress) {
3240     // If the callee is a GlobalAddress node (quite common, every direct call
3241     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
3242     // it.
3243     GlobalAddressSDNode* G = cast<GlobalAddressSDNode>(Callee);
3244
3245     // We should use extra load for direct calls to dllimported functions in
3246     // non-JIT mode.
3247     const GlobalValue *GV = G->getGlobal();
3248     if (!GV->hasDLLImportStorageClass()) {
3249       unsigned char OpFlags = 0;
3250       bool ExtraLoad = false;
3251       unsigned WrapperKind = ISD::DELETED_NODE;
3252
3253       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
3254       // external symbols most go through the PLT in PIC mode.  If the symbol
3255       // has hidden or protected visibility, or if it is static or local, then
3256       // we don't need to use the PLT - we can directly call it.
3257       if (Subtarget->isTargetELF() &&
3258           DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
3259           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
3260         OpFlags = X86II::MO_PLT;
3261       } else if (Subtarget->isPICStyleStubAny() &&
3262                  !GV->isStrongDefinitionForLinker() &&
3263                  (!Subtarget->getTargetTriple().isMacOSX() ||
3264                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3265         // PC-relative references to external symbols should go through $stub,
3266         // unless we're building with the leopard linker or later, which
3267         // automatically synthesizes these stubs.
3268         OpFlags = X86II::MO_DARWIN_STUB;
3269       } else if (Subtarget->isPICStyleRIPRel() && isa<Function>(GV) &&
3270                  cast<Function>(GV)->hasFnAttribute(Attribute::NonLazyBind)) {
3271         // If the function is marked as non-lazy, generate an indirect call
3272         // which loads from the GOT directly. This avoids runtime overhead
3273         // at the cost of eager binding (and one extra byte of encoding).
3274         OpFlags = X86II::MO_GOTPCREL;
3275         WrapperKind = X86ISD::WrapperRIP;
3276         ExtraLoad = true;
3277       }
3278
3279       Callee = DAG.getTargetGlobalAddress(
3280           GV, dl, getPointerTy(DAG.getDataLayout()), G->getOffset(), OpFlags);
3281
3282       // Add a wrapper if needed.
3283       if (WrapperKind != ISD::DELETED_NODE)
3284         Callee = DAG.getNode(X86ISD::WrapperRIP, dl,
3285                              getPointerTy(DAG.getDataLayout()), Callee);
3286       // Add extra indirection if needed.
3287       if (ExtraLoad)
3288         Callee = DAG.getLoad(
3289             getPointerTy(DAG.getDataLayout()), dl, DAG.getEntryNode(), Callee,
3290             MachinePointerInfo::getGOT(DAG.getMachineFunction()), false, false,
3291             false, 0);
3292     }
3293   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3294     unsigned char OpFlags = 0;
3295
3296     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
3297     // external symbols should go through the PLT.
3298     if (Subtarget->isTargetELF() &&
3299         DAG.getTarget().getRelocationModel() == Reloc::PIC_) {
3300       OpFlags = X86II::MO_PLT;
3301     } else if (Subtarget->isPICStyleStubAny() &&
3302                (!Subtarget->getTargetTriple().isMacOSX() ||
3303                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3304       // PC-relative references to external symbols should go through $stub,
3305       // unless we're building with the leopard linker or later, which
3306       // automatically synthesizes these stubs.
3307       OpFlags = X86II::MO_DARWIN_STUB;
3308     }
3309
3310     Callee = DAG.getTargetExternalSymbol(
3311         S->getSymbol(), getPointerTy(DAG.getDataLayout()), OpFlags);
3312   } else if (Subtarget->isTarget64BitILP32() &&
3313              Callee->getValueType(0) == MVT::i32) {
3314     // Zero-extend the 32-bit Callee address into a 64-bit according to x32 ABI
3315     Callee = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, Callee);
3316   }
3317
3318   // Returns a chain & a flag for retval copy to use.
3319   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3320   SmallVector<SDValue, 8> Ops;
3321
3322   if (!IsSibcall && isTailCall) {
3323     Chain = DAG.getCALLSEQ_END(Chain,
3324                                DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3325                                DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
3326     InFlag = Chain.getValue(1);
3327   }
3328
3329   Ops.push_back(Chain);
3330   Ops.push_back(Callee);
3331
3332   if (isTailCall)
3333     Ops.push_back(DAG.getConstant(FPDiff, dl, MVT::i32));
3334
3335   // Add argument registers to the end of the list so that they are known live
3336   // into the call.
3337   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3338     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3339                                   RegsToPass[i].second.getValueType()));
3340
3341   // Add a register mask operand representing the call-preserved registers.
3342   const uint32_t *Mask = RegInfo->getCallPreservedMask(MF, CallConv);
3343   assert(Mask && "Missing call preserved mask for calling convention");
3344
3345   // If this is an invoke in a 32-bit function using an MSVC personality, assume
3346   // the function clobbers all registers. If an exception is thrown, the runtime
3347   // will not restore CSRs.
3348   // FIXME: Model this more precisely so that we can register allocate across
3349   // the normal edge and spill and fill across the exceptional edge.
3350   if (!Is64Bit && CLI.CS && CLI.CS->isInvoke()) {
3351     const Function *CallerFn = MF.getFunction();
3352     EHPersonality Pers =
3353         CallerFn->hasPersonalityFn()
3354             ? classifyEHPersonality(CallerFn->getPersonalityFn())
3355             : EHPersonality::Unknown;
3356     if (isMSVCEHPersonality(Pers))
3357       Mask = RegInfo->getNoPreservedMask();
3358   }
3359
3360   Ops.push_back(DAG.getRegisterMask(Mask));
3361
3362   if (InFlag.getNode())
3363     Ops.push_back(InFlag);
3364
3365   if (isTailCall) {
3366     // We used to do:
3367     //// If this is the first return lowered for this function, add the regs
3368     //// to the liveout set for the function.
3369     // This isn't right, although it's probably harmless on x86; liveouts
3370     // should be computed from returns not tail calls.  Consider a void
3371     // function making a tail call to a function returning int.
3372     MF.getFrameInfo()->setHasTailCall();
3373     return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
3374   }
3375
3376   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
3377   InFlag = Chain.getValue(1);
3378
3379   // Create the CALLSEQ_END node.
3380   unsigned NumBytesForCalleeToPop;
3381   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
3382                        DAG.getTarget().Options.GuaranteedTailCallOpt))
3383     NumBytesForCalleeToPop = NumBytes;    // Callee pops everything
3384   else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
3385            !Subtarget->getTargetTriple().isOSMSVCRT() &&
3386            SR == StackStructReturn)
3387     // If this is a call to a struct-return function, the callee
3388     // pops the hidden struct pointer, so we have to push it back.
3389     // This is common for Darwin/X86, Linux & Mingw32 targets.
3390     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
3391     NumBytesForCalleeToPop = 4;
3392   else
3393     NumBytesForCalleeToPop = 0;  // Callee pops nothing.
3394
3395   // Returns a flag for retval copy to use.
3396   if (!IsSibcall) {
3397     Chain = DAG.getCALLSEQ_END(Chain,
3398                                DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3399                                DAG.getIntPtrConstant(NumBytesForCalleeToPop, dl,
3400                                                      true),
3401                                InFlag, dl);
3402     InFlag = Chain.getValue(1);
3403   }
3404
3405   // Handle result values, copying them out of physregs into vregs that we
3406   // return.
3407   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3408                          Ins, dl, DAG, InVals);
3409 }
3410
3411 //===----------------------------------------------------------------------===//
3412 //                Fast Calling Convention (tail call) implementation
3413 //===----------------------------------------------------------------------===//
3414
3415 //  Like std call, callee cleans arguments, convention except that ECX is
3416 //  reserved for storing the tail called function address. Only 2 registers are
3417 //  free for argument passing (inreg). Tail call optimization is performed
3418 //  provided:
3419 //                * tailcallopt is enabled
3420 //                * caller/callee are fastcc
3421 //  On X86_64 architecture with GOT-style position independent code only local
3422 //  (within module) calls are supported at the moment.
3423 //  To keep the stack aligned according to platform abi the function
3424 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
3425 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3426 //  If a tail called function callee has more arguments than the caller the
3427 //  caller needs to make sure that there is room to move the RETADDR to. This is
3428 //  achieved by reserving an area the size of the argument delta right after the
3429 //  original RETADDR, but before the saved framepointer or the spilled registers
3430 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3431 //  stack layout:
3432 //    arg1
3433 //    arg2
3434 //    RETADDR
3435 //    [ new RETADDR
3436 //      move area ]
3437 //    (possible EBP)
3438 //    ESI
3439 //    EDI
3440 //    local1 ..
3441
3442 /// Make the stack size align e.g 16n + 12 aligned for a 16-byte align
3443 /// requirement.
3444 unsigned
3445 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3446                                                SelectionDAG& DAG) const {
3447   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3448   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
3449   unsigned StackAlignment = TFI.getStackAlignment();
3450   uint64_t AlignMask = StackAlignment - 1;
3451   int64_t Offset = StackSize;
3452   unsigned SlotSize = RegInfo->getSlotSize();
3453   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3454     // Number smaller than 12 so just add the difference.
3455     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3456   } else {
3457     // Mask out lower bits, add stackalignment once plus the 12 bytes.
3458     Offset = ((~AlignMask) & Offset) + StackAlignment +
3459       (StackAlignment-SlotSize);
3460   }
3461   return Offset;
3462 }
3463
3464 /// Return true if the given stack call argument is already available in the
3465 /// same position (relatively) of the caller's incoming argument stack.
3466 static
3467 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3468                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3469                          const X86InstrInfo *TII) {
3470   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3471   int FI = INT_MAX;
3472   if (Arg.getOpcode() == ISD::CopyFromReg) {
3473     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3474     if (!TargetRegisterInfo::isVirtualRegister(VR))
3475       return false;
3476     MachineInstr *Def = MRI->getVRegDef(VR);
3477     if (!Def)
3478       return false;
3479     if (!Flags.isByVal()) {
3480       if (!TII->isLoadFromStackSlot(Def, FI))
3481         return false;
3482     } else {
3483       unsigned Opcode = Def->getOpcode();
3484       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r ||
3485            Opcode == X86::LEA64_32r) &&
3486           Def->getOperand(1).isFI()) {
3487         FI = Def->getOperand(1).getIndex();
3488         Bytes = Flags.getByValSize();
3489       } else
3490         return false;
3491     }
3492   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3493     if (Flags.isByVal())
3494       // ByVal argument is passed in as a pointer but it's now being
3495       // dereferenced. e.g.
3496       // define @foo(%struct.X* %A) {
3497       //   tail call @bar(%struct.X* byval %A)
3498       // }
3499       return false;
3500     SDValue Ptr = Ld->getBasePtr();
3501     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3502     if (!FINode)
3503       return false;
3504     FI = FINode->getIndex();
3505   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3506     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3507     FI = FINode->getIndex();
3508     Bytes = Flags.getByValSize();
3509   } else
3510     return false;
3511
3512   assert(FI != INT_MAX);
3513   if (!MFI->isFixedObjectIndex(FI))
3514     return false;
3515   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3516 }
3517
3518 /// Check whether the call is eligible for tail call optimization. Targets
3519 /// that want to do tail call optimization should implement this function.
3520 bool
3521 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3522                                                      CallingConv::ID CalleeCC,
3523                                                      bool isVarArg,
3524                                                      bool isCalleeStructRet,
3525                                                      bool isCallerStructRet,
3526                                                      Type *RetTy,
3527                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
3528                                     const SmallVectorImpl<SDValue> &OutVals,
3529                                     const SmallVectorImpl<ISD::InputArg> &Ins,
3530                                                      SelectionDAG &DAG) const {
3531   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3532     return false;
3533
3534   // If -tailcallopt is specified, make fastcc functions tail-callable.
3535   const MachineFunction &MF = DAG.getMachineFunction();
3536   const Function *CallerF = MF.getFunction();
3537
3538   // If the function return type is x86_fp80 and the callee return type is not,
3539   // then the FP_EXTEND of the call result is not a nop. It's not safe to
3540   // perform a tailcall optimization here.
3541   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3542     return false;
3543
3544   CallingConv::ID CallerCC = CallerF->getCallingConv();
3545   bool CCMatch = CallerCC == CalleeCC;
3546   bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3547   bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3548
3549   // Win64 functions have extra shadow space for argument homing. Don't do the
3550   // sibcall if the caller and callee have mismatched expectations for this
3551   // space.
3552   if (IsCalleeWin64 != IsCallerWin64)
3553     return false;
3554
3555   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3556     if (IsTailCallConvention(CalleeCC) && CCMatch)
3557       return true;
3558     return false;
3559   }
3560
3561   // Look for obvious safe cases to perform tail call optimization that do not
3562   // require ABI changes. This is what gcc calls sibcall.
3563
3564   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3565   // emit a special epilogue.
3566   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3567   if (RegInfo->needsStackRealignment(MF))
3568     return false;
3569
3570   // Also avoid sibcall optimization if either caller or callee uses struct
3571   // return semantics.
3572   if (isCalleeStructRet || isCallerStructRet)
3573     return false;
3574
3575   // An stdcall/thiscall caller is expected to clean up its arguments; the
3576   // callee isn't going to do that.
3577   // FIXME: this is more restrictive than needed. We could produce a tailcall
3578   // when the stack adjustment matches. For example, with a thiscall that takes
3579   // only one argument.
3580   if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3581                    CallerCC == CallingConv::X86_ThisCall))
3582     return false;
3583
3584   // Do not sibcall optimize vararg calls unless all arguments are passed via
3585   // registers.
3586   if (isVarArg && !Outs.empty()) {
3587
3588     // Optimizing for varargs on Win64 is unlikely to be safe without
3589     // additional testing.
3590     if (IsCalleeWin64 || IsCallerWin64)
3591       return false;
3592
3593     SmallVector<CCValAssign, 16> ArgLocs;
3594     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3595                    *DAG.getContext());
3596
3597     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3598     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3599       if (!ArgLocs[i].isRegLoc())
3600         return false;
3601   }
3602
3603   // If the call result is in ST0 / ST1, it needs to be popped off the x87
3604   // stack.  Therefore, if it's not used by the call it is not safe to optimize
3605   // this into a sibcall.
3606   bool Unused = false;
3607   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3608     if (!Ins[i].Used) {
3609       Unused = true;
3610       break;
3611     }
3612   }
3613   if (Unused) {
3614     SmallVector<CCValAssign, 16> RVLocs;
3615     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(), RVLocs,
3616                    *DAG.getContext());
3617     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3618     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3619       CCValAssign &VA = RVLocs[i];
3620       if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
3621         return false;
3622     }
3623   }
3624
3625   // If the calling conventions do not match, then we'd better make sure the
3626   // results are returned in the same way as what the caller expects.
3627   if (!CCMatch) {
3628     SmallVector<CCValAssign, 16> RVLocs1;
3629     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
3630                     *DAG.getContext());
3631     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3632
3633     SmallVector<CCValAssign, 16> RVLocs2;
3634     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
3635                     *DAG.getContext());
3636     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3637
3638     if (RVLocs1.size() != RVLocs2.size())
3639       return false;
3640     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3641       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3642         return false;
3643       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3644         return false;
3645       if (RVLocs1[i].isRegLoc()) {
3646         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3647           return false;
3648       } else {
3649         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3650           return false;
3651       }
3652     }
3653   }
3654
3655   // If the callee takes no arguments then go on to check the results of the
3656   // call.
3657   if (!Outs.empty()) {
3658     // Check if stack adjustment is needed. For now, do not do this if any
3659     // argument is passed on the stack.
3660     SmallVector<CCValAssign, 16> ArgLocs;
3661     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3662                    *DAG.getContext());
3663
3664     // Allocate shadow area for Win64
3665     if (IsCalleeWin64)
3666       CCInfo.AllocateStack(32, 8);
3667
3668     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3669     if (CCInfo.getNextStackOffset()) {
3670       MachineFunction &MF = DAG.getMachineFunction();
3671       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3672         return false;
3673
3674       // Check if the arguments are already laid out in the right way as
3675       // the caller's fixed stack objects.
3676       MachineFrameInfo *MFI = MF.getFrameInfo();
3677       const MachineRegisterInfo *MRI = &MF.getRegInfo();
3678       const X86InstrInfo *TII = Subtarget->getInstrInfo();
3679       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3680         CCValAssign &VA = ArgLocs[i];
3681         SDValue Arg = OutVals[i];
3682         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3683         if (VA.getLocInfo() == CCValAssign::Indirect)
3684           return false;
3685         if (!VA.isRegLoc()) {
3686           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3687                                    MFI, MRI, TII))
3688             return false;
3689         }
3690       }
3691     }
3692
3693     // If the tailcall address may be in a register, then make sure it's
3694     // possible to register allocate for it. In 32-bit, the call address can
3695     // only target EAX, EDX, or ECX since the tail call must be scheduled after
3696     // callee-saved registers are restored. These happen to be the same
3697     // registers used to pass 'inreg' arguments so watch out for those.
3698     if (!Subtarget->is64Bit() &&
3699         ((!isa<GlobalAddressSDNode>(Callee) &&
3700           !isa<ExternalSymbolSDNode>(Callee)) ||
3701          DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3702       unsigned NumInRegs = 0;
3703       // In PIC we need an extra register to formulate the address computation
3704       // for the callee.
3705       unsigned MaxInRegs =
3706         (DAG.getTarget().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3707
3708       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3709         CCValAssign &VA = ArgLocs[i];
3710         if (!VA.isRegLoc())
3711           continue;
3712         unsigned Reg = VA.getLocReg();
3713         switch (Reg) {
3714         default: break;
3715         case X86::EAX: case X86::EDX: case X86::ECX:
3716           if (++NumInRegs == MaxInRegs)
3717             return false;
3718           break;
3719         }
3720       }
3721     }
3722   }
3723
3724   return true;
3725 }
3726
3727 FastISel *
3728 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3729                                   const TargetLibraryInfo *libInfo) const {
3730   return X86::createFastISel(funcInfo, libInfo);
3731 }
3732
3733 //===----------------------------------------------------------------------===//
3734 //                           Other Lowering Hooks
3735 //===----------------------------------------------------------------------===//
3736
3737 static bool MayFoldLoad(SDValue Op) {
3738   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3739 }
3740
3741 static bool MayFoldIntoStore(SDValue Op) {
3742   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3743 }
3744
3745 static bool isTargetShuffle(unsigned Opcode) {
3746   switch(Opcode) {
3747   default: return false;
3748   case X86ISD::BLENDI:
3749   case X86ISD::PSHUFB:
3750   case X86ISD::PSHUFD:
3751   case X86ISD::PSHUFHW:
3752   case X86ISD::PSHUFLW:
3753   case X86ISD::SHUFP:
3754   case X86ISD::PALIGNR:
3755   case X86ISD::MOVLHPS:
3756   case X86ISD::MOVLHPD:
3757   case X86ISD::MOVHLPS:
3758   case X86ISD::MOVLPS:
3759   case X86ISD::MOVLPD:
3760   case X86ISD::MOVSHDUP:
3761   case X86ISD::MOVSLDUP:
3762   case X86ISD::MOVDDUP:
3763   case X86ISD::MOVSS:
3764   case X86ISD::MOVSD:
3765   case X86ISD::UNPCKL:
3766   case X86ISD::UNPCKH:
3767   case X86ISD::VPERMILPI:
3768   case X86ISD::VPERM2X128:
3769   case X86ISD::VPERMI:
3770     return true;
3771   }
3772 }
3773
3774 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3775                                     SDValue V1, unsigned TargetMask,
3776                                     SelectionDAG &DAG) {
3777   switch(Opc) {
3778   default: llvm_unreachable("Unknown x86 shuffle node");
3779   case X86ISD::PSHUFD:
3780   case X86ISD::PSHUFHW:
3781   case X86ISD::PSHUFLW:
3782   case X86ISD::VPERMILPI:
3783   case X86ISD::VPERMI:
3784     return DAG.getNode(Opc, dl, VT, V1,
3785                        DAG.getConstant(TargetMask, dl, MVT::i8));
3786   }
3787 }
3788
3789 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3790                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
3791   switch(Opc) {
3792   default: llvm_unreachable("Unknown x86 shuffle node");
3793   case X86ISD::MOVLHPS:
3794   case X86ISD::MOVLHPD:
3795   case X86ISD::MOVHLPS:
3796   case X86ISD::MOVLPS:
3797   case X86ISD::MOVLPD:
3798   case X86ISD::MOVSS:
3799   case X86ISD::MOVSD:
3800   case X86ISD::UNPCKL:
3801   case X86ISD::UNPCKH:
3802     return DAG.getNode(Opc, dl, VT, V1, V2);
3803   }
3804 }
3805
3806 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3807   MachineFunction &MF = DAG.getMachineFunction();
3808   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3809   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3810   int ReturnAddrIndex = FuncInfo->getRAIndex();
3811
3812   if (ReturnAddrIndex == 0) {
3813     // Set up a frame object for the return address.
3814     unsigned SlotSize = RegInfo->getSlotSize();
3815     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3816                                                            -(int64_t)SlotSize,
3817                                                            false);
3818     FuncInfo->setRAIndex(ReturnAddrIndex);
3819   }
3820
3821   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy(DAG.getDataLayout()));
3822 }
3823
3824 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3825                                        bool hasSymbolicDisplacement) {
3826   // Offset should fit into 32 bit immediate field.
3827   if (!isInt<32>(Offset))
3828     return false;
3829
3830   // If we don't have a symbolic displacement - we don't have any extra
3831   // restrictions.
3832   if (!hasSymbolicDisplacement)
3833     return true;
3834
3835   // FIXME: Some tweaks might be needed for medium code model.
3836   if (M != CodeModel::Small && M != CodeModel::Kernel)
3837     return false;
3838
3839   // For small code model we assume that latest object is 16MB before end of 31
3840   // bits boundary. We may also accept pretty large negative constants knowing
3841   // that all objects are in the positive half of address space.
3842   if (M == CodeModel::Small && Offset < 16*1024*1024)
3843     return true;
3844
3845   // For kernel code model we know that all object resist in the negative half
3846   // of 32bits address space. We may not accept negative offsets, since they may
3847   // be just off and we may accept pretty large positive ones.
3848   if (M == CodeModel::Kernel && Offset >= 0)
3849     return true;
3850
3851   return false;
3852 }
3853
3854 /// Determines whether the callee is required to pop its own arguments.
3855 /// Callee pop is necessary to support tail calls.
3856 bool X86::isCalleePop(CallingConv::ID CallingConv,
3857                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3858   switch (CallingConv) {
3859   default:
3860     return false;
3861   case CallingConv::X86_StdCall:
3862   case CallingConv::X86_FastCall:
3863   case CallingConv::X86_ThisCall:
3864     return !is64Bit;
3865   case CallingConv::Fast:
3866   case CallingConv::GHC:
3867   case CallingConv::HiPE:
3868     if (IsVarArg)
3869       return false;
3870     return TailCallOpt;
3871   }
3872 }
3873
3874 /// \brief Return true if the condition is an unsigned comparison operation.
3875 static bool isX86CCUnsigned(unsigned X86CC) {
3876   switch (X86CC) {
3877   default: llvm_unreachable("Invalid integer condition!");
3878   case X86::COND_E:     return true;
3879   case X86::COND_G:     return false;
3880   case X86::COND_GE:    return false;
3881   case X86::COND_L:     return false;
3882   case X86::COND_LE:    return false;
3883   case X86::COND_NE:    return true;
3884   case X86::COND_B:     return true;
3885   case X86::COND_A:     return true;
3886   case X86::COND_BE:    return true;
3887   case X86::COND_AE:    return true;
3888   }
3889   llvm_unreachable("covered switch fell through?!");
3890 }
3891
3892 /// Do a one-to-one translation of a ISD::CondCode to the X86-specific
3893 /// condition code, returning the condition code and the LHS/RHS of the
3894 /// comparison to make.
3895 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, SDLoc DL, bool isFP,
3896                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3897   if (!isFP) {
3898     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3899       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3900         // X > -1   -> X == 0, jump !sign.
3901         RHS = DAG.getConstant(0, DL, RHS.getValueType());
3902         return X86::COND_NS;
3903       }
3904       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3905         // X < 0   -> X == 0, jump on sign.
3906         return X86::COND_S;
3907       }
3908       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3909         // X < 1   -> X <= 0
3910         RHS = DAG.getConstant(0, DL, RHS.getValueType());
3911         return X86::COND_LE;
3912       }
3913     }
3914
3915     switch (SetCCOpcode) {
3916     default: llvm_unreachable("Invalid integer condition!");
3917     case ISD::SETEQ:  return X86::COND_E;
3918     case ISD::SETGT:  return X86::COND_G;
3919     case ISD::SETGE:  return X86::COND_GE;
3920     case ISD::SETLT:  return X86::COND_L;
3921     case ISD::SETLE:  return X86::COND_LE;
3922     case ISD::SETNE:  return X86::COND_NE;
3923     case ISD::SETULT: return X86::COND_B;
3924     case ISD::SETUGT: return X86::COND_A;
3925     case ISD::SETULE: return X86::COND_BE;
3926     case ISD::SETUGE: return X86::COND_AE;
3927     }
3928   }
3929
3930   // First determine if it is required or is profitable to flip the operands.
3931
3932   // If LHS is a foldable load, but RHS is not, flip the condition.
3933   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3934       !ISD::isNON_EXTLoad(RHS.getNode())) {
3935     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3936     std::swap(LHS, RHS);
3937   }
3938
3939   switch (SetCCOpcode) {
3940   default: break;
3941   case ISD::SETOLT:
3942   case ISD::SETOLE:
3943   case ISD::SETUGT:
3944   case ISD::SETUGE:
3945     std::swap(LHS, RHS);
3946     break;
3947   }
3948
3949   // On a floating point condition, the flags are set as follows:
3950   // ZF  PF  CF   op
3951   //  0 | 0 | 0 | X > Y
3952   //  0 | 0 | 1 | X < Y
3953   //  1 | 0 | 0 | X == Y
3954   //  1 | 1 | 1 | unordered
3955   switch (SetCCOpcode) {
3956   default: llvm_unreachable("Condcode should be pre-legalized away");
3957   case ISD::SETUEQ:
3958   case ISD::SETEQ:   return X86::COND_E;
3959   case ISD::SETOLT:              // flipped
3960   case ISD::SETOGT:
3961   case ISD::SETGT:   return X86::COND_A;
3962   case ISD::SETOLE:              // flipped
3963   case ISD::SETOGE:
3964   case ISD::SETGE:   return X86::COND_AE;
3965   case ISD::SETUGT:              // flipped
3966   case ISD::SETULT:
3967   case ISD::SETLT:   return X86::COND_B;
3968   case ISD::SETUGE:              // flipped
3969   case ISD::SETULE:
3970   case ISD::SETLE:   return X86::COND_BE;
3971   case ISD::SETONE:
3972   case ISD::SETNE:   return X86::COND_NE;
3973   case ISD::SETUO:   return X86::COND_P;
3974   case ISD::SETO:    return X86::COND_NP;
3975   case ISD::SETOEQ:
3976   case ISD::SETUNE:  return X86::COND_INVALID;
3977   }
3978 }
3979
3980 /// Is there a floating point cmov for the specific X86 condition code?
3981 /// Current x86 isa includes the following FP cmov instructions:
3982 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3983 static bool hasFPCMov(unsigned X86CC) {
3984   switch (X86CC) {
3985   default:
3986     return false;
3987   case X86::COND_B:
3988   case X86::COND_BE:
3989   case X86::COND_E:
3990   case X86::COND_P:
3991   case X86::COND_A:
3992   case X86::COND_AE:
3993   case X86::COND_NE:
3994   case X86::COND_NP:
3995     return true;
3996   }
3997 }
3998
3999 /// Returns true if the target can instruction select the
4000 /// specified FP immediate natively. If false, the legalizer will
4001 /// materialize the FP immediate as a load from a constant pool.
4002 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
4003   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
4004     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
4005       return true;
4006   }
4007   return false;
4008 }
4009
4010 bool X86TargetLowering::shouldReduceLoadWidth(SDNode *Load,
4011                                               ISD::LoadExtType ExtTy,
4012                                               EVT NewVT) const {
4013   // "ELF Handling for Thread-Local Storage" specifies that R_X86_64_GOTTPOFF
4014   // relocation target a movq or addq instruction: don't let the load shrink.
4015   SDValue BasePtr = cast<LoadSDNode>(Load)->getBasePtr();
4016   if (BasePtr.getOpcode() == X86ISD::WrapperRIP)
4017     if (const auto *GA = dyn_cast<GlobalAddressSDNode>(BasePtr.getOperand(0)))
4018       return GA->getTargetFlags() != X86II::MO_GOTTPOFF;
4019   return true;
4020 }
4021
4022 /// \brief Returns true if it is beneficial to convert a load of a constant
4023 /// to just the constant itself.
4024 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
4025                                                           Type *Ty) const {
4026   assert(Ty->isIntegerTy());
4027
4028   unsigned BitSize = Ty->getPrimitiveSizeInBits();
4029   if (BitSize == 0 || BitSize > 64)
4030     return false;
4031   return true;
4032 }
4033
4034 bool X86TargetLowering::isExtractSubvectorCheap(EVT ResVT,
4035                                                 unsigned Index) const {
4036   if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
4037     return false;
4038
4039   return (Index == 0 || Index == ResVT.getVectorNumElements());
4040 }
4041
4042 bool X86TargetLowering::isCheapToSpeculateCttz() const {
4043   // Speculate cttz only if we can directly use TZCNT.
4044   return Subtarget->hasBMI();
4045 }
4046
4047 bool X86TargetLowering::isCheapToSpeculateCtlz() const {
4048   // Speculate ctlz only if we can directly use LZCNT.
4049   return Subtarget->hasLZCNT();
4050 }
4051
4052 /// Return true if every element in Mask, beginning
4053 /// from position Pos and ending in Pos+Size is undef.
4054 static bool isUndefInRange(ArrayRef<int> Mask, unsigned Pos, unsigned Size) {
4055   for (unsigned i = Pos, e = Pos + Size; i != e; ++i)
4056     if (0 <= Mask[i])
4057       return false;
4058   return true;
4059 }
4060
4061 /// Return true if Val is undef or if its value falls within the
4062 /// specified range (L, H].
4063 static bool isUndefOrInRange(int Val, int Low, int Hi) {
4064   return (Val < 0) || (Val >= Low && Val < Hi);
4065 }
4066
4067 /// Val is either less than zero (undef) or equal to the specified value.
4068 static bool isUndefOrEqual(int Val, int CmpVal) {
4069   return (Val < 0 || Val == CmpVal);
4070 }
4071
4072 /// Return true if every element in Mask, beginning
4073 /// from position Pos and ending in Pos+Size, falls within the specified
4074 /// sequential range (Low, Low+Size]. or is undef.
4075 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
4076                                        unsigned Pos, unsigned Size, int Low) {
4077   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
4078     if (!isUndefOrEqual(Mask[i], Low))
4079       return false;
4080   return true;
4081 }
4082
4083 /// Return true if the specified EXTRACT_SUBVECTOR operand specifies a vector
4084 /// extract that is suitable for instruction that extract 128 or 256 bit vectors
4085 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4086   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4087   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4088     return false;
4089
4090   // The index should be aligned on a vecWidth-bit boundary.
4091   uint64_t Index =
4092     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4093
4094   MVT VT = N->getSimpleValueType(0);
4095   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4096   bool Result = (Index * ElSize) % vecWidth == 0;
4097
4098   return Result;
4099 }
4100
4101 /// Return true if the specified INSERT_SUBVECTOR
4102 /// operand specifies a subvector insert that is suitable for input to
4103 /// insertion of 128 or 256-bit subvectors
4104 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4105   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4106   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4107     return false;
4108   // The index should be aligned on a vecWidth-bit boundary.
4109   uint64_t Index =
4110     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4111
4112   MVT VT = N->getSimpleValueType(0);
4113   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4114   bool Result = (Index * ElSize) % vecWidth == 0;
4115
4116   return Result;
4117 }
4118
4119 bool X86::isVINSERT128Index(SDNode *N) {
4120   return isVINSERTIndex(N, 128);
4121 }
4122
4123 bool X86::isVINSERT256Index(SDNode *N) {
4124   return isVINSERTIndex(N, 256);
4125 }
4126
4127 bool X86::isVEXTRACT128Index(SDNode *N) {
4128   return isVEXTRACTIndex(N, 128);
4129 }
4130
4131 bool X86::isVEXTRACT256Index(SDNode *N) {
4132   return isVEXTRACTIndex(N, 256);
4133 }
4134
4135 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4136   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4137   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4138     llvm_unreachable("Illegal extract subvector for VEXTRACT");
4139
4140   uint64_t Index =
4141     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4142
4143   MVT VecVT = N->getOperand(0).getSimpleValueType();
4144   MVT ElVT = VecVT.getVectorElementType();
4145
4146   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4147   return Index / NumElemsPerChunk;
4148 }
4149
4150 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4151   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4152   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4153     llvm_unreachable("Illegal insert subvector for VINSERT");
4154
4155   uint64_t Index =
4156     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4157
4158   MVT VecVT = N->getSimpleValueType(0);
4159   MVT ElVT = VecVT.getVectorElementType();
4160
4161   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4162   return Index / NumElemsPerChunk;
4163 }
4164
4165 /// Return the appropriate immediate to extract the specified
4166 /// EXTRACT_SUBVECTOR index with VEXTRACTF128 and VINSERTI128 instructions.
4167 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4168   return getExtractVEXTRACTImmediate(N, 128);
4169 }
4170
4171 /// Return the appropriate immediate to extract the specified
4172 /// EXTRACT_SUBVECTOR index with VEXTRACTF64x4 and VINSERTI64x4 instructions.
4173 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4174   return getExtractVEXTRACTImmediate(N, 256);
4175 }
4176
4177 /// Return the appropriate immediate to insert at the specified
4178 /// INSERT_SUBVECTOR index with VINSERTF128 and VINSERTI128 instructions.
4179 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4180   return getInsertVINSERTImmediate(N, 128);
4181 }
4182
4183 /// Return the appropriate immediate to insert at the specified
4184 /// INSERT_SUBVECTOR index with VINSERTF46x4 and VINSERTI64x4 instructions.
4185 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4186   return getInsertVINSERTImmediate(N, 256);
4187 }
4188
4189 /// Returns true if Elt is a constant integer zero
4190 static bool isZero(SDValue V) {
4191   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
4192   return C && C->isNullValue();
4193 }
4194
4195 /// Returns true if Elt is a constant zero or a floating point constant +0.0.
4196 bool X86::isZeroNode(SDValue Elt) {
4197   if (isZero(Elt))
4198     return true;
4199   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4200     return CFP->getValueAPF().isPosZero();
4201   return false;
4202 }
4203
4204 /// Returns a vector of specified type with all zero elements.
4205 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4206                              SelectionDAG &DAG, SDLoc dl) {
4207   assert(VT.isVector() && "Expected a vector type");
4208
4209   // Always build SSE zero vectors as <4 x i32> bitcasted
4210   // to their dest type. This ensures they get CSE'd.
4211   SDValue Vec;
4212   if (VT.is128BitVector()) {  // SSE
4213     if (Subtarget->hasSSE2()) {  // SSE2
4214       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4215       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4216     } else { // SSE1
4217       SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4218       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4219     }
4220   } else if (VT.is256BitVector()) { // AVX
4221     if (Subtarget->hasInt256()) { // AVX2
4222       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4223       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4224       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4225     } else {
4226       // 256-bit logic and arithmetic instructions in AVX are all
4227       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4228       SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4229       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4230       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
4231     }
4232   } else if (VT.is512BitVector()) { // AVX-512
4233       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4234       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4235                         Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4236       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4237   } else if (VT.getScalarType() == MVT::i1) {
4238
4239     assert((Subtarget->hasBWI() || VT.getVectorNumElements() <= 16)
4240             && "Unexpected vector type");
4241     assert((Subtarget->hasVLX() || VT.getVectorNumElements() >= 8)
4242             && "Unexpected vector type");
4243     SDValue Cst = DAG.getConstant(0, dl, MVT::i1);
4244     SmallVector<SDValue, 64> Ops(VT.getVectorNumElements(), Cst);
4245     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
4246   } else
4247     llvm_unreachable("Unexpected vector type");
4248
4249   return DAG.getBitcast(VT, Vec);
4250 }
4251
4252 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
4253                                 SelectionDAG &DAG, SDLoc dl,
4254                                 unsigned vectorWidth) {
4255   assert((vectorWidth == 128 || vectorWidth == 256) &&
4256          "Unsupported vector width");
4257   EVT VT = Vec.getValueType();
4258   EVT ElVT = VT.getVectorElementType();
4259   unsigned Factor = VT.getSizeInBits()/vectorWidth;
4260   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
4261                                   VT.getVectorNumElements()/Factor);
4262
4263   // Extract from UNDEF is UNDEF.
4264   if (Vec.getOpcode() == ISD::UNDEF)
4265     return DAG.getUNDEF(ResultVT);
4266
4267   // Extract the relevant vectorWidth bits.  Generate an EXTRACT_SUBVECTOR
4268   unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
4269
4270   // This is the index of the first element of the vectorWidth-bit chunk
4271   // we want.
4272   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / vectorWidth)
4273                                * ElemsPerChunk);
4274
4275   // If the input is a buildvector just emit a smaller one.
4276   if (Vec.getOpcode() == ISD::BUILD_VECTOR)
4277     return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
4278                        makeArrayRef(Vec->op_begin() + NormalizedIdxVal,
4279                                     ElemsPerChunk));
4280
4281   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal, dl);
4282   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec, VecIdx);
4283 }
4284
4285 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
4286 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
4287 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
4288 /// instructions or a simple subregister reference. Idx is an index in the
4289 /// 128 bits we want.  It need not be aligned to a 128-bit boundary.  That makes
4290 /// lowering EXTRACT_VECTOR_ELT operations easier.
4291 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
4292                                    SelectionDAG &DAG, SDLoc dl) {
4293   assert((Vec.getValueType().is256BitVector() ||
4294           Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
4295   return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
4296 }
4297
4298 /// Generate a DAG to grab 256-bits from a 512-bit vector.
4299 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
4300                                    SelectionDAG &DAG, SDLoc dl) {
4301   assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
4302   return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
4303 }
4304
4305 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
4306                                unsigned IdxVal, SelectionDAG &DAG,
4307                                SDLoc dl, unsigned vectorWidth) {
4308   assert((vectorWidth == 128 || vectorWidth == 256) &&
4309          "Unsupported vector width");
4310   // Inserting UNDEF is Result
4311   if (Vec.getOpcode() == ISD::UNDEF)
4312     return Result;
4313   EVT VT = Vec.getValueType();
4314   EVT ElVT = VT.getVectorElementType();
4315   EVT ResultVT = Result.getValueType();
4316
4317   // Insert the relevant vectorWidth bits.
4318   unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
4319
4320   // This is the index of the first element of the vectorWidth-bit chunk
4321   // we want.
4322   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/vectorWidth)
4323                                * ElemsPerChunk);
4324
4325   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal, dl);
4326   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec, VecIdx);
4327 }
4328
4329 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
4330 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
4331 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
4332 /// simple superregister reference.  Idx is an index in the 128 bits
4333 /// we want.  It need not be aligned to a 128-bit boundary.  That makes
4334 /// lowering INSERT_VECTOR_ELT operations easier.
4335 static SDValue Insert128BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4336                                   SelectionDAG &DAG, SDLoc dl) {
4337   assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
4338
4339   // For insertion into the zero index (low half) of a 256-bit vector, it is
4340   // more efficient to generate a blend with immediate instead of an insert*128.
4341   // We are still creating an INSERT_SUBVECTOR below with an undef node to
4342   // extend the subvector to the size of the result vector. Make sure that
4343   // we are not recursing on that node by checking for undef here.
4344   if (IdxVal == 0 && Result.getValueType().is256BitVector() &&
4345       Result.getOpcode() != ISD::UNDEF) {
4346     EVT ResultVT = Result.getValueType();
4347     SDValue ZeroIndex = DAG.getIntPtrConstant(0, dl);
4348     SDValue Undef = DAG.getUNDEF(ResultVT);
4349     SDValue Vec256 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Undef,
4350                                  Vec, ZeroIndex);
4351
4352     // The blend instruction, and therefore its mask, depend on the data type.
4353     MVT ScalarType = ResultVT.getScalarType().getSimpleVT();
4354     if (ScalarType.isFloatingPoint()) {
4355       // Choose either vblendps (float) or vblendpd (double).
4356       unsigned ScalarSize = ScalarType.getSizeInBits();
4357       assert((ScalarSize == 64 || ScalarSize == 32) && "Unknown float type");
4358       unsigned MaskVal = (ScalarSize == 64) ? 0x03 : 0x0f;
4359       SDValue Mask = DAG.getConstant(MaskVal, dl, MVT::i8);
4360       return DAG.getNode(X86ISD::BLENDI, dl, ResultVT, Result, Vec256, Mask);
4361     }
4362
4363     const X86Subtarget &Subtarget =
4364     static_cast<const X86Subtarget &>(DAG.getSubtarget());
4365
4366     // AVX2 is needed for 256-bit integer blend support.
4367     // Integers must be cast to 32-bit because there is only vpblendd;
4368     // vpblendw can't be used for this because it has a handicapped mask.
4369
4370     // If we don't have AVX2, then cast to float. Using a wrong domain blend
4371     // is still more efficient than using the wrong domain vinsertf128 that
4372     // will be created by InsertSubVector().
4373     MVT CastVT = Subtarget.hasAVX2() ? MVT::v8i32 : MVT::v8f32;
4374
4375     SDValue Mask = DAG.getConstant(0x0f, dl, MVT::i8);
4376     Vec256 = DAG.getBitcast(CastVT, Vec256);
4377     Vec256 = DAG.getNode(X86ISD::BLENDI, dl, CastVT, Result, Vec256, Mask);
4378     return DAG.getBitcast(ResultVT, Vec256);
4379   }
4380
4381   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
4382 }
4383
4384 static SDValue Insert256BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4385                                   SelectionDAG &DAG, SDLoc dl) {
4386   assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
4387   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
4388 }
4389
4390 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
4391 /// instructions. This is used because creating CONCAT_VECTOR nodes of
4392 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
4393 /// large BUILD_VECTORS.
4394 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
4395                                    unsigned NumElems, SelectionDAG &DAG,
4396                                    SDLoc dl) {
4397   SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4398   return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
4399 }
4400
4401 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
4402                                    unsigned NumElems, SelectionDAG &DAG,
4403                                    SDLoc dl) {
4404   SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4405   return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
4406 }
4407
4408 /// Returns a vector of specified type with all bits set.
4409 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4410 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4411 /// Then bitcast to their original type, ensuring they get CSE'd.
4412 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4413                              SDLoc dl) {
4414   assert(VT.isVector() && "Expected a vector type");
4415
4416   SDValue Cst = DAG.getConstant(~0U, dl, MVT::i32);
4417   SDValue Vec;
4418   if (VT.is256BitVector()) {
4419     if (HasInt256) { // AVX2
4420       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4421       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4422     } else { // AVX
4423       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4424       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4425     }
4426   } else if (VT.is128BitVector()) {
4427     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4428   } else
4429     llvm_unreachable("Unexpected vector type");
4430
4431   return DAG.getBitcast(VT, Vec);
4432 }
4433
4434 /// Returns a vector_shuffle node for an unpackl operation.
4435 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4436                           SDValue V2) {
4437   unsigned NumElems = VT.getVectorNumElements();
4438   SmallVector<int, 8> Mask;
4439   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4440     Mask.push_back(i);
4441     Mask.push_back(i + NumElems);
4442   }
4443   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4444 }
4445
4446 /// Returns a vector_shuffle node for an unpackh operation.
4447 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4448                           SDValue V2) {
4449   unsigned NumElems = VT.getVectorNumElements();
4450   SmallVector<int, 8> Mask;
4451   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4452     Mask.push_back(i + Half);
4453     Mask.push_back(i + NumElems + Half);
4454   }
4455   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4456 }
4457
4458 /// Return a vector_shuffle of the specified vector of zero or undef vector.
4459 /// This produces a shuffle where the low element of V2 is swizzled into the
4460 /// zero/undef vector, landing at element Idx.
4461 /// This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
4462 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4463                                            bool IsZero,
4464                                            const X86Subtarget *Subtarget,
4465                                            SelectionDAG &DAG) {
4466   MVT VT = V2.getSimpleValueType();
4467   SDValue V1 = IsZero
4468     ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
4469   unsigned NumElems = VT.getVectorNumElements();
4470   SmallVector<int, 16> MaskVec;
4471   for (unsigned i = 0; i != NumElems; ++i)
4472     // If this is the insertion idx, put the low elt of V2 here.
4473     MaskVec.push_back(i == Idx ? NumElems : i);
4474   return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
4475 }
4476
4477 /// Calculates the shuffle mask corresponding to the target-specific opcode.
4478 /// Returns true if the Mask could be calculated. Sets IsUnary to true if only
4479 /// uses one source. Note that this will set IsUnary for shuffles which use a
4480 /// single input multiple times, and in those cases it will
4481 /// adjust the mask to only have indices within that single input.
4482 /// FIXME: Add support for Decode*Mask functions that return SM_SentinelZero.
4483 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4484                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
4485   unsigned NumElems = VT.getVectorNumElements();
4486   SDValue ImmN;
4487
4488   IsUnary = false;
4489   bool IsFakeUnary = false;
4490   switch(N->getOpcode()) {
4491   case X86ISD::BLENDI:
4492     ImmN = N->getOperand(N->getNumOperands()-1);
4493     DecodeBLENDMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4494     break;
4495   case X86ISD::SHUFP:
4496     ImmN = N->getOperand(N->getNumOperands()-1);
4497     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4498     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4499     break;
4500   case X86ISD::UNPCKH:
4501     DecodeUNPCKHMask(VT, Mask);
4502     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4503     break;
4504   case X86ISD::UNPCKL:
4505     DecodeUNPCKLMask(VT, Mask);
4506     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4507     break;
4508   case X86ISD::MOVHLPS:
4509     DecodeMOVHLPSMask(NumElems, Mask);
4510     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4511     break;
4512   case X86ISD::MOVLHPS:
4513     DecodeMOVLHPSMask(NumElems, Mask);
4514     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4515     break;
4516   case X86ISD::PALIGNR:
4517     ImmN = N->getOperand(N->getNumOperands()-1);
4518     DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4519     break;
4520   case X86ISD::PSHUFD:
4521   case X86ISD::VPERMILPI:
4522     ImmN = N->getOperand(N->getNumOperands()-1);
4523     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4524     IsUnary = true;
4525     break;
4526   case X86ISD::PSHUFHW:
4527     ImmN = N->getOperand(N->getNumOperands()-1);
4528     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4529     IsUnary = true;
4530     break;
4531   case X86ISD::PSHUFLW:
4532     ImmN = N->getOperand(N->getNumOperands()-1);
4533     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4534     IsUnary = true;
4535     break;
4536   case X86ISD::PSHUFB: {
4537     IsUnary = true;
4538     SDValue MaskNode = N->getOperand(1);
4539     while (MaskNode->getOpcode() == ISD::BITCAST)
4540       MaskNode = MaskNode->getOperand(0);
4541
4542     if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
4543       // If we have a build-vector, then things are easy.
4544       EVT VT = MaskNode.getValueType();
4545       assert(VT.isVector() &&
4546              "Can't produce a non-vector with a build_vector!");
4547       if (!VT.isInteger())
4548         return false;
4549
4550       int NumBytesPerElement = VT.getVectorElementType().getSizeInBits() / 8;
4551
4552       SmallVector<uint64_t, 32> RawMask;
4553       for (int i = 0, e = MaskNode->getNumOperands(); i < e; ++i) {
4554         SDValue Op = MaskNode->getOperand(i);
4555         if (Op->getOpcode() == ISD::UNDEF) {
4556           RawMask.push_back((uint64_t)SM_SentinelUndef);
4557           continue;
4558         }
4559         auto *CN = dyn_cast<ConstantSDNode>(Op.getNode());
4560         if (!CN)
4561           return false;
4562         APInt MaskElement = CN->getAPIntValue();
4563
4564         // We now have to decode the element which could be any integer size and
4565         // extract each byte of it.
4566         for (int j = 0; j < NumBytesPerElement; ++j) {
4567           // Note that this is x86 and so always little endian: the low byte is
4568           // the first byte of the mask.
4569           RawMask.push_back(MaskElement.getLoBits(8).getZExtValue());
4570           MaskElement = MaskElement.lshr(8);
4571         }
4572       }
4573       DecodePSHUFBMask(RawMask, Mask);
4574       break;
4575     }
4576
4577     auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
4578     if (!MaskLoad)
4579       return false;
4580
4581     SDValue Ptr = MaskLoad->getBasePtr();
4582     if (Ptr->getOpcode() == X86ISD::Wrapper ||
4583         Ptr->getOpcode() == X86ISD::WrapperRIP)
4584       Ptr = Ptr->getOperand(0);
4585
4586     auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
4587     if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
4588       return false;
4589
4590     if (auto *C = dyn_cast<Constant>(MaskCP->getConstVal())) {
4591       DecodePSHUFBMask(C, Mask);
4592       if (Mask.empty())
4593         return false;
4594       break;
4595     }
4596
4597     return false;
4598   }
4599   case X86ISD::VPERMI:
4600     ImmN = N->getOperand(N->getNumOperands()-1);
4601     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4602     IsUnary = true;
4603     break;
4604   case X86ISD::MOVSS:
4605   case X86ISD::MOVSD:
4606     DecodeScalarMoveMask(VT, /* IsLoad */ false, Mask);
4607     break;
4608   case X86ISD::VPERM2X128:
4609     ImmN = N->getOperand(N->getNumOperands()-1);
4610     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4611     if (Mask.empty()) return false;
4612     // Mask only contains negative index if an element is zero.
4613     if (std::any_of(Mask.begin(), Mask.end(),
4614                     [](int M){ return M == SM_SentinelZero; }))
4615       return false;
4616     break;
4617   case X86ISD::MOVSLDUP:
4618     DecodeMOVSLDUPMask(VT, Mask);
4619     IsUnary = true;
4620     break;
4621   case X86ISD::MOVSHDUP:
4622     DecodeMOVSHDUPMask(VT, Mask);
4623     IsUnary = true;
4624     break;
4625   case X86ISD::MOVDDUP:
4626     DecodeMOVDDUPMask(VT, Mask);
4627     IsUnary = true;
4628     break;
4629   case X86ISD::MOVLHPD:
4630   case X86ISD::MOVLPD:
4631   case X86ISD::MOVLPS:
4632     // Not yet implemented
4633     return false;
4634   default: llvm_unreachable("unknown target shuffle node");
4635   }
4636
4637   // If we have a fake unary shuffle, the shuffle mask is spread across two
4638   // inputs that are actually the same node. Re-map the mask to always point
4639   // into the first input.
4640   if (IsFakeUnary)
4641     for (int &M : Mask)
4642       if (M >= (int)Mask.size())
4643         M -= Mask.size();
4644
4645   return true;
4646 }
4647
4648 /// Returns the scalar element that will make up the ith
4649 /// element of the result of the vector shuffle.
4650 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4651                                    unsigned Depth) {
4652   if (Depth == 6)
4653     return SDValue();  // Limit search depth.
4654
4655   SDValue V = SDValue(N, 0);
4656   EVT VT = V.getValueType();
4657   unsigned Opcode = V.getOpcode();
4658
4659   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4660   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4661     int Elt = SV->getMaskElt(Index);
4662
4663     if (Elt < 0)
4664       return DAG.getUNDEF(VT.getVectorElementType());
4665
4666     unsigned NumElems = VT.getVectorNumElements();
4667     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4668                                          : SV->getOperand(1);
4669     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4670   }
4671
4672   // Recurse into target specific vector shuffles to find scalars.
4673   if (isTargetShuffle(Opcode)) {
4674     MVT ShufVT = V.getSimpleValueType();
4675     unsigned NumElems = ShufVT.getVectorNumElements();
4676     SmallVector<int, 16> ShuffleMask;
4677     bool IsUnary;
4678
4679     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4680       return SDValue();
4681
4682     int Elt = ShuffleMask[Index];
4683     if (Elt < 0)
4684       return DAG.getUNDEF(ShufVT.getVectorElementType());
4685
4686     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4687                                          : N->getOperand(1);
4688     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4689                                Depth+1);
4690   }
4691
4692   // Actual nodes that may contain scalar elements
4693   if (Opcode == ISD::BITCAST) {
4694     V = V.getOperand(0);
4695     EVT SrcVT = V.getValueType();
4696     unsigned NumElems = VT.getVectorNumElements();
4697
4698     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4699       return SDValue();
4700   }
4701
4702   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4703     return (Index == 0) ? V.getOperand(0)
4704                         : DAG.getUNDEF(VT.getVectorElementType());
4705
4706   if (V.getOpcode() == ISD::BUILD_VECTOR)
4707     return V.getOperand(Index);
4708
4709   return SDValue();
4710 }
4711
4712 /// Custom lower build_vector of v16i8.
4713 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4714                                        unsigned NumNonZero, unsigned NumZero,
4715                                        SelectionDAG &DAG,
4716                                        const X86Subtarget* Subtarget,
4717                                        const TargetLowering &TLI) {
4718   if (NumNonZero > 8)
4719     return SDValue();
4720
4721   SDLoc dl(Op);
4722   SDValue V;
4723   bool First = true;
4724
4725   // SSE4.1 - use PINSRB to insert each byte directly.
4726   if (Subtarget->hasSSE41()) {
4727     for (unsigned i = 0; i < 16; ++i) {
4728       bool isNonZero = (NonZeros & (1 << i)) != 0;
4729       if (isNonZero) {
4730         if (First) {
4731           if (NumZero)
4732             V = getZeroVector(MVT::v16i8, Subtarget, DAG, dl);
4733           else
4734             V = DAG.getUNDEF(MVT::v16i8);
4735           First = false;
4736         }
4737         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4738                         MVT::v16i8, V, Op.getOperand(i),
4739                         DAG.getIntPtrConstant(i, dl));
4740       }
4741     }
4742
4743     return V;
4744   }
4745
4746   // Pre-SSE4.1 - merge byte pairs and insert with PINSRW.
4747   for (unsigned i = 0; i < 16; ++i) {
4748     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4749     if (ThisIsNonZero && First) {
4750       if (NumZero)
4751         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4752       else
4753         V = DAG.getUNDEF(MVT::v8i16);
4754       First = false;
4755     }
4756
4757     if ((i & 1) != 0) {
4758       SDValue ThisElt, LastElt;
4759       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4760       if (LastIsNonZero) {
4761         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4762                               MVT::i16, Op.getOperand(i-1));
4763       }
4764       if (ThisIsNonZero) {
4765         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4766         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4767                               ThisElt, DAG.getConstant(8, dl, MVT::i8));
4768         if (LastIsNonZero)
4769           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4770       } else
4771         ThisElt = LastElt;
4772
4773       if (ThisElt.getNode())
4774         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4775                         DAG.getIntPtrConstant(i/2, dl));
4776     }
4777   }
4778
4779   return DAG.getBitcast(MVT::v16i8, V);
4780 }
4781
4782 /// Custom lower build_vector of v8i16.
4783 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4784                                      unsigned NumNonZero, unsigned NumZero,
4785                                      SelectionDAG &DAG,
4786                                      const X86Subtarget* Subtarget,
4787                                      const TargetLowering &TLI) {
4788   if (NumNonZero > 4)
4789     return SDValue();
4790
4791   SDLoc dl(Op);
4792   SDValue V;
4793   bool First = true;
4794   for (unsigned i = 0; i < 8; ++i) {
4795     bool isNonZero = (NonZeros & (1 << i)) != 0;
4796     if (isNonZero) {
4797       if (First) {
4798         if (NumZero)
4799           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4800         else
4801           V = DAG.getUNDEF(MVT::v8i16);
4802         First = false;
4803       }
4804       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4805                       MVT::v8i16, V, Op.getOperand(i),
4806                       DAG.getIntPtrConstant(i, dl));
4807     }
4808   }
4809
4810   return V;
4811 }
4812
4813 /// Custom lower build_vector of v4i32 or v4f32.
4814 static SDValue LowerBuildVectorv4x32(SDValue Op, SelectionDAG &DAG,
4815                                      const X86Subtarget *Subtarget,
4816                                      const TargetLowering &TLI) {
4817   // Find all zeroable elements.
4818   std::bitset<4> Zeroable;
4819   for (int i=0; i < 4; ++i) {
4820     SDValue Elt = Op->getOperand(i);
4821     Zeroable[i] = (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt));
4822   }
4823   assert(Zeroable.size() - Zeroable.count() > 1 &&
4824          "We expect at least two non-zero elements!");
4825
4826   // We only know how to deal with build_vector nodes where elements are either
4827   // zeroable or extract_vector_elt with constant index.
4828   SDValue FirstNonZero;
4829   unsigned FirstNonZeroIdx;
4830   for (unsigned i=0; i < 4; ++i) {
4831     if (Zeroable[i])
4832       continue;
4833     SDValue Elt = Op->getOperand(i);
4834     if (Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4835         !isa<ConstantSDNode>(Elt.getOperand(1)))
4836       return SDValue();
4837     // Make sure that this node is extracting from a 128-bit vector.
4838     MVT VT = Elt.getOperand(0).getSimpleValueType();
4839     if (!VT.is128BitVector())
4840       return SDValue();
4841     if (!FirstNonZero.getNode()) {
4842       FirstNonZero = Elt;
4843       FirstNonZeroIdx = i;
4844     }
4845   }
4846
4847   assert(FirstNonZero.getNode() && "Unexpected build vector of all zeros!");
4848   SDValue V1 = FirstNonZero.getOperand(0);
4849   MVT VT = V1.getSimpleValueType();
4850
4851   // See if this build_vector can be lowered as a blend with zero.
4852   SDValue Elt;
4853   unsigned EltMaskIdx, EltIdx;
4854   int Mask[4];
4855   for (EltIdx = 0; EltIdx < 4; ++EltIdx) {
4856     if (Zeroable[EltIdx]) {
4857       // The zero vector will be on the right hand side.
4858       Mask[EltIdx] = EltIdx+4;
4859       continue;
4860     }
4861
4862     Elt = Op->getOperand(EltIdx);
4863     // By construction, Elt is a EXTRACT_VECTOR_ELT with constant index.
4864     EltMaskIdx = cast<ConstantSDNode>(Elt.getOperand(1))->getZExtValue();
4865     if (Elt.getOperand(0) != V1 || EltMaskIdx != EltIdx)
4866       break;
4867     Mask[EltIdx] = EltIdx;
4868   }
4869
4870   if (EltIdx == 4) {
4871     // Let the shuffle legalizer deal with blend operations.
4872     SDValue VZero = getZeroVector(VT, Subtarget, DAG, SDLoc(Op));
4873     if (V1.getSimpleValueType() != VT)
4874       V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), VT, V1);
4875     return DAG.getVectorShuffle(VT, SDLoc(V1), V1, VZero, &Mask[0]);
4876   }
4877
4878   // See if we can lower this build_vector to a INSERTPS.
4879   if (!Subtarget->hasSSE41())
4880     return SDValue();
4881
4882   SDValue V2 = Elt.getOperand(0);
4883   if (Elt == FirstNonZero && EltIdx == FirstNonZeroIdx)
4884     V1 = SDValue();
4885
4886   bool CanFold = true;
4887   for (unsigned i = EltIdx + 1; i < 4 && CanFold; ++i) {
4888     if (Zeroable[i])
4889       continue;
4890
4891     SDValue Current = Op->getOperand(i);
4892     SDValue SrcVector = Current->getOperand(0);
4893     if (!V1.getNode())
4894       V1 = SrcVector;
4895     CanFold = SrcVector == V1 &&
4896       cast<ConstantSDNode>(Current.getOperand(1))->getZExtValue() == i;
4897   }
4898
4899   if (!CanFold)
4900     return SDValue();
4901
4902   assert(V1.getNode() && "Expected at least two non-zero elements!");
4903   if (V1.getSimpleValueType() != MVT::v4f32)
4904     V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), MVT::v4f32, V1);
4905   if (V2.getSimpleValueType() != MVT::v4f32)
4906     V2 = DAG.getNode(ISD::BITCAST, SDLoc(V2), MVT::v4f32, V2);
4907
4908   // Ok, we can emit an INSERTPS instruction.
4909   unsigned ZMask = Zeroable.to_ulong();
4910
4911   unsigned InsertPSMask = EltMaskIdx << 6 | EltIdx << 4 | ZMask;
4912   assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
4913   SDLoc DL(Op);
4914   SDValue Result = DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
4915                                DAG.getIntPtrConstant(InsertPSMask, DL));
4916   return DAG.getBitcast(VT, Result);
4917 }
4918
4919 /// Return a vector logical shift node.
4920 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4921                          unsigned NumBits, SelectionDAG &DAG,
4922                          const TargetLowering &TLI, SDLoc dl) {
4923   assert(VT.is128BitVector() && "Unknown type for VShift");
4924   MVT ShVT = MVT::v2i64;
4925   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
4926   SrcOp = DAG.getBitcast(ShVT, SrcOp);
4927   MVT ScalarShiftTy = TLI.getScalarShiftAmountTy(DAG.getDataLayout(), VT);
4928   assert(NumBits % 8 == 0 && "Only support byte sized shifts");
4929   SDValue ShiftVal = DAG.getConstant(NumBits/8, dl, ScalarShiftTy);
4930   return DAG.getBitcast(VT, DAG.getNode(Opc, dl, ShVT, SrcOp, ShiftVal));
4931 }
4932
4933 static SDValue
4934 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
4935
4936   // Check if the scalar load can be widened into a vector load. And if
4937   // the address is "base + cst" see if the cst can be "absorbed" into
4938   // the shuffle mask.
4939   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4940     SDValue Ptr = LD->getBasePtr();
4941     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4942       return SDValue();
4943     EVT PVT = LD->getValueType(0);
4944     if (PVT != MVT::i32 && PVT != MVT::f32)
4945       return SDValue();
4946
4947     int FI = -1;
4948     int64_t Offset = 0;
4949     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4950       FI = FINode->getIndex();
4951       Offset = 0;
4952     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4953                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4954       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4955       Offset = Ptr.getConstantOperandVal(1);
4956       Ptr = Ptr.getOperand(0);
4957     } else {
4958       return SDValue();
4959     }
4960
4961     // FIXME: 256-bit vector instructions don't require a strict alignment,
4962     // improve this code to support it better.
4963     unsigned RequiredAlign = VT.getSizeInBits()/8;
4964     SDValue Chain = LD->getChain();
4965     // Make sure the stack object alignment is at least 16 or 32.
4966     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4967     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
4968       if (MFI->isFixedObjectIndex(FI)) {
4969         // Can't change the alignment. FIXME: It's possible to compute
4970         // the exact stack offset and reference FI + adjust offset instead.
4971         // If someone *really* cares about this. That's the way to implement it.
4972         return SDValue();
4973       } else {
4974         MFI->setObjectAlignment(FI, RequiredAlign);
4975       }
4976     }
4977
4978     // (Offset % 16 or 32) must be multiple of 4. Then address is then
4979     // Ptr + (Offset & ~15).
4980     if (Offset < 0)
4981       return SDValue();
4982     if ((Offset % RequiredAlign) & 3)
4983       return SDValue();
4984     int64_t StartOffset = Offset & ~int64_t(RequiredAlign - 1);
4985     if (StartOffset) {
4986       SDLoc DL(Ptr);
4987       Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
4988                         DAG.getConstant(StartOffset, DL, Ptr.getValueType()));
4989     }
4990
4991     int EltNo = (Offset - StartOffset) >> 2;
4992     unsigned NumElems = VT.getVectorNumElements();
4993
4994     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
4995     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
4996                              LD->getPointerInfo().getWithOffset(StartOffset),
4997                              false, false, false, 0);
4998
4999     SmallVector<int, 8> Mask(NumElems, EltNo);
5000
5001     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5002   }
5003
5004   return SDValue();
5005 }
5006
5007 /// Given the initializing elements 'Elts' of a vector of type 'VT', see if the
5008 /// elements can be replaced by a single large load which has the same value as
5009 /// a build_vector or insert_subvector whose loaded operands are 'Elts'.
5010 ///
5011 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5012 ///
5013 /// FIXME: we'd also like to handle the case where the last elements are zero
5014 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5015 /// There's even a handy isZeroNode for that purpose.
5016 static SDValue EltsFromConsecutiveLoads(EVT VT, ArrayRef<SDValue> Elts,
5017                                         SDLoc &DL, SelectionDAG &DAG,
5018                                         bool isAfterLegalize) {
5019   unsigned NumElems = Elts.size();
5020
5021   LoadSDNode *LDBase = nullptr;
5022   unsigned LastLoadedElt = -1U;
5023
5024   // For each element in the initializer, see if we've found a load or an undef.
5025   // If we don't find an initial load element, or later load elements are
5026   // non-consecutive, bail out.
5027   for (unsigned i = 0; i < NumElems; ++i) {
5028     SDValue Elt = Elts[i];
5029     // Look through a bitcast.
5030     if (Elt.getNode() && Elt.getOpcode() == ISD::BITCAST)
5031       Elt = Elt.getOperand(0);
5032     if (!Elt.getNode() ||
5033         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5034       return SDValue();
5035     if (!LDBase) {
5036       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5037         return SDValue();
5038       LDBase = cast<LoadSDNode>(Elt.getNode());
5039       LastLoadedElt = i;
5040       continue;
5041     }
5042     if (Elt.getOpcode() == ISD::UNDEF)
5043       continue;
5044
5045     LoadSDNode *LD = cast<LoadSDNode>(Elt);
5046     EVT LdVT = Elt.getValueType();
5047     // Each loaded element must be the correct fractional portion of the
5048     // requested vector load.
5049     if (LdVT.getSizeInBits() != VT.getSizeInBits() / NumElems)
5050       return SDValue();
5051     if (!DAG.isConsecutiveLoad(LD, LDBase, LdVT.getSizeInBits() / 8, i))
5052       return SDValue();
5053     LastLoadedElt = i;
5054   }
5055
5056   // If we have found an entire vector of loads and undefs, then return a large
5057   // load of the entire vector width starting at the base pointer.  If we found
5058   // consecutive loads for the low half, generate a vzext_load node.
5059   if (LastLoadedElt == NumElems - 1) {
5060     assert(LDBase && "Did not find base load for merging consecutive loads");
5061     EVT EltVT = LDBase->getValueType(0);
5062     // Ensure that the input vector size for the merged loads matches the
5063     // cumulative size of the input elements.
5064     if (VT.getSizeInBits() != EltVT.getSizeInBits() * NumElems)
5065       return SDValue();
5066
5067     if (isAfterLegalize &&
5068         !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
5069       return SDValue();
5070
5071     SDValue NewLd = SDValue();
5072
5073     NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5074                         LDBase->getPointerInfo(), LDBase->isVolatile(),
5075                         LDBase->isNonTemporal(), LDBase->isInvariant(),
5076                         LDBase->getAlignment());
5077
5078     if (LDBase->hasAnyUseOfValue(1)) {
5079       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5080                                      SDValue(LDBase, 1),
5081                                      SDValue(NewLd.getNode(), 1));
5082       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5083       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5084                              SDValue(NewLd.getNode(), 1));
5085     }
5086
5087     return NewLd;
5088   }
5089
5090   //TODO: The code below fires only for for loading the low v2i32 / v2f32
5091   //of a v4i32 / v4f32. It's probably worth generalizing.
5092   EVT EltVT = VT.getVectorElementType();
5093   if (NumElems == 4 && LastLoadedElt == 1 && (EltVT.getSizeInBits() == 32) &&
5094       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5095     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5096     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5097     SDValue ResNode =
5098         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
5099                                 LDBase->getPointerInfo(),
5100                                 LDBase->getAlignment(),
5101                                 false/*isVolatile*/, true/*ReadMem*/,
5102                                 false/*WriteMem*/);
5103
5104     // Make sure the newly-created LOAD is in the same position as LDBase in
5105     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5106     // update uses of LDBase's output chain to use the TokenFactor.
5107     if (LDBase->hasAnyUseOfValue(1)) {
5108       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5109                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5110       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5111       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5112                              SDValue(ResNode.getNode(), 1));
5113     }
5114
5115     return DAG.getBitcast(VT, ResNode);
5116   }
5117   return SDValue();
5118 }
5119
5120 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5121 /// to generate a splat value for the following cases:
5122 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5123 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5124 /// a scalar load, or a constant.
5125 /// The VBROADCAST node is returned when a pattern is found,
5126 /// or SDValue() otherwise.
5127 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5128                                     SelectionDAG &DAG) {
5129   // VBROADCAST requires AVX.
5130   // TODO: Splats could be generated for non-AVX CPUs using SSE
5131   // instructions, but there's less potential gain for only 128-bit vectors.
5132   if (!Subtarget->hasAVX())
5133     return SDValue();
5134
5135   MVT VT = Op.getSimpleValueType();
5136   SDLoc dl(Op);
5137
5138   assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5139          "Unsupported vector type for broadcast.");
5140
5141   SDValue Ld;
5142   bool ConstSplatVal;
5143
5144   switch (Op.getOpcode()) {
5145     default:
5146       // Unknown pattern found.
5147       return SDValue();
5148
5149     case ISD::BUILD_VECTOR: {
5150       auto *BVOp = cast<BuildVectorSDNode>(Op.getNode());
5151       BitVector UndefElements;
5152       SDValue Splat = BVOp->getSplatValue(&UndefElements);
5153
5154       // We need a splat of a single value to use broadcast, and it doesn't
5155       // make any sense if the value is only in one element of the vector.
5156       if (!Splat || (VT.getVectorNumElements() - UndefElements.count()) <= 1)
5157         return SDValue();
5158
5159       Ld = Splat;
5160       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5161                        Ld.getOpcode() == ISD::ConstantFP);
5162
5163       // Make sure that all of the users of a non-constant load are from the
5164       // BUILD_VECTOR node.
5165       if (!ConstSplatVal && !BVOp->isOnlyUserOf(Ld.getNode()))
5166         return SDValue();
5167       break;
5168     }
5169
5170     case ISD::VECTOR_SHUFFLE: {
5171       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5172
5173       // Shuffles must have a splat mask where the first element is
5174       // broadcasted.
5175       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5176         return SDValue();
5177
5178       SDValue Sc = Op.getOperand(0);
5179       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5180           Sc.getOpcode() != ISD::BUILD_VECTOR) {
5181
5182         if (!Subtarget->hasInt256())
5183           return SDValue();
5184
5185         // Use the register form of the broadcast instruction available on AVX2.
5186         if (VT.getSizeInBits() >= 256)
5187           Sc = Extract128BitVector(Sc, 0, DAG, dl);
5188         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5189       }
5190
5191       Ld = Sc.getOperand(0);
5192       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5193                        Ld.getOpcode() == ISD::ConstantFP);
5194
5195       // The scalar_to_vector node and the suspected
5196       // load node must have exactly one user.
5197       // Constants may have multiple users.
5198
5199       // AVX-512 has register version of the broadcast
5200       bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5201         Ld.getValueType().getSizeInBits() >= 32;
5202       if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5203           !hasRegVer))
5204         return SDValue();
5205       break;
5206     }
5207   }
5208
5209   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5210   bool IsGE256 = (VT.getSizeInBits() >= 256);
5211
5212   // When optimizing for size, generate up to 5 extra bytes for a broadcast
5213   // instruction to save 8 or more bytes of constant pool data.
5214   // TODO: If multiple splats are generated to load the same constant,
5215   // it may be detrimental to overall size. There needs to be a way to detect
5216   // that condition to know if this is truly a size win.
5217   bool OptForSize = DAG.getMachineFunction().getFunction()->optForSize();
5218
5219   // Handle broadcasting a single constant scalar from the constant pool
5220   // into a vector.
5221   // On Sandybridge (no AVX2), it is still better to load a constant vector
5222   // from the constant pool and not to broadcast it from a scalar.
5223   // But override that restriction when optimizing for size.
5224   // TODO: Check if splatting is recommended for other AVX-capable CPUs.
5225   if (ConstSplatVal && (Subtarget->hasAVX2() || OptForSize)) {
5226     EVT CVT = Ld.getValueType();
5227     assert(!CVT.isVector() && "Must not broadcast a vector type");
5228
5229     // Splat f32, i32, v4f64, v4i64 in all cases with AVX2.
5230     // For size optimization, also splat v2f64 and v2i64, and for size opt
5231     // with AVX2, also splat i8 and i16.
5232     // With pattern matching, the VBROADCAST node may become a VMOVDDUP.
5233     if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5234         (OptForSize && (ScalarSize == 64 || Subtarget->hasAVX2()))) {
5235       const Constant *C = nullptr;
5236       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5237         C = CI->getConstantIntValue();
5238       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5239         C = CF->getConstantFPValue();
5240
5241       assert(C && "Invalid constant type");
5242
5243       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5244       SDValue CP =
5245           DAG.getConstantPool(C, TLI.getPointerTy(DAG.getDataLayout()));
5246       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5247       Ld = DAG.getLoad(
5248           CVT, dl, DAG.getEntryNode(), CP,
5249           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
5250           false, false, Alignment);
5251
5252       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5253     }
5254   }
5255
5256   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5257
5258   // Handle AVX2 in-register broadcasts.
5259   if (!IsLoad && Subtarget->hasInt256() &&
5260       (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5261     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5262
5263   // The scalar source must be a normal load.
5264   if (!IsLoad)
5265     return SDValue();
5266
5267   if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5268       (Subtarget->hasVLX() && ScalarSize == 64))
5269     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5270
5271   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5272   // double since there is no vbroadcastsd xmm
5273   if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5274     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5275       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5276   }
5277
5278   // Unsupported broadcast.
5279   return SDValue();
5280 }
5281
5282 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
5283 /// underlying vector and index.
5284 ///
5285 /// Modifies \p ExtractedFromVec to the real vector and returns the real
5286 /// index.
5287 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
5288                                          SDValue ExtIdx) {
5289   int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5290   if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
5291     return Idx;
5292
5293   // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
5294   // lowered this:
5295   //   (extract_vector_elt (v8f32 %vreg1), Constant<6>)
5296   // to:
5297   //   (extract_vector_elt (vector_shuffle<2,u,u,u>
5298   //                           (extract_subvector (v8f32 %vreg0), Constant<4>),
5299   //                           undef)
5300   //                       Constant<0>)
5301   // In this case the vector is the extract_subvector expression and the index
5302   // is 2, as specified by the shuffle.
5303   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
5304   SDValue ShuffleVec = SVOp->getOperand(0);
5305   MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
5306   assert(ShuffleVecVT.getVectorElementType() ==
5307          ExtractedFromVec.getSimpleValueType().getVectorElementType());
5308
5309   int ShuffleIdx = SVOp->getMaskElt(Idx);
5310   if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
5311     ExtractedFromVec = ShuffleVec;
5312     return ShuffleIdx;
5313   }
5314   return Idx;
5315 }
5316
5317 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5318   MVT VT = Op.getSimpleValueType();
5319
5320   // Skip if insert_vec_elt is not supported.
5321   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5322   if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5323     return SDValue();
5324
5325   SDLoc DL(Op);
5326   unsigned NumElems = Op.getNumOperands();
5327
5328   SDValue VecIn1;
5329   SDValue VecIn2;
5330   SmallVector<unsigned, 4> InsertIndices;
5331   SmallVector<int, 8> Mask(NumElems, -1);
5332
5333   for (unsigned i = 0; i != NumElems; ++i) {
5334     unsigned Opc = Op.getOperand(i).getOpcode();
5335
5336     if (Opc == ISD::UNDEF)
5337       continue;
5338
5339     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5340       // Quit if more than 1 elements need inserting.
5341       if (InsertIndices.size() > 1)
5342         return SDValue();
5343
5344       InsertIndices.push_back(i);
5345       continue;
5346     }
5347
5348     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5349     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5350     // Quit if non-constant index.
5351     if (!isa<ConstantSDNode>(ExtIdx))
5352       return SDValue();
5353     int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5354
5355     // Quit if extracted from vector of different type.
5356     if (ExtractedFromVec.getValueType() != VT)
5357       return SDValue();
5358
5359     if (!VecIn1.getNode())
5360       VecIn1 = ExtractedFromVec;
5361     else if (VecIn1 != ExtractedFromVec) {
5362       if (!VecIn2.getNode())
5363         VecIn2 = ExtractedFromVec;
5364       else if (VecIn2 != ExtractedFromVec)
5365         // Quit if more than 2 vectors to shuffle
5366         return SDValue();
5367     }
5368
5369     if (ExtractedFromVec == VecIn1)
5370       Mask[i] = Idx;
5371     else if (ExtractedFromVec == VecIn2)
5372       Mask[i] = Idx + NumElems;
5373   }
5374
5375   if (!VecIn1.getNode())
5376     return SDValue();
5377
5378   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5379   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5380   for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5381     unsigned Idx = InsertIndices[i];
5382     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5383                      DAG.getIntPtrConstant(Idx, DL));
5384   }
5385
5386   return NV;
5387 }
5388
5389 static SDValue ConvertI1VectorToInteger(SDValue Op, SelectionDAG &DAG) {
5390   assert(ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) &&
5391          Op.getScalarValueSizeInBits() == 1 &&
5392          "Can not convert non-constant vector");
5393   uint64_t Immediate = 0;
5394   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5395     SDValue In = Op.getOperand(idx);
5396     if (In.getOpcode() != ISD::UNDEF)
5397       Immediate |= cast<ConstantSDNode>(In)->getZExtValue() << idx;
5398   }
5399   SDLoc dl(Op);
5400   MVT VT =
5401    MVT::getIntegerVT(std::max((int)Op.getValueType().getSizeInBits(), 8));
5402   return DAG.getConstant(Immediate, dl, VT);
5403 }
5404 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5405 SDValue
5406 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5407
5408   MVT VT = Op.getSimpleValueType();
5409   assert((VT.getVectorElementType() == MVT::i1) &&
5410          "Unexpected type in LowerBUILD_VECTORvXi1!");
5411
5412   SDLoc dl(Op);
5413   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5414     SDValue Cst = DAG.getTargetConstant(0, dl, MVT::i1);
5415     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5416     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5417   }
5418
5419   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5420     SDValue Cst = DAG.getTargetConstant(1, dl, MVT::i1);
5421     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5422     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5423   }
5424
5425   if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) {
5426     SDValue Imm = ConvertI1VectorToInteger(Op, DAG);
5427     if (Imm.getValueSizeInBits() == VT.getSizeInBits())
5428       return DAG.getBitcast(VT, Imm);
5429     SDValue ExtVec = DAG.getBitcast(MVT::v8i1, Imm);
5430     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, ExtVec,
5431                         DAG.getIntPtrConstant(0, dl));
5432   }
5433
5434   // Vector has one or more non-const elements
5435   uint64_t Immediate = 0;
5436   SmallVector<unsigned, 16> NonConstIdx;
5437   bool IsSplat = true;
5438   bool HasConstElts = false;
5439   int SplatIdx = -1;
5440   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5441     SDValue In = Op.getOperand(idx);
5442     if (In.getOpcode() == ISD::UNDEF)
5443       continue;
5444     if (!isa<ConstantSDNode>(In))
5445       NonConstIdx.push_back(idx);
5446     else {
5447       Immediate |= cast<ConstantSDNode>(In)->getZExtValue() << idx;
5448       HasConstElts = true;
5449     }
5450     if (SplatIdx == -1)
5451       SplatIdx = idx;
5452     else if (In != Op.getOperand(SplatIdx))
5453       IsSplat = false;
5454   }
5455
5456   // for splat use " (select i1 splat_elt, all-ones, all-zeroes)"
5457   if (IsSplat)
5458     return DAG.getNode(ISD::SELECT, dl, VT, Op.getOperand(SplatIdx),
5459                        DAG.getConstant(1, dl, VT),
5460                        DAG.getConstant(0, dl, VT));
5461
5462   // insert elements one by one
5463   SDValue DstVec;
5464   SDValue Imm;
5465   if (Immediate) {
5466     MVT ImmVT = MVT::getIntegerVT(std::max((int)VT.getSizeInBits(), 8));
5467     Imm = DAG.getConstant(Immediate, dl, ImmVT);
5468   }
5469   else if (HasConstElts)
5470     Imm = DAG.getConstant(0, dl, VT);
5471   else
5472     Imm = DAG.getUNDEF(VT);
5473   if (Imm.getValueSizeInBits() == VT.getSizeInBits())
5474     DstVec = DAG.getBitcast(VT, Imm);
5475   else {
5476     SDValue ExtVec = DAG.getBitcast(MVT::v8i1, Imm);
5477     DstVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, ExtVec,
5478                          DAG.getIntPtrConstant(0, dl));
5479   }
5480
5481   for (unsigned i = 0; i < NonConstIdx.size(); ++i) {
5482     unsigned InsertIdx = NonConstIdx[i];
5483     DstVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5484                          Op.getOperand(InsertIdx),
5485                          DAG.getIntPtrConstant(InsertIdx, dl));
5486   }
5487   return DstVec;
5488 }
5489
5490 /// \brief Return true if \p N implements a horizontal binop and return the
5491 /// operands for the horizontal binop into V0 and V1.
5492 ///
5493 /// This is a helper function of LowerToHorizontalOp().
5494 /// This function checks that the build_vector \p N in input implements a
5495 /// horizontal operation. Parameter \p Opcode defines the kind of horizontal
5496 /// operation to match.
5497 /// For example, if \p Opcode is equal to ISD::ADD, then this function
5498 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
5499 /// is equal to ISD::SUB, then this function checks if this is a horizontal
5500 /// arithmetic sub.
5501 ///
5502 /// This function only analyzes elements of \p N whose indices are
5503 /// in range [BaseIdx, LastIdx).
5504 static bool isHorizontalBinOp(const BuildVectorSDNode *N, unsigned Opcode,
5505                               SelectionDAG &DAG,
5506                               unsigned BaseIdx, unsigned LastIdx,
5507                               SDValue &V0, SDValue &V1) {
5508   EVT VT = N->getValueType(0);
5509
5510   assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
5511   assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
5512          "Invalid Vector in input!");
5513
5514   bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
5515   bool CanFold = true;
5516   unsigned ExpectedVExtractIdx = BaseIdx;
5517   unsigned NumElts = LastIdx - BaseIdx;
5518   V0 = DAG.getUNDEF(VT);
5519   V1 = DAG.getUNDEF(VT);
5520
5521   // Check if N implements a horizontal binop.
5522   for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
5523     SDValue Op = N->getOperand(i + BaseIdx);
5524
5525     // Skip UNDEFs.
5526     if (Op->getOpcode() == ISD::UNDEF) {
5527       // Update the expected vector extract index.
5528       if (i * 2 == NumElts)
5529         ExpectedVExtractIdx = BaseIdx;
5530       ExpectedVExtractIdx += 2;
5531       continue;
5532     }
5533
5534     CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
5535
5536     if (!CanFold)
5537       break;
5538
5539     SDValue Op0 = Op.getOperand(0);
5540     SDValue Op1 = Op.getOperand(1);
5541
5542     // Try to match the following pattern:
5543     // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
5544     CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5545         Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5546         Op0.getOperand(0) == Op1.getOperand(0) &&
5547         isa<ConstantSDNode>(Op0.getOperand(1)) &&
5548         isa<ConstantSDNode>(Op1.getOperand(1)));
5549     if (!CanFold)
5550       break;
5551
5552     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5553     unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
5554
5555     if (i * 2 < NumElts) {
5556       if (V0.getOpcode() == ISD::UNDEF) {
5557         V0 = Op0.getOperand(0);
5558         if (V0.getValueType() != VT)
5559           return false;
5560       }
5561     } else {
5562       if (V1.getOpcode() == ISD::UNDEF) {
5563         V1 = Op0.getOperand(0);
5564         if (V1.getValueType() != VT)
5565           return false;
5566       }
5567       if (i * 2 == NumElts)
5568         ExpectedVExtractIdx = BaseIdx;
5569     }
5570
5571     SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
5572     if (I0 == ExpectedVExtractIdx)
5573       CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
5574     else if (IsCommutable && I1 == ExpectedVExtractIdx) {
5575       // Try to match the following dag sequence:
5576       // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
5577       CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
5578     } else
5579       CanFold = false;
5580
5581     ExpectedVExtractIdx += 2;
5582   }
5583
5584   return CanFold;
5585 }
5586
5587 /// \brief Emit a sequence of two 128-bit horizontal add/sub followed by
5588 /// a concat_vector.
5589 ///
5590 /// This is a helper function of LowerToHorizontalOp().
5591 /// This function expects two 256-bit vectors called V0 and V1.
5592 /// At first, each vector is split into two separate 128-bit vectors.
5593 /// Then, the resulting 128-bit vectors are used to implement two
5594 /// horizontal binary operations.
5595 ///
5596 /// The kind of horizontal binary operation is defined by \p X86Opcode.
5597 ///
5598 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
5599 /// the two new horizontal binop.
5600 /// When Mode is set, the first horizontal binop dag node would take as input
5601 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
5602 /// horizontal binop dag node would take as input the lower 128-bit of V1
5603 /// and the upper 128-bit of V1.
5604 ///   Example:
5605 ///     HADD V0_LO, V0_HI
5606 ///     HADD V1_LO, V1_HI
5607 ///
5608 /// Otherwise, the first horizontal binop dag node takes as input the lower
5609 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
5610 /// dag node takes the upper 128-bit of V0 and the upper 128-bit of V1.
5611 ///   Example:
5612 ///     HADD V0_LO, V1_LO
5613 ///     HADD V0_HI, V1_HI
5614 ///
5615 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
5616 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
5617 /// the upper 128-bits of the result.
5618 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
5619                                      SDLoc DL, SelectionDAG &DAG,
5620                                      unsigned X86Opcode, bool Mode,
5621                                      bool isUndefLO, bool isUndefHI) {
5622   EVT VT = V0.getValueType();
5623   assert(VT.is256BitVector() && VT == V1.getValueType() &&
5624          "Invalid nodes in input!");
5625
5626   unsigned NumElts = VT.getVectorNumElements();
5627   SDValue V0_LO = Extract128BitVector(V0, 0, DAG, DL);
5628   SDValue V0_HI = Extract128BitVector(V0, NumElts/2, DAG, DL);
5629   SDValue V1_LO = Extract128BitVector(V1, 0, DAG, DL);
5630   SDValue V1_HI = Extract128BitVector(V1, NumElts/2, DAG, DL);
5631   EVT NewVT = V0_LO.getValueType();
5632
5633   SDValue LO = DAG.getUNDEF(NewVT);
5634   SDValue HI = DAG.getUNDEF(NewVT);
5635
5636   if (Mode) {
5637     // Don't emit a horizontal binop if the result is expected to be UNDEF.
5638     if (!isUndefLO && V0->getOpcode() != ISD::UNDEF)
5639       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
5640     if (!isUndefHI && V1->getOpcode() != ISD::UNDEF)
5641       HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
5642   } else {
5643     // Don't emit a horizontal binop if the result is expected to be UNDEF.
5644     if (!isUndefLO && (V0_LO->getOpcode() != ISD::UNDEF ||
5645                        V1_LO->getOpcode() != ISD::UNDEF))
5646       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
5647
5648     if (!isUndefHI && (V0_HI->getOpcode() != ISD::UNDEF ||
5649                        V1_HI->getOpcode() != ISD::UNDEF))
5650       HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
5651   }
5652
5653   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
5654 }
5655
5656 /// Try to fold a build_vector that performs an 'addsub' to an X86ISD::ADDSUB
5657 /// node.
5658 static SDValue LowerToAddSub(const BuildVectorSDNode *BV,
5659                              const X86Subtarget *Subtarget, SelectionDAG &DAG) {
5660   EVT VT = BV->getValueType(0);
5661   if ((!Subtarget->hasSSE3() || (VT != MVT::v4f32 && VT != MVT::v2f64)) &&
5662       (!Subtarget->hasAVX() || (VT != MVT::v8f32 && VT != MVT::v4f64)))
5663     return SDValue();
5664
5665   SDLoc DL(BV);
5666   unsigned NumElts = VT.getVectorNumElements();
5667   SDValue InVec0 = DAG.getUNDEF(VT);
5668   SDValue InVec1 = DAG.getUNDEF(VT);
5669
5670   assert((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v4f32 ||
5671           VT == MVT::v2f64) && "build_vector with an invalid type found!");
5672
5673   // Odd-numbered elements in the input build vector are obtained from
5674   // adding two integer/float elements.
5675   // Even-numbered elements in the input build vector are obtained from
5676   // subtracting two integer/float elements.
5677   unsigned ExpectedOpcode = ISD::FSUB;
5678   unsigned NextExpectedOpcode = ISD::FADD;
5679   bool AddFound = false;
5680   bool SubFound = false;
5681
5682   for (unsigned i = 0, e = NumElts; i != e; ++i) {
5683     SDValue Op = BV->getOperand(i);
5684
5685     // Skip 'undef' values.
5686     unsigned Opcode = Op.getOpcode();
5687     if (Opcode == ISD::UNDEF) {
5688       std::swap(ExpectedOpcode, NextExpectedOpcode);
5689       continue;
5690     }
5691
5692     // Early exit if we found an unexpected opcode.
5693     if (Opcode != ExpectedOpcode)
5694       return SDValue();
5695
5696     SDValue Op0 = Op.getOperand(0);
5697     SDValue Op1 = Op.getOperand(1);
5698
5699     // Try to match the following pattern:
5700     // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
5701     // Early exit if we cannot match that sequence.
5702     if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5703         Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5704         !isa<ConstantSDNode>(Op0.getOperand(1)) ||
5705         !isa<ConstantSDNode>(Op1.getOperand(1)) ||
5706         Op0.getOperand(1) != Op1.getOperand(1))
5707       return SDValue();
5708
5709     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5710     if (I0 != i)
5711       return SDValue();
5712
5713     // We found a valid add/sub node. Update the information accordingly.
5714     if (i & 1)
5715       AddFound = true;
5716     else
5717       SubFound = true;
5718
5719     // Update InVec0 and InVec1.
5720     if (InVec0.getOpcode() == ISD::UNDEF) {
5721       InVec0 = Op0.getOperand(0);
5722       if (InVec0.getValueType() != VT)
5723         return SDValue();
5724     }
5725     if (InVec1.getOpcode() == ISD::UNDEF) {
5726       InVec1 = Op1.getOperand(0);
5727       if (InVec1.getValueType() != VT)
5728         return SDValue();
5729     }
5730
5731     // Make sure that operands in input to each add/sub node always
5732     // come from a same pair of vectors.
5733     if (InVec0 != Op0.getOperand(0)) {
5734       if (ExpectedOpcode == ISD::FSUB)
5735         return SDValue();
5736
5737       // FADD is commutable. Try to commute the operands
5738       // and then test again.
5739       std::swap(Op0, Op1);
5740       if (InVec0 != Op0.getOperand(0))
5741         return SDValue();
5742     }
5743
5744     if (InVec1 != Op1.getOperand(0))
5745       return SDValue();
5746
5747     // Update the pair of expected opcodes.
5748     std::swap(ExpectedOpcode, NextExpectedOpcode);
5749   }
5750
5751   // Don't try to fold this build_vector into an ADDSUB if the inputs are undef.
5752   if (AddFound && SubFound && InVec0.getOpcode() != ISD::UNDEF &&
5753       InVec1.getOpcode() != ISD::UNDEF)
5754     return DAG.getNode(X86ISD::ADDSUB, DL, VT, InVec0, InVec1);
5755
5756   return SDValue();
5757 }
5758
5759 /// Lower BUILD_VECTOR to a horizontal add/sub operation if possible.
5760 static SDValue LowerToHorizontalOp(const BuildVectorSDNode *BV,
5761                                    const X86Subtarget *Subtarget,
5762                                    SelectionDAG &DAG) {
5763   EVT VT = BV->getValueType(0);
5764   unsigned NumElts = VT.getVectorNumElements();
5765   unsigned NumUndefsLO = 0;
5766   unsigned NumUndefsHI = 0;
5767   unsigned Half = NumElts/2;
5768
5769   // Count the number of UNDEF operands in the build_vector in input.
5770   for (unsigned i = 0, e = Half; i != e; ++i)
5771     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
5772       NumUndefsLO++;
5773
5774   for (unsigned i = Half, e = NumElts; i != e; ++i)
5775     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
5776       NumUndefsHI++;
5777
5778   // Early exit if this is either a build_vector of all UNDEFs or all the
5779   // operands but one are UNDEF.
5780   if (NumUndefsLO + NumUndefsHI + 1 >= NumElts)
5781     return SDValue();
5782
5783   SDLoc DL(BV);
5784   SDValue InVec0, InVec1;
5785   if ((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) {
5786     // Try to match an SSE3 float HADD/HSUB.
5787     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
5788       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
5789
5790     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
5791       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
5792   } else if ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) {
5793     // Try to match an SSSE3 integer HADD/HSUB.
5794     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
5795       return DAG.getNode(X86ISD::HADD, DL, VT, InVec0, InVec1);
5796
5797     if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
5798       return DAG.getNode(X86ISD::HSUB, DL, VT, InVec0, InVec1);
5799   }
5800
5801   if (!Subtarget->hasAVX())
5802     return SDValue();
5803
5804   if ((VT == MVT::v8f32 || VT == MVT::v4f64)) {
5805     // Try to match an AVX horizontal add/sub of packed single/double
5806     // precision floating point values from 256-bit vectors.
5807     SDValue InVec2, InVec3;
5808     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, Half, InVec0, InVec1) &&
5809         isHorizontalBinOp(BV, ISD::FADD, DAG, Half, NumElts, InVec2, InVec3) &&
5810         ((InVec0.getOpcode() == ISD::UNDEF ||
5811           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5812         ((InVec1.getOpcode() == ISD::UNDEF ||
5813           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5814       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
5815
5816     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, Half, InVec0, InVec1) &&
5817         isHorizontalBinOp(BV, ISD::FSUB, DAG, Half, NumElts, InVec2, InVec3) &&
5818         ((InVec0.getOpcode() == ISD::UNDEF ||
5819           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5820         ((InVec1.getOpcode() == ISD::UNDEF ||
5821           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5822       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
5823   } else if (VT == MVT::v8i32 || VT == MVT::v16i16) {
5824     // Try to match an AVX2 horizontal add/sub of signed integers.
5825     SDValue InVec2, InVec3;
5826     unsigned X86Opcode;
5827     bool CanFold = true;
5828
5829     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
5830         isHorizontalBinOp(BV, ISD::ADD, DAG, Half, NumElts, InVec2, InVec3) &&
5831         ((InVec0.getOpcode() == ISD::UNDEF ||
5832           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5833         ((InVec1.getOpcode() == ISD::UNDEF ||
5834           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5835       X86Opcode = X86ISD::HADD;
5836     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, Half, InVec0, InVec1) &&
5837         isHorizontalBinOp(BV, ISD::SUB, DAG, Half, NumElts, InVec2, InVec3) &&
5838         ((InVec0.getOpcode() == ISD::UNDEF ||
5839           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5840         ((InVec1.getOpcode() == ISD::UNDEF ||
5841           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5842       X86Opcode = X86ISD::HSUB;
5843     else
5844       CanFold = false;
5845
5846     if (CanFold) {
5847       // Fold this build_vector into a single horizontal add/sub.
5848       // Do this only if the target has AVX2.
5849       if (Subtarget->hasAVX2())
5850         return DAG.getNode(X86Opcode, DL, VT, InVec0, InVec1);
5851
5852       // Do not try to expand this build_vector into a pair of horizontal
5853       // add/sub if we can emit a pair of scalar add/sub.
5854       if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
5855         return SDValue();
5856
5857       // Convert this build_vector into a pair of horizontal binop followed by
5858       // a concat vector.
5859       bool isUndefLO = NumUndefsLO == Half;
5860       bool isUndefHI = NumUndefsHI == Half;
5861       return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, false,
5862                                    isUndefLO, isUndefHI);
5863     }
5864   }
5865
5866   if ((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
5867        VT == MVT::v16i16) && Subtarget->hasAVX()) {
5868     unsigned X86Opcode;
5869     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
5870       X86Opcode = X86ISD::HADD;
5871     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
5872       X86Opcode = X86ISD::HSUB;
5873     else if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
5874       X86Opcode = X86ISD::FHADD;
5875     else if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
5876       X86Opcode = X86ISD::FHSUB;
5877     else
5878       return SDValue();
5879
5880     // Don't try to expand this build_vector into a pair of horizontal add/sub
5881     // if we can simply emit a pair of scalar add/sub.
5882     if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
5883       return SDValue();
5884
5885     // Convert this build_vector into two horizontal add/sub followed by
5886     // a concat vector.
5887     bool isUndefLO = NumUndefsLO == Half;
5888     bool isUndefHI = NumUndefsHI == Half;
5889     return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
5890                                  isUndefLO, isUndefHI);
5891   }
5892
5893   return SDValue();
5894 }
5895
5896 SDValue
5897 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5898   SDLoc dl(Op);
5899
5900   MVT VT = Op.getSimpleValueType();
5901   MVT ExtVT = VT.getVectorElementType();
5902   unsigned NumElems = Op.getNumOperands();
5903
5904   // Generate vectors for predicate vectors.
5905   if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
5906     return LowerBUILD_VECTORvXi1(Op, DAG);
5907
5908   // Vectors containing all zeros can be matched by pxor and xorps later
5909   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5910     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5911     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5912     if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
5913       return Op;
5914
5915     return getZeroVector(VT, Subtarget, DAG, dl);
5916   }
5917
5918   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5919   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5920   // vpcmpeqd on 256-bit vectors.
5921   if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
5922     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
5923       return Op;
5924
5925     if (!VT.is512BitVector())
5926       return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
5927   }
5928
5929   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(Op.getNode());
5930   if (SDValue AddSub = LowerToAddSub(BV, Subtarget, DAG))
5931     return AddSub;
5932   if (SDValue HorizontalOp = LowerToHorizontalOp(BV, Subtarget, DAG))
5933     return HorizontalOp;
5934   if (SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG))
5935     return Broadcast;
5936
5937   unsigned EVTBits = ExtVT.getSizeInBits();
5938
5939   unsigned NumZero  = 0;
5940   unsigned NumNonZero = 0;
5941   unsigned NonZeros = 0;
5942   bool IsAllConstants = true;
5943   SmallSet<SDValue, 8> Values;
5944   for (unsigned i = 0; i < NumElems; ++i) {
5945     SDValue Elt = Op.getOperand(i);
5946     if (Elt.getOpcode() == ISD::UNDEF)
5947       continue;
5948     Values.insert(Elt);
5949     if (Elt.getOpcode() != ISD::Constant &&
5950         Elt.getOpcode() != ISD::ConstantFP)
5951       IsAllConstants = false;
5952     if (X86::isZeroNode(Elt))
5953       NumZero++;
5954     else {
5955       NonZeros |= (1 << i);
5956       NumNonZero++;
5957     }
5958   }
5959
5960   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
5961   if (NumNonZero == 0)
5962     return DAG.getUNDEF(VT);
5963
5964   // Special case for single non-zero, non-undef, element.
5965   if (NumNonZero == 1) {
5966     unsigned Idx = countTrailingZeros(NonZeros);
5967     SDValue Item = Op.getOperand(Idx);
5968
5969     // If this is an insertion of an i64 value on x86-32, and if the top bits of
5970     // the value are obviously zero, truncate the value to i32 and do the
5971     // insertion that way.  Only do this if the value is non-constant or if the
5972     // value is a constant being inserted into element 0.  It is cheaper to do
5973     // a constant pool load than it is to do a movd + shuffle.
5974     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5975         (!IsAllConstants || Idx == 0)) {
5976       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5977         // Handle SSE only.
5978         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5979         EVT VecVT = MVT::v4i32;
5980
5981         // Truncate the value (which may itself be a constant) to i32, and
5982         // convert it to a vector with movd (S2V+shuffle to zero extend).
5983         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5984         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5985         return DAG.getBitcast(VT, getShuffleVectorZeroOrUndef(
5986                                       Item, Idx * 2, true, Subtarget, DAG));
5987       }
5988     }
5989
5990     // If we have a constant or non-constant insertion into the low element of
5991     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5992     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
5993     // depending on what the source datatype is.
5994     if (Idx == 0) {
5995       if (NumZero == 0)
5996         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5997
5998       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5999           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
6000         if (VT.is512BitVector()) {
6001           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
6002           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
6003                              Item, DAG.getIntPtrConstant(0, dl));
6004         }
6005         assert((VT.is128BitVector() || VT.is256BitVector()) &&
6006                "Expected an SSE value type!");
6007         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6008         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
6009         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6010       }
6011
6012       // We can't directly insert an i8 or i16 into a vector, so zero extend
6013       // it to i32 first.
6014       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
6015         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
6016         if (VT.is256BitVector()) {
6017           if (Subtarget->hasAVX()) {
6018             Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v8i32, Item);
6019             Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6020           } else {
6021             // Without AVX, we need to extend to a 128-bit vector and then
6022             // insert into the 256-bit vector.
6023             Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6024             SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
6025             Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
6026           }
6027         } else {
6028           assert(VT.is128BitVector() && "Expected an SSE value type!");
6029           Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6030           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6031         }
6032         return DAG.getBitcast(VT, Item);
6033       }
6034     }
6035
6036     // Is it a vector logical left shift?
6037     if (NumElems == 2 && Idx == 1 &&
6038         X86::isZeroNode(Op.getOperand(0)) &&
6039         !X86::isZeroNode(Op.getOperand(1))) {
6040       unsigned NumBits = VT.getSizeInBits();
6041       return getVShift(true, VT,
6042                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6043                                    VT, Op.getOperand(1)),
6044                        NumBits/2, DAG, *this, dl);
6045     }
6046
6047     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
6048       return SDValue();
6049
6050     // Otherwise, if this is a vector with i32 or f32 elements, and the element
6051     // is a non-constant being inserted into an element other than the low one,
6052     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
6053     // movd/movss) to move this into the low element, then shuffle it into
6054     // place.
6055     if (EVTBits == 32) {
6056       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6057       return getShuffleVectorZeroOrUndef(Item, Idx, NumZero > 0, Subtarget, DAG);
6058     }
6059   }
6060
6061   // Splat is obviously ok. Let legalizer expand it to a shuffle.
6062   if (Values.size() == 1) {
6063     if (EVTBits == 32) {
6064       // Instead of a shuffle like this:
6065       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6066       // Check if it's possible to issue this instead.
6067       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6068       unsigned Idx = countTrailingZeros(NonZeros);
6069       SDValue Item = Op.getOperand(Idx);
6070       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6071         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6072     }
6073     return SDValue();
6074   }
6075
6076   // A vector full of immediates; various special cases are already
6077   // handled, so this is best done with a single constant-pool load.
6078   if (IsAllConstants)
6079     return SDValue();
6080
6081   // For AVX-length vectors, see if we can use a vector load to get all of the
6082   // elements, otherwise build the individual 128-bit pieces and use
6083   // shuffles to put them in place.
6084   if (VT.is256BitVector() || VT.is512BitVector()) {
6085     SmallVector<SDValue, 64> V(Op->op_begin(), Op->op_begin() + NumElems);
6086
6087     // Check for a build vector of consecutive loads.
6088     if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
6089       return LD;
6090
6091     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6092
6093     // Build both the lower and upper subvector.
6094     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6095                                 makeArrayRef(&V[0], NumElems/2));
6096     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6097                                 makeArrayRef(&V[NumElems / 2], NumElems/2));
6098
6099     // Recreate the wider vector with the lower and upper part.
6100     if (VT.is256BitVector())
6101       return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6102     return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6103   }
6104
6105   // Let legalizer expand 2-wide build_vectors.
6106   if (EVTBits == 64) {
6107     if (NumNonZero == 1) {
6108       // One half is zero or undef.
6109       unsigned Idx = countTrailingZeros(NonZeros);
6110       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6111                                  Op.getOperand(Idx));
6112       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6113     }
6114     return SDValue();
6115   }
6116
6117   // If element VT is < 32 bits, convert it to inserts into a zero vector.
6118   if (EVTBits == 8 && NumElems == 16)
6119     if (SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
6120                                         Subtarget, *this))
6121       return V;
6122
6123   if (EVTBits == 16 && NumElems == 8)
6124     if (SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
6125                                       Subtarget, *this))
6126       return V;
6127
6128   // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
6129   if (EVTBits == 32 && NumElems == 4)
6130     if (SDValue V = LowerBuildVectorv4x32(Op, DAG, Subtarget, *this))
6131       return V;
6132
6133   // If element VT is == 32 bits, turn it into a number of shuffles.
6134   SmallVector<SDValue, 8> V(NumElems);
6135   if (NumElems == 4 && NumZero > 0) {
6136     for (unsigned i = 0; i < 4; ++i) {
6137       bool isZero = !(NonZeros & (1 << i));
6138       if (isZero)
6139         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6140       else
6141         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6142     }
6143
6144     for (unsigned i = 0; i < 2; ++i) {
6145       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6146         default: break;
6147         case 0:
6148           V[i] = V[i*2];  // Must be a zero vector.
6149           break;
6150         case 1:
6151           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6152           break;
6153         case 2:
6154           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6155           break;
6156         case 3:
6157           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6158           break;
6159       }
6160     }
6161
6162     bool Reverse1 = (NonZeros & 0x3) == 2;
6163     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6164     int MaskVec[] = {
6165       Reverse1 ? 1 : 0,
6166       Reverse1 ? 0 : 1,
6167       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6168       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
6169     };
6170     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6171   }
6172
6173   if (Values.size() > 1 && VT.is128BitVector()) {
6174     // Check for a build vector of consecutive loads.
6175     for (unsigned i = 0; i < NumElems; ++i)
6176       V[i] = Op.getOperand(i);
6177
6178     // Check for elements which are consecutive loads.
6179     if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
6180       return LD;
6181
6182     // Check for a build vector from mostly shuffle plus few inserting.
6183     if (SDValue Sh = buildFromShuffleMostly(Op, DAG))
6184       return Sh;
6185
6186     // For SSE 4.1, use insertps to put the high elements into the low element.
6187     if (Subtarget->hasSSE41()) {
6188       SDValue Result;
6189       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6190         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6191       else
6192         Result = DAG.getUNDEF(VT);
6193
6194       for (unsigned i = 1; i < NumElems; ++i) {
6195         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6196         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6197                              Op.getOperand(i), DAG.getIntPtrConstant(i, dl));
6198       }
6199       return Result;
6200     }
6201
6202     // Otherwise, expand into a number of unpckl*, start by extending each of
6203     // our (non-undef) elements to the full vector width with the element in the
6204     // bottom slot of the vector (which generates no code for SSE).
6205     for (unsigned i = 0; i < NumElems; ++i) {
6206       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6207         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6208       else
6209         V[i] = DAG.getUNDEF(VT);
6210     }
6211
6212     // Next, we iteratively mix elements, e.g. for v4f32:
6213     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6214     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6215     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
6216     unsigned EltStride = NumElems >> 1;
6217     while (EltStride != 0) {
6218       for (unsigned i = 0; i < EltStride; ++i) {
6219         // If V[i+EltStride] is undef and this is the first round of mixing,
6220         // then it is safe to just drop this shuffle: V[i] is already in the
6221         // right place, the one element (since it's the first round) being
6222         // inserted as undef can be dropped.  This isn't safe for successive
6223         // rounds because they will permute elements within both vectors.
6224         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6225             EltStride == NumElems/2)
6226           continue;
6227
6228         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6229       }
6230       EltStride >>= 1;
6231     }
6232     return V[0];
6233   }
6234   return SDValue();
6235 }
6236
6237 // 256-bit AVX can use the vinsertf128 instruction
6238 // to create 256-bit vectors from two other 128-bit ones.
6239 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6240   SDLoc dl(Op);
6241   MVT ResVT = Op.getSimpleValueType();
6242
6243   assert((ResVT.is256BitVector() ||
6244           ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6245
6246   SDValue V1 = Op.getOperand(0);
6247   SDValue V2 = Op.getOperand(1);
6248   unsigned NumElems = ResVT.getVectorNumElements();
6249   if (ResVT.is256BitVector())
6250     return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6251
6252   if (Op.getNumOperands() == 4) {
6253     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6254                                 ResVT.getVectorNumElements()/2);
6255     SDValue V3 = Op.getOperand(2);
6256     SDValue V4 = Op.getOperand(3);
6257     return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6258       Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6259   }
6260   return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6261 }
6262
6263 static SDValue LowerCONCAT_VECTORSvXi1(SDValue Op,
6264                                        const X86Subtarget *Subtarget,
6265                                        SelectionDAG & DAG) {
6266   SDLoc dl(Op);
6267   MVT ResVT = Op.getSimpleValueType();
6268   unsigned NumOfOperands = Op.getNumOperands();
6269
6270   assert(isPowerOf2_32(NumOfOperands) &&
6271          "Unexpected number of operands in CONCAT_VECTORS");
6272
6273   if (NumOfOperands > 2) {
6274     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6275                                   ResVT.getVectorNumElements()/2);
6276     SmallVector<SDValue, 2> Ops;
6277     for (unsigned i = 0; i < NumOfOperands/2; i++)
6278       Ops.push_back(Op.getOperand(i));
6279     SDValue Lo = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6280     Ops.clear();
6281     for (unsigned i = NumOfOperands/2; i < NumOfOperands; i++)
6282       Ops.push_back(Op.getOperand(i));
6283     SDValue Hi = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6284     return DAG.getNode(ISD::CONCAT_VECTORS, dl, ResVT, Lo, Hi);
6285   }
6286
6287   SDValue V1 = Op.getOperand(0);
6288   SDValue V2 = Op.getOperand(1);
6289   bool IsZeroV1 = ISD::isBuildVectorAllZeros(V1.getNode());
6290   bool IsZeroV2 = ISD::isBuildVectorAllZeros(V2.getNode());
6291
6292   if (IsZeroV1 && IsZeroV2)
6293     return getZeroVector(ResVT, Subtarget, DAG, dl);
6294
6295   SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
6296   SDValue Undef = DAG.getUNDEF(ResVT);
6297   unsigned NumElems = ResVT.getVectorNumElements();
6298   SDValue ShiftBits = DAG.getConstant(NumElems/2, dl, MVT::i8);
6299
6300   V2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V2, ZeroIdx);
6301   V2 = DAG.getNode(X86ISD::VSHLI, dl, ResVT, V2, ShiftBits);
6302   if (IsZeroV1)
6303     return V2;
6304
6305   V1 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V1, ZeroIdx);
6306   // Zero the upper bits of V1
6307   V1 = DAG.getNode(X86ISD::VSHLI, dl, ResVT, V1, ShiftBits);
6308   V1 = DAG.getNode(X86ISD::VSRLI, dl, ResVT, V1, ShiftBits);
6309   if (IsZeroV2)
6310     return V1;
6311   return DAG.getNode(ISD::OR, dl, ResVT, V1, V2);
6312 }
6313
6314 static SDValue LowerCONCAT_VECTORS(SDValue Op,
6315                                    const X86Subtarget *Subtarget,
6316                                    SelectionDAG &DAG) {
6317   MVT VT = Op.getSimpleValueType();
6318   if (VT.getVectorElementType() == MVT::i1)
6319     return LowerCONCAT_VECTORSvXi1(Op, Subtarget, DAG);
6320
6321   assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6322          (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6323           Op.getNumOperands() == 4)));
6324
6325   // AVX can use the vinsertf128 instruction to create 256-bit vectors
6326   // from two other 128-bit ones.
6327
6328   // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6329   return LowerAVXCONCAT_VECTORS(Op, DAG);
6330 }
6331
6332
6333 //===----------------------------------------------------------------------===//
6334 // Vector shuffle lowering
6335 //
6336 // This is an experimental code path for lowering vector shuffles on x86. It is
6337 // designed to handle arbitrary vector shuffles and blends, gracefully
6338 // degrading performance as necessary. It works hard to recognize idiomatic
6339 // shuffles and lower them to optimal instruction patterns without leaving
6340 // a framework that allows reasonably efficient handling of all vector shuffle
6341 // patterns.
6342 //===----------------------------------------------------------------------===//
6343
6344 /// \brief Tiny helper function to identify a no-op mask.
6345 ///
6346 /// This is a somewhat boring predicate function. It checks whether the mask
6347 /// array input, which is assumed to be a single-input shuffle mask of the kind
6348 /// used by the X86 shuffle instructions (not a fully general
6349 /// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
6350 /// in-place shuffle are 'no-op's.
6351 static bool isNoopShuffleMask(ArrayRef<int> Mask) {
6352   for (int i = 0, Size = Mask.size(); i < Size; ++i)
6353     if (Mask[i] != -1 && Mask[i] != i)
6354       return false;
6355   return true;
6356 }
6357
6358 /// \brief Helper function to classify a mask as a single-input mask.
6359 ///
6360 /// This isn't a generic single-input test because in the vector shuffle
6361 /// lowering we canonicalize single inputs to be the first input operand. This
6362 /// means we can more quickly test for a single input by only checking whether
6363 /// an input from the second operand exists. We also assume that the size of
6364 /// mask corresponds to the size of the input vectors which isn't true in the
6365 /// fully general case.
6366 static bool isSingleInputShuffleMask(ArrayRef<int> Mask) {
6367   for (int M : Mask)
6368     if (M >= (int)Mask.size())
6369       return false;
6370   return true;
6371 }
6372
6373 /// \brief Test whether there are elements crossing 128-bit lanes in this
6374 /// shuffle mask.
6375 ///
6376 /// X86 divides up its shuffles into in-lane and cross-lane shuffle operations
6377 /// and we routinely test for these.
6378 static bool is128BitLaneCrossingShuffleMask(MVT VT, ArrayRef<int> Mask) {
6379   int LaneSize = 128 / VT.getScalarSizeInBits();
6380   int Size = Mask.size();
6381   for (int i = 0; i < Size; ++i)
6382     if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
6383       return true;
6384   return false;
6385 }
6386
6387 /// \brief Test whether a shuffle mask is equivalent within each 128-bit lane.
6388 ///
6389 /// This checks a shuffle mask to see if it is performing the same
6390 /// 128-bit lane-relative shuffle in each 128-bit lane. This trivially implies
6391 /// that it is also not lane-crossing. It may however involve a blend from the
6392 /// same lane of a second vector.
6393 ///
6394 /// The specific repeated shuffle mask is populated in \p RepeatedMask, as it is
6395 /// non-trivial to compute in the face of undef lanes. The representation is
6396 /// *not* suitable for use with existing 128-bit shuffles as it will contain
6397 /// entries from both V1 and V2 inputs to the wider mask.
6398 static bool
6399 is128BitLaneRepeatedShuffleMask(MVT VT, ArrayRef<int> Mask,
6400                                 SmallVectorImpl<int> &RepeatedMask) {
6401   int LaneSize = 128 / VT.getScalarSizeInBits();
6402   RepeatedMask.resize(LaneSize, -1);
6403   int Size = Mask.size();
6404   for (int i = 0; i < Size; ++i) {
6405     if (Mask[i] < 0)
6406       continue;
6407     if ((Mask[i] % Size) / LaneSize != i / LaneSize)
6408       // This entry crosses lanes, so there is no way to model this shuffle.
6409       return false;
6410
6411     // Ok, handle the in-lane shuffles by detecting if and when they repeat.
6412     if (RepeatedMask[i % LaneSize] == -1)
6413       // This is the first non-undef entry in this slot of a 128-bit lane.
6414       RepeatedMask[i % LaneSize] =
6415           Mask[i] < Size ? Mask[i] % LaneSize : Mask[i] % LaneSize + Size;
6416     else if (RepeatedMask[i % LaneSize] + (i / LaneSize) * LaneSize != Mask[i])
6417       // Found a mismatch with the repeated mask.
6418       return false;
6419   }
6420   return true;
6421 }
6422
6423 /// \brief Checks whether a shuffle mask is equivalent to an explicit list of
6424 /// arguments.
6425 ///
6426 /// This is a fast way to test a shuffle mask against a fixed pattern:
6427 ///
6428 ///   if (isShuffleEquivalent(Mask, 3, 2, {1, 0})) { ... }
6429 ///
6430 /// It returns true if the mask is exactly as wide as the argument list, and
6431 /// each element of the mask is either -1 (signifying undef) or the value given
6432 /// in the argument.
6433 static bool isShuffleEquivalent(SDValue V1, SDValue V2, ArrayRef<int> Mask,
6434                                 ArrayRef<int> ExpectedMask) {
6435   if (Mask.size() != ExpectedMask.size())
6436     return false;
6437
6438   int Size = Mask.size();
6439
6440   // If the values are build vectors, we can look through them to find
6441   // equivalent inputs that make the shuffles equivalent.
6442   auto *BV1 = dyn_cast<BuildVectorSDNode>(V1);
6443   auto *BV2 = dyn_cast<BuildVectorSDNode>(V2);
6444
6445   for (int i = 0; i < Size; ++i)
6446     if (Mask[i] != -1 && Mask[i] != ExpectedMask[i]) {
6447       auto *MaskBV = Mask[i] < Size ? BV1 : BV2;
6448       auto *ExpectedBV = ExpectedMask[i] < Size ? BV1 : BV2;
6449       if (!MaskBV || !ExpectedBV ||
6450           MaskBV->getOperand(Mask[i] % Size) !=
6451               ExpectedBV->getOperand(ExpectedMask[i] % Size))
6452         return false;
6453     }
6454
6455   return true;
6456 }
6457
6458 /// \brief Get a 4-lane 8-bit shuffle immediate for a mask.
6459 ///
6460 /// This helper function produces an 8-bit shuffle immediate corresponding to
6461 /// the ubiquitous shuffle encoding scheme used in x86 instructions for
6462 /// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
6463 /// example.
6464 ///
6465 /// NB: We rely heavily on "undef" masks preserving the input lane.
6466 static SDValue getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask, SDLoc DL,
6467                                           SelectionDAG &DAG) {
6468   assert(Mask.size() == 4 && "Only 4-lane shuffle masks");
6469   assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!");
6470   assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!");
6471   assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!");
6472   assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!");
6473
6474   unsigned Imm = 0;
6475   Imm |= (Mask[0] == -1 ? 0 : Mask[0]) << 0;
6476   Imm |= (Mask[1] == -1 ? 1 : Mask[1]) << 2;
6477   Imm |= (Mask[2] == -1 ? 2 : Mask[2]) << 4;
6478   Imm |= (Mask[3] == -1 ? 3 : Mask[3]) << 6;
6479   return DAG.getConstant(Imm, DL, MVT::i8);
6480 }
6481
6482 /// \brief Compute whether each element of a shuffle is zeroable.
6483 ///
6484 /// A "zeroable" vector shuffle element is one which can be lowered to zero.
6485 /// Either it is an undef element in the shuffle mask, the element of the input
6486 /// referenced is undef, or the element of the input referenced is known to be
6487 /// zero. Many x86 shuffles can zero lanes cheaply and we often want to handle
6488 /// as many lanes with this technique as possible to simplify the remaining
6489 /// shuffle.
6490 static SmallBitVector computeZeroableShuffleElements(ArrayRef<int> Mask,
6491                                                      SDValue V1, SDValue V2) {
6492   SmallBitVector Zeroable(Mask.size(), false);
6493
6494   while (V1.getOpcode() == ISD::BITCAST)
6495     V1 = V1->getOperand(0);
6496   while (V2.getOpcode() == ISD::BITCAST)
6497     V2 = V2->getOperand(0);
6498
6499   bool V1IsZero = ISD::isBuildVectorAllZeros(V1.getNode());
6500   bool V2IsZero = ISD::isBuildVectorAllZeros(V2.getNode());
6501
6502   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6503     int M = Mask[i];
6504     // Handle the easy cases.
6505     if (M < 0 || (M >= 0 && M < Size && V1IsZero) || (M >= Size && V2IsZero)) {
6506       Zeroable[i] = true;
6507       continue;
6508     }
6509
6510     // If this is an index into a build_vector node (which has the same number
6511     // of elements), dig out the input value and use it.
6512     SDValue V = M < Size ? V1 : V2;
6513     if (V.getOpcode() != ISD::BUILD_VECTOR || Size != (int)V.getNumOperands())
6514       continue;
6515
6516     SDValue Input = V.getOperand(M % Size);
6517     // The UNDEF opcode check really should be dead code here, but not quite
6518     // worth asserting on (it isn't invalid, just unexpected).
6519     if (Input.getOpcode() == ISD::UNDEF || X86::isZeroNode(Input))
6520       Zeroable[i] = true;
6521   }
6522
6523   return Zeroable;
6524 }
6525
6526 /// \brief Try to emit a bitmask instruction for a shuffle.
6527 ///
6528 /// This handles cases where we can model a blend exactly as a bitmask due to
6529 /// one of the inputs being zeroable.
6530 static SDValue lowerVectorShuffleAsBitMask(SDLoc DL, MVT VT, SDValue V1,
6531                                            SDValue V2, ArrayRef<int> Mask,
6532                                            SelectionDAG &DAG) {
6533   MVT EltVT = VT.getScalarType();
6534   int NumEltBits = EltVT.getSizeInBits();
6535   MVT IntEltVT = MVT::getIntegerVT(NumEltBits);
6536   SDValue Zero = DAG.getConstant(0, DL, IntEltVT);
6537   SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
6538                                     IntEltVT);
6539   if (EltVT.isFloatingPoint()) {
6540     Zero = DAG.getBitcast(EltVT, Zero);
6541     AllOnes = DAG.getBitcast(EltVT, AllOnes);
6542   }
6543   SmallVector<SDValue, 16> VMaskOps(Mask.size(), Zero);
6544   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6545   SDValue V;
6546   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6547     if (Zeroable[i])
6548       continue;
6549     if (Mask[i] % Size != i)
6550       return SDValue(); // Not a blend.
6551     if (!V)
6552       V = Mask[i] < Size ? V1 : V2;
6553     else if (V != (Mask[i] < Size ? V1 : V2))
6554       return SDValue(); // Can only let one input through the mask.
6555
6556     VMaskOps[i] = AllOnes;
6557   }
6558   if (!V)
6559     return SDValue(); // No non-zeroable elements!
6560
6561   SDValue VMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, VMaskOps);
6562   V = DAG.getNode(VT.isFloatingPoint()
6563                   ? (unsigned) X86ISD::FAND : (unsigned) ISD::AND,
6564                   DL, VT, V, VMask);
6565   return V;
6566 }
6567
6568 /// \brief Try to emit a blend instruction for a shuffle using bit math.
6569 ///
6570 /// This is used as a fallback approach when first class blend instructions are
6571 /// unavailable. Currently it is only suitable for integer vectors, but could
6572 /// be generalized for floating point vectors if desirable.
6573 static SDValue lowerVectorShuffleAsBitBlend(SDLoc DL, MVT VT, SDValue V1,
6574                                             SDValue V2, ArrayRef<int> Mask,
6575                                             SelectionDAG &DAG) {
6576   assert(VT.isInteger() && "Only supports integer vector types!");
6577   MVT EltVT = VT.getScalarType();
6578   int NumEltBits = EltVT.getSizeInBits();
6579   SDValue Zero = DAG.getConstant(0, DL, EltVT);
6580   SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
6581                                     EltVT);
6582   SmallVector<SDValue, 16> MaskOps;
6583   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6584     if (Mask[i] != -1 && Mask[i] != i && Mask[i] != i + Size)
6585       return SDValue(); // Shuffled input!
6586     MaskOps.push_back(Mask[i] < Size ? AllOnes : Zero);
6587   }
6588
6589   SDValue V1Mask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, MaskOps);
6590   V1 = DAG.getNode(ISD::AND, DL, VT, V1, V1Mask);
6591   // We have to cast V2 around.
6592   MVT MaskVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
6593   V2 = DAG.getBitcast(VT, DAG.getNode(X86ISD::ANDNP, DL, MaskVT,
6594                                       DAG.getBitcast(MaskVT, V1Mask),
6595                                       DAG.getBitcast(MaskVT, V2)));
6596   return DAG.getNode(ISD::OR, DL, VT, V1, V2);
6597 }
6598
6599 /// \brief Try to emit a blend instruction for a shuffle.
6600 ///
6601 /// This doesn't do any checks for the availability of instructions for blending
6602 /// these values. It relies on the availability of the X86ISD::BLENDI pattern to
6603 /// be matched in the backend with the type given. What it does check for is
6604 /// that the shuffle mask is in fact a blend.
6605 static SDValue lowerVectorShuffleAsBlend(SDLoc DL, MVT VT, SDValue V1,
6606                                          SDValue V2, ArrayRef<int> Mask,
6607                                          const X86Subtarget *Subtarget,
6608                                          SelectionDAG &DAG) {
6609   unsigned BlendMask = 0;
6610   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6611     if (Mask[i] >= Size) {
6612       if (Mask[i] != i + Size)
6613         return SDValue(); // Shuffled V2 input!
6614       BlendMask |= 1u << i;
6615       continue;
6616     }
6617     if (Mask[i] >= 0 && Mask[i] != i)
6618       return SDValue(); // Shuffled V1 input!
6619   }
6620   switch (VT.SimpleTy) {
6621   case MVT::v2f64:
6622   case MVT::v4f32:
6623   case MVT::v4f64:
6624   case MVT::v8f32:
6625     return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V2,
6626                        DAG.getConstant(BlendMask, DL, MVT::i8));
6627
6628   case MVT::v4i64:
6629   case MVT::v8i32:
6630     assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6631     // FALLTHROUGH
6632   case MVT::v2i64:
6633   case MVT::v4i32:
6634     // If we have AVX2 it is faster to use VPBLENDD when the shuffle fits into
6635     // that instruction.
6636     if (Subtarget->hasAVX2()) {
6637       // Scale the blend by the number of 32-bit dwords per element.
6638       int Scale =  VT.getScalarSizeInBits() / 32;
6639       BlendMask = 0;
6640       for (int i = 0, Size = Mask.size(); i < Size; ++i)
6641         if (Mask[i] >= Size)
6642           for (int j = 0; j < Scale; ++j)
6643             BlendMask |= 1u << (i * Scale + j);
6644
6645       MVT BlendVT = VT.getSizeInBits() > 128 ? MVT::v8i32 : MVT::v4i32;
6646       V1 = DAG.getBitcast(BlendVT, V1);
6647       V2 = DAG.getBitcast(BlendVT, V2);
6648       return DAG.getBitcast(
6649           VT, DAG.getNode(X86ISD::BLENDI, DL, BlendVT, V1, V2,
6650                           DAG.getConstant(BlendMask, DL, MVT::i8)));
6651     }
6652     // FALLTHROUGH
6653   case MVT::v8i16: {
6654     // For integer shuffles we need to expand the mask and cast the inputs to
6655     // v8i16s prior to blending.
6656     int Scale = 8 / VT.getVectorNumElements();
6657     BlendMask = 0;
6658     for (int i = 0, Size = Mask.size(); i < Size; ++i)
6659       if (Mask[i] >= Size)
6660         for (int j = 0; j < Scale; ++j)
6661           BlendMask |= 1u << (i * Scale + j);
6662
6663     V1 = DAG.getBitcast(MVT::v8i16, V1);
6664     V2 = DAG.getBitcast(MVT::v8i16, V2);
6665     return DAG.getBitcast(VT,
6666                           DAG.getNode(X86ISD::BLENDI, DL, MVT::v8i16, V1, V2,
6667                                       DAG.getConstant(BlendMask, DL, MVT::i8)));
6668   }
6669
6670   case MVT::v16i16: {
6671     assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6672     SmallVector<int, 8> RepeatedMask;
6673     if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
6674       // We can lower these with PBLENDW which is mirrored across 128-bit lanes.
6675       assert(RepeatedMask.size() == 8 && "Repeated mask size doesn't match!");
6676       BlendMask = 0;
6677       for (int i = 0; i < 8; ++i)
6678         if (RepeatedMask[i] >= 16)
6679           BlendMask |= 1u << i;
6680       return DAG.getNode(X86ISD::BLENDI, DL, MVT::v16i16, V1, V2,
6681                          DAG.getConstant(BlendMask, DL, MVT::i8));
6682     }
6683   }
6684     // FALLTHROUGH
6685   case MVT::v16i8:
6686   case MVT::v32i8: {
6687     assert((VT.getSizeInBits() == 128 || Subtarget->hasAVX2()) &&
6688            "256-bit byte-blends require AVX2 support!");
6689
6690     // Attempt to lower to a bitmask if we can. VPAND is faster than VPBLENDVB.
6691     if (SDValue Masked = lowerVectorShuffleAsBitMask(DL, VT, V1, V2, Mask, DAG))
6692       return Masked;
6693
6694     // Scale the blend by the number of bytes per element.
6695     int Scale = VT.getScalarSizeInBits() / 8;
6696
6697     // This form of blend is always done on bytes. Compute the byte vector
6698     // type.
6699     MVT BlendVT = MVT::getVectorVT(MVT::i8, VT.getSizeInBits() / 8);
6700
6701     // Compute the VSELECT mask. Note that VSELECT is really confusing in the
6702     // mix of LLVM's code generator and the x86 backend. We tell the code
6703     // generator that boolean values in the elements of an x86 vector register
6704     // are -1 for true and 0 for false. We then use the LLVM semantics of 'true'
6705     // mapping a select to operand #1, and 'false' mapping to operand #2. The
6706     // reality in x86 is that vector masks (pre-AVX-512) use only the high bit
6707     // of the element (the remaining are ignored) and 0 in that high bit would
6708     // mean operand #1 while 1 in the high bit would mean operand #2. So while
6709     // the LLVM model for boolean values in vector elements gets the relevant
6710     // bit set, it is set backwards and over constrained relative to x86's
6711     // actual model.
6712     SmallVector<SDValue, 32> VSELECTMask;
6713     for (int i = 0, Size = Mask.size(); i < Size; ++i)
6714       for (int j = 0; j < Scale; ++j)
6715         VSELECTMask.push_back(
6716             Mask[i] < 0 ? DAG.getUNDEF(MVT::i8)
6717                         : DAG.getConstant(Mask[i] < Size ? -1 : 0, DL,
6718                                           MVT::i8));
6719
6720     V1 = DAG.getBitcast(BlendVT, V1);
6721     V2 = DAG.getBitcast(BlendVT, V2);
6722     return DAG.getBitcast(VT, DAG.getNode(ISD::VSELECT, DL, BlendVT,
6723                                           DAG.getNode(ISD::BUILD_VECTOR, DL,
6724                                                       BlendVT, VSELECTMask),
6725                                           V1, V2));
6726   }
6727
6728   default:
6729     llvm_unreachable("Not a supported integer vector type!");
6730   }
6731 }
6732
6733 /// \brief Try to lower as a blend of elements from two inputs followed by
6734 /// a single-input permutation.
6735 ///
6736 /// This matches the pattern where we can blend elements from two inputs and
6737 /// then reduce the shuffle to a single-input permutation.
6738 static SDValue lowerVectorShuffleAsBlendAndPermute(SDLoc DL, MVT VT, SDValue V1,
6739                                                    SDValue V2,
6740                                                    ArrayRef<int> Mask,
6741                                                    SelectionDAG &DAG) {
6742   // We build up the blend mask while checking whether a blend is a viable way
6743   // to reduce the shuffle.
6744   SmallVector<int, 32> BlendMask(Mask.size(), -1);
6745   SmallVector<int, 32> PermuteMask(Mask.size(), -1);
6746
6747   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6748     if (Mask[i] < 0)
6749       continue;
6750
6751     assert(Mask[i] < Size * 2 && "Shuffle input is out of bounds.");
6752
6753     if (BlendMask[Mask[i] % Size] == -1)
6754       BlendMask[Mask[i] % Size] = Mask[i];
6755     else if (BlendMask[Mask[i] % Size] != Mask[i])
6756       return SDValue(); // Can't blend in the needed input!
6757
6758     PermuteMask[i] = Mask[i] % Size;
6759   }
6760
6761   SDValue V = DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
6762   return DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), PermuteMask);
6763 }
6764
6765 /// \brief Generic routine to decompose a shuffle and blend into indepndent
6766 /// blends and permutes.
6767 ///
6768 /// This matches the extremely common pattern for handling combined
6769 /// shuffle+blend operations on newer X86 ISAs where we have very fast blend
6770 /// operations. It will try to pick the best arrangement of shuffles and
6771 /// blends.
6772 static SDValue lowerVectorShuffleAsDecomposedShuffleBlend(SDLoc DL, MVT VT,
6773                                                           SDValue V1,
6774                                                           SDValue V2,
6775                                                           ArrayRef<int> Mask,
6776                                                           SelectionDAG &DAG) {
6777   // Shuffle the input elements into the desired positions in V1 and V2 and
6778   // blend them together.
6779   SmallVector<int, 32> V1Mask(Mask.size(), -1);
6780   SmallVector<int, 32> V2Mask(Mask.size(), -1);
6781   SmallVector<int, 32> BlendMask(Mask.size(), -1);
6782   for (int i = 0, Size = Mask.size(); i < Size; ++i)
6783     if (Mask[i] >= 0 && Mask[i] < Size) {
6784       V1Mask[i] = Mask[i];
6785       BlendMask[i] = i;
6786     } else if (Mask[i] >= Size) {
6787       V2Mask[i] = Mask[i] - Size;
6788       BlendMask[i] = i + Size;
6789     }
6790
6791   // Try to lower with the simpler initial blend strategy unless one of the
6792   // input shuffles would be a no-op. We prefer to shuffle inputs as the
6793   // shuffle may be able to fold with a load or other benefit. However, when
6794   // we'll have to do 2x as many shuffles in order to achieve this, blending
6795   // first is a better strategy.
6796   if (!isNoopShuffleMask(V1Mask) && !isNoopShuffleMask(V2Mask))
6797     if (SDValue BlendPerm =
6798             lowerVectorShuffleAsBlendAndPermute(DL, VT, V1, V2, Mask, DAG))
6799       return BlendPerm;
6800
6801   V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
6802   V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
6803   return DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
6804 }
6805
6806 /// \brief Try to lower a vector shuffle as a byte rotation.
6807 ///
6808 /// SSSE3 has a generic PALIGNR instruction in x86 that will do an arbitrary
6809 /// byte-rotation of the concatenation of two vectors; pre-SSSE3 can use
6810 /// a PSRLDQ/PSLLDQ/POR pattern to get a similar effect. This routine will
6811 /// try to generically lower a vector shuffle through such an pattern. It
6812 /// does not check for the profitability of lowering either as PALIGNR or
6813 /// PSRLDQ/PSLLDQ/POR, only whether the mask is valid to lower in that form.
6814 /// This matches shuffle vectors that look like:
6815 ///
6816 ///   v8i16 [11, 12, 13, 14, 15, 0, 1, 2]
6817 ///
6818 /// Essentially it concatenates V1 and V2, shifts right by some number of
6819 /// elements, and takes the low elements as the result. Note that while this is
6820 /// specified as a *right shift* because x86 is little-endian, it is a *left
6821 /// rotate* of the vector lanes.
6822 static SDValue lowerVectorShuffleAsByteRotate(SDLoc DL, MVT VT, SDValue V1,
6823                                               SDValue V2,
6824                                               ArrayRef<int> Mask,
6825                                               const X86Subtarget *Subtarget,
6826                                               SelectionDAG &DAG) {
6827   assert(!isNoopShuffleMask(Mask) && "We shouldn't lower no-op shuffles!");
6828
6829   int NumElts = Mask.size();
6830   int NumLanes = VT.getSizeInBits() / 128;
6831   int NumLaneElts = NumElts / NumLanes;
6832
6833   // We need to detect various ways of spelling a rotation:
6834   //   [11, 12, 13, 14, 15,  0,  1,  2]
6835   //   [-1, 12, 13, 14, -1, -1,  1, -1]
6836   //   [-1, -1, -1, -1, -1, -1,  1,  2]
6837   //   [ 3,  4,  5,  6,  7,  8,  9, 10]
6838   //   [-1,  4,  5,  6, -1, -1,  9, -1]
6839   //   [-1,  4,  5,  6, -1, -1, -1, -1]
6840   int Rotation = 0;
6841   SDValue Lo, Hi;
6842   for (int l = 0; l < NumElts; l += NumLaneElts) {
6843     for (int i = 0; i < NumLaneElts; ++i) {
6844       if (Mask[l + i] == -1)
6845         continue;
6846       assert(Mask[l + i] >= 0 && "Only -1 is a valid negative mask element!");
6847
6848       // Get the mod-Size index and lane correct it.
6849       int LaneIdx = (Mask[l + i] % NumElts) - l;
6850       // Make sure it was in this lane.
6851       if (LaneIdx < 0 || LaneIdx >= NumLaneElts)
6852         return SDValue();
6853
6854       // Determine where a rotated vector would have started.
6855       int StartIdx = i - LaneIdx;
6856       if (StartIdx == 0)
6857         // The identity rotation isn't interesting, stop.
6858         return SDValue();
6859
6860       // If we found the tail of a vector the rotation must be the missing
6861       // front. If we found the head of a vector, it must be how much of the
6862       // head.
6863       int CandidateRotation = StartIdx < 0 ? -StartIdx : NumLaneElts - StartIdx;
6864
6865       if (Rotation == 0)
6866         Rotation = CandidateRotation;
6867       else if (Rotation != CandidateRotation)
6868         // The rotations don't match, so we can't match this mask.
6869         return SDValue();
6870
6871       // Compute which value this mask is pointing at.
6872       SDValue MaskV = Mask[l + i] < NumElts ? V1 : V2;
6873
6874       // Compute which of the two target values this index should be assigned
6875       // to. This reflects whether the high elements are remaining or the low
6876       // elements are remaining.
6877       SDValue &TargetV = StartIdx < 0 ? Hi : Lo;
6878
6879       // Either set up this value if we've not encountered it before, or check
6880       // that it remains consistent.
6881       if (!TargetV)
6882         TargetV = MaskV;
6883       else if (TargetV != MaskV)
6884         // This may be a rotation, but it pulls from the inputs in some
6885         // unsupported interleaving.
6886         return SDValue();
6887     }
6888   }
6889
6890   // Check that we successfully analyzed the mask, and normalize the results.
6891   assert(Rotation != 0 && "Failed to locate a viable rotation!");
6892   assert((Lo || Hi) && "Failed to find a rotated input vector!");
6893   if (!Lo)
6894     Lo = Hi;
6895   else if (!Hi)
6896     Hi = Lo;
6897
6898   // The actual rotate instruction rotates bytes, so we need to scale the
6899   // rotation based on how many bytes are in the vector lane.
6900   int Scale = 16 / NumLaneElts;
6901
6902   // SSSE3 targets can use the palignr instruction.
6903   if (Subtarget->hasSSSE3()) {
6904     // Cast the inputs to i8 vector of correct length to match PALIGNR.
6905     MVT AlignVT = MVT::getVectorVT(MVT::i8, 16 * NumLanes);
6906     Lo = DAG.getBitcast(AlignVT, Lo);
6907     Hi = DAG.getBitcast(AlignVT, Hi);
6908
6909     return DAG.getBitcast(
6910         VT, DAG.getNode(X86ISD::PALIGNR, DL, AlignVT, Hi, Lo,
6911                         DAG.getConstant(Rotation * Scale, DL, MVT::i8)));
6912   }
6913
6914   assert(VT.getSizeInBits() == 128 &&
6915          "Rotate-based lowering only supports 128-bit lowering!");
6916   assert(Mask.size() <= 16 &&
6917          "Can shuffle at most 16 bytes in a 128-bit vector!");
6918
6919   // Default SSE2 implementation
6920   int LoByteShift = 16 - Rotation * Scale;
6921   int HiByteShift = Rotation * Scale;
6922
6923   // Cast the inputs to v2i64 to match PSLLDQ/PSRLDQ.
6924   Lo = DAG.getBitcast(MVT::v2i64, Lo);
6925   Hi = DAG.getBitcast(MVT::v2i64, Hi);
6926
6927   SDValue LoShift = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v2i64, Lo,
6928                                 DAG.getConstant(LoByteShift, DL, MVT::i8));
6929   SDValue HiShift = DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v2i64, Hi,
6930                                 DAG.getConstant(HiByteShift, DL, MVT::i8));
6931   return DAG.getBitcast(VT,
6932                         DAG.getNode(ISD::OR, DL, MVT::v2i64, LoShift, HiShift));
6933 }
6934
6935 /// \brief Try to lower a vector shuffle as a bit shift (shifts in zeros).
6936 ///
6937 /// Attempts to match a shuffle mask against the PSLL(W/D/Q/DQ) and
6938 /// PSRL(W/D/Q/DQ) SSE2 and AVX2 logical bit-shift instructions. The function
6939 /// matches elements from one of the input vectors shuffled to the left or
6940 /// right with zeroable elements 'shifted in'. It handles both the strictly
6941 /// bit-wise element shifts and the byte shift across an entire 128-bit double
6942 /// quad word lane.
6943 ///
6944 /// PSHL : (little-endian) left bit shift.
6945 /// [ zz, 0, zz,  2 ]
6946 /// [ -1, 4, zz, -1 ]
6947 /// PSRL : (little-endian) right bit shift.
6948 /// [  1, zz,  3, zz]
6949 /// [ -1, -1,  7, zz]
6950 /// PSLLDQ : (little-endian) left byte shift
6951 /// [ zz,  0,  1,  2,  3,  4,  5,  6]
6952 /// [ zz, zz, -1, -1,  2,  3,  4, -1]
6953 /// [ zz, zz, zz, zz, zz, zz, -1,  1]
6954 /// PSRLDQ : (little-endian) right byte shift
6955 /// [  5, 6,  7, zz, zz, zz, zz, zz]
6956 /// [ -1, 5,  6,  7, zz, zz, zz, zz]
6957 /// [  1, 2, -1, -1, -1, -1, zz, zz]
6958 static SDValue lowerVectorShuffleAsShift(SDLoc DL, MVT VT, SDValue V1,
6959                                          SDValue V2, ArrayRef<int> Mask,
6960                                          SelectionDAG &DAG) {
6961   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6962
6963   int Size = Mask.size();
6964   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
6965
6966   auto CheckZeros = [&](int Shift, int Scale, bool Left) {
6967     for (int i = 0; i < Size; i += Scale)
6968       for (int j = 0; j < Shift; ++j)
6969         if (!Zeroable[i + j + (Left ? 0 : (Scale - Shift))])
6970           return false;
6971
6972     return true;
6973   };
6974
6975   auto MatchShift = [&](int Shift, int Scale, bool Left, SDValue V) {
6976     for (int i = 0; i != Size; i += Scale) {
6977       unsigned Pos = Left ? i + Shift : i;
6978       unsigned Low = Left ? i : i + Shift;
6979       unsigned Len = Scale - Shift;
6980       if (!isSequentialOrUndefInRange(Mask, Pos, Len,
6981                                       Low + (V == V1 ? 0 : Size)))
6982         return SDValue();
6983     }
6984
6985     int ShiftEltBits = VT.getScalarSizeInBits() * Scale;
6986     bool ByteShift = ShiftEltBits > 64;
6987     unsigned OpCode = Left ? (ByteShift ? X86ISD::VSHLDQ : X86ISD::VSHLI)
6988                            : (ByteShift ? X86ISD::VSRLDQ : X86ISD::VSRLI);
6989     int ShiftAmt = Shift * VT.getScalarSizeInBits() / (ByteShift ? 8 : 1);
6990
6991     // Normalize the scale for byte shifts to still produce an i64 element
6992     // type.
6993     Scale = ByteShift ? Scale / 2 : Scale;
6994
6995     // We need to round trip through the appropriate type for the shift.
6996     MVT ShiftSVT = MVT::getIntegerVT(VT.getScalarSizeInBits() * Scale);
6997     MVT ShiftVT = MVT::getVectorVT(ShiftSVT, Size / Scale);
6998     assert(DAG.getTargetLoweringInfo().isTypeLegal(ShiftVT) &&
6999            "Illegal integer vector type");
7000     V = DAG.getBitcast(ShiftVT, V);
7001
7002     V = DAG.getNode(OpCode, DL, ShiftVT, V,
7003                     DAG.getConstant(ShiftAmt, DL, MVT::i8));
7004     return DAG.getBitcast(VT, V);
7005   };
7006
7007   // SSE/AVX supports logical shifts up to 64-bit integers - so we can just
7008   // keep doubling the size of the integer elements up to that. We can
7009   // then shift the elements of the integer vector by whole multiples of
7010   // their width within the elements of the larger integer vector. Test each
7011   // multiple to see if we can find a match with the moved element indices
7012   // and that the shifted in elements are all zeroable.
7013   for (int Scale = 2; Scale * VT.getScalarSizeInBits() <= 128; Scale *= 2)
7014     for (int Shift = 1; Shift != Scale; ++Shift)
7015       for (bool Left : {true, false})
7016         if (CheckZeros(Shift, Scale, Left))
7017           for (SDValue V : {V1, V2})
7018             if (SDValue Match = MatchShift(Shift, Scale, Left, V))
7019               return Match;
7020
7021   // no match
7022   return SDValue();
7023 }
7024
7025 /// \brief Try to lower a vector shuffle using SSE4a EXTRQ/INSERTQ.
7026 static SDValue lowerVectorShuffleWithSSE4A(SDLoc DL, MVT VT, SDValue V1,
7027                                            SDValue V2, ArrayRef<int> Mask,
7028                                            SelectionDAG &DAG) {
7029   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7030   assert(!Zeroable.all() && "Fully zeroable shuffle mask");
7031
7032   int Size = Mask.size();
7033   int HalfSize = Size / 2;
7034   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
7035
7036   // Upper half must be undefined.
7037   if (!isUndefInRange(Mask, HalfSize, HalfSize))
7038     return SDValue();
7039
7040   // EXTRQ: Extract Len elements from lower half of source, starting at Idx.
7041   // Remainder of lower half result is zero and upper half is all undef.
7042   auto LowerAsEXTRQ = [&]() {
7043     // Determine the extraction length from the part of the
7044     // lower half that isn't zeroable.
7045     int Len = HalfSize;
7046     for (; Len >= 0; --Len)
7047       if (!Zeroable[Len - 1])
7048         break;
7049     assert(Len > 0 && "Zeroable shuffle mask");
7050
7051     // Attempt to match first Len sequential elements from the lower half.
7052     SDValue Src;
7053     int Idx = -1;
7054     for (int i = 0; i != Len; ++i) {
7055       int M = Mask[i];
7056       if (M < 0)
7057         continue;
7058       SDValue &V = (M < Size ? V1 : V2);
7059       M = M % Size;
7060
7061       // All mask elements must be in the lower half.
7062       if (M > HalfSize)
7063         return SDValue();
7064
7065       if (Idx < 0 || (Src == V && Idx == (M - i))) {
7066         Src = V;
7067         Idx = M - i;
7068         continue;
7069       }
7070       return SDValue();
7071     }
7072
7073     if (Idx < 0)
7074       return SDValue();
7075
7076     assert((Idx + Len) <= HalfSize && "Illegal extraction mask");
7077     int BitLen = (Len * VT.getScalarSizeInBits()) & 0x3f;
7078     int BitIdx = (Idx * VT.getScalarSizeInBits()) & 0x3f;
7079     return DAG.getNode(X86ISD::EXTRQI, DL, VT, Src,
7080                        DAG.getConstant(BitLen, DL, MVT::i8),
7081                        DAG.getConstant(BitIdx, DL, MVT::i8));
7082   };
7083
7084   if (SDValue ExtrQ = LowerAsEXTRQ())
7085     return ExtrQ;
7086
7087   // INSERTQ: Extract lowest Len elements from lower half of second source and
7088   // insert over first source, starting at Idx.
7089   // { A[0], .., A[Idx-1], B[0], .., B[Len-1], A[Idx+Len], .., UNDEF, ... }
7090   auto LowerAsInsertQ = [&]() {
7091     for (int Idx = 0; Idx != HalfSize; ++Idx) {
7092       SDValue Base;
7093
7094       // Attempt to match first source from mask before insertion point.
7095       if (isUndefInRange(Mask, 0, Idx)) {
7096         /* EMPTY */
7097       } else if (isSequentialOrUndefInRange(Mask, 0, Idx, 0)) {
7098         Base = V1;
7099       } else if (isSequentialOrUndefInRange(Mask, 0, Idx, Size)) {
7100         Base = V2;
7101       } else {
7102         continue;
7103       }
7104
7105       // Extend the extraction length looking to match both the insertion of
7106       // the second source and the remaining elements of the first.
7107       for (int Hi = Idx + 1; Hi <= HalfSize; ++Hi) {
7108         SDValue Insert;
7109         int Len = Hi - Idx;
7110
7111         // Match insertion.
7112         if (isSequentialOrUndefInRange(Mask, Idx, Len, 0)) {
7113           Insert = V1;
7114         } else if (isSequentialOrUndefInRange(Mask, Idx, Len, Size)) {
7115           Insert = V2;
7116         } else {
7117           continue;
7118         }
7119
7120         // Match the remaining elements of the lower half.
7121         if (isUndefInRange(Mask, Hi, HalfSize - Hi)) {
7122           /* EMPTY */
7123         } else if ((!Base || (Base == V1)) &&
7124                    isSequentialOrUndefInRange(Mask, Hi, HalfSize - Hi, Hi)) {
7125           Base = V1;
7126         } else if ((!Base || (Base == V2)) &&
7127                    isSequentialOrUndefInRange(Mask, Hi, HalfSize - Hi,
7128                                               Size + Hi)) {
7129           Base = V2;
7130         } else {
7131           continue;
7132         }
7133
7134         // We may not have a base (first source) - this can safely be undefined.
7135         if (!Base)
7136           Base = DAG.getUNDEF(VT);
7137
7138         int BitLen = (Len * VT.getScalarSizeInBits()) & 0x3f;
7139         int BitIdx = (Idx * VT.getScalarSizeInBits()) & 0x3f;
7140         return DAG.getNode(X86ISD::INSERTQI, DL, VT, Base, Insert,
7141                            DAG.getConstant(BitLen, DL, MVT::i8),
7142                            DAG.getConstant(BitIdx, DL, MVT::i8));
7143       }
7144     }
7145
7146     return SDValue();
7147   };
7148
7149   if (SDValue InsertQ = LowerAsInsertQ())
7150     return InsertQ;
7151
7152   return SDValue();
7153 }
7154
7155 /// \brief Lower a vector shuffle as a zero or any extension.
7156 ///
7157 /// Given a specific number of elements, element bit width, and extension
7158 /// stride, produce either a zero or any extension based on the available
7159 /// features of the subtarget.
7160 static SDValue lowerVectorShuffleAsSpecificZeroOrAnyExtend(
7161     SDLoc DL, MVT VT, int Scale, bool AnyExt, SDValue InputV,
7162     ArrayRef<int> Mask, const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7163   assert(Scale > 1 && "Need a scale to extend.");
7164   int NumElements = VT.getVectorNumElements();
7165   int EltBits = VT.getScalarSizeInBits();
7166   assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
7167          "Only 8, 16, and 32 bit elements can be extended.");
7168   assert(Scale * EltBits <= 64 && "Cannot zero extend past 64 bits.");
7169
7170   // Found a valid zext mask! Try various lowering strategies based on the
7171   // input type and available ISA extensions.
7172   if (Subtarget->hasSSE41()) {
7173     MVT ExtVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits * Scale),
7174                                  NumElements / Scale);
7175     return DAG.getBitcast(VT, DAG.getNode(X86ISD::VZEXT, DL, ExtVT, InputV));
7176   }
7177
7178   // For any extends we can cheat for larger element sizes and use shuffle
7179   // instructions that can fold with a load and/or copy.
7180   if (AnyExt && EltBits == 32) {
7181     int PSHUFDMask[4] = {0, -1, 1, -1};
7182     return DAG.getBitcast(
7183         VT, DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7184                         DAG.getBitcast(MVT::v4i32, InputV),
7185                         getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
7186   }
7187   if (AnyExt && EltBits == 16 && Scale > 2) {
7188     int PSHUFDMask[4] = {0, -1, 0, -1};
7189     InputV = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7190                          DAG.getBitcast(MVT::v4i32, InputV),
7191                          getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG));
7192     int PSHUFHWMask[4] = {1, -1, -1, -1};
7193     return DAG.getBitcast(
7194         VT, DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16,
7195                         DAG.getBitcast(MVT::v8i16, InputV),
7196                         getV4X86ShuffleImm8ForMask(PSHUFHWMask, DL, DAG)));
7197   }
7198
7199   // The SSE4A EXTRQ instruction can efficiently extend the first 2 lanes
7200   // to 64-bits.
7201   if ((Scale * EltBits) == 64 && EltBits < 32 && Subtarget->hasSSE4A()) {
7202     assert(NumElements == (int)Mask.size() && "Unexpected shuffle mask size!");
7203     assert(VT.getSizeInBits() == 128 && "Unexpected vector width!");
7204
7205     SDValue Lo = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7206                              DAG.getNode(X86ISD::EXTRQI, DL, VT, InputV,
7207                                          DAG.getConstant(EltBits, DL, MVT::i8),
7208                                          DAG.getConstant(0, DL, MVT::i8)));
7209     if (isUndefInRange(Mask, NumElements/2, NumElements/2))
7210       return DAG.getNode(ISD::BITCAST, DL, VT, Lo);
7211
7212     SDValue Hi =
7213         DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7214                     DAG.getNode(X86ISD::EXTRQI, DL, VT, InputV,
7215                                 DAG.getConstant(EltBits, DL, MVT::i8),
7216                                 DAG.getConstant(EltBits, DL, MVT::i8)));
7217     return DAG.getNode(ISD::BITCAST, DL, VT,
7218                        DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, Lo, Hi));
7219   }
7220
7221   // If this would require more than 2 unpack instructions to expand, use
7222   // pshufb when available. We can only use more than 2 unpack instructions
7223   // when zero extending i8 elements which also makes it easier to use pshufb.
7224   if (Scale > 4 && EltBits == 8 && Subtarget->hasSSSE3()) {
7225     assert(NumElements == 16 && "Unexpected byte vector width!");
7226     SDValue PSHUFBMask[16];
7227     for (int i = 0; i < 16; ++i)
7228       PSHUFBMask[i] =
7229           DAG.getConstant((i % Scale == 0) ? i / Scale : 0x80, DL, MVT::i8);
7230     InputV = DAG.getBitcast(MVT::v16i8, InputV);
7231     return DAG.getBitcast(VT,
7232                           DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, InputV,
7233                                       DAG.getNode(ISD::BUILD_VECTOR, DL,
7234                                                   MVT::v16i8, PSHUFBMask)));
7235   }
7236
7237   // Otherwise emit a sequence of unpacks.
7238   do {
7239     MVT InputVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits), NumElements);
7240     SDValue Ext = AnyExt ? DAG.getUNDEF(InputVT)
7241                          : getZeroVector(InputVT, Subtarget, DAG, DL);
7242     InputV = DAG.getBitcast(InputVT, InputV);
7243     InputV = DAG.getNode(X86ISD::UNPCKL, DL, InputVT, InputV, Ext);
7244     Scale /= 2;
7245     EltBits *= 2;
7246     NumElements /= 2;
7247   } while (Scale > 1);
7248   return DAG.getBitcast(VT, InputV);
7249 }
7250
7251 /// \brief Try to lower a vector shuffle as a zero extension on any microarch.
7252 ///
7253 /// This routine will try to do everything in its power to cleverly lower
7254 /// a shuffle which happens to match the pattern of a zero extend. It doesn't
7255 /// check for the profitability of this lowering,  it tries to aggressively
7256 /// match this pattern. It will use all of the micro-architectural details it
7257 /// can to emit an efficient lowering. It handles both blends with all-zero
7258 /// inputs to explicitly zero-extend and undef-lanes (sometimes undef due to
7259 /// masking out later).
7260 ///
7261 /// The reason we have dedicated lowering for zext-style shuffles is that they
7262 /// are both incredibly common and often quite performance sensitive.
7263 static SDValue lowerVectorShuffleAsZeroOrAnyExtend(
7264     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7265     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7266   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7267
7268   int Bits = VT.getSizeInBits();
7269   int NumElements = VT.getVectorNumElements();
7270   assert(VT.getScalarSizeInBits() <= 32 &&
7271          "Exceeds 32-bit integer zero extension limit");
7272   assert((int)Mask.size() == NumElements && "Unexpected shuffle mask size");
7273
7274   // Define a helper function to check a particular ext-scale and lower to it if
7275   // valid.
7276   auto Lower = [&](int Scale) -> SDValue {
7277     SDValue InputV;
7278     bool AnyExt = true;
7279     for (int i = 0; i < NumElements; ++i) {
7280       if (Mask[i] == -1)
7281         continue; // Valid anywhere but doesn't tell us anything.
7282       if (i % Scale != 0) {
7283         // Each of the extended elements need to be zeroable.
7284         if (!Zeroable[i])
7285           return SDValue();
7286
7287         // We no longer are in the anyext case.
7288         AnyExt = false;
7289         continue;
7290       }
7291
7292       // Each of the base elements needs to be consecutive indices into the
7293       // same input vector.
7294       SDValue V = Mask[i] < NumElements ? V1 : V2;
7295       if (!InputV)
7296         InputV = V;
7297       else if (InputV != V)
7298         return SDValue(); // Flip-flopping inputs.
7299
7300       if (Mask[i] % NumElements != i / Scale)
7301         return SDValue(); // Non-consecutive strided elements.
7302     }
7303
7304     // If we fail to find an input, we have a zero-shuffle which should always
7305     // have already been handled.
7306     // FIXME: Maybe handle this here in case during blending we end up with one?
7307     if (!InputV)
7308       return SDValue();
7309
7310     return lowerVectorShuffleAsSpecificZeroOrAnyExtend(
7311         DL, VT, Scale, AnyExt, InputV, Mask, Subtarget, DAG);
7312   };
7313
7314   // The widest scale possible for extending is to a 64-bit integer.
7315   assert(Bits % 64 == 0 &&
7316          "The number of bits in a vector must be divisible by 64 on x86!");
7317   int NumExtElements = Bits / 64;
7318
7319   // Each iteration, try extending the elements half as much, but into twice as
7320   // many elements.
7321   for (; NumExtElements < NumElements; NumExtElements *= 2) {
7322     assert(NumElements % NumExtElements == 0 &&
7323            "The input vector size must be divisible by the extended size.");
7324     if (SDValue V = Lower(NumElements / NumExtElements))
7325       return V;
7326   }
7327
7328   // General extends failed, but 128-bit vectors may be able to use MOVQ.
7329   if (Bits != 128)
7330     return SDValue();
7331
7332   // Returns one of the source operands if the shuffle can be reduced to a
7333   // MOVQ, copying the lower 64-bits and zero-extending to the upper 64-bits.
7334   auto CanZExtLowHalf = [&]() {
7335     for (int i = NumElements / 2; i != NumElements; ++i)
7336       if (!Zeroable[i])
7337         return SDValue();
7338     if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, 0))
7339       return V1;
7340     if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, NumElements))
7341       return V2;
7342     return SDValue();
7343   };
7344
7345   if (SDValue V = CanZExtLowHalf()) {
7346     V = DAG.getBitcast(MVT::v2i64, V);
7347     V = DAG.getNode(X86ISD::VZEXT_MOVL, DL, MVT::v2i64, V);
7348     return DAG.getBitcast(VT, V);
7349   }
7350
7351   // No viable ext lowering found.
7352   return SDValue();
7353 }
7354
7355 /// \brief Try to get a scalar value for a specific element of a vector.
7356 ///
7357 /// Looks through BUILD_VECTOR and SCALAR_TO_VECTOR nodes to find a scalar.
7358 static SDValue getScalarValueForVectorElement(SDValue V, int Idx,
7359                                               SelectionDAG &DAG) {
7360   MVT VT = V.getSimpleValueType();
7361   MVT EltVT = VT.getVectorElementType();
7362   while (V.getOpcode() == ISD::BITCAST)
7363     V = V.getOperand(0);
7364   // If the bitcasts shift the element size, we can't extract an equivalent
7365   // element from it.
7366   MVT NewVT = V.getSimpleValueType();
7367   if (!NewVT.isVector() || NewVT.getScalarSizeInBits() != VT.getScalarSizeInBits())
7368     return SDValue();
7369
7370   if (V.getOpcode() == ISD::BUILD_VECTOR ||
7371       (Idx == 0 && V.getOpcode() == ISD::SCALAR_TO_VECTOR)) {
7372     // Ensure the scalar operand is the same size as the destination.
7373     // FIXME: Add support for scalar truncation where possible.
7374     SDValue S = V.getOperand(Idx);
7375     if (EltVT.getSizeInBits() == S.getSimpleValueType().getSizeInBits())
7376       return DAG.getNode(ISD::BITCAST, SDLoc(V), EltVT, S);
7377   }
7378
7379   return SDValue();
7380 }
7381
7382 /// \brief Helper to test for a load that can be folded with x86 shuffles.
7383 ///
7384 /// This is particularly important because the set of instructions varies
7385 /// significantly based on whether the operand is a load or not.
7386 static bool isShuffleFoldableLoad(SDValue V) {
7387   while (V.getOpcode() == ISD::BITCAST)
7388     V = V.getOperand(0);
7389
7390   return ISD::isNON_EXTLoad(V.getNode());
7391 }
7392
7393 /// \brief Try to lower insertion of a single element into a zero vector.
7394 ///
7395 /// This is a common pattern that we have especially efficient patterns to lower
7396 /// across all subtarget feature sets.
7397 static SDValue lowerVectorShuffleAsElementInsertion(
7398     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7399     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7400   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7401   MVT ExtVT = VT;
7402   MVT EltVT = VT.getVectorElementType();
7403
7404   int V2Index = std::find_if(Mask.begin(), Mask.end(),
7405                              [&Mask](int M) { return M >= (int)Mask.size(); }) -
7406                 Mask.begin();
7407   bool IsV1Zeroable = true;
7408   for (int i = 0, Size = Mask.size(); i < Size; ++i)
7409     if (i != V2Index && !Zeroable[i]) {
7410       IsV1Zeroable = false;
7411       break;
7412     }
7413
7414   // Check for a single input from a SCALAR_TO_VECTOR node.
7415   // FIXME: All of this should be canonicalized into INSERT_VECTOR_ELT and
7416   // all the smarts here sunk into that routine. However, the current
7417   // lowering of BUILD_VECTOR makes that nearly impossible until the old
7418   // vector shuffle lowering is dead.
7419   SDValue V2S = getScalarValueForVectorElement(V2, Mask[V2Index] - Mask.size(),
7420                                                DAG);
7421   if (V2S && DAG.getTargetLoweringInfo().isTypeLegal(V2S.getValueType())) {
7422     // We need to zext the scalar if it is smaller than an i32.
7423     V2S = DAG.getBitcast(EltVT, V2S);
7424     if (EltVT == MVT::i8 || EltVT == MVT::i16) {
7425       // Using zext to expand a narrow element won't work for non-zero
7426       // insertions.
7427       if (!IsV1Zeroable)
7428         return SDValue();
7429
7430       // Zero-extend directly to i32.
7431       ExtVT = MVT::v4i32;
7432       V2S = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, V2S);
7433     }
7434     V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, ExtVT, V2S);
7435   } else if (Mask[V2Index] != (int)Mask.size() || EltVT == MVT::i8 ||
7436              EltVT == MVT::i16) {
7437     // Either not inserting from the low element of the input or the input
7438     // element size is too small to use VZEXT_MOVL to clear the high bits.
7439     return SDValue();
7440   }
7441
7442   if (!IsV1Zeroable) {
7443     // If V1 can't be treated as a zero vector we have fewer options to lower
7444     // this. We can't support integer vectors or non-zero targets cheaply, and
7445     // the V1 elements can't be permuted in any way.
7446     assert(VT == ExtVT && "Cannot change extended type when non-zeroable!");
7447     if (!VT.isFloatingPoint() || V2Index != 0)
7448       return SDValue();
7449     SmallVector<int, 8> V1Mask(Mask.begin(), Mask.end());
7450     V1Mask[V2Index] = -1;
7451     if (!isNoopShuffleMask(V1Mask))
7452       return SDValue();
7453     // This is essentially a special case blend operation, but if we have
7454     // general purpose blend operations, they are always faster. Bail and let
7455     // the rest of the lowering handle these as blends.
7456     if (Subtarget->hasSSE41())
7457       return SDValue();
7458
7459     // Otherwise, use MOVSD or MOVSS.
7460     assert((EltVT == MVT::f32 || EltVT == MVT::f64) &&
7461            "Only two types of floating point element types to handle!");
7462     return DAG.getNode(EltVT == MVT::f32 ? X86ISD::MOVSS : X86ISD::MOVSD, DL,
7463                        ExtVT, V1, V2);
7464   }
7465
7466   // This lowering only works for the low element with floating point vectors.
7467   if (VT.isFloatingPoint() && V2Index != 0)
7468     return SDValue();
7469
7470   V2 = DAG.getNode(X86ISD::VZEXT_MOVL, DL, ExtVT, V2);
7471   if (ExtVT != VT)
7472     V2 = DAG.getBitcast(VT, V2);
7473
7474   if (V2Index != 0) {
7475     // If we have 4 or fewer lanes we can cheaply shuffle the element into
7476     // the desired position. Otherwise it is more efficient to do a vector
7477     // shift left. We know that we can do a vector shift left because all
7478     // the inputs are zero.
7479     if (VT.isFloatingPoint() || VT.getVectorNumElements() <= 4) {
7480       SmallVector<int, 4> V2Shuffle(Mask.size(), 1);
7481       V2Shuffle[V2Index] = 0;
7482       V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Shuffle);
7483     } else {
7484       V2 = DAG.getBitcast(MVT::v2i64, V2);
7485       V2 = DAG.getNode(
7486           X86ISD::VSHLDQ, DL, MVT::v2i64, V2,
7487           DAG.getConstant(V2Index * EltVT.getSizeInBits() / 8, DL,
7488                           DAG.getTargetLoweringInfo().getScalarShiftAmountTy(
7489                               DAG.getDataLayout(), VT)));
7490       V2 = DAG.getBitcast(VT, V2);
7491     }
7492   }
7493   return V2;
7494 }
7495
7496 /// \brief Try to lower broadcast of a single element.
7497 ///
7498 /// For convenience, this code also bundles all of the subtarget feature set
7499 /// filtering. While a little annoying to re-dispatch on type here, there isn't
7500 /// a convenient way to factor it out.
7501 static SDValue lowerVectorShuffleAsBroadcast(SDLoc DL, MVT VT, SDValue V,
7502                                              ArrayRef<int> Mask,
7503                                              const X86Subtarget *Subtarget,
7504                                              SelectionDAG &DAG) {
7505   if (!Subtarget->hasAVX())
7506     return SDValue();
7507   if (VT.isInteger() && !Subtarget->hasAVX2())
7508     return SDValue();
7509
7510   // Check that the mask is a broadcast.
7511   int BroadcastIdx = -1;
7512   for (int M : Mask)
7513     if (M >= 0 && BroadcastIdx == -1)
7514       BroadcastIdx = M;
7515     else if (M >= 0 && M != BroadcastIdx)
7516       return SDValue();
7517
7518   assert(BroadcastIdx < (int)Mask.size() && "We only expect to be called with "
7519                                             "a sorted mask where the broadcast "
7520                                             "comes from V1.");
7521
7522   // Go up the chain of (vector) values to find a scalar load that we can
7523   // combine with the broadcast.
7524   for (;;) {
7525     switch (V.getOpcode()) {
7526     case ISD::CONCAT_VECTORS: {
7527       int OperandSize = Mask.size() / V.getNumOperands();
7528       V = V.getOperand(BroadcastIdx / OperandSize);
7529       BroadcastIdx %= OperandSize;
7530       continue;
7531     }
7532
7533     case ISD::INSERT_SUBVECTOR: {
7534       SDValue VOuter = V.getOperand(0), VInner = V.getOperand(1);
7535       auto ConstantIdx = dyn_cast<ConstantSDNode>(V.getOperand(2));
7536       if (!ConstantIdx)
7537         break;
7538
7539       int BeginIdx = (int)ConstantIdx->getZExtValue();
7540       int EndIdx =
7541           BeginIdx + (int)VInner.getValueType().getVectorNumElements();
7542       if (BroadcastIdx >= BeginIdx && BroadcastIdx < EndIdx) {
7543         BroadcastIdx -= BeginIdx;
7544         V = VInner;
7545       } else {
7546         V = VOuter;
7547       }
7548       continue;
7549     }
7550     }
7551     break;
7552   }
7553
7554   // Check if this is a broadcast of a scalar. We special case lowering
7555   // for scalars so that we can more effectively fold with loads.
7556   if (V.getOpcode() == ISD::BUILD_VECTOR ||
7557       (V.getOpcode() == ISD::SCALAR_TO_VECTOR && BroadcastIdx == 0)) {
7558     V = V.getOperand(BroadcastIdx);
7559
7560     // If the scalar isn't a load, we can't broadcast from it in AVX1.
7561     // Only AVX2 has register broadcasts.
7562     if (!Subtarget->hasAVX2() && !isShuffleFoldableLoad(V))
7563       return SDValue();
7564   } else if (BroadcastIdx != 0 || !Subtarget->hasAVX2()) {
7565     // We can't broadcast from a vector register without AVX2, and we can only
7566     // broadcast from the zero-element of a vector register.
7567     return SDValue();
7568   }
7569
7570   return DAG.getNode(X86ISD::VBROADCAST, DL, VT, V);
7571 }
7572
7573 // Check for whether we can use INSERTPS to perform the shuffle. We only use
7574 // INSERTPS when the V1 elements are already in the correct locations
7575 // because otherwise we can just always use two SHUFPS instructions which
7576 // are much smaller to encode than a SHUFPS and an INSERTPS. We can also
7577 // perform INSERTPS if a single V1 element is out of place and all V2
7578 // elements are zeroable.
7579 static SDValue lowerVectorShuffleAsInsertPS(SDValue Op, SDValue V1, SDValue V2,
7580                                             ArrayRef<int> Mask,
7581                                             SelectionDAG &DAG) {
7582   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
7583   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7584   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7585   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7586
7587   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7588
7589   unsigned ZMask = 0;
7590   int V1DstIndex = -1;
7591   int V2DstIndex = -1;
7592   bool V1UsedInPlace = false;
7593
7594   for (int i = 0; i < 4; ++i) {
7595     // Synthesize a zero mask from the zeroable elements (includes undefs).
7596     if (Zeroable[i]) {
7597       ZMask |= 1 << i;
7598       continue;
7599     }
7600
7601     // Flag if we use any V1 inputs in place.
7602     if (i == Mask[i]) {
7603       V1UsedInPlace = true;
7604       continue;
7605     }
7606
7607     // We can only insert a single non-zeroable element.
7608     if (V1DstIndex != -1 || V2DstIndex != -1)
7609       return SDValue();
7610
7611     if (Mask[i] < 4) {
7612       // V1 input out of place for insertion.
7613       V1DstIndex = i;
7614     } else {
7615       // V2 input for insertion.
7616       V2DstIndex = i;
7617     }
7618   }
7619
7620   // Don't bother if we have no (non-zeroable) element for insertion.
7621   if (V1DstIndex == -1 && V2DstIndex == -1)
7622     return SDValue();
7623
7624   // Determine element insertion src/dst indices. The src index is from the
7625   // start of the inserted vector, not the start of the concatenated vector.
7626   unsigned V2SrcIndex = 0;
7627   if (V1DstIndex != -1) {
7628     // If we have a V1 input out of place, we use V1 as the V2 element insertion
7629     // and don't use the original V2 at all.
7630     V2SrcIndex = Mask[V1DstIndex];
7631     V2DstIndex = V1DstIndex;
7632     V2 = V1;
7633   } else {
7634     V2SrcIndex = Mask[V2DstIndex] - 4;
7635   }
7636
7637   // If no V1 inputs are used in place, then the result is created only from
7638   // the zero mask and the V2 insertion - so remove V1 dependency.
7639   if (!V1UsedInPlace)
7640     V1 = DAG.getUNDEF(MVT::v4f32);
7641
7642   unsigned InsertPSMask = V2SrcIndex << 6 | V2DstIndex << 4 | ZMask;
7643   assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
7644
7645   // Insert the V2 element into the desired position.
7646   SDLoc DL(Op);
7647   return DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
7648                      DAG.getConstant(InsertPSMask, DL, MVT::i8));
7649 }
7650
7651 /// \brief Try to lower a shuffle as a permute of the inputs followed by an
7652 /// UNPCK instruction.
7653 ///
7654 /// This specifically targets cases where we end up with alternating between
7655 /// the two inputs, and so can permute them into something that feeds a single
7656 /// UNPCK instruction. Note that this routine only targets integer vectors
7657 /// because for floating point vectors we have a generalized SHUFPS lowering
7658 /// strategy that handles everything that doesn't *exactly* match an unpack,
7659 /// making this clever lowering unnecessary.
7660 static SDValue lowerVectorShuffleAsUnpack(SDLoc DL, MVT VT, SDValue V1,
7661                                           SDValue V2, ArrayRef<int> Mask,
7662                                           SelectionDAG &DAG) {
7663   assert(!VT.isFloatingPoint() &&
7664          "This routine only supports integer vectors.");
7665   assert(!isSingleInputShuffleMask(Mask) &&
7666          "This routine should only be used when blending two inputs.");
7667   assert(Mask.size() >= 2 && "Single element masks are invalid.");
7668
7669   int Size = Mask.size();
7670
7671   int NumLoInputs = std::count_if(Mask.begin(), Mask.end(), [Size](int M) {
7672     return M >= 0 && M % Size < Size / 2;
7673   });
7674   int NumHiInputs = std::count_if(
7675       Mask.begin(), Mask.end(), [Size](int M) { return M % Size >= Size / 2; });
7676
7677   bool UnpackLo = NumLoInputs >= NumHiInputs;
7678
7679   auto TryUnpack = [&](MVT UnpackVT, int Scale) {
7680     SmallVector<int, 32> V1Mask(Mask.size(), -1);
7681     SmallVector<int, 32> V2Mask(Mask.size(), -1);
7682
7683     for (int i = 0; i < Size; ++i) {
7684       if (Mask[i] < 0)
7685         continue;
7686
7687       // Each element of the unpack contains Scale elements from this mask.
7688       int UnpackIdx = i / Scale;
7689
7690       // We only handle the case where V1 feeds the first slots of the unpack.
7691       // We rely on canonicalization to ensure this is the case.
7692       if ((UnpackIdx % 2 == 0) != (Mask[i] < Size))
7693         return SDValue();
7694
7695       // Setup the mask for this input. The indexing is tricky as we have to
7696       // handle the unpack stride.
7697       SmallVectorImpl<int> &VMask = (UnpackIdx % 2 == 0) ? V1Mask : V2Mask;
7698       VMask[(UnpackIdx / 2) * Scale + i % Scale + (UnpackLo ? 0 : Size / 2)] =
7699           Mask[i] % Size;
7700     }
7701
7702     // If we will have to shuffle both inputs to use the unpack, check whether
7703     // we can just unpack first and shuffle the result. If so, skip this unpack.
7704     if ((NumLoInputs == 0 || NumHiInputs == 0) && !isNoopShuffleMask(V1Mask) &&
7705         !isNoopShuffleMask(V2Mask))
7706       return SDValue();
7707
7708     // Shuffle the inputs into place.
7709     V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
7710     V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
7711
7712     // Cast the inputs to the type we will use to unpack them.
7713     V1 = DAG.getBitcast(UnpackVT, V1);
7714     V2 = DAG.getBitcast(UnpackVT, V2);
7715
7716     // Unpack the inputs and cast the result back to the desired type.
7717     return DAG.getBitcast(
7718         VT, DAG.getNode(UnpackLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
7719                         UnpackVT, V1, V2));
7720   };
7721
7722   // We try each unpack from the largest to the smallest to try and find one
7723   // that fits this mask.
7724   int OrigNumElements = VT.getVectorNumElements();
7725   int OrigScalarSize = VT.getScalarSizeInBits();
7726   for (int ScalarSize = 64; ScalarSize >= OrigScalarSize; ScalarSize /= 2) {
7727     int Scale = ScalarSize / OrigScalarSize;
7728     int NumElements = OrigNumElements / Scale;
7729     MVT UnpackVT = MVT::getVectorVT(MVT::getIntegerVT(ScalarSize), NumElements);
7730     if (SDValue Unpack = TryUnpack(UnpackVT, Scale))
7731       return Unpack;
7732   }
7733
7734   // If none of the unpack-rooted lowerings worked (or were profitable) try an
7735   // initial unpack.
7736   if (NumLoInputs == 0 || NumHiInputs == 0) {
7737     assert((NumLoInputs > 0 || NumHiInputs > 0) &&
7738            "We have to have *some* inputs!");
7739     int HalfOffset = NumLoInputs == 0 ? Size / 2 : 0;
7740
7741     // FIXME: We could consider the total complexity of the permute of each
7742     // possible unpacking. Or at the least we should consider how many
7743     // half-crossings are created.
7744     // FIXME: We could consider commuting the unpacks.
7745
7746     SmallVector<int, 32> PermMask;
7747     PermMask.assign(Size, -1);
7748     for (int i = 0; i < Size; ++i) {
7749       if (Mask[i] < 0)
7750         continue;
7751
7752       assert(Mask[i] % Size >= HalfOffset && "Found input from wrong half!");
7753
7754       PermMask[i] =
7755           2 * ((Mask[i] % Size) - HalfOffset) + (Mask[i] < Size ? 0 : 1);
7756     }
7757     return DAG.getVectorShuffle(
7758         VT, DL, DAG.getNode(NumLoInputs == 0 ? X86ISD::UNPCKH : X86ISD::UNPCKL,
7759                             DL, VT, V1, V2),
7760         DAG.getUNDEF(VT), PermMask);
7761   }
7762
7763   return SDValue();
7764 }
7765
7766 /// \brief Handle lowering of 2-lane 64-bit floating point shuffles.
7767 ///
7768 /// This is the basis function for the 2-lane 64-bit shuffles as we have full
7769 /// support for floating point shuffles but not integer shuffles. These
7770 /// instructions will incur a domain crossing penalty on some chips though so
7771 /// it is better to avoid lowering through this for integer vectors where
7772 /// possible.
7773 static SDValue lowerV2F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7774                                        const X86Subtarget *Subtarget,
7775                                        SelectionDAG &DAG) {
7776   SDLoc DL(Op);
7777   assert(Op.getSimpleValueType() == MVT::v2f64 && "Bad shuffle type!");
7778   assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7779   assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7780   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7781   ArrayRef<int> Mask = SVOp->getMask();
7782   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7783
7784   if (isSingleInputShuffleMask(Mask)) {
7785     // Use low duplicate instructions for masks that match their pattern.
7786     if (Subtarget->hasSSE3())
7787       if (isShuffleEquivalent(V1, V2, Mask, {0, 0}))
7788         return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v2f64, V1);
7789
7790     // Straight shuffle of a single input vector. Simulate this by using the
7791     // single input as both of the "inputs" to this instruction..
7792     unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
7793
7794     if (Subtarget->hasAVX()) {
7795       // If we have AVX, we can use VPERMILPS which will allow folding a load
7796       // into the shuffle.
7797       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v2f64, V1,
7798                          DAG.getConstant(SHUFPDMask, DL, MVT::i8));
7799     }
7800
7801     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V1,
7802                        DAG.getConstant(SHUFPDMask, DL, MVT::i8));
7803   }
7804   assert(Mask[0] >= 0 && Mask[0] < 2 && "Non-canonicalized blend!");
7805   assert(Mask[1] >= 2 && "Non-canonicalized blend!");
7806
7807   // If we have a single input, insert that into V1 if we can do so cheaply.
7808   if ((Mask[0] >= 2) + (Mask[1] >= 2) == 1) {
7809     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7810             DL, MVT::v2f64, V1, V2, Mask, Subtarget, DAG))
7811       return Insertion;
7812     // Try inverting the insertion since for v2 masks it is easy to do and we
7813     // can't reliably sort the mask one way or the other.
7814     int InverseMask[2] = {Mask[0] < 0 ? -1 : (Mask[0] ^ 2),
7815                           Mask[1] < 0 ? -1 : (Mask[1] ^ 2)};
7816     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7817             DL, MVT::v2f64, V2, V1, InverseMask, Subtarget, DAG))
7818       return Insertion;
7819   }
7820
7821   // Try to use one of the special instruction patterns to handle two common
7822   // blend patterns if a zero-blend above didn't work.
7823   if (isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
7824       isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7825     if (SDValue V1S = getScalarValueForVectorElement(V1, Mask[0], DAG))
7826       // We can either use a special instruction to load over the low double or
7827       // to move just the low double.
7828       return DAG.getNode(
7829           isShuffleFoldableLoad(V1S) ? X86ISD::MOVLPD : X86ISD::MOVSD,
7830           DL, MVT::v2f64, V2,
7831           DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64, V1S));
7832
7833   if (Subtarget->hasSSE41())
7834     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2f64, V1, V2, Mask,
7835                                                   Subtarget, DAG))
7836       return Blend;
7837
7838   // Use dedicated unpack instructions for masks that match their pattern.
7839   if (isShuffleEquivalent(V1, V2, Mask, {0, 2}))
7840     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2f64, V1, V2);
7841   if (isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7842     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2f64, V1, V2);
7843
7844   unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
7845   return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V2,
7846                      DAG.getConstant(SHUFPDMask, DL, MVT::i8));
7847 }
7848
7849 /// \brief Handle lowering of 2-lane 64-bit integer shuffles.
7850 ///
7851 /// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
7852 /// the integer unit to minimize domain crossing penalties. However, for blends
7853 /// it falls back to the floating point shuffle operation with appropriate bit
7854 /// casting.
7855 static SDValue lowerV2I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7856                                        const X86Subtarget *Subtarget,
7857                                        SelectionDAG &DAG) {
7858   SDLoc DL(Op);
7859   assert(Op.getSimpleValueType() == MVT::v2i64 && "Bad shuffle type!");
7860   assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7861   assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7862   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7863   ArrayRef<int> Mask = SVOp->getMask();
7864   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7865
7866   if (isSingleInputShuffleMask(Mask)) {
7867     // Check for being able to broadcast a single element.
7868     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v2i64, V1,
7869                                                           Mask, Subtarget, DAG))
7870       return Broadcast;
7871
7872     // Straight shuffle of a single input vector. For everything from SSE2
7873     // onward this has a single fast instruction with no scary immediates.
7874     // We have to map the mask as it is actually a v4i32 shuffle instruction.
7875     V1 = DAG.getBitcast(MVT::v4i32, V1);
7876     int WidenedMask[4] = {
7877         std::max(Mask[0], 0) * 2, std::max(Mask[0], 0) * 2 + 1,
7878         std::max(Mask[1], 0) * 2, std::max(Mask[1], 0) * 2 + 1};
7879     return DAG.getBitcast(
7880         MVT::v2i64,
7881         DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
7882                     getV4X86ShuffleImm8ForMask(WidenedMask, DL, DAG)));
7883   }
7884   assert(Mask[0] != -1 && "No undef lanes in multi-input v2 shuffles!");
7885   assert(Mask[1] != -1 && "No undef lanes in multi-input v2 shuffles!");
7886   assert(Mask[0] < 2 && "We sort V1 to be the first input.");
7887   assert(Mask[1] >= 2 && "We sort V2 to be the second input.");
7888
7889   // If we have a blend of two PACKUS operations an the blend aligns with the
7890   // low and half halves, we can just merge the PACKUS operations. This is
7891   // particularly important as it lets us merge shuffles that this routine itself
7892   // creates.
7893   auto GetPackNode = [](SDValue V) {
7894     while (V.getOpcode() == ISD::BITCAST)
7895       V = V.getOperand(0);
7896
7897     return V.getOpcode() == X86ISD::PACKUS ? V : SDValue();
7898   };
7899   if (SDValue V1Pack = GetPackNode(V1))
7900     if (SDValue V2Pack = GetPackNode(V2))
7901       return DAG.getBitcast(MVT::v2i64,
7902                             DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8,
7903                                         Mask[0] == 0 ? V1Pack.getOperand(0)
7904                                                      : V1Pack.getOperand(1),
7905                                         Mask[1] == 2 ? V2Pack.getOperand(0)
7906                                                      : V2Pack.getOperand(1)));
7907
7908   // Try to use shift instructions.
7909   if (SDValue Shift =
7910           lowerVectorShuffleAsShift(DL, MVT::v2i64, V1, V2, Mask, DAG))
7911     return Shift;
7912
7913   // When loading a scalar and then shuffling it into a vector we can often do
7914   // the insertion cheaply.
7915   if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7916           DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
7917     return Insertion;
7918   // Try inverting the insertion since for v2 masks it is easy to do and we
7919   // can't reliably sort the mask one way or the other.
7920   int InverseMask[2] = {Mask[0] ^ 2, Mask[1] ^ 2};
7921   if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7922           DL, MVT::v2i64, V2, V1, InverseMask, Subtarget, DAG))
7923     return Insertion;
7924
7925   // We have different paths for blend lowering, but they all must use the
7926   // *exact* same predicate.
7927   bool IsBlendSupported = Subtarget->hasSSE41();
7928   if (IsBlendSupported)
7929     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2i64, V1, V2, Mask,
7930                                                   Subtarget, DAG))
7931       return Blend;
7932
7933   // Use dedicated unpack instructions for masks that match their pattern.
7934   if (isShuffleEquivalent(V1, V2, Mask, {0, 2}))
7935     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, V1, V2);
7936   if (isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7937     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2i64, V1, V2);
7938
7939   // Try to use byte rotation instructions.
7940   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
7941   if (Subtarget->hasSSSE3())
7942     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
7943             DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
7944       return Rotate;
7945
7946   // If we have direct support for blends, we should lower by decomposing into
7947   // a permute. That will be faster than the domain cross.
7948   if (IsBlendSupported)
7949     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v2i64, V1, V2,
7950                                                       Mask, DAG);
7951
7952   // We implement this with SHUFPD which is pretty lame because it will likely
7953   // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
7954   // However, all the alternatives are still more cycles and newer chips don't
7955   // have this problem. It would be really nice if x86 had better shuffles here.
7956   V1 = DAG.getBitcast(MVT::v2f64, V1);
7957   V2 = DAG.getBitcast(MVT::v2f64, V2);
7958   return DAG.getBitcast(MVT::v2i64,
7959                         DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
7960 }
7961
7962 /// \brief Test whether this can be lowered with a single SHUFPS instruction.
7963 ///
7964 /// This is used to disable more specialized lowerings when the shufps lowering
7965 /// will happen to be efficient.
7966 static bool isSingleSHUFPSMask(ArrayRef<int> Mask) {
7967   // This routine only handles 128-bit shufps.
7968   assert(Mask.size() == 4 && "Unsupported mask size!");
7969
7970   // To lower with a single SHUFPS we need to have the low half and high half
7971   // each requiring a single input.
7972   if (Mask[0] != -1 && Mask[1] != -1 && (Mask[0] < 4) != (Mask[1] < 4))
7973     return false;
7974   if (Mask[2] != -1 && Mask[3] != -1 && (Mask[2] < 4) != (Mask[3] < 4))
7975     return false;
7976
7977   return true;
7978 }
7979
7980 /// \brief Lower a vector shuffle using the SHUFPS instruction.
7981 ///
7982 /// This is a helper routine dedicated to lowering vector shuffles using SHUFPS.
7983 /// It makes no assumptions about whether this is the *best* lowering, it simply
7984 /// uses it.
7985 static SDValue lowerVectorShuffleWithSHUFPS(SDLoc DL, MVT VT,
7986                                             ArrayRef<int> Mask, SDValue V1,
7987                                             SDValue V2, SelectionDAG &DAG) {
7988   SDValue LowV = V1, HighV = V2;
7989   int NewMask[4] = {Mask[0], Mask[1], Mask[2], Mask[3]};
7990
7991   int NumV2Elements =
7992       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7993
7994   if (NumV2Elements == 1) {
7995     int V2Index =
7996         std::find_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; }) -
7997         Mask.begin();
7998
7999     // Compute the index adjacent to V2Index and in the same half by toggling
8000     // the low bit.
8001     int V2AdjIndex = V2Index ^ 1;
8002
8003     if (Mask[V2AdjIndex] == -1) {
8004       // Handles all the cases where we have a single V2 element and an undef.
8005       // This will only ever happen in the high lanes because we commute the
8006       // vector otherwise.
8007       if (V2Index < 2)
8008         std::swap(LowV, HighV);
8009       NewMask[V2Index] -= 4;
8010     } else {
8011       // Handle the case where the V2 element ends up adjacent to a V1 element.
8012       // To make this work, blend them together as the first step.
8013       int V1Index = V2AdjIndex;
8014       int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
8015       V2 = DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
8016                        getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
8017
8018       // Now proceed to reconstruct the final blend as we have the necessary
8019       // high or low half formed.
8020       if (V2Index < 2) {
8021         LowV = V2;
8022         HighV = V1;
8023       } else {
8024         HighV = V2;
8025       }
8026       NewMask[V1Index] = 2; // We put the V1 element in V2[2].
8027       NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
8028     }
8029   } else if (NumV2Elements == 2) {
8030     if (Mask[0] < 4 && Mask[1] < 4) {
8031       // Handle the easy case where we have V1 in the low lanes and V2 in the
8032       // high lanes.
8033       NewMask[2] -= 4;
8034       NewMask[3] -= 4;
8035     } else if (Mask[2] < 4 && Mask[3] < 4) {
8036       // We also handle the reversed case because this utility may get called
8037       // when we detect a SHUFPS pattern but can't easily commute the shuffle to
8038       // arrange things in the right direction.
8039       NewMask[0] -= 4;
8040       NewMask[1] -= 4;
8041       HighV = V1;
8042       LowV = V2;
8043     } else {
8044       // We have a mixture of V1 and V2 in both low and high lanes. Rather than
8045       // trying to place elements directly, just blend them and set up the final
8046       // shuffle to place them.
8047
8048       // The first two blend mask elements are for V1, the second two are for
8049       // V2.
8050       int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
8051                           Mask[2] < 4 ? Mask[2] : Mask[3],
8052                           (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
8053                           (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
8054       V1 = DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
8055                        getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
8056
8057       // Now we do a normal shuffle of V1 by giving V1 as both operands to
8058       // a blend.
8059       LowV = HighV = V1;
8060       NewMask[0] = Mask[0] < 4 ? 0 : 2;
8061       NewMask[1] = Mask[0] < 4 ? 2 : 0;
8062       NewMask[2] = Mask[2] < 4 ? 1 : 3;
8063       NewMask[3] = Mask[2] < 4 ? 3 : 1;
8064     }
8065   }
8066   return DAG.getNode(X86ISD::SHUFP, DL, VT, LowV, HighV,
8067                      getV4X86ShuffleImm8ForMask(NewMask, DL, DAG));
8068 }
8069
8070 /// \brief Lower 4-lane 32-bit floating point shuffles.
8071 ///
8072 /// Uses instructions exclusively from the floating point unit to minimize
8073 /// domain crossing penalties, as these are sufficient to implement all v4f32
8074 /// shuffles.
8075 static SDValue lowerV4F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8076                                        const X86Subtarget *Subtarget,
8077                                        SelectionDAG &DAG) {
8078   SDLoc DL(Op);
8079   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
8080   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8081   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8082   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8083   ArrayRef<int> Mask = SVOp->getMask();
8084   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8085
8086   int NumV2Elements =
8087       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8088
8089   if (NumV2Elements == 0) {
8090     // Check for being able to broadcast a single element.
8091     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f32, V1,
8092                                                           Mask, Subtarget, DAG))
8093       return Broadcast;
8094
8095     // Use even/odd duplicate instructions for masks that match their pattern.
8096     if (Subtarget->hasSSE3()) {
8097       if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
8098         return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v4f32, V1);
8099       if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3}))
8100         return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v4f32, V1);
8101     }
8102
8103     if (Subtarget->hasAVX()) {
8104       // If we have AVX, we can use VPERMILPS which will allow folding a load
8105       // into the shuffle.
8106       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f32, V1,
8107                          getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8108     }
8109
8110     // Otherwise, use a straight shuffle of a single input vector. We pass the
8111     // input vector to both operands to simulate this with a SHUFPS.
8112     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
8113                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8114   }
8115
8116   // There are special ways we can lower some single-element blends. However, we
8117   // have custom ways we can lower more complex single-element blends below that
8118   // we defer to if both this and BLENDPS fail to match, so restrict this to
8119   // when the V2 input is targeting element 0 of the mask -- that is the fast
8120   // case here.
8121   if (NumV2Elements == 1 && Mask[0] >= 4)
8122     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4f32, V1, V2,
8123                                                          Mask, Subtarget, DAG))
8124       return V;
8125
8126   if (Subtarget->hasSSE41()) {
8127     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f32, V1, V2, Mask,
8128                                                   Subtarget, DAG))
8129       return Blend;
8130
8131     // Use INSERTPS if we can complete the shuffle efficiently.
8132     if (SDValue V = lowerVectorShuffleAsInsertPS(Op, V1, V2, Mask, DAG))
8133       return V;
8134
8135     if (!isSingleSHUFPSMask(Mask))
8136       if (SDValue BlendPerm = lowerVectorShuffleAsBlendAndPermute(
8137               DL, MVT::v4f32, V1, V2, Mask, DAG))
8138         return BlendPerm;
8139   }
8140
8141   // Use dedicated unpack instructions for masks that match their pattern.
8142   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 1, 5}))
8143     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V1, V2);
8144   if (isShuffleEquivalent(V1, V2, Mask, {2, 6, 3, 7}))
8145     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V1, V2);
8146   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 5, 1}))
8147     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V2, V1);
8148   if (isShuffleEquivalent(V1, V2, Mask, {6, 2, 7, 3}))
8149     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V2, V1);
8150
8151   // Otherwise fall back to a SHUFPS lowering strategy.
8152   return lowerVectorShuffleWithSHUFPS(DL, MVT::v4f32, Mask, V1, V2, DAG);
8153 }
8154
8155 /// \brief Lower 4-lane i32 vector shuffles.
8156 ///
8157 /// We try to handle these with integer-domain shuffles where we can, but for
8158 /// blends we use the floating point domain blend instructions.
8159 static SDValue lowerV4I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8160                                        const X86Subtarget *Subtarget,
8161                                        SelectionDAG &DAG) {
8162   SDLoc DL(Op);
8163   assert(Op.getSimpleValueType() == MVT::v4i32 && "Bad shuffle type!");
8164   assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
8165   assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
8166   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8167   ArrayRef<int> Mask = SVOp->getMask();
8168   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8169
8170   // Whenever we can lower this as a zext, that instruction is strictly faster
8171   // than any alternative. It also allows us to fold memory operands into the
8172   // shuffle in many cases.
8173   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v4i32, V1, V2,
8174                                                          Mask, Subtarget, DAG))
8175     return ZExt;
8176
8177   int NumV2Elements =
8178       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8179
8180   if (NumV2Elements == 0) {
8181     // Check for being able to broadcast a single element.
8182     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i32, V1,
8183                                                           Mask, Subtarget, DAG))
8184       return Broadcast;
8185
8186     // Straight shuffle of a single input vector. For everything from SSE2
8187     // onward this has a single fast instruction with no scary immediates.
8188     // We coerce the shuffle pattern to be compatible with UNPCK instructions
8189     // but we aren't actually going to use the UNPCK instruction because doing
8190     // so prevents folding a load into this instruction or making a copy.
8191     const int UnpackLoMask[] = {0, 0, 1, 1};
8192     const int UnpackHiMask[] = {2, 2, 3, 3};
8193     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 1, 1}))
8194       Mask = UnpackLoMask;
8195     else if (isShuffleEquivalent(V1, V2, Mask, {2, 2, 3, 3}))
8196       Mask = UnpackHiMask;
8197
8198     return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
8199                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8200   }
8201
8202   // Try to use shift instructions.
8203   if (SDValue Shift =
8204           lowerVectorShuffleAsShift(DL, MVT::v4i32, V1, V2, Mask, DAG))
8205     return Shift;
8206
8207   // There are special ways we can lower some single-element blends.
8208   if (NumV2Elements == 1)
8209     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4i32, V1, V2,
8210                                                          Mask, Subtarget, DAG))
8211       return V;
8212
8213   // We have different paths for blend lowering, but they all must use the
8214   // *exact* same predicate.
8215   bool IsBlendSupported = Subtarget->hasSSE41();
8216   if (IsBlendSupported)
8217     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i32, V1, V2, Mask,
8218                                                   Subtarget, DAG))
8219       return Blend;
8220
8221   if (SDValue Masked =
8222           lowerVectorShuffleAsBitMask(DL, MVT::v4i32, V1, V2, Mask, DAG))
8223     return Masked;
8224
8225   // Use dedicated unpack instructions for masks that match their pattern.
8226   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 1, 5}))
8227     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V1, V2);
8228   if (isShuffleEquivalent(V1, V2, Mask, {2, 6, 3, 7}))
8229     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V1, V2);
8230   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 5, 1}))
8231     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V2, V1);
8232   if (isShuffleEquivalent(V1, V2, Mask, {6, 2, 7, 3}))
8233     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V2, V1);
8234
8235   // Try to use byte rotation instructions.
8236   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
8237   if (Subtarget->hasSSSE3())
8238     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8239             DL, MVT::v4i32, V1, V2, Mask, Subtarget, DAG))
8240       return Rotate;
8241
8242   // If we have direct support for blends, we should lower by decomposing into
8243   // a permute. That will be faster than the domain cross.
8244   if (IsBlendSupported)
8245     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i32, V1, V2,
8246                                                       Mask, DAG);
8247
8248   // Try to lower by permuting the inputs into an unpack instruction.
8249   if (SDValue Unpack =
8250           lowerVectorShuffleAsUnpack(DL, MVT::v4i32, V1, V2, Mask, DAG))
8251     return Unpack;
8252
8253   // We implement this with SHUFPS because it can blend from two vectors.
8254   // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
8255   // up the inputs, bypassing domain shift penalties that we would encur if we
8256   // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
8257   // relevant.
8258   return DAG.getBitcast(
8259       MVT::v4i32,
8260       DAG.getVectorShuffle(MVT::v4f32, DL, DAG.getBitcast(MVT::v4f32, V1),
8261                            DAG.getBitcast(MVT::v4f32, V2), Mask));
8262 }
8263
8264 /// \brief Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
8265 /// shuffle lowering, and the most complex part.
8266 ///
8267 /// The lowering strategy is to try to form pairs of input lanes which are
8268 /// targeted at the same half of the final vector, and then use a dword shuffle
8269 /// to place them onto the right half, and finally unpack the paired lanes into
8270 /// their final position.
8271 ///
8272 /// The exact breakdown of how to form these dword pairs and align them on the
8273 /// correct sides is really tricky. See the comments within the function for
8274 /// more of the details.
8275 ///
8276 /// This code also handles repeated 128-bit lanes of v8i16 shuffles, but each
8277 /// lane must shuffle the *exact* same way. In fact, you must pass a v8 Mask to
8278 /// this routine for it to work correctly. To shuffle a 256-bit or 512-bit i16
8279 /// vector, form the analogous 128-bit 8-element Mask.
8280 static SDValue lowerV8I16GeneralSingleInputVectorShuffle(
8281     SDLoc DL, MVT VT, SDValue V, MutableArrayRef<int> Mask,
8282     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
8283   assert(VT.getScalarType() == MVT::i16 && "Bad input type!");
8284   MVT PSHUFDVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
8285
8286   assert(Mask.size() == 8 && "Shuffle mask length doen't match!");
8287   MutableArrayRef<int> LoMask = Mask.slice(0, 4);
8288   MutableArrayRef<int> HiMask = Mask.slice(4, 4);
8289
8290   SmallVector<int, 4> LoInputs;
8291   std::copy_if(LoMask.begin(), LoMask.end(), std::back_inserter(LoInputs),
8292                [](int M) { return M >= 0; });
8293   std::sort(LoInputs.begin(), LoInputs.end());
8294   LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()), LoInputs.end());
8295   SmallVector<int, 4> HiInputs;
8296   std::copy_if(HiMask.begin(), HiMask.end(), std::back_inserter(HiInputs),
8297                [](int M) { return M >= 0; });
8298   std::sort(HiInputs.begin(), HiInputs.end());
8299   HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()), HiInputs.end());
8300   int NumLToL =
8301       std::lower_bound(LoInputs.begin(), LoInputs.end(), 4) - LoInputs.begin();
8302   int NumHToL = LoInputs.size() - NumLToL;
8303   int NumLToH =
8304       std::lower_bound(HiInputs.begin(), HiInputs.end(), 4) - HiInputs.begin();
8305   int NumHToH = HiInputs.size() - NumLToH;
8306   MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
8307   MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
8308   MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
8309   MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
8310
8311   // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
8312   // such inputs we can swap two of the dwords across the half mark and end up
8313   // with <=2 inputs to each half in each half. Once there, we can fall through
8314   // to the generic code below. For example:
8315   //
8316   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
8317   // Mask:  [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
8318   //
8319   // However in some very rare cases we have a 1-into-3 or 3-into-1 on one half
8320   // and an existing 2-into-2 on the other half. In this case we may have to
8321   // pre-shuffle the 2-into-2 half to avoid turning it into a 3-into-1 or
8322   // 1-into-3 which could cause us to cycle endlessly fixing each side in turn.
8323   // Fortunately, we don't have to handle anything but a 2-into-2 pattern
8324   // because any other situation (including a 3-into-1 or 1-into-3 in the other
8325   // half than the one we target for fixing) will be fixed when we re-enter this
8326   // path. We will also combine away any sequence of PSHUFD instructions that
8327   // result into a single instruction. Here is an example of the tricky case:
8328   //
8329   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
8330   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -THIS-IS-BAD!!!!-> [5, 7, 1, 0, 4, 7, 5, 3]
8331   //
8332   // This now has a 1-into-3 in the high half! Instead, we do two shuffles:
8333   //
8334   // Input: [a, b, c, d, e, f, g, h] PSHUFHW[0,2,1,3]-> [a, b, c, d, e, g, f, h]
8335   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -----------------> [3, 7, 1, 0, 2, 7, 3, 6]
8336   //
8337   // Input: [a, b, c, d, e, g, f, h] -PSHUFD[0,2,1,3]-> [a, b, e, g, c, d, f, h]
8338   // Mask:  [3, 7, 1, 0, 2, 7, 3, 6] -----------------> [5, 7, 1, 0, 4, 7, 5, 6]
8339   //
8340   // The result is fine to be handled by the generic logic.
8341   auto balanceSides = [&](ArrayRef<int> AToAInputs, ArrayRef<int> BToAInputs,
8342                           ArrayRef<int> BToBInputs, ArrayRef<int> AToBInputs,
8343                           int AOffset, int BOffset) {
8344     assert((AToAInputs.size() == 3 || AToAInputs.size() == 1) &&
8345            "Must call this with A having 3 or 1 inputs from the A half.");
8346     assert((BToAInputs.size() == 1 || BToAInputs.size() == 3) &&
8347            "Must call this with B having 1 or 3 inputs from the B half.");
8348     assert(AToAInputs.size() + BToAInputs.size() == 4 &&
8349            "Must call this with either 3:1 or 1:3 inputs (summing to 4).");
8350
8351     bool ThreeAInputs = AToAInputs.size() == 3;
8352
8353     // Compute the index of dword with only one word among the three inputs in
8354     // a half by taking the sum of the half with three inputs and subtracting
8355     // the sum of the actual three inputs. The difference is the remaining
8356     // slot.
8357     int ADWord, BDWord;
8358     int &TripleDWord = ThreeAInputs ? ADWord : BDWord;
8359     int &OneInputDWord = ThreeAInputs ? BDWord : ADWord;
8360     int TripleInputOffset = ThreeAInputs ? AOffset : BOffset;
8361     ArrayRef<int> TripleInputs = ThreeAInputs ? AToAInputs : BToAInputs;
8362     int OneInput = ThreeAInputs ? BToAInputs[0] : AToAInputs[0];
8363     int TripleInputSum = 0 + 1 + 2 + 3 + (4 * TripleInputOffset);
8364     int TripleNonInputIdx =
8365         TripleInputSum - std::accumulate(TripleInputs.begin(), TripleInputs.end(), 0);
8366     TripleDWord = TripleNonInputIdx / 2;
8367
8368     // We use xor with one to compute the adjacent DWord to whichever one the
8369     // OneInput is in.
8370     OneInputDWord = (OneInput / 2) ^ 1;
8371
8372     // Check for one tricky case: We're fixing a 3<-1 or a 1<-3 shuffle for AToA
8373     // and BToA inputs. If there is also such a problem with the BToB and AToB
8374     // inputs, we don't try to fix it necessarily -- we'll recurse and see it in
8375     // the next pass. However, if we have a 2<-2 in the BToB and AToB inputs, it
8376     // is essential that we don't *create* a 3<-1 as then we might oscillate.
8377     if (BToBInputs.size() == 2 && AToBInputs.size() == 2) {
8378       // Compute how many inputs will be flipped by swapping these DWords. We
8379       // need
8380       // to balance this to ensure we don't form a 3-1 shuffle in the other
8381       // half.
8382       int NumFlippedAToBInputs =
8383           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord) +
8384           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord + 1);
8385       int NumFlippedBToBInputs =
8386           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord) +
8387           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord + 1);
8388       if ((NumFlippedAToBInputs == 1 &&
8389            (NumFlippedBToBInputs == 0 || NumFlippedBToBInputs == 2)) ||
8390           (NumFlippedBToBInputs == 1 &&
8391            (NumFlippedAToBInputs == 0 || NumFlippedAToBInputs == 2))) {
8392         // We choose whether to fix the A half or B half based on whether that
8393         // half has zero flipped inputs. At zero, we may not be able to fix it
8394         // with that half. We also bias towards fixing the B half because that
8395         // will more commonly be the high half, and we have to bias one way.
8396         auto FixFlippedInputs = [&V, &DL, &Mask, &DAG](int PinnedIdx, int DWord,
8397                                                        ArrayRef<int> Inputs) {
8398           int FixIdx = PinnedIdx ^ 1; // The adjacent slot to the pinned slot.
8399           bool IsFixIdxInput = std::find(Inputs.begin(), Inputs.end(),
8400                                          PinnedIdx ^ 1) != Inputs.end();
8401           // Determine whether the free index is in the flipped dword or the
8402           // unflipped dword based on where the pinned index is. We use this bit
8403           // in an xor to conditionally select the adjacent dword.
8404           int FixFreeIdx = 2 * (DWord ^ (PinnedIdx / 2 == DWord));
8405           bool IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
8406                                              FixFreeIdx) != Inputs.end();
8407           if (IsFixIdxInput == IsFixFreeIdxInput)
8408             FixFreeIdx += 1;
8409           IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
8410                                         FixFreeIdx) != Inputs.end();
8411           assert(IsFixIdxInput != IsFixFreeIdxInput &&
8412                  "We need to be changing the number of flipped inputs!");
8413           int PSHUFHalfMask[] = {0, 1, 2, 3};
8414           std::swap(PSHUFHalfMask[FixFreeIdx % 4], PSHUFHalfMask[FixIdx % 4]);
8415           V = DAG.getNode(FixIdx < 4 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW, DL,
8416                           MVT::v8i16, V,
8417                           getV4X86ShuffleImm8ForMask(PSHUFHalfMask, DL, DAG));
8418
8419           for (int &M : Mask)
8420             if (M != -1 && M == FixIdx)
8421               M = FixFreeIdx;
8422             else if (M != -1 && M == FixFreeIdx)
8423               M = FixIdx;
8424         };
8425         if (NumFlippedBToBInputs != 0) {
8426           int BPinnedIdx =
8427               BToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
8428           FixFlippedInputs(BPinnedIdx, BDWord, BToBInputs);
8429         } else {
8430           assert(NumFlippedAToBInputs != 0 && "Impossible given predicates!");
8431           int APinnedIdx = ThreeAInputs ? TripleNonInputIdx : OneInput;
8432           FixFlippedInputs(APinnedIdx, ADWord, AToBInputs);
8433         }
8434       }
8435     }
8436
8437     int PSHUFDMask[] = {0, 1, 2, 3};
8438     PSHUFDMask[ADWord] = BDWord;
8439     PSHUFDMask[BDWord] = ADWord;
8440     V = DAG.getBitcast(
8441         VT,
8442         DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, DAG.getBitcast(PSHUFDVT, V),
8443                     getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
8444
8445     // Adjust the mask to match the new locations of A and B.
8446     for (int &M : Mask)
8447       if (M != -1 && M/2 == ADWord)
8448         M = 2 * BDWord + M % 2;
8449       else if (M != -1 && M/2 == BDWord)
8450         M = 2 * ADWord + M % 2;
8451
8452     // Recurse back into this routine to re-compute state now that this isn't
8453     // a 3 and 1 problem.
8454     return lowerV8I16GeneralSingleInputVectorShuffle(DL, VT, V, Mask, Subtarget,
8455                                                      DAG);
8456   };
8457   if ((NumLToL == 3 && NumHToL == 1) || (NumLToL == 1 && NumHToL == 3))
8458     return balanceSides(LToLInputs, HToLInputs, HToHInputs, LToHInputs, 0, 4);
8459   else if ((NumHToH == 3 && NumLToH == 1) || (NumHToH == 1 && NumLToH == 3))
8460     return balanceSides(HToHInputs, LToHInputs, LToLInputs, HToLInputs, 4, 0);
8461
8462   // At this point there are at most two inputs to the low and high halves from
8463   // each half. That means the inputs can always be grouped into dwords and
8464   // those dwords can then be moved to the correct half with a dword shuffle.
8465   // We use at most one low and one high word shuffle to collect these paired
8466   // inputs into dwords, and finally a dword shuffle to place them.
8467   int PSHUFLMask[4] = {-1, -1, -1, -1};
8468   int PSHUFHMask[4] = {-1, -1, -1, -1};
8469   int PSHUFDMask[4] = {-1, -1, -1, -1};
8470
8471   // First fix the masks for all the inputs that are staying in their
8472   // original halves. This will then dictate the targets of the cross-half
8473   // shuffles.
8474   auto fixInPlaceInputs =
8475       [&PSHUFDMask](ArrayRef<int> InPlaceInputs, ArrayRef<int> IncomingInputs,
8476                     MutableArrayRef<int> SourceHalfMask,
8477                     MutableArrayRef<int> HalfMask, int HalfOffset) {
8478     if (InPlaceInputs.empty())
8479       return;
8480     if (InPlaceInputs.size() == 1) {
8481       SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8482           InPlaceInputs[0] - HalfOffset;
8483       PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
8484       return;
8485     }
8486     if (IncomingInputs.empty()) {
8487       // Just fix all of the in place inputs.
8488       for (int Input : InPlaceInputs) {
8489         SourceHalfMask[Input - HalfOffset] = Input - HalfOffset;
8490         PSHUFDMask[Input / 2] = Input / 2;
8491       }
8492       return;
8493     }
8494
8495     assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!");
8496     SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8497         InPlaceInputs[0] - HalfOffset;
8498     // Put the second input next to the first so that they are packed into
8499     // a dword. We find the adjacent index by toggling the low bit.
8500     int AdjIndex = InPlaceInputs[0] ^ 1;
8501     SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
8502     std::replace(HalfMask.begin(), HalfMask.end(), InPlaceInputs[1], AdjIndex);
8503     PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
8504   };
8505   fixInPlaceInputs(LToLInputs, HToLInputs, PSHUFLMask, LoMask, 0);
8506   fixInPlaceInputs(HToHInputs, LToHInputs, PSHUFHMask, HiMask, 4);
8507
8508   // Now gather the cross-half inputs and place them into a free dword of
8509   // their target half.
8510   // FIXME: This operation could almost certainly be simplified dramatically to
8511   // look more like the 3-1 fixing operation.
8512   auto moveInputsToRightHalf = [&PSHUFDMask](
8513       MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
8514       MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
8515       MutableArrayRef<int> FinalSourceHalfMask, int SourceOffset,
8516       int DestOffset) {
8517     auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
8518       return SourceHalfMask[Word] != -1 && SourceHalfMask[Word] != Word;
8519     };
8520     auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
8521                                                int Word) {
8522       int LowWord = Word & ~1;
8523       int HighWord = Word | 1;
8524       return isWordClobbered(SourceHalfMask, LowWord) ||
8525              isWordClobbered(SourceHalfMask, HighWord);
8526     };
8527
8528     if (IncomingInputs.empty())
8529       return;
8530
8531     if (ExistingInputs.empty()) {
8532       // Map any dwords with inputs from them into the right half.
8533       for (int Input : IncomingInputs) {
8534         // If the source half mask maps over the inputs, turn those into
8535         // swaps and use the swapped lane.
8536         if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
8537           if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] == -1) {
8538             SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
8539                 Input - SourceOffset;
8540             // We have to swap the uses in our half mask in one sweep.
8541             for (int &M : HalfMask)
8542               if (M == SourceHalfMask[Input - SourceOffset] + SourceOffset)
8543                 M = Input;
8544               else if (M == Input)
8545                 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8546           } else {
8547             assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==
8548                        Input - SourceOffset &&
8549                    "Previous placement doesn't match!");
8550           }
8551           // Note that this correctly re-maps both when we do a swap and when
8552           // we observe the other side of the swap above. We rely on that to
8553           // avoid swapping the members of the input list directly.
8554           Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8555         }
8556
8557         // Map the input's dword into the correct half.
8558         if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] == -1)
8559           PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
8560         else
8561           assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==
8562                      Input / 2 &&
8563                  "Previous placement doesn't match!");
8564       }
8565
8566       // And just directly shift any other-half mask elements to be same-half
8567       // as we will have mirrored the dword containing the element into the
8568       // same position within that half.
8569       for (int &M : HalfMask)
8570         if (M >= SourceOffset && M < SourceOffset + 4) {
8571           M = M - SourceOffset + DestOffset;
8572           assert(M >= 0 && "This should never wrap below zero!");
8573         }
8574       return;
8575     }
8576
8577     // Ensure we have the input in a viable dword of its current half. This
8578     // is particularly tricky because the original position may be clobbered
8579     // by inputs being moved and *staying* in that half.
8580     if (IncomingInputs.size() == 1) {
8581       if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8582         int InputFixed = std::find(std::begin(SourceHalfMask),
8583                                    std::end(SourceHalfMask), -1) -
8584                          std::begin(SourceHalfMask) + SourceOffset;
8585         SourceHalfMask[InputFixed - SourceOffset] =
8586             IncomingInputs[0] - SourceOffset;
8587         std::replace(HalfMask.begin(), HalfMask.end(), IncomingInputs[0],
8588                      InputFixed);
8589         IncomingInputs[0] = InputFixed;
8590       }
8591     } else if (IncomingInputs.size() == 2) {
8592       if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
8593           isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8594         // We have two non-adjacent or clobbered inputs we need to extract from
8595         // the source half. To do this, we need to map them into some adjacent
8596         // dword slot in the source mask.
8597         int InputsFixed[2] = {IncomingInputs[0] - SourceOffset,
8598                               IncomingInputs[1] - SourceOffset};
8599
8600         // If there is a free slot in the source half mask adjacent to one of
8601         // the inputs, place the other input in it. We use (Index XOR 1) to
8602         // compute an adjacent index.
8603         if (!isWordClobbered(SourceHalfMask, InputsFixed[0]) &&
8604             SourceHalfMask[InputsFixed[0] ^ 1] == -1) {
8605           SourceHalfMask[InputsFixed[0]] = InputsFixed[0];
8606           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8607           InputsFixed[1] = InputsFixed[0] ^ 1;
8608         } else if (!isWordClobbered(SourceHalfMask, InputsFixed[1]) &&
8609                    SourceHalfMask[InputsFixed[1] ^ 1] == -1) {
8610           SourceHalfMask[InputsFixed[1]] = InputsFixed[1];
8611           SourceHalfMask[InputsFixed[1] ^ 1] = InputsFixed[0];
8612           InputsFixed[0] = InputsFixed[1] ^ 1;
8613         } else if (SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] == -1 &&
8614                    SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] == -1) {
8615           // The two inputs are in the same DWord but it is clobbered and the
8616           // adjacent DWord isn't used at all. Move both inputs to the free
8617           // slot.
8618           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] = InputsFixed[0];
8619           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] = InputsFixed[1];
8620           InputsFixed[0] = 2 * ((InputsFixed[0] / 2) ^ 1);
8621           InputsFixed[1] = 2 * ((InputsFixed[0] / 2) ^ 1) + 1;
8622         } else {
8623           // The only way we hit this point is if there is no clobbering
8624           // (because there are no off-half inputs to this half) and there is no
8625           // free slot adjacent to one of the inputs. In this case, we have to
8626           // swap an input with a non-input.
8627           for (int i = 0; i < 4; ++i)
8628             assert((SourceHalfMask[i] == -1 || SourceHalfMask[i] == i) &&
8629                    "We can't handle any clobbers here!");
8630           assert(InputsFixed[1] != (InputsFixed[0] ^ 1) &&
8631                  "Cannot have adjacent inputs here!");
8632
8633           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8634           SourceHalfMask[InputsFixed[1]] = InputsFixed[0] ^ 1;
8635
8636           // We also have to update the final source mask in this case because
8637           // it may need to undo the above swap.
8638           for (int &M : FinalSourceHalfMask)
8639             if (M == (InputsFixed[0] ^ 1) + SourceOffset)
8640               M = InputsFixed[1] + SourceOffset;
8641             else if (M == InputsFixed[1] + SourceOffset)
8642               M = (InputsFixed[0] ^ 1) + SourceOffset;
8643
8644           InputsFixed[1] = InputsFixed[0] ^ 1;
8645         }
8646
8647         // Point everything at the fixed inputs.
8648         for (int &M : HalfMask)
8649           if (M == IncomingInputs[0])
8650             M = InputsFixed[0] + SourceOffset;
8651           else if (M == IncomingInputs[1])
8652             M = InputsFixed[1] + SourceOffset;
8653
8654         IncomingInputs[0] = InputsFixed[0] + SourceOffset;
8655         IncomingInputs[1] = InputsFixed[1] + SourceOffset;
8656       }
8657     } else {
8658       llvm_unreachable("Unhandled input size!");
8659     }
8660
8661     // Now hoist the DWord down to the right half.
8662     int FreeDWord = (PSHUFDMask[DestOffset / 2] == -1 ? 0 : 1) + DestOffset / 2;
8663     assert(PSHUFDMask[FreeDWord] == -1 && "DWord not free");
8664     PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
8665     for (int &M : HalfMask)
8666       for (int Input : IncomingInputs)
8667         if (M == Input)
8668           M = FreeDWord * 2 + Input % 2;
8669   };
8670   moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask, HiMask,
8671                         /*SourceOffset*/ 4, /*DestOffset*/ 0);
8672   moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask, LoMask,
8673                         /*SourceOffset*/ 0, /*DestOffset*/ 4);
8674
8675   // Now enact all the shuffles we've computed to move the inputs into their
8676   // target half.
8677   if (!isNoopShuffleMask(PSHUFLMask))
8678     V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
8679                     getV4X86ShuffleImm8ForMask(PSHUFLMask, DL, DAG));
8680   if (!isNoopShuffleMask(PSHUFHMask))
8681     V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
8682                     getV4X86ShuffleImm8ForMask(PSHUFHMask, DL, DAG));
8683   if (!isNoopShuffleMask(PSHUFDMask))
8684     V = DAG.getBitcast(
8685         VT,
8686         DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, DAG.getBitcast(PSHUFDVT, V),
8687                     getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
8688
8689   // At this point, each half should contain all its inputs, and we can then
8690   // just shuffle them into their final position.
8691   assert(std::count_if(LoMask.begin(), LoMask.end(),
8692                        [](int M) { return M >= 4; }) == 0 &&
8693          "Failed to lift all the high half inputs to the low mask!");
8694   assert(std::count_if(HiMask.begin(), HiMask.end(),
8695                        [](int M) { return M >= 0 && M < 4; }) == 0 &&
8696          "Failed to lift all the low half inputs to the high mask!");
8697
8698   // Do a half shuffle for the low mask.
8699   if (!isNoopShuffleMask(LoMask))
8700     V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
8701                     getV4X86ShuffleImm8ForMask(LoMask, DL, DAG));
8702
8703   // Do a half shuffle with the high mask after shifting its values down.
8704   for (int &M : HiMask)
8705     if (M >= 0)
8706       M -= 4;
8707   if (!isNoopShuffleMask(HiMask))
8708     V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
8709                     getV4X86ShuffleImm8ForMask(HiMask, DL, DAG));
8710
8711   return V;
8712 }
8713
8714 /// \brief Helper to form a PSHUFB-based shuffle+blend.
8715 static SDValue lowerVectorShuffleAsPSHUFB(SDLoc DL, MVT VT, SDValue V1,
8716                                           SDValue V2, ArrayRef<int> Mask,
8717                                           SelectionDAG &DAG, bool &V1InUse,
8718                                           bool &V2InUse) {
8719   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
8720   SDValue V1Mask[16];
8721   SDValue V2Mask[16];
8722   V1InUse = false;
8723   V2InUse = false;
8724
8725   int Size = Mask.size();
8726   int Scale = 16 / Size;
8727   for (int i = 0; i < 16; ++i) {
8728     if (Mask[i / Scale] == -1) {
8729       V1Mask[i] = V2Mask[i] = DAG.getUNDEF(MVT::i8);
8730     } else {
8731       const int ZeroMask = 0x80;
8732       int V1Idx = Mask[i / Scale] < Size ? Mask[i / Scale] * Scale + i % Scale
8733                                           : ZeroMask;
8734       int V2Idx = Mask[i / Scale] < Size
8735                       ? ZeroMask
8736                       : (Mask[i / Scale] - Size) * Scale + i % Scale;
8737       if (Zeroable[i / Scale])
8738         V1Idx = V2Idx = ZeroMask;
8739       V1Mask[i] = DAG.getConstant(V1Idx, DL, MVT::i8);
8740       V2Mask[i] = DAG.getConstant(V2Idx, DL, MVT::i8);
8741       V1InUse |= (ZeroMask != V1Idx);
8742       V2InUse |= (ZeroMask != V2Idx);
8743     }
8744   }
8745
8746   if (V1InUse)
8747     V1 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
8748                      DAG.getBitcast(MVT::v16i8, V1),
8749                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V1Mask));
8750   if (V2InUse)
8751     V2 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
8752                      DAG.getBitcast(MVT::v16i8, V2),
8753                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V2Mask));
8754
8755   // If we need shuffled inputs from both, blend the two.
8756   SDValue V;
8757   if (V1InUse && V2InUse)
8758     V = DAG.getNode(ISD::OR, DL, MVT::v16i8, V1, V2);
8759   else
8760     V = V1InUse ? V1 : V2;
8761
8762   // Cast the result back to the correct type.
8763   return DAG.getBitcast(VT, V);
8764 }
8765
8766 /// \brief Generic lowering of 8-lane i16 shuffles.
8767 ///
8768 /// This handles both single-input shuffles and combined shuffle/blends with
8769 /// two inputs. The single input shuffles are immediately delegated to
8770 /// a dedicated lowering routine.
8771 ///
8772 /// The blends are lowered in one of three fundamental ways. If there are few
8773 /// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
8774 /// of the input is significantly cheaper when lowered as an interleaving of
8775 /// the two inputs, try to interleave them. Otherwise, blend the low and high
8776 /// halves of the inputs separately (making them have relatively few inputs)
8777 /// and then concatenate them.
8778 static SDValue lowerV8I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8779                                        const X86Subtarget *Subtarget,
8780                                        SelectionDAG &DAG) {
8781   SDLoc DL(Op);
8782   assert(Op.getSimpleValueType() == MVT::v8i16 && "Bad shuffle type!");
8783   assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
8784   assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
8785   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8786   ArrayRef<int> OrigMask = SVOp->getMask();
8787   int MaskStorage[8] = {OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
8788                         OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7]};
8789   MutableArrayRef<int> Mask(MaskStorage);
8790
8791   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
8792
8793   // Whenever we can lower this as a zext, that instruction is strictly faster
8794   // than any alternative.
8795   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
8796           DL, MVT::v8i16, V1, V2, OrigMask, Subtarget, DAG))
8797     return ZExt;
8798
8799   auto isV1 = [](int M) { return M >= 0 && M < 8; };
8800   (void)isV1;
8801   auto isV2 = [](int M) { return M >= 8; };
8802
8803   int NumV2Inputs = std::count_if(Mask.begin(), Mask.end(), isV2);
8804
8805   if (NumV2Inputs == 0) {
8806     // Check for being able to broadcast a single element.
8807     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i16, V1,
8808                                                           Mask, Subtarget, DAG))
8809       return Broadcast;
8810
8811     // Try to use shift instructions.
8812     if (SDValue Shift =
8813             lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V1, Mask, DAG))
8814       return Shift;
8815
8816     // Use dedicated unpack instructions for masks that match their pattern.
8817     if (isShuffleEquivalent(V1, V1, Mask, {0, 0, 1, 1, 2, 2, 3, 3}))
8818       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V1, V1);
8819     if (isShuffleEquivalent(V1, V1, Mask, {4, 4, 5, 5, 6, 6, 7, 7}))
8820       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V1, V1);
8821
8822     // Try to use byte rotation instructions.
8823     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(DL, MVT::v8i16, V1, V1,
8824                                                         Mask, Subtarget, DAG))
8825       return Rotate;
8826
8827     return lowerV8I16GeneralSingleInputVectorShuffle(DL, MVT::v8i16, V1, Mask,
8828                                                      Subtarget, DAG);
8829   }
8830
8831   assert(std::any_of(Mask.begin(), Mask.end(), isV1) &&
8832          "All single-input shuffles should be canonicalized to be V1-input "
8833          "shuffles.");
8834
8835   // Try to use shift instructions.
8836   if (SDValue Shift =
8837           lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V2, Mask, DAG))
8838     return Shift;
8839
8840   // See if we can use SSE4A Extraction / Insertion.
8841   if (Subtarget->hasSSE4A())
8842     if (SDValue V = lowerVectorShuffleWithSSE4A(DL, MVT::v8i16, V1, V2, Mask, DAG))
8843       return V;
8844
8845   // There are special ways we can lower some single-element blends.
8846   if (NumV2Inputs == 1)
8847     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v8i16, V1, V2,
8848                                                          Mask, Subtarget, DAG))
8849       return V;
8850
8851   // We have different paths for blend lowering, but they all must use the
8852   // *exact* same predicate.
8853   bool IsBlendSupported = Subtarget->hasSSE41();
8854   if (IsBlendSupported)
8855     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i16, V1, V2, Mask,
8856                                                   Subtarget, DAG))
8857       return Blend;
8858
8859   if (SDValue Masked =
8860           lowerVectorShuffleAsBitMask(DL, MVT::v8i16, V1, V2, Mask, DAG))
8861     return Masked;
8862
8863   // Use dedicated unpack instructions for masks that match their pattern.
8864   if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 2, 10, 3, 11}))
8865     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V1, V2);
8866   if (isShuffleEquivalent(V1, V2, Mask, {4, 12, 5, 13, 6, 14, 7, 15}))
8867     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V1, V2);
8868
8869   // Try to use byte rotation instructions.
8870   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8871           DL, MVT::v8i16, V1, V2, Mask, Subtarget, DAG))
8872     return Rotate;
8873
8874   if (SDValue BitBlend =
8875           lowerVectorShuffleAsBitBlend(DL, MVT::v8i16, V1, V2, Mask, DAG))
8876     return BitBlend;
8877
8878   if (SDValue Unpack =
8879           lowerVectorShuffleAsUnpack(DL, MVT::v8i16, V1, V2, Mask, DAG))
8880     return Unpack;
8881
8882   // If we can't directly blend but can use PSHUFB, that will be better as it
8883   // can both shuffle and set up the inefficient blend.
8884   if (!IsBlendSupported && Subtarget->hasSSSE3()) {
8885     bool V1InUse, V2InUse;
8886     return lowerVectorShuffleAsPSHUFB(DL, MVT::v8i16, V1, V2, Mask, DAG,
8887                                       V1InUse, V2InUse);
8888   }
8889
8890   // We can always bit-blend if we have to so the fallback strategy is to
8891   // decompose into single-input permutes and blends.
8892   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i16, V1, V2,
8893                                                       Mask, DAG);
8894 }
8895
8896 /// \brief Check whether a compaction lowering can be done by dropping even
8897 /// elements and compute how many times even elements must be dropped.
8898 ///
8899 /// This handles shuffles which take every Nth element where N is a power of
8900 /// two. Example shuffle masks:
8901 ///
8902 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14,  0,  2,  4,  6,  8, 10, 12, 14
8903 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30
8904 ///  N = 2:  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12
8905 ///  N = 2:  0,  4,  8, 12, 16, 20, 24, 28,  0,  4,  8, 12, 16, 20, 24, 28
8906 ///  N = 3:  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8
8907 ///  N = 3:  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24
8908 ///
8909 /// Any of these lanes can of course be undef.
8910 ///
8911 /// This routine only supports N <= 3.
8912 /// FIXME: Evaluate whether either AVX or AVX-512 have any opportunities here
8913 /// for larger N.
8914 ///
8915 /// \returns N above, or the number of times even elements must be dropped if
8916 /// there is such a number. Otherwise returns zero.
8917 static int canLowerByDroppingEvenElements(ArrayRef<int> Mask) {
8918   // Figure out whether we're looping over two inputs or just one.
8919   bool IsSingleInput = isSingleInputShuffleMask(Mask);
8920
8921   // The modulus for the shuffle vector entries is based on whether this is
8922   // a single input or not.
8923   int ShuffleModulus = Mask.size() * (IsSingleInput ? 1 : 2);
8924   assert(isPowerOf2_32((uint32_t)ShuffleModulus) &&
8925          "We should only be called with masks with a power-of-2 size!");
8926
8927   uint64_t ModMask = (uint64_t)ShuffleModulus - 1;
8928
8929   // We track whether the input is viable for all power-of-2 strides 2^1, 2^2,
8930   // and 2^3 simultaneously. This is because we may have ambiguity with
8931   // partially undef inputs.
8932   bool ViableForN[3] = {true, true, true};
8933
8934   for (int i = 0, e = Mask.size(); i < e; ++i) {
8935     // Ignore undef lanes, we'll optimistically collapse them to the pattern we
8936     // want.
8937     if (Mask[i] == -1)
8938       continue;
8939
8940     bool IsAnyViable = false;
8941     for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
8942       if (ViableForN[j]) {
8943         uint64_t N = j + 1;
8944
8945         // The shuffle mask must be equal to (i * 2^N) % M.
8946         if ((uint64_t)Mask[i] == (((uint64_t)i << N) & ModMask))
8947           IsAnyViable = true;
8948         else
8949           ViableForN[j] = false;
8950       }
8951     // Early exit if we exhaust the possible powers of two.
8952     if (!IsAnyViable)
8953       break;
8954   }
8955
8956   for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
8957     if (ViableForN[j])
8958       return j + 1;
8959
8960   // Return 0 as there is no viable power of two.
8961   return 0;
8962 }
8963
8964 /// \brief Generic lowering of v16i8 shuffles.
8965 ///
8966 /// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
8967 /// detect any complexity reducing interleaving. If that doesn't help, it uses
8968 /// UNPCK to spread the i8 elements across two i16-element vectors, and uses
8969 /// the existing lowering for v8i16 blends on each half, finally PACK-ing them
8970 /// back together.
8971 static SDValue lowerV16I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8972                                        const X86Subtarget *Subtarget,
8973                                        SelectionDAG &DAG) {
8974   SDLoc DL(Op);
8975   assert(Op.getSimpleValueType() == MVT::v16i8 && "Bad shuffle type!");
8976   assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
8977   assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
8978   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8979   ArrayRef<int> Mask = SVOp->getMask();
8980   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
8981
8982   // Try to use shift instructions.
8983   if (SDValue Shift =
8984           lowerVectorShuffleAsShift(DL, MVT::v16i8, V1, V2, Mask, DAG))
8985     return Shift;
8986
8987   // Try to use byte rotation instructions.
8988   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8989           DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
8990     return Rotate;
8991
8992   // Try to use a zext lowering.
8993   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
8994           DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
8995     return ZExt;
8996
8997   // See if we can use SSE4A Extraction / Insertion.
8998   if (Subtarget->hasSSE4A())
8999     if (SDValue V = lowerVectorShuffleWithSSE4A(DL, MVT::v16i8, V1, V2, Mask, DAG))
9000       return V;
9001
9002   int NumV2Elements =
9003       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 16; });
9004
9005   // For single-input shuffles, there are some nicer lowering tricks we can use.
9006   if (NumV2Elements == 0) {
9007     // Check for being able to broadcast a single element.
9008     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i8, V1,
9009                                                           Mask, Subtarget, DAG))
9010       return Broadcast;
9011
9012     // Check whether we can widen this to an i16 shuffle by duplicating bytes.
9013     // Notably, this handles splat and partial-splat shuffles more efficiently.
9014     // However, it only makes sense if the pre-duplication shuffle simplifies
9015     // things significantly. Currently, this means we need to be able to
9016     // express the pre-duplication shuffle as an i16 shuffle.
9017     //
9018     // FIXME: We should check for other patterns which can be widened into an
9019     // i16 shuffle as well.
9020     auto canWidenViaDuplication = [](ArrayRef<int> Mask) {
9021       for (int i = 0; i < 16; i += 2)
9022         if (Mask[i] != -1 && Mask[i + 1] != -1 && Mask[i] != Mask[i + 1])
9023           return false;
9024
9025       return true;
9026     };
9027     auto tryToWidenViaDuplication = [&]() -> SDValue {
9028       if (!canWidenViaDuplication(Mask))
9029         return SDValue();
9030       SmallVector<int, 4> LoInputs;
9031       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(LoInputs),
9032                    [](int M) { return M >= 0 && M < 8; });
9033       std::sort(LoInputs.begin(), LoInputs.end());
9034       LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()),
9035                      LoInputs.end());
9036       SmallVector<int, 4> HiInputs;
9037       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(HiInputs),
9038                    [](int M) { return M >= 8; });
9039       std::sort(HiInputs.begin(), HiInputs.end());
9040       HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()),
9041                      HiInputs.end());
9042
9043       bool TargetLo = LoInputs.size() >= HiInputs.size();
9044       ArrayRef<int> InPlaceInputs = TargetLo ? LoInputs : HiInputs;
9045       ArrayRef<int> MovingInputs = TargetLo ? HiInputs : LoInputs;
9046
9047       int PreDupI16Shuffle[] = {-1, -1, -1, -1, -1, -1, -1, -1};
9048       SmallDenseMap<int, int, 8> LaneMap;
9049       for (int I : InPlaceInputs) {
9050         PreDupI16Shuffle[I/2] = I/2;
9051         LaneMap[I] = I;
9052       }
9053       int j = TargetLo ? 0 : 4, je = j + 4;
9054       for (int i = 0, ie = MovingInputs.size(); i < ie; ++i) {
9055         // Check if j is already a shuffle of this input. This happens when
9056         // there are two adjacent bytes after we move the low one.
9057         if (PreDupI16Shuffle[j] != MovingInputs[i] / 2) {
9058           // If we haven't yet mapped the input, search for a slot into which
9059           // we can map it.
9060           while (j < je && PreDupI16Shuffle[j] != -1)
9061             ++j;
9062
9063           if (j == je)
9064             // We can't place the inputs into a single half with a simple i16 shuffle, so bail.
9065             return SDValue();
9066
9067           // Map this input with the i16 shuffle.
9068           PreDupI16Shuffle[j] = MovingInputs[i] / 2;
9069         }
9070
9071         // Update the lane map based on the mapping we ended up with.
9072         LaneMap[MovingInputs[i]] = 2 * j + MovingInputs[i] % 2;
9073       }
9074       V1 = DAG.getBitcast(
9075           MVT::v16i8,
9076           DAG.getVectorShuffle(MVT::v8i16, DL, DAG.getBitcast(MVT::v8i16, V1),
9077                                DAG.getUNDEF(MVT::v8i16), PreDupI16Shuffle));
9078
9079       // Unpack the bytes to form the i16s that will be shuffled into place.
9080       V1 = DAG.getNode(TargetLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
9081                        MVT::v16i8, V1, V1);
9082
9083       int PostDupI16Shuffle[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9084       for (int i = 0; i < 16; ++i)
9085         if (Mask[i] != -1) {
9086           int MappedMask = LaneMap[Mask[i]] - (TargetLo ? 0 : 8);
9087           assert(MappedMask < 8 && "Invalid v8 shuffle mask!");
9088           if (PostDupI16Shuffle[i / 2] == -1)
9089             PostDupI16Shuffle[i / 2] = MappedMask;
9090           else
9091             assert(PostDupI16Shuffle[i / 2] == MappedMask &&
9092                    "Conflicting entrties in the original shuffle!");
9093         }
9094       return DAG.getBitcast(
9095           MVT::v16i8,
9096           DAG.getVectorShuffle(MVT::v8i16, DL, DAG.getBitcast(MVT::v8i16, V1),
9097                                DAG.getUNDEF(MVT::v8i16), PostDupI16Shuffle));
9098     };
9099     if (SDValue V = tryToWidenViaDuplication())
9100       return V;
9101   }
9102
9103   if (SDValue Masked =
9104           lowerVectorShuffleAsBitMask(DL, MVT::v16i8, V1, V2, Mask, DAG))
9105     return Masked;
9106
9107   // Use dedicated unpack instructions for masks that match their pattern.
9108   if (isShuffleEquivalent(V1, V2, Mask, {// Low half.
9109                                          0, 16, 1, 17, 2, 18, 3, 19,
9110                                          // High half.
9111                                          4, 20, 5, 21, 6, 22, 7, 23}))
9112     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V1, V2);
9113   if (isShuffleEquivalent(V1, V2, Mask, {// Low half.
9114                                          8, 24, 9, 25, 10, 26, 11, 27,
9115                                          // High half.
9116                                          12, 28, 13, 29, 14, 30, 15, 31}))
9117     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V1, V2);
9118
9119   // Check for SSSE3 which lets us lower all v16i8 shuffles much more directly
9120   // with PSHUFB. It is important to do this before we attempt to generate any
9121   // blends but after all of the single-input lowerings. If the single input
9122   // lowerings can find an instruction sequence that is faster than a PSHUFB, we
9123   // want to preserve that and we can DAG combine any longer sequences into
9124   // a PSHUFB in the end. But once we start blending from multiple inputs,
9125   // the complexity of DAG combining bad patterns back into PSHUFB is too high,
9126   // and there are *very* few patterns that would actually be faster than the
9127   // PSHUFB approach because of its ability to zero lanes.
9128   //
9129   // FIXME: The only exceptions to the above are blends which are exact
9130   // interleavings with direct instructions supporting them. We currently don't
9131   // handle those well here.
9132   if (Subtarget->hasSSSE3()) {
9133     bool V1InUse = false;
9134     bool V2InUse = false;
9135
9136     SDValue PSHUFB = lowerVectorShuffleAsPSHUFB(DL, MVT::v16i8, V1, V2, Mask,
9137                                                 DAG, V1InUse, V2InUse);
9138
9139     // If both V1 and V2 are in use and we can use a direct blend or an unpack,
9140     // do so. This avoids using them to handle blends-with-zero which is
9141     // important as a single pshufb is significantly faster for that.
9142     if (V1InUse && V2InUse) {
9143       if (Subtarget->hasSSE41())
9144         if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i8, V1, V2,
9145                                                       Mask, Subtarget, DAG))
9146           return Blend;
9147
9148       // We can use an unpack to do the blending rather than an or in some
9149       // cases. Even though the or may be (very minorly) more efficient, we
9150       // preference this lowering because there are common cases where part of
9151       // the complexity of the shuffles goes away when we do the final blend as
9152       // an unpack.
9153       // FIXME: It might be worth trying to detect if the unpack-feeding
9154       // shuffles will both be pshufb, in which case we shouldn't bother with
9155       // this.
9156       if (SDValue Unpack =
9157               lowerVectorShuffleAsUnpack(DL, MVT::v16i8, V1, V2, Mask, DAG))
9158         return Unpack;
9159     }
9160
9161     return PSHUFB;
9162   }
9163
9164   // There are special ways we can lower some single-element blends.
9165   if (NumV2Elements == 1)
9166     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v16i8, V1, V2,
9167                                                          Mask, Subtarget, DAG))
9168       return V;
9169
9170   if (SDValue BitBlend =
9171           lowerVectorShuffleAsBitBlend(DL, MVT::v16i8, V1, V2, Mask, DAG))
9172     return BitBlend;
9173
9174   // Check whether a compaction lowering can be done. This handles shuffles
9175   // which take every Nth element for some even N. See the helper function for
9176   // details.
9177   //
9178   // We special case these as they can be particularly efficiently handled with
9179   // the PACKUSB instruction on x86 and they show up in common patterns of
9180   // rearranging bytes to truncate wide elements.
9181   if (int NumEvenDrops = canLowerByDroppingEvenElements(Mask)) {
9182     // NumEvenDrops is the power of two stride of the elements. Another way of
9183     // thinking about it is that we need to drop the even elements this many
9184     // times to get the original input.
9185     bool IsSingleInput = isSingleInputShuffleMask(Mask);
9186
9187     // First we need to zero all the dropped bytes.
9188     assert(NumEvenDrops <= 3 &&
9189            "No support for dropping even elements more than 3 times.");
9190     // We use the mask type to pick which bytes are preserved based on how many
9191     // elements are dropped.
9192     MVT MaskVTs[] = { MVT::v8i16, MVT::v4i32, MVT::v2i64 };
9193     SDValue ByteClearMask = DAG.getBitcast(
9194         MVT::v16i8, DAG.getConstant(0xFF, DL, MaskVTs[NumEvenDrops - 1]));
9195     V1 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V1, ByteClearMask);
9196     if (!IsSingleInput)
9197       V2 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V2, ByteClearMask);
9198
9199     // Now pack things back together.
9200     V1 = DAG.getBitcast(MVT::v8i16, V1);
9201     V2 = IsSingleInput ? V1 : DAG.getBitcast(MVT::v8i16, V2);
9202     SDValue Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, V1, V2);
9203     for (int i = 1; i < NumEvenDrops; ++i) {
9204       Result = DAG.getBitcast(MVT::v8i16, Result);
9205       Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, Result, Result);
9206     }
9207
9208     return Result;
9209   }
9210
9211   // Handle multi-input cases by blending single-input shuffles.
9212   if (NumV2Elements > 0)
9213     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v16i8, V1, V2,
9214                                                       Mask, DAG);
9215
9216   // The fallback path for single-input shuffles widens this into two v8i16
9217   // vectors with unpacks, shuffles those, and then pulls them back together
9218   // with a pack.
9219   SDValue V = V1;
9220
9221   int LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9222   int HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9223   for (int i = 0; i < 16; ++i)
9224     if (Mask[i] >= 0)
9225       (i < 8 ? LoBlendMask[i] : HiBlendMask[i % 8]) = Mask[i];
9226
9227   SDValue Zero = getZeroVector(MVT::v8i16, Subtarget, DAG, DL);
9228
9229   SDValue VLoHalf, VHiHalf;
9230   // Check if any of the odd lanes in the v16i8 are used. If not, we can mask
9231   // them out and avoid using UNPCK{L,H} to extract the elements of V as
9232   // i16s.
9233   if (std::none_of(std::begin(LoBlendMask), std::end(LoBlendMask),
9234                    [](int M) { return M >= 0 && M % 2 == 1; }) &&
9235       std::none_of(std::begin(HiBlendMask), std::end(HiBlendMask),
9236                    [](int M) { return M >= 0 && M % 2 == 1; })) {
9237     // Use a mask to drop the high bytes.
9238     VLoHalf = DAG.getBitcast(MVT::v8i16, V);
9239     VLoHalf = DAG.getNode(ISD::AND, DL, MVT::v8i16, VLoHalf,
9240                      DAG.getConstant(0x00FF, DL, MVT::v8i16));
9241
9242     // This will be a single vector shuffle instead of a blend so nuke VHiHalf.
9243     VHiHalf = DAG.getUNDEF(MVT::v8i16);
9244
9245     // Squash the masks to point directly into VLoHalf.
9246     for (int &M : LoBlendMask)
9247       if (M >= 0)
9248         M /= 2;
9249     for (int &M : HiBlendMask)
9250       if (M >= 0)
9251         M /= 2;
9252   } else {
9253     // Otherwise just unpack the low half of V into VLoHalf and the high half into
9254     // VHiHalf so that we can blend them as i16s.
9255     VLoHalf = DAG.getBitcast(
9256         MVT::v8i16, DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V, Zero));
9257     VHiHalf = DAG.getBitcast(
9258         MVT::v8i16, DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V, Zero));
9259   }
9260
9261   SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, LoBlendMask);
9262   SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, HiBlendMask);
9263
9264   return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
9265 }
9266
9267 /// \brief Dispatching routine to lower various 128-bit x86 vector shuffles.
9268 ///
9269 /// This routine breaks down the specific type of 128-bit shuffle and
9270 /// dispatches to the lowering routines accordingly.
9271 static SDValue lower128BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9272                                         MVT VT, const X86Subtarget *Subtarget,
9273                                         SelectionDAG &DAG) {
9274   switch (VT.SimpleTy) {
9275   case MVT::v2i64:
9276     return lowerV2I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9277   case MVT::v2f64:
9278     return lowerV2F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9279   case MVT::v4i32:
9280     return lowerV4I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9281   case MVT::v4f32:
9282     return lowerV4F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9283   case MVT::v8i16:
9284     return lowerV8I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
9285   case MVT::v16i8:
9286     return lowerV16I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
9287
9288   default:
9289     llvm_unreachable("Unimplemented!");
9290   }
9291 }
9292
9293 /// \brief Helper function to test whether a shuffle mask could be
9294 /// simplified by widening the elements being shuffled.
9295 ///
9296 /// Appends the mask for wider elements in WidenedMask if valid. Otherwise
9297 /// leaves it in an unspecified state.
9298 ///
9299 /// NOTE: This must handle normal vector shuffle masks and *target* vector
9300 /// shuffle masks. The latter have the special property of a '-2' representing
9301 /// a zero-ed lane of a vector.
9302 static bool canWidenShuffleElements(ArrayRef<int> Mask,
9303                                     SmallVectorImpl<int> &WidenedMask) {
9304   for (int i = 0, Size = Mask.size(); i < Size; i += 2) {
9305     // If both elements are undef, its trivial.
9306     if (Mask[i] == SM_SentinelUndef && Mask[i + 1] == SM_SentinelUndef) {
9307       WidenedMask.push_back(SM_SentinelUndef);
9308       continue;
9309     }
9310
9311     // Check for an undef mask and a mask value properly aligned to fit with
9312     // a pair of values. If we find such a case, use the non-undef mask's value.
9313     if (Mask[i] == SM_SentinelUndef && Mask[i + 1] >= 0 && Mask[i + 1] % 2 == 1) {
9314       WidenedMask.push_back(Mask[i + 1] / 2);
9315       continue;
9316     }
9317     if (Mask[i + 1] == SM_SentinelUndef && Mask[i] >= 0 && Mask[i] % 2 == 0) {
9318       WidenedMask.push_back(Mask[i] / 2);
9319       continue;
9320     }
9321
9322     // When zeroing, we need to spread the zeroing across both lanes to widen.
9323     if (Mask[i] == SM_SentinelZero || Mask[i + 1] == SM_SentinelZero) {
9324       if ((Mask[i] == SM_SentinelZero || Mask[i] == SM_SentinelUndef) &&
9325           (Mask[i + 1] == SM_SentinelZero || Mask[i + 1] == SM_SentinelUndef)) {
9326         WidenedMask.push_back(SM_SentinelZero);
9327         continue;
9328       }
9329       return false;
9330     }
9331
9332     // Finally check if the two mask values are adjacent and aligned with
9333     // a pair.
9334     if (Mask[i] != SM_SentinelUndef && Mask[i] % 2 == 0 && Mask[i] + 1 == Mask[i + 1]) {
9335       WidenedMask.push_back(Mask[i] / 2);
9336       continue;
9337     }
9338
9339     // Otherwise we can't safely widen the elements used in this shuffle.
9340     return false;
9341   }
9342   assert(WidenedMask.size() == Mask.size() / 2 &&
9343          "Incorrect size of mask after widening the elements!");
9344
9345   return true;
9346 }
9347
9348 /// \brief Generic routine to split vector shuffle into half-sized shuffles.
9349 ///
9350 /// This routine just extracts two subvectors, shuffles them independently, and
9351 /// then concatenates them back together. This should work effectively with all
9352 /// AVX vector shuffle types.
9353 static SDValue splitAndLowerVectorShuffle(SDLoc DL, MVT VT, SDValue V1,
9354                                           SDValue V2, ArrayRef<int> Mask,
9355                                           SelectionDAG &DAG) {
9356   assert(VT.getSizeInBits() >= 256 &&
9357          "Only for 256-bit or wider vector shuffles!");
9358   assert(V1.getSimpleValueType() == VT && "Bad operand type!");
9359   assert(V2.getSimpleValueType() == VT && "Bad operand type!");
9360
9361   ArrayRef<int> LoMask = Mask.slice(0, Mask.size() / 2);
9362   ArrayRef<int> HiMask = Mask.slice(Mask.size() / 2);
9363
9364   int NumElements = VT.getVectorNumElements();
9365   int SplitNumElements = NumElements / 2;
9366   MVT ScalarVT = VT.getScalarType();
9367   MVT SplitVT = MVT::getVectorVT(ScalarVT, NumElements / 2);
9368
9369   // Rather than splitting build-vectors, just build two narrower build
9370   // vectors. This helps shuffling with splats and zeros.
9371   auto SplitVector = [&](SDValue V) {
9372     while (V.getOpcode() == ISD::BITCAST)
9373       V = V->getOperand(0);
9374
9375     MVT OrigVT = V.getSimpleValueType();
9376     int OrigNumElements = OrigVT.getVectorNumElements();
9377     int OrigSplitNumElements = OrigNumElements / 2;
9378     MVT OrigScalarVT = OrigVT.getScalarType();
9379     MVT OrigSplitVT = MVT::getVectorVT(OrigScalarVT, OrigNumElements / 2);
9380
9381     SDValue LoV, HiV;
9382
9383     auto *BV = dyn_cast<BuildVectorSDNode>(V);
9384     if (!BV) {
9385       LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
9386                         DAG.getIntPtrConstant(0, DL));
9387       HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
9388                         DAG.getIntPtrConstant(OrigSplitNumElements, DL));
9389     } else {
9390
9391       SmallVector<SDValue, 16> LoOps, HiOps;
9392       for (int i = 0; i < OrigSplitNumElements; ++i) {
9393         LoOps.push_back(BV->getOperand(i));
9394         HiOps.push_back(BV->getOperand(i + OrigSplitNumElements));
9395       }
9396       LoV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, LoOps);
9397       HiV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, HiOps);
9398     }
9399     return std::make_pair(DAG.getBitcast(SplitVT, LoV),
9400                           DAG.getBitcast(SplitVT, HiV));
9401   };
9402
9403   SDValue LoV1, HiV1, LoV2, HiV2;
9404   std::tie(LoV1, HiV1) = SplitVector(V1);
9405   std::tie(LoV2, HiV2) = SplitVector(V2);
9406
9407   // Now create two 4-way blends of these half-width vectors.
9408   auto HalfBlend = [&](ArrayRef<int> HalfMask) {
9409     bool UseLoV1 = false, UseHiV1 = false, UseLoV2 = false, UseHiV2 = false;
9410     SmallVector<int, 32> V1BlendMask, V2BlendMask, BlendMask;
9411     for (int i = 0; i < SplitNumElements; ++i) {
9412       int M = HalfMask[i];
9413       if (M >= NumElements) {
9414         if (M >= NumElements + SplitNumElements)
9415           UseHiV2 = true;
9416         else
9417           UseLoV2 = true;
9418         V2BlendMask.push_back(M - NumElements);
9419         V1BlendMask.push_back(-1);
9420         BlendMask.push_back(SplitNumElements + i);
9421       } else if (M >= 0) {
9422         if (M >= SplitNumElements)
9423           UseHiV1 = true;
9424         else
9425           UseLoV1 = true;
9426         V2BlendMask.push_back(-1);
9427         V1BlendMask.push_back(M);
9428         BlendMask.push_back(i);
9429       } else {
9430         V2BlendMask.push_back(-1);
9431         V1BlendMask.push_back(-1);
9432         BlendMask.push_back(-1);
9433       }
9434     }
9435
9436     // Because the lowering happens after all combining takes place, we need to
9437     // manually combine these blend masks as much as possible so that we create
9438     // a minimal number of high-level vector shuffle nodes.
9439
9440     // First try just blending the halves of V1 or V2.
9441     if (!UseLoV1 && !UseHiV1 && !UseLoV2 && !UseHiV2)
9442       return DAG.getUNDEF(SplitVT);
9443     if (!UseLoV2 && !UseHiV2)
9444       return DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9445     if (!UseLoV1 && !UseHiV1)
9446       return DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9447
9448     SDValue V1Blend, V2Blend;
9449     if (UseLoV1 && UseHiV1) {
9450       V1Blend =
9451         DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9452     } else {
9453       // We only use half of V1 so map the usage down into the final blend mask.
9454       V1Blend = UseLoV1 ? LoV1 : HiV1;
9455       for (int i = 0; i < SplitNumElements; ++i)
9456         if (BlendMask[i] >= 0 && BlendMask[i] < SplitNumElements)
9457           BlendMask[i] = V1BlendMask[i] - (UseLoV1 ? 0 : SplitNumElements);
9458     }
9459     if (UseLoV2 && UseHiV2) {
9460       V2Blend =
9461         DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9462     } else {
9463       // We only use half of V2 so map the usage down into the final blend mask.
9464       V2Blend = UseLoV2 ? LoV2 : HiV2;
9465       for (int i = 0; i < SplitNumElements; ++i)
9466         if (BlendMask[i] >= SplitNumElements)
9467           BlendMask[i] = V2BlendMask[i] + (UseLoV2 ? SplitNumElements : 0);
9468     }
9469     return DAG.getVectorShuffle(SplitVT, DL, V1Blend, V2Blend, BlendMask);
9470   };
9471   SDValue Lo = HalfBlend(LoMask);
9472   SDValue Hi = HalfBlend(HiMask);
9473   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
9474 }
9475
9476 /// \brief Either split a vector in halves or decompose the shuffles and the
9477 /// blend.
9478 ///
9479 /// This is provided as a good fallback for many lowerings of non-single-input
9480 /// shuffles with more than one 128-bit lane. In those cases, we want to select
9481 /// between splitting the shuffle into 128-bit components and stitching those
9482 /// back together vs. extracting the single-input shuffles and blending those
9483 /// results.
9484 static SDValue lowerVectorShuffleAsSplitOrBlend(SDLoc DL, MVT VT, SDValue V1,
9485                                                 SDValue V2, ArrayRef<int> Mask,
9486                                                 SelectionDAG &DAG) {
9487   assert(!isSingleInputShuffleMask(Mask) && "This routine must not be used to "
9488                                             "lower single-input shuffles as it "
9489                                             "could then recurse on itself.");
9490   int Size = Mask.size();
9491
9492   // If this can be modeled as a broadcast of two elements followed by a blend,
9493   // prefer that lowering. This is especially important because broadcasts can
9494   // often fold with memory operands.
9495   auto DoBothBroadcast = [&] {
9496     int V1BroadcastIdx = -1, V2BroadcastIdx = -1;
9497     for (int M : Mask)
9498       if (M >= Size) {
9499         if (V2BroadcastIdx == -1)
9500           V2BroadcastIdx = M - Size;
9501         else if (M - Size != V2BroadcastIdx)
9502           return false;
9503       } else if (M >= 0) {
9504         if (V1BroadcastIdx == -1)
9505           V1BroadcastIdx = M;
9506         else if (M != V1BroadcastIdx)
9507           return false;
9508       }
9509     return true;
9510   };
9511   if (DoBothBroadcast())
9512     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask,
9513                                                       DAG);
9514
9515   // If the inputs all stem from a single 128-bit lane of each input, then we
9516   // split them rather than blending because the split will decompose to
9517   // unusually few instructions.
9518   int LaneCount = VT.getSizeInBits() / 128;
9519   int LaneSize = Size / LaneCount;
9520   SmallBitVector LaneInputs[2];
9521   LaneInputs[0].resize(LaneCount, false);
9522   LaneInputs[1].resize(LaneCount, false);
9523   for (int i = 0; i < Size; ++i)
9524     if (Mask[i] >= 0)
9525       LaneInputs[Mask[i] / Size][(Mask[i] % Size) / LaneSize] = true;
9526   if (LaneInputs[0].count() <= 1 && LaneInputs[1].count() <= 1)
9527     return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9528
9529   // Otherwise, just fall back to decomposed shuffles and a blend. This requires
9530   // that the decomposed single-input shuffles don't end up here.
9531   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9532 }
9533
9534 /// \brief Lower a vector shuffle crossing multiple 128-bit lanes as
9535 /// a permutation and blend of those lanes.
9536 ///
9537 /// This essentially blends the out-of-lane inputs to each lane into the lane
9538 /// from a permuted copy of the vector. This lowering strategy results in four
9539 /// instructions in the worst case for a single-input cross lane shuffle which
9540 /// is lower than any other fully general cross-lane shuffle strategy I'm aware
9541 /// of. Special cases for each particular shuffle pattern should be handled
9542 /// prior to trying this lowering.
9543 static SDValue lowerVectorShuffleAsLanePermuteAndBlend(SDLoc DL, MVT VT,
9544                                                        SDValue V1, SDValue V2,
9545                                                        ArrayRef<int> Mask,
9546                                                        SelectionDAG &DAG) {
9547   // FIXME: This should probably be generalized for 512-bit vectors as well.
9548   assert(VT.getSizeInBits() == 256 && "Only for 256-bit vector shuffles!");
9549   int LaneSize = Mask.size() / 2;
9550
9551   // If there are only inputs from one 128-bit lane, splitting will in fact be
9552   // less expensive. The flags track whether the given lane contains an element
9553   // that crosses to another lane.
9554   bool LaneCrossing[2] = {false, false};
9555   for (int i = 0, Size = Mask.size(); i < Size; ++i)
9556     if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
9557       LaneCrossing[(Mask[i] % Size) / LaneSize] = true;
9558   if (!LaneCrossing[0] || !LaneCrossing[1])
9559     return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9560
9561   if (isSingleInputShuffleMask(Mask)) {
9562     SmallVector<int, 32> FlippedBlendMask;
9563     for (int i = 0, Size = Mask.size(); i < Size; ++i)
9564       FlippedBlendMask.push_back(
9565           Mask[i] < 0 ? -1 : (((Mask[i] % Size) / LaneSize == i / LaneSize)
9566                                   ? Mask[i]
9567                                   : Mask[i] % LaneSize +
9568                                         (i / LaneSize) * LaneSize + Size));
9569
9570     // Flip the vector, and blend the results which should now be in-lane. The
9571     // VPERM2X128 mask uses the low 2 bits for the low source and bits 4 and
9572     // 5 for the high source. The value 3 selects the high half of source 2 and
9573     // the value 2 selects the low half of source 2. We only use source 2 to
9574     // allow folding it into a memory operand.
9575     unsigned PERMMask = 3 | 2 << 4;
9576     SDValue Flipped = DAG.getNode(X86ISD::VPERM2X128, DL, VT, DAG.getUNDEF(VT),
9577                                   V1, DAG.getConstant(PERMMask, DL, MVT::i8));
9578     return DAG.getVectorShuffle(VT, DL, V1, Flipped, FlippedBlendMask);
9579   }
9580
9581   // This now reduces to two single-input shuffles of V1 and V2 which at worst
9582   // will be handled by the above logic and a blend of the results, much like
9583   // other patterns in AVX.
9584   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9585 }
9586
9587 /// \brief Handle lowering 2-lane 128-bit shuffles.
9588 static SDValue lowerV2X128VectorShuffle(SDLoc DL, MVT VT, SDValue V1,
9589                                         SDValue V2, ArrayRef<int> Mask,
9590                                         const X86Subtarget *Subtarget,
9591                                         SelectionDAG &DAG) {
9592   // TODO: If minimizing size and one of the inputs is a zero vector and the
9593   // the zero vector has only one use, we could use a VPERM2X128 to save the
9594   // instruction bytes needed to explicitly generate the zero vector.
9595
9596   // Blends are faster and handle all the non-lane-crossing cases.
9597   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, VT, V1, V2, Mask,
9598                                                 Subtarget, DAG))
9599     return Blend;
9600
9601   bool IsV1Zero = ISD::isBuildVectorAllZeros(V1.getNode());
9602   bool IsV2Zero = ISD::isBuildVectorAllZeros(V2.getNode());
9603
9604   // If either input operand is a zero vector, use VPERM2X128 because its mask
9605   // allows us to replace the zero input with an implicit zero.
9606   if (!IsV1Zero && !IsV2Zero) {
9607     // Check for patterns which can be matched with a single insert of a 128-bit
9608     // subvector.
9609     bool OnlyUsesV1 = isShuffleEquivalent(V1, V2, Mask, {0, 1, 0, 1});
9610     if (OnlyUsesV1 || isShuffleEquivalent(V1, V2, Mask, {0, 1, 4, 5})) {
9611       MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(),
9612                                    VT.getVectorNumElements() / 2);
9613       SDValue LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V1,
9614                                 DAG.getIntPtrConstant(0, DL));
9615       SDValue HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT,
9616                                 OnlyUsesV1 ? V1 : V2,
9617                                 DAG.getIntPtrConstant(0, DL));
9618       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LoV, HiV);
9619     }
9620   }
9621
9622   // Otherwise form a 128-bit permutation. After accounting for undefs,
9623   // convert the 64-bit shuffle mask selection values into 128-bit
9624   // selection bits by dividing the indexes by 2 and shifting into positions
9625   // defined by a vperm2*128 instruction's immediate control byte.
9626
9627   // The immediate permute control byte looks like this:
9628   //    [1:0] - select 128 bits from sources for low half of destination
9629   //    [2]   - ignore
9630   //    [3]   - zero low half of destination
9631   //    [5:4] - select 128 bits from sources for high half of destination
9632   //    [6]   - ignore
9633   //    [7]   - zero high half of destination
9634
9635   int MaskLO = Mask[0];
9636   if (MaskLO == SM_SentinelUndef)
9637     MaskLO = Mask[1] == SM_SentinelUndef ? 0 : Mask[1];
9638
9639   int MaskHI = Mask[2];
9640   if (MaskHI == SM_SentinelUndef)
9641     MaskHI = Mask[3] == SM_SentinelUndef ? 0 : Mask[3];
9642
9643   unsigned PermMask = MaskLO / 2 | (MaskHI / 2) << 4;
9644
9645   // If either input is a zero vector, replace it with an undef input.
9646   // Shuffle mask values <  4 are selecting elements of V1.
9647   // Shuffle mask values >= 4 are selecting elements of V2.
9648   // Adjust each half of the permute mask by clearing the half that was
9649   // selecting the zero vector and setting the zero mask bit.
9650   if (IsV1Zero) {
9651     V1 = DAG.getUNDEF(VT);
9652     if (MaskLO < 4)
9653       PermMask = (PermMask & 0xf0) | 0x08;
9654     if (MaskHI < 4)
9655       PermMask = (PermMask & 0x0f) | 0x80;
9656   }
9657   if (IsV2Zero) {
9658     V2 = DAG.getUNDEF(VT);
9659     if (MaskLO >= 4)
9660       PermMask = (PermMask & 0xf0) | 0x08;
9661     if (MaskHI >= 4)
9662       PermMask = (PermMask & 0x0f) | 0x80;
9663   }
9664
9665   return DAG.getNode(X86ISD::VPERM2X128, DL, VT, V1, V2,
9666                      DAG.getConstant(PermMask, DL, MVT::i8));
9667 }
9668
9669 /// \brief Lower a vector shuffle by first fixing the 128-bit lanes and then
9670 /// shuffling each lane.
9671 ///
9672 /// This will only succeed when the result of fixing the 128-bit lanes results
9673 /// in a single-input non-lane-crossing shuffle with a repeating shuffle mask in
9674 /// each 128-bit lanes. This handles many cases where we can quickly blend away
9675 /// the lane crosses early and then use simpler shuffles within each lane.
9676 ///
9677 /// FIXME: It might be worthwhile at some point to support this without
9678 /// requiring the 128-bit lane-relative shuffles to be repeating, but currently
9679 /// in x86 only floating point has interesting non-repeating shuffles, and even
9680 /// those are still *marginally* more expensive.
9681 static SDValue lowerVectorShuffleByMerging128BitLanes(
9682     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
9683     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
9684   assert(!isSingleInputShuffleMask(Mask) &&
9685          "This is only useful with multiple inputs.");
9686
9687   int Size = Mask.size();
9688   int LaneSize = 128 / VT.getScalarSizeInBits();
9689   int NumLanes = Size / LaneSize;
9690   assert(NumLanes > 1 && "Only handles 256-bit and wider shuffles.");
9691
9692   // See if we can build a hypothetical 128-bit lane-fixing shuffle mask. Also
9693   // check whether the in-128-bit lane shuffles share a repeating pattern.
9694   SmallVector<int, 4> Lanes;
9695   Lanes.resize(NumLanes, -1);
9696   SmallVector<int, 4> InLaneMask;
9697   InLaneMask.resize(LaneSize, -1);
9698   for (int i = 0; i < Size; ++i) {
9699     if (Mask[i] < 0)
9700       continue;
9701
9702     int j = i / LaneSize;
9703
9704     if (Lanes[j] < 0) {
9705       // First entry we've seen for this lane.
9706       Lanes[j] = Mask[i] / LaneSize;
9707     } else if (Lanes[j] != Mask[i] / LaneSize) {
9708       // This doesn't match the lane selected previously!
9709       return SDValue();
9710     }
9711
9712     // Check that within each lane we have a consistent shuffle mask.
9713     int k = i % LaneSize;
9714     if (InLaneMask[k] < 0) {
9715       InLaneMask[k] = Mask[i] % LaneSize;
9716     } else if (InLaneMask[k] != Mask[i] % LaneSize) {
9717       // This doesn't fit a repeating in-lane mask.
9718       return SDValue();
9719     }
9720   }
9721
9722   // First shuffle the lanes into place.
9723   MVT LaneVT = MVT::getVectorVT(VT.isFloatingPoint() ? MVT::f64 : MVT::i64,
9724                                 VT.getSizeInBits() / 64);
9725   SmallVector<int, 8> LaneMask;
9726   LaneMask.resize(NumLanes * 2, -1);
9727   for (int i = 0; i < NumLanes; ++i)
9728     if (Lanes[i] >= 0) {
9729       LaneMask[2 * i + 0] = 2*Lanes[i] + 0;
9730       LaneMask[2 * i + 1] = 2*Lanes[i] + 1;
9731     }
9732
9733   V1 = DAG.getBitcast(LaneVT, V1);
9734   V2 = DAG.getBitcast(LaneVT, V2);
9735   SDValue LaneShuffle = DAG.getVectorShuffle(LaneVT, DL, V1, V2, LaneMask);
9736
9737   // Cast it back to the type we actually want.
9738   LaneShuffle = DAG.getBitcast(VT, LaneShuffle);
9739
9740   // Now do a simple shuffle that isn't lane crossing.
9741   SmallVector<int, 8> NewMask;
9742   NewMask.resize(Size, -1);
9743   for (int i = 0; i < Size; ++i)
9744     if (Mask[i] >= 0)
9745       NewMask[i] = (i / LaneSize) * LaneSize + Mask[i] % LaneSize;
9746   assert(!is128BitLaneCrossingShuffleMask(VT, NewMask) &&
9747          "Must not introduce lane crosses at this point!");
9748
9749   return DAG.getVectorShuffle(VT, DL, LaneShuffle, DAG.getUNDEF(VT), NewMask);
9750 }
9751
9752 /// \brief Test whether the specified input (0 or 1) is in-place blended by the
9753 /// given mask.
9754 ///
9755 /// This returns true if the elements from a particular input are already in the
9756 /// slot required by the given mask and require no permutation.
9757 static bool isShuffleMaskInputInPlace(int Input, ArrayRef<int> Mask) {
9758   assert((Input == 0 || Input == 1) && "Only two inputs to shuffles.");
9759   int Size = Mask.size();
9760   for (int i = 0; i < Size; ++i)
9761     if (Mask[i] >= 0 && Mask[i] / Size == Input && Mask[i] % Size != i)
9762       return false;
9763
9764   return true;
9765 }
9766
9767 static SDValue lowerVectorShuffleWithSHUFPD(SDLoc DL, MVT VT,
9768                                             ArrayRef<int> Mask, SDValue V1,
9769                                             SDValue V2, SelectionDAG &DAG) {
9770
9771   // Mask for V8F64: 0/1,  8/9,  2/3,  10/11, 4/5, ..
9772   // Mask for V4F64; 0/1,  4/5,  2/3,  6/7..
9773   assert(VT.getScalarSizeInBits() == 64 && "Unexpected data type for VSHUFPD");
9774   int NumElts = VT.getVectorNumElements();
9775   bool ShufpdMask = true;
9776   bool CommutableMask = true;
9777   unsigned Immediate = 0;
9778   for (int i = 0; i < NumElts; ++i) {
9779     if (Mask[i] < 0)
9780       continue;
9781     int Val = (i & 6) + NumElts * (i & 1);
9782     int CommutVal = (i & 0xe) + NumElts * ((i & 1)^1);
9783     if (Mask[i] < Val ||  Mask[i] > Val + 1)
9784       ShufpdMask = false;
9785     if (Mask[i] < CommutVal ||  Mask[i] > CommutVal + 1)
9786       CommutableMask = false;
9787     Immediate |= (Mask[i] % 2) << i;
9788   }
9789   if (ShufpdMask)
9790     return DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
9791                        DAG.getConstant(Immediate, DL, MVT::i8));
9792   if (CommutableMask)
9793     return DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
9794                        DAG.getConstant(Immediate, DL, MVT::i8));
9795   return SDValue();
9796 }
9797
9798 /// \brief Handle lowering of 4-lane 64-bit floating point shuffles.
9799 ///
9800 /// Also ends up handling lowering of 4-lane 64-bit integer shuffles when AVX2
9801 /// isn't available.
9802 static SDValue lowerV4F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9803                                        const X86Subtarget *Subtarget,
9804                                        SelectionDAG &DAG) {
9805   SDLoc DL(Op);
9806   assert(V1.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
9807   assert(V2.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
9808   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9809   ArrayRef<int> Mask = SVOp->getMask();
9810   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
9811
9812   SmallVector<int, 4> WidenedMask;
9813   if (canWidenShuffleElements(Mask, WidenedMask))
9814     return lowerV2X128VectorShuffle(DL, MVT::v4f64, V1, V2, Mask, Subtarget,
9815                                     DAG);
9816
9817   if (isSingleInputShuffleMask(Mask)) {
9818     // Check for being able to broadcast a single element.
9819     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f64, V1,
9820                                                           Mask, Subtarget, DAG))
9821       return Broadcast;
9822
9823     // Use low duplicate instructions for masks that match their pattern.
9824     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
9825       return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v4f64, V1);
9826
9827     if (!is128BitLaneCrossingShuffleMask(MVT::v4f64, Mask)) {
9828       // Non-half-crossing single input shuffles can be lowerid with an
9829       // interleaved permutation.
9830       unsigned VPERMILPMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1) |
9831                               ((Mask[2] == 3) << 2) | ((Mask[3] == 3) << 3);
9832       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f64, V1,
9833                          DAG.getConstant(VPERMILPMask, DL, MVT::i8));
9834     }
9835
9836     // With AVX2 we have direct support for this permutation.
9837     if (Subtarget->hasAVX2())
9838       return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4f64, V1,
9839                          getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
9840
9841     // Otherwise, fall back.
9842     return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v4f64, V1, V2, Mask,
9843                                                    DAG);
9844   }
9845
9846   // X86 has dedicated unpack instructions that can handle specific blend
9847   // operations: UNPCKH and UNPCKL.
9848   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 2, 6}))
9849     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V1, V2);
9850   if (isShuffleEquivalent(V1, V2, Mask, {1, 5, 3, 7}))
9851     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V1, V2);
9852   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 6, 2}))
9853     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V2, V1);
9854   if (isShuffleEquivalent(V1, V2, Mask, {5, 1, 7, 3}))
9855     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V2, V1);
9856
9857   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f64, V1, V2, Mask,
9858                                                 Subtarget, DAG))
9859     return Blend;
9860
9861   // Check if the blend happens to exactly fit that of SHUFPD.
9862   if (SDValue Op =
9863       lowerVectorShuffleWithSHUFPD(DL, MVT::v4f64, Mask, V1, V2, DAG))
9864     return Op;
9865
9866   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9867   // shuffle. However, if we have AVX2 and either inputs are already in place,
9868   // we will be able to shuffle even across lanes the other input in a single
9869   // instruction so skip this pattern.
9870   if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
9871                                  isShuffleMaskInputInPlace(1, Mask))))
9872     if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9873             DL, MVT::v4f64, V1, V2, Mask, Subtarget, DAG))
9874       return Result;
9875
9876   // If we have AVX2 then we always want to lower with a blend because an v4 we
9877   // can fully permute the elements.
9878   if (Subtarget->hasAVX2())
9879     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4f64, V1, V2,
9880                                                       Mask, DAG);
9881
9882   // Otherwise fall back on generic lowering.
9883   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v4f64, V1, V2, Mask, DAG);
9884 }
9885
9886 /// \brief Handle lowering of 4-lane 64-bit integer shuffles.
9887 ///
9888 /// This routine is only called when we have AVX2 and thus a reasonable
9889 /// instruction set for v4i64 shuffling..
9890 static SDValue lowerV4I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9891                                        const X86Subtarget *Subtarget,
9892                                        SelectionDAG &DAG) {
9893   SDLoc DL(Op);
9894   assert(V1.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
9895   assert(V2.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
9896   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9897   ArrayRef<int> Mask = SVOp->getMask();
9898   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
9899   assert(Subtarget->hasAVX2() && "We can only lower v4i64 with AVX2!");
9900
9901   SmallVector<int, 4> WidenedMask;
9902   if (canWidenShuffleElements(Mask, WidenedMask))
9903     return lowerV2X128VectorShuffle(DL, MVT::v4i64, V1, V2, Mask, Subtarget,
9904                                     DAG);
9905
9906   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i64, V1, V2, Mask,
9907                                                 Subtarget, DAG))
9908     return Blend;
9909
9910   // Check for being able to broadcast a single element.
9911   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i64, V1,
9912                                                         Mask, Subtarget, DAG))
9913     return Broadcast;
9914
9915   // When the shuffle is mirrored between the 128-bit lanes of the unit, we can
9916   // use lower latency instructions that will operate on both 128-bit lanes.
9917   SmallVector<int, 2> RepeatedMask;
9918   if (is128BitLaneRepeatedShuffleMask(MVT::v4i64, Mask, RepeatedMask)) {
9919     if (isSingleInputShuffleMask(Mask)) {
9920       int PSHUFDMask[] = {-1, -1, -1, -1};
9921       for (int i = 0; i < 2; ++i)
9922         if (RepeatedMask[i] >= 0) {
9923           PSHUFDMask[2 * i] = 2 * RepeatedMask[i];
9924           PSHUFDMask[2 * i + 1] = 2 * RepeatedMask[i] + 1;
9925         }
9926       return DAG.getBitcast(
9927           MVT::v4i64,
9928           DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32,
9929                       DAG.getBitcast(MVT::v8i32, V1),
9930                       getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
9931     }
9932   }
9933
9934   // AVX2 provides a direct instruction for permuting a single input across
9935   // lanes.
9936   if (isSingleInputShuffleMask(Mask))
9937     return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4i64, V1,
9938                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
9939
9940   // Try to use shift instructions.
9941   if (SDValue Shift =
9942           lowerVectorShuffleAsShift(DL, MVT::v4i64, V1, V2, Mask, DAG))
9943     return Shift;
9944
9945   // Use dedicated unpack instructions for masks that match their pattern.
9946   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 2, 6}))
9947     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V1, V2);
9948   if (isShuffleEquivalent(V1, V2, Mask, {1, 5, 3, 7}))
9949     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V1, V2);
9950   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 6, 2}))
9951     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V2, V1);
9952   if (isShuffleEquivalent(V1, V2, Mask, {5, 1, 7, 3}))
9953     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V2, V1);
9954
9955   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9956   // shuffle. However, if we have AVX2 and either inputs are already in place,
9957   // we will be able to shuffle even across lanes the other input in a single
9958   // instruction so skip this pattern.
9959   if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
9960                                  isShuffleMaskInputInPlace(1, Mask))))
9961     if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9962             DL, MVT::v4i64, V1, V2, Mask, Subtarget, DAG))
9963       return Result;
9964
9965   // Otherwise fall back on generic blend lowering.
9966   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i64, V1, V2,
9967                                                     Mask, DAG);
9968 }
9969
9970 /// \brief Handle lowering of 8-lane 32-bit floating point shuffles.
9971 ///
9972 /// Also ends up handling lowering of 8-lane 32-bit integer shuffles when AVX2
9973 /// isn't available.
9974 static SDValue lowerV8F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9975                                        const X86Subtarget *Subtarget,
9976                                        SelectionDAG &DAG) {
9977   SDLoc DL(Op);
9978   assert(V1.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
9979   assert(V2.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
9980   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9981   ArrayRef<int> Mask = SVOp->getMask();
9982   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9983
9984   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8f32, V1, V2, Mask,
9985                                                 Subtarget, DAG))
9986     return Blend;
9987
9988   // Check for being able to broadcast a single element.
9989   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8f32, V1,
9990                                                         Mask, Subtarget, DAG))
9991     return Broadcast;
9992
9993   // If the shuffle mask is repeated in each 128-bit lane, we have many more
9994   // options to efficiently lower the shuffle.
9995   SmallVector<int, 4> RepeatedMask;
9996   if (is128BitLaneRepeatedShuffleMask(MVT::v8f32, Mask, RepeatedMask)) {
9997     assert(RepeatedMask.size() == 4 &&
9998            "Repeated masks must be half the mask width!");
9999
10000     // Use even/odd duplicate instructions for masks that match their pattern.
10001     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2, 4, 4, 6, 6}))
10002       return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v8f32, V1);
10003     if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3, 5, 5, 7, 7}))
10004       return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v8f32, V1);
10005
10006     if (isSingleInputShuffleMask(Mask))
10007       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v8f32, V1,
10008                          getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
10009
10010     // Use dedicated unpack instructions for masks that match their pattern.
10011     if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 4, 12, 5, 13}))
10012       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V1, V2);
10013     if (isShuffleEquivalent(V1, V2, Mask, {2, 10, 3, 11, 6, 14, 7, 15}))
10014       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V1, V2);
10015     if (isShuffleEquivalent(V1, V2, Mask, {8, 0, 9, 1, 12, 4, 13, 5}))
10016       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V2, V1);
10017     if (isShuffleEquivalent(V1, V2, Mask, {10, 2, 11, 3, 14, 6, 15, 7}))
10018       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V2, V1);
10019
10020     // Otherwise, fall back to a SHUFPS sequence. Here it is important that we
10021     // have already handled any direct blends. We also need to squash the
10022     // repeated mask into a simulated v4f32 mask.
10023     for (int i = 0; i < 4; ++i)
10024       if (RepeatedMask[i] >= 8)
10025         RepeatedMask[i] -= 4;
10026     return lowerVectorShuffleWithSHUFPS(DL, MVT::v8f32, RepeatedMask, V1, V2, DAG);
10027   }
10028
10029   // If we have a single input shuffle with different shuffle patterns in the
10030   // two 128-bit lanes use the variable mask to VPERMILPS.
10031   if (isSingleInputShuffleMask(Mask)) {
10032     SDValue VPermMask[8];
10033     for (int i = 0; i < 8; ++i)
10034       VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
10035                                  : DAG.getConstant(Mask[i], DL, MVT::i32);
10036     if (!is128BitLaneCrossingShuffleMask(MVT::v8f32, Mask))
10037       return DAG.getNode(
10038           X86ISD::VPERMILPV, DL, MVT::v8f32, V1,
10039           DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask));
10040
10041     if (Subtarget->hasAVX2())
10042       return DAG.getNode(
10043           X86ISD::VPERMV, DL, MVT::v8f32,
10044           DAG.getBitcast(MVT::v8f32, DAG.getNode(ISD::BUILD_VECTOR, DL,
10045                                                  MVT::v8i32, VPermMask)),
10046           V1);
10047
10048     // Otherwise, fall back.
10049     return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v8f32, V1, V2, Mask,
10050                                                    DAG);
10051   }
10052
10053   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10054   // shuffle.
10055   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10056           DL, MVT::v8f32, V1, V2, Mask, Subtarget, DAG))
10057     return Result;
10058
10059   // If we have AVX2 then we always want to lower with a blend because at v8 we
10060   // can fully permute the elements.
10061   if (Subtarget->hasAVX2())
10062     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8f32, V1, V2,
10063                                                       Mask, DAG);
10064
10065   // Otherwise fall back on generic lowering.
10066   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v8f32, V1, V2, Mask, DAG);
10067 }
10068
10069 /// \brief Handle lowering of 8-lane 32-bit integer shuffles.
10070 ///
10071 /// This routine is only called when we have AVX2 and thus a reasonable
10072 /// instruction set for v8i32 shuffling..
10073 static SDValue lowerV8I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10074                                        const X86Subtarget *Subtarget,
10075                                        SelectionDAG &DAG) {
10076   SDLoc DL(Op);
10077   assert(V1.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
10078   assert(V2.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
10079   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10080   ArrayRef<int> Mask = SVOp->getMask();
10081   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10082   assert(Subtarget->hasAVX2() && "We can only lower v8i32 with AVX2!");
10083
10084   // Whenever we can lower this as a zext, that instruction is strictly faster
10085   // than any alternative. It also allows us to fold memory operands into the
10086   // shuffle in many cases.
10087   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v8i32, V1, V2,
10088                                                          Mask, Subtarget, DAG))
10089     return ZExt;
10090
10091   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i32, V1, V2, Mask,
10092                                                 Subtarget, DAG))
10093     return Blend;
10094
10095   // Check for being able to broadcast a single element.
10096   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i32, V1,
10097                                                         Mask, Subtarget, DAG))
10098     return Broadcast;
10099
10100   // If the shuffle mask is repeated in each 128-bit lane we can use more
10101   // efficient instructions that mirror the shuffles across the two 128-bit
10102   // lanes.
10103   SmallVector<int, 4> RepeatedMask;
10104   if (is128BitLaneRepeatedShuffleMask(MVT::v8i32, Mask, RepeatedMask)) {
10105     assert(RepeatedMask.size() == 4 && "Unexpected repeated mask size!");
10106     if (isSingleInputShuffleMask(Mask))
10107       return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32, V1,
10108                          getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
10109
10110     // Use dedicated unpack instructions for masks that match their pattern.
10111     if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 4, 12, 5, 13}))
10112       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V1, V2);
10113     if (isShuffleEquivalent(V1, V2, Mask, {2, 10, 3, 11, 6, 14, 7, 15}))
10114       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V1, V2);
10115     if (isShuffleEquivalent(V1, V2, Mask, {8, 0, 9, 1, 12, 4, 13, 5}))
10116       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V2, V1);
10117     if (isShuffleEquivalent(V1, V2, Mask, {10, 2, 11, 3, 14, 6, 15, 7}))
10118       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V2, V1);
10119   }
10120
10121   // Try to use shift instructions.
10122   if (SDValue Shift =
10123           lowerVectorShuffleAsShift(DL, MVT::v8i32, V1, V2, Mask, DAG))
10124     return Shift;
10125
10126   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10127           DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
10128     return Rotate;
10129
10130   // If the shuffle patterns aren't repeated but it is a single input, directly
10131   // generate a cross-lane VPERMD instruction.
10132   if (isSingleInputShuffleMask(Mask)) {
10133     SDValue VPermMask[8];
10134     for (int i = 0; i < 8; ++i)
10135       VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
10136                                  : DAG.getConstant(Mask[i], DL, MVT::i32);
10137     return DAG.getNode(
10138         X86ISD::VPERMV, DL, MVT::v8i32,
10139         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask), V1);
10140   }
10141
10142   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10143   // shuffle.
10144   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10145           DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
10146     return Result;
10147
10148   // Otherwise fall back on generic blend lowering.
10149   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i32, V1, V2,
10150                                                     Mask, DAG);
10151 }
10152
10153 /// \brief Handle lowering of 16-lane 16-bit integer shuffles.
10154 ///
10155 /// This routine is only called when we have AVX2 and thus a reasonable
10156 /// instruction set for v16i16 shuffling..
10157 static SDValue lowerV16I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10158                                         const X86Subtarget *Subtarget,
10159                                         SelectionDAG &DAG) {
10160   SDLoc DL(Op);
10161   assert(V1.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
10162   assert(V2.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
10163   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10164   ArrayRef<int> Mask = SVOp->getMask();
10165   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10166   assert(Subtarget->hasAVX2() && "We can only lower v16i16 with AVX2!");
10167
10168   // Whenever we can lower this as a zext, that instruction is strictly faster
10169   // than any alternative. It also allows us to fold memory operands into the
10170   // shuffle in many cases.
10171   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v16i16, V1, V2,
10172                                                          Mask, Subtarget, DAG))
10173     return ZExt;
10174
10175   // Check for being able to broadcast a single element.
10176   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i16, V1,
10177                                                         Mask, Subtarget, DAG))
10178     return Broadcast;
10179
10180   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i16, V1, V2, Mask,
10181                                                 Subtarget, DAG))
10182     return Blend;
10183
10184   // Use dedicated unpack instructions for masks that match their pattern.
10185   if (isShuffleEquivalent(V1, V2, Mask,
10186                           {// First 128-bit lane:
10187                            0, 16, 1, 17, 2, 18, 3, 19,
10188                            // Second 128-bit lane:
10189                            8, 24, 9, 25, 10, 26, 11, 27}))
10190     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i16, V1, V2);
10191   if (isShuffleEquivalent(V1, V2, Mask,
10192                           {// First 128-bit lane:
10193                            4, 20, 5, 21, 6, 22, 7, 23,
10194                            // Second 128-bit lane:
10195                            12, 28, 13, 29, 14, 30, 15, 31}))
10196     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i16, V1, V2);
10197
10198   // Try to use shift instructions.
10199   if (SDValue Shift =
10200           lowerVectorShuffleAsShift(DL, MVT::v16i16, V1, V2, Mask, DAG))
10201     return Shift;
10202
10203   // Try to use byte rotation instructions.
10204   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10205           DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
10206     return Rotate;
10207
10208   if (isSingleInputShuffleMask(Mask)) {
10209     // There are no generalized cross-lane shuffle operations available on i16
10210     // element types.
10211     if (is128BitLaneCrossingShuffleMask(MVT::v16i16, Mask))
10212       return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v16i16, V1, V2,
10213                                                      Mask, DAG);
10214
10215     SmallVector<int, 8> RepeatedMask;
10216     if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
10217       // As this is a single-input shuffle, the repeated mask should be
10218       // a strictly valid v8i16 mask that we can pass through to the v8i16
10219       // lowering to handle even the v16 case.
10220       return lowerV8I16GeneralSingleInputVectorShuffle(
10221           DL, MVT::v16i16, V1, RepeatedMask, Subtarget, DAG);
10222     }
10223
10224     SDValue PSHUFBMask[32];
10225     for (int i = 0; i < 16; ++i) {
10226       if (Mask[i] == -1) {
10227         PSHUFBMask[2 * i] = PSHUFBMask[2 * i + 1] = DAG.getUNDEF(MVT::i8);
10228         continue;
10229       }
10230
10231       int M = i < 8 ? Mask[i] : Mask[i] - 8;
10232       assert(M >= 0 && M < 8 && "Invalid single-input mask!");
10233       PSHUFBMask[2 * i] = DAG.getConstant(2 * M, DL, MVT::i8);
10234       PSHUFBMask[2 * i + 1] = DAG.getConstant(2 * M + 1, DL, MVT::i8);
10235     }
10236     return DAG.getBitcast(MVT::v16i16,
10237                           DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8,
10238                                       DAG.getBitcast(MVT::v32i8, V1),
10239                                       DAG.getNode(ISD::BUILD_VECTOR, DL,
10240                                                   MVT::v32i8, PSHUFBMask)));
10241   }
10242
10243   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10244   // shuffle.
10245   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10246           DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
10247     return Result;
10248
10249   // Otherwise fall back on generic lowering.
10250   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v16i16, V1, V2, Mask, DAG);
10251 }
10252
10253 /// \brief Handle lowering of 32-lane 8-bit integer shuffles.
10254 ///
10255 /// This routine is only called when we have AVX2 and thus a reasonable
10256 /// instruction set for v32i8 shuffling..
10257 static SDValue lowerV32I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10258                                        const X86Subtarget *Subtarget,
10259                                        SelectionDAG &DAG) {
10260   SDLoc DL(Op);
10261   assert(V1.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
10262   assert(V2.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
10263   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10264   ArrayRef<int> Mask = SVOp->getMask();
10265   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
10266   assert(Subtarget->hasAVX2() && "We can only lower v32i8 with AVX2!");
10267
10268   // Whenever we can lower this as a zext, that instruction is strictly faster
10269   // than any alternative. It also allows us to fold memory operands into the
10270   // shuffle in many cases.
10271   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v32i8, V1, V2,
10272                                                          Mask, Subtarget, DAG))
10273     return ZExt;
10274
10275   // Check for being able to broadcast a single element.
10276   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v32i8, V1,
10277                                                         Mask, Subtarget, DAG))
10278     return Broadcast;
10279
10280   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v32i8, V1, V2, Mask,
10281                                                 Subtarget, DAG))
10282     return Blend;
10283
10284   // Use dedicated unpack instructions for masks that match their pattern.
10285   // Note that these are repeated 128-bit lane unpacks, not unpacks across all
10286   // 256-bit lanes.
10287   if (isShuffleEquivalent(
10288           V1, V2, Mask,
10289           {// First 128-bit lane:
10290            0, 32, 1, 33, 2, 34, 3, 35, 4, 36, 5, 37, 6, 38, 7, 39,
10291            // Second 128-bit lane:
10292            16, 48, 17, 49, 18, 50, 19, 51, 20, 52, 21, 53, 22, 54, 23, 55}))
10293     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v32i8, V1, V2);
10294   if (isShuffleEquivalent(
10295           V1, V2, Mask,
10296           {// First 128-bit lane:
10297            8, 40, 9, 41, 10, 42, 11, 43, 12, 44, 13, 45, 14, 46, 15, 47,
10298            // Second 128-bit lane:
10299            24, 56, 25, 57, 26, 58, 27, 59, 28, 60, 29, 61, 30, 62, 31, 63}))
10300     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v32i8, V1, V2);
10301
10302   // Try to use shift instructions.
10303   if (SDValue Shift =
10304           lowerVectorShuffleAsShift(DL, MVT::v32i8, V1, V2, Mask, DAG))
10305     return Shift;
10306
10307   // Try to use byte rotation instructions.
10308   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10309           DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
10310     return Rotate;
10311
10312   if (isSingleInputShuffleMask(Mask)) {
10313     // There are no generalized cross-lane shuffle operations available on i8
10314     // element types.
10315     if (is128BitLaneCrossingShuffleMask(MVT::v32i8, Mask))
10316       return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v32i8, V1, V2,
10317                                                      Mask, DAG);
10318
10319     SDValue PSHUFBMask[32];
10320     for (int i = 0; i < 32; ++i)
10321       PSHUFBMask[i] =
10322           Mask[i] < 0
10323               ? DAG.getUNDEF(MVT::i8)
10324               : DAG.getConstant(Mask[i] < 16 ? Mask[i] : Mask[i] - 16, DL,
10325                                 MVT::i8);
10326
10327     return DAG.getNode(
10328         X86ISD::PSHUFB, DL, MVT::v32i8, V1,
10329         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, PSHUFBMask));
10330   }
10331
10332   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10333   // shuffle.
10334   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10335           DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
10336     return Result;
10337
10338   // Otherwise fall back on generic lowering.
10339   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v32i8, V1, V2, Mask, DAG);
10340 }
10341
10342 /// \brief High-level routine to lower various 256-bit x86 vector shuffles.
10343 ///
10344 /// This routine either breaks down the specific type of a 256-bit x86 vector
10345 /// shuffle or splits it into two 128-bit shuffles and fuses the results back
10346 /// together based on the available instructions.
10347 static SDValue lower256BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10348                                         MVT VT, const X86Subtarget *Subtarget,
10349                                         SelectionDAG &DAG) {
10350   SDLoc DL(Op);
10351   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10352   ArrayRef<int> Mask = SVOp->getMask();
10353
10354   // If we have a single input to the zero element, insert that into V1 if we
10355   // can do so cheaply.
10356   int NumElts = VT.getVectorNumElements();
10357   int NumV2Elements = std::count_if(Mask.begin(), Mask.end(), [NumElts](int M) {
10358     return M >= NumElts;
10359   });
10360
10361   if (NumV2Elements == 1 && Mask[0] >= NumElts)
10362     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
10363                               DL, VT, V1, V2, Mask, Subtarget, DAG))
10364       return Insertion;
10365
10366   // There is a really nice hard cut-over between AVX1 and AVX2 that means we can
10367   // check for those subtargets here and avoid much of the subtarget querying in
10368   // the per-vector-type lowering routines. With AVX1 we have essentially *zero*
10369   // ability to manipulate a 256-bit vector with integer types. Since we'll use
10370   // floating point types there eventually, just immediately cast everything to
10371   // a float and operate entirely in that domain.
10372   if (VT.isInteger() && !Subtarget->hasAVX2()) {
10373     int ElementBits = VT.getScalarSizeInBits();
10374     if (ElementBits < 32)
10375       // No floating point type available, decompose into 128-bit vectors.
10376       return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10377
10378     MVT FpVT = MVT::getVectorVT(MVT::getFloatingPointVT(ElementBits),
10379                                 VT.getVectorNumElements());
10380     V1 = DAG.getBitcast(FpVT, V1);
10381     V2 = DAG.getBitcast(FpVT, V2);
10382     return DAG.getBitcast(VT, DAG.getVectorShuffle(FpVT, DL, V1, V2, Mask));
10383   }
10384
10385   switch (VT.SimpleTy) {
10386   case MVT::v4f64:
10387     return lowerV4F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10388   case MVT::v4i64:
10389     return lowerV4I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10390   case MVT::v8f32:
10391     return lowerV8F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10392   case MVT::v8i32:
10393     return lowerV8I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10394   case MVT::v16i16:
10395     return lowerV16I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
10396   case MVT::v32i8:
10397     return lowerV32I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
10398
10399   default:
10400     llvm_unreachable("Not a valid 256-bit x86 vector type!");
10401   }
10402 }
10403
10404 /// \brief Handle lowering of 8-lane 64-bit floating point shuffles.
10405 static SDValue lowerV8F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10406                                        const X86Subtarget *Subtarget,
10407                                        SelectionDAG &DAG) {
10408   SDLoc DL(Op);
10409   assert(V1.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
10410   assert(V2.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
10411   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10412   ArrayRef<int> Mask = SVOp->getMask();
10413   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10414
10415   // X86 has dedicated unpack instructions that can handle specific blend
10416   // operations: UNPCKH and UNPCKL.
10417   if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 2, 10, 4, 12, 6, 14}))
10418     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f64, V1, V2);
10419   if (isShuffleEquivalent(V1, V2, Mask, {1, 9, 3, 11, 5, 13, 7, 15}))
10420     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f64, V1, V2);
10421
10422   // FIXME: Implement direct support for this type!
10423   return splitAndLowerVectorShuffle(DL, MVT::v8f64, V1, V2, Mask, DAG);
10424 }
10425
10426 /// \brief Handle lowering of 16-lane 32-bit floating point shuffles.
10427 static SDValue lowerV16F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10428                                        const X86Subtarget *Subtarget,
10429                                        SelectionDAG &DAG) {
10430   SDLoc DL(Op);
10431   assert(V1.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
10432   assert(V2.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
10433   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10434   ArrayRef<int> Mask = SVOp->getMask();
10435   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10436
10437   // Use dedicated unpack instructions for masks that match their pattern.
10438   if (isShuffleEquivalent(V1, V2, Mask,
10439                           {// First 128-bit lane.
10440                            0, 16, 1, 17, 4, 20, 5, 21,
10441                            // Second 128-bit lane.
10442                            8, 24, 9, 25, 12, 28, 13, 29}))
10443     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16f32, V1, V2);
10444   if (isShuffleEquivalent(V1, V2, Mask,
10445                           {// First 128-bit lane.
10446                            2, 18, 3, 19, 6, 22, 7, 23,
10447                            // Second 128-bit lane.
10448                            10, 26, 11, 27, 14, 30, 15, 31}))
10449     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16f32, V1, V2);
10450
10451   // FIXME: Implement direct support for this type!
10452   return splitAndLowerVectorShuffle(DL, MVT::v16f32, V1, V2, Mask, DAG);
10453 }
10454
10455 /// \brief Handle lowering of 8-lane 64-bit integer shuffles.
10456 static SDValue lowerV8I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10457                                        const X86Subtarget *Subtarget,
10458                                        SelectionDAG &DAG) {
10459   SDLoc DL(Op);
10460   assert(V1.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
10461   assert(V2.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
10462   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10463   ArrayRef<int> Mask = SVOp->getMask();
10464   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10465
10466   // X86 has dedicated unpack instructions that can handle specific blend
10467   // operations: UNPCKH and UNPCKL.
10468   if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 2, 10, 4, 12, 6, 14}))
10469     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i64, V1, V2);
10470   if (isShuffleEquivalent(V1, V2, Mask, {1, 9, 3, 11, 5, 13, 7, 15}))
10471     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i64, V1, V2);
10472
10473   // FIXME: Implement direct support for this type!
10474   return splitAndLowerVectorShuffle(DL, MVT::v8i64, V1, V2, Mask, DAG);
10475 }
10476
10477 /// \brief Handle lowering of 16-lane 32-bit integer shuffles.
10478 static SDValue lowerV16I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10479                                        const X86Subtarget *Subtarget,
10480                                        SelectionDAG &DAG) {
10481   SDLoc DL(Op);
10482   assert(V1.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
10483   assert(V2.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
10484   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10485   ArrayRef<int> Mask = SVOp->getMask();
10486   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10487
10488   // Use dedicated unpack instructions for masks that match their pattern.
10489   if (isShuffleEquivalent(V1, V2, Mask,
10490                           {// First 128-bit lane.
10491                            0, 16, 1, 17, 4, 20, 5, 21,
10492                            // Second 128-bit lane.
10493                            8, 24, 9, 25, 12, 28, 13, 29}))
10494     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i32, V1, V2);
10495   if (isShuffleEquivalent(V1, V2, Mask,
10496                           {// First 128-bit lane.
10497                            2, 18, 3, 19, 6, 22, 7, 23,
10498                            // Second 128-bit lane.
10499                            10, 26, 11, 27, 14, 30, 15, 31}))
10500     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i32, V1, V2);
10501
10502   // FIXME: Implement direct support for this type!
10503   return splitAndLowerVectorShuffle(DL, MVT::v16i32, V1, V2, Mask, DAG);
10504 }
10505
10506 /// \brief Handle lowering of 32-lane 16-bit integer shuffles.
10507 static SDValue lowerV32I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10508                                         const X86Subtarget *Subtarget,
10509                                         SelectionDAG &DAG) {
10510   SDLoc DL(Op);
10511   assert(V1.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10512   assert(V2.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10513   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10514   ArrayRef<int> Mask = SVOp->getMask();
10515   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
10516   assert(Subtarget->hasBWI() && "We can only lower v32i16 with AVX-512-BWI!");
10517
10518   // FIXME: Implement direct support for this type!
10519   return splitAndLowerVectorShuffle(DL, MVT::v32i16, V1, V2, Mask, DAG);
10520 }
10521
10522 /// \brief Handle lowering of 64-lane 8-bit integer shuffles.
10523 static SDValue lowerV64I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10524                                        const X86Subtarget *Subtarget,
10525                                        SelectionDAG &DAG) {
10526   SDLoc DL(Op);
10527   assert(V1.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10528   assert(V2.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10529   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10530   ArrayRef<int> Mask = SVOp->getMask();
10531   assert(Mask.size() == 64 && "Unexpected mask size for v64 shuffle!");
10532   assert(Subtarget->hasBWI() && "We can only lower v64i8 with AVX-512-BWI!");
10533
10534   // FIXME: Implement direct support for this type!
10535   return splitAndLowerVectorShuffle(DL, MVT::v64i8, V1, V2, Mask, DAG);
10536 }
10537
10538 /// \brief High-level routine to lower various 512-bit x86 vector shuffles.
10539 ///
10540 /// This routine either breaks down the specific type of a 512-bit x86 vector
10541 /// shuffle or splits it into two 256-bit shuffles and fuses the results back
10542 /// together based on the available instructions.
10543 static SDValue lower512BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10544                                         MVT VT, const X86Subtarget *Subtarget,
10545                                         SelectionDAG &DAG) {
10546   SDLoc DL(Op);
10547   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10548   ArrayRef<int> Mask = SVOp->getMask();
10549   assert(Subtarget->hasAVX512() &&
10550          "Cannot lower 512-bit vectors w/ basic ISA!");
10551
10552   // Check for being able to broadcast a single element.
10553   if (SDValue Broadcast =
10554           lowerVectorShuffleAsBroadcast(DL, VT, V1, Mask, Subtarget, DAG))
10555     return Broadcast;
10556
10557   // Dispatch to each element type for lowering. If we don't have supprot for
10558   // specific element type shuffles at 512 bits, immediately split them and
10559   // lower them. Each lowering routine of a given type is allowed to assume that
10560   // the requisite ISA extensions for that element type are available.
10561   switch (VT.SimpleTy) {
10562   case MVT::v8f64:
10563     return lowerV8F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10564   case MVT::v16f32:
10565     return lowerV16F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10566   case MVT::v8i64:
10567     return lowerV8I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10568   case MVT::v16i32:
10569     return lowerV16I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10570   case MVT::v32i16:
10571     if (Subtarget->hasBWI())
10572       return lowerV32I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
10573     break;
10574   case MVT::v64i8:
10575     if (Subtarget->hasBWI())
10576       return lowerV64I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
10577     break;
10578
10579   default:
10580     llvm_unreachable("Not a valid 512-bit x86 vector type!");
10581   }
10582
10583   // Otherwise fall back on splitting.
10584   return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10585 }
10586
10587 /// \brief Top-level lowering for x86 vector shuffles.
10588 ///
10589 /// This handles decomposition, canonicalization, and lowering of all x86
10590 /// vector shuffles. Most of the specific lowering strategies are encapsulated
10591 /// above in helper routines. The canonicalization attempts to widen shuffles
10592 /// to involve fewer lanes of wider elements, consolidate symmetric patterns
10593 /// s.t. only one of the two inputs needs to be tested, etc.
10594 static SDValue lowerVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
10595                                   SelectionDAG &DAG) {
10596   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10597   ArrayRef<int> Mask = SVOp->getMask();
10598   SDValue V1 = Op.getOperand(0);
10599   SDValue V2 = Op.getOperand(1);
10600   MVT VT = Op.getSimpleValueType();
10601   int NumElements = VT.getVectorNumElements();
10602   SDLoc dl(Op);
10603
10604   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
10605
10606   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
10607   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
10608   if (V1IsUndef && V2IsUndef)
10609     return DAG.getUNDEF(VT);
10610
10611   // When we create a shuffle node we put the UNDEF node to second operand,
10612   // but in some cases the first operand may be transformed to UNDEF.
10613   // In this case we should just commute the node.
10614   if (V1IsUndef)
10615     return DAG.getCommutedVectorShuffle(*SVOp);
10616
10617   // Check for non-undef masks pointing at an undef vector and make the masks
10618   // undef as well. This makes it easier to match the shuffle based solely on
10619   // the mask.
10620   if (V2IsUndef)
10621     for (int M : Mask)
10622       if (M >= NumElements) {
10623         SmallVector<int, 8> NewMask(Mask.begin(), Mask.end());
10624         for (int &M : NewMask)
10625           if (M >= NumElements)
10626             M = -1;
10627         return DAG.getVectorShuffle(VT, dl, V1, V2, NewMask);
10628       }
10629
10630   // We actually see shuffles that are entirely re-arrangements of a set of
10631   // zero inputs. This mostly happens while decomposing complex shuffles into
10632   // simple ones. Directly lower these as a buildvector of zeros.
10633   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
10634   if (Zeroable.all())
10635     return getZeroVector(VT, Subtarget, DAG, dl);
10636
10637   // Try to collapse shuffles into using a vector type with fewer elements but
10638   // wider element types. We cap this to not form integers or floating point
10639   // elements wider than 64 bits, but it might be interesting to form i128
10640   // integers to handle flipping the low and high halves of AVX 256-bit vectors.
10641   SmallVector<int, 16> WidenedMask;
10642   if (VT.getScalarSizeInBits() < 64 &&
10643       canWidenShuffleElements(Mask, WidenedMask)) {
10644     MVT NewEltVT = VT.isFloatingPoint()
10645                        ? MVT::getFloatingPointVT(VT.getScalarSizeInBits() * 2)
10646                        : MVT::getIntegerVT(VT.getScalarSizeInBits() * 2);
10647     MVT NewVT = MVT::getVectorVT(NewEltVT, VT.getVectorNumElements() / 2);
10648     // Make sure that the new vector type is legal. For example, v2f64 isn't
10649     // legal on SSE1.
10650     if (DAG.getTargetLoweringInfo().isTypeLegal(NewVT)) {
10651       V1 = DAG.getBitcast(NewVT, V1);
10652       V2 = DAG.getBitcast(NewVT, V2);
10653       return DAG.getBitcast(
10654           VT, DAG.getVectorShuffle(NewVT, dl, V1, V2, WidenedMask));
10655     }
10656   }
10657
10658   int NumV1Elements = 0, NumUndefElements = 0, NumV2Elements = 0;
10659   for (int M : SVOp->getMask())
10660     if (M < 0)
10661       ++NumUndefElements;
10662     else if (M < NumElements)
10663       ++NumV1Elements;
10664     else
10665       ++NumV2Elements;
10666
10667   // Commute the shuffle as needed such that more elements come from V1 than
10668   // V2. This allows us to match the shuffle pattern strictly on how many
10669   // elements come from V1 without handling the symmetric cases.
10670   if (NumV2Elements > NumV1Elements)
10671     return DAG.getCommutedVectorShuffle(*SVOp);
10672
10673   // When the number of V1 and V2 elements are the same, try to minimize the
10674   // number of uses of V2 in the low half of the vector. When that is tied,
10675   // ensure that the sum of indices for V1 is equal to or lower than the sum
10676   // indices for V2. When those are equal, try to ensure that the number of odd
10677   // indices for V1 is lower than the number of odd indices for V2.
10678   if (NumV1Elements == NumV2Elements) {
10679     int LowV1Elements = 0, LowV2Elements = 0;
10680     for (int M : SVOp->getMask().slice(0, NumElements / 2))
10681       if (M >= NumElements)
10682         ++LowV2Elements;
10683       else if (M >= 0)
10684         ++LowV1Elements;
10685     if (LowV2Elements > LowV1Elements) {
10686       return DAG.getCommutedVectorShuffle(*SVOp);
10687     } else if (LowV2Elements == LowV1Elements) {
10688       int SumV1Indices = 0, SumV2Indices = 0;
10689       for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
10690         if (SVOp->getMask()[i] >= NumElements)
10691           SumV2Indices += i;
10692         else if (SVOp->getMask()[i] >= 0)
10693           SumV1Indices += i;
10694       if (SumV2Indices < SumV1Indices) {
10695         return DAG.getCommutedVectorShuffle(*SVOp);
10696       } else if (SumV2Indices == SumV1Indices) {
10697         int NumV1OddIndices = 0, NumV2OddIndices = 0;
10698         for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
10699           if (SVOp->getMask()[i] >= NumElements)
10700             NumV2OddIndices += i % 2;
10701           else if (SVOp->getMask()[i] >= 0)
10702             NumV1OddIndices += i % 2;
10703         if (NumV2OddIndices < NumV1OddIndices)
10704           return DAG.getCommutedVectorShuffle(*SVOp);
10705       }
10706     }
10707   }
10708
10709   // For each vector width, delegate to a specialized lowering routine.
10710   if (VT.getSizeInBits() == 128)
10711     return lower128BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10712
10713   if (VT.getSizeInBits() == 256)
10714     return lower256BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10715
10716   // Force AVX-512 vectors to be scalarized for now.
10717   // FIXME: Implement AVX-512 support!
10718   if (VT.getSizeInBits() == 512)
10719     return lower512BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10720
10721   llvm_unreachable("Unimplemented!");
10722 }
10723
10724 // This function assumes its argument is a BUILD_VECTOR of constants or
10725 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
10726 // true.
10727 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
10728                                     unsigned &MaskValue) {
10729   MaskValue = 0;
10730   unsigned NumElems = BuildVector->getNumOperands();
10731   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
10732   unsigned NumLanes = (NumElems - 1) / 8 + 1;
10733   unsigned NumElemsInLane = NumElems / NumLanes;
10734
10735   // Blend for v16i16 should be symetric for the both lanes.
10736   for (unsigned i = 0; i < NumElemsInLane; ++i) {
10737     SDValue EltCond = BuildVector->getOperand(i);
10738     SDValue SndLaneEltCond =
10739         (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
10740
10741     int Lane1Cond = -1, Lane2Cond = -1;
10742     if (isa<ConstantSDNode>(EltCond))
10743       Lane1Cond = !isZero(EltCond);
10744     if (isa<ConstantSDNode>(SndLaneEltCond))
10745       Lane2Cond = !isZero(SndLaneEltCond);
10746
10747     if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
10748       // Lane1Cond != 0, means we want the first argument.
10749       // Lane1Cond == 0, means we want the second argument.
10750       // The encoding of this argument is 0 for the first argument, 1
10751       // for the second. Therefore, invert the condition.
10752       MaskValue |= !Lane1Cond << i;
10753     else if (Lane1Cond < 0)
10754       MaskValue |= !Lane2Cond << i;
10755     else
10756       return false;
10757   }
10758   return true;
10759 }
10760
10761 /// \brief Try to lower a VSELECT instruction to a vector shuffle.
10762 static SDValue lowerVSELECTtoVectorShuffle(SDValue Op,
10763                                            const X86Subtarget *Subtarget,
10764                                            SelectionDAG &DAG) {
10765   SDValue Cond = Op.getOperand(0);
10766   SDValue LHS = Op.getOperand(1);
10767   SDValue RHS = Op.getOperand(2);
10768   SDLoc dl(Op);
10769   MVT VT = Op.getSimpleValueType();
10770
10771   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
10772     return SDValue();
10773   auto *CondBV = cast<BuildVectorSDNode>(Cond);
10774
10775   // Only non-legal VSELECTs reach this lowering, convert those into generic
10776   // shuffles and re-use the shuffle lowering path for blends.
10777   SmallVector<int, 32> Mask;
10778   for (int i = 0, Size = VT.getVectorNumElements(); i < Size; ++i) {
10779     SDValue CondElt = CondBV->getOperand(i);
10780     Mask.push_back(
10781         isa<ConstantSDNode>(CondElt) ? i + (isZero(CondElt) ? Size : 0) : -1);
10782   }
10783   return DAG.getVectorShuffle(VT, dl, LHS, RHS, Mask);
10784 }
10785
10786 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
10787   // A vselect where all conditions and data are constants can be optimized into
10788   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
10789   if (ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(0).getNode()) &&
10790       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(1).getNode()) &&
10791       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(2).getNode()))
10792     return SDValue();
10793
10794   // Try to lower this to a blend-style vector shuffle. This can handle all
10795   // constant condition cases.
10796   if (SDValue BlendOp = lowerVSELECTtoVectorShuffle(Op, Subtarget, DAG))
10797     return BlendOp;
10798
10799   // Variable blends are only legal from SSE4.1 onward.
10800   if (!Subtarget->hasSSE41())
10801     return SDValue();
10802
10803   // Only some types will be legal on some subtargets. If we can emit a legal
10804   // VSELECT-matching blend, return Op, and but if we need to expand, return
10805   // a null value.
10806   switch (Op.getSimpleValueType().SimpleTy) {
10807   default:
10808     // Most of the vector types have blends past SSE4.1.
10809     return Op;
10810
10811   case MVT::v32i8:
10812     // The byte blends for AVX vectors were introduced only in AVX2.
10813     if (Subtarget->hasAVX2())
10814       return Op;
10815
10816     return SDValue();
10817
10818   case MVT::v8i16:
10819   case MVT::v16i16:
10820     // AVX-512 BWI and VLX features support VSELECT with i16 elements.
10821     if (Subtarget->hasBWI() && Subtarget->hasVLX())
10822       return Op;
10823
10824     // FIXME: We should custom lower this by fixing the condition and using i8
10825     // blends.
10826     return SDValue();
10827   }
10828 }
10829
10830 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
10831   MVT VT = Op.getSimpleValueType();
10832   SDLoc dl(Op);
10833
10834   if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
10835     return SDValue();
10836
10837   if (VT.getSizeInBits() == 8) {
10838     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
10839                                   Op.getOperand(0), Op.getOperand(1));
10840     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
10841                                   DAG.getValueType(VT));
10842     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10843   }
10844
10845   if (VT.getSizeInBits() == 16) {
10846     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10847     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
10848     if (Idx == 0)
10849       return DAG.getNode(
10850           ISD::TRUNCATE, dl, MVT::i16,
10851           DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10852                       DAG.getBitcast(MVT::v4i32, Op.getOperand(0)),
10853                       Op.getOperand(1)));
10854     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
10855                                   Op.getOperand(0), Op.getOperand(1));
10856     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
10857                                   DAG.getValueType(VT));
10858     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10859   }
10860
10861   if (VT == MVT::f32) {
10862     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
10863     // the result back to FR32 register. It's only worth matching if the
10864     // result has a single use which is a store or a bitcast to i32.  And in
10865     // the case of a store, it's not worth it if the index is a constant 0,
10866     // because a MOVSSmr can be used instead, which is smaller and faster.
10867     if (!Op.hasOneUse())
10868       return SDValue();
10869     SDNode *User = *Op.getNode()->use_begin();
10870     if ((User->getOpcode() != ISD::STORE ||
10871          (isa<ConstantSDNode>(Op.getOperand(1)) &&
10872           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
10873         (User->getOpcode() != ISD::BITCAST ||
10874          User->getValueType(0) != MVT::i32))
10875       return SDValue();
10876     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10877                                   DAG.getBitcast(MVT::v4i32, Op.getOperand(0)),
10878                                   Op.getOperand(1));
10879     return DAG.getBitcast(MVT::f32, Extract);
10880   }
10881
10882   if (VT == MVT::i32 || VT == MVT::i64) {
10883     // ExtractPS/pextrq works with constant index.
10884     if (isa<ConstantSDNode>(Op.getOperand(1)))
10885       return Op;
10886   }
10887   return SDValue();
10888 }
10889
10890 /// Extract one bit from mask vector, like v16i1 or v8i1.
10891 /// AVX-512 feature.
10892 SDValue
10893 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
10894   SDValue Vec = Op.getOperand(0);
10895   SDLoc dl(Vec);
10896   MVT VecVT = Vec.getSimpleValueType();
10897   SDValue Idx = Op.getOperand(1);
10898   MVT EltVT = Op.getSimpleValueType();
10899
10900   assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
10901   assert((VecVT.getVectorNumElements() <= 16 || Subtarget->hasBWI()) &&
10902          "Unexpected vector type in ExtractBitFromMaskVector");
10903
10904   // variable index can't be handled in mask registers,
10905   // extend vector to VR512
10906   if (!isa<ConstantSDNode>(Idx)) {
10907     MVT ExtVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
10908     SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
10909     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
10910                               ExtVT.getVectorElementType(), Ext, Idx);
10911     return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
10912   }
10913
10914   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10915   const TargetRegisterClass* rc = getRegClassFor(VecVT);
10916   if (!Subtarget->hasDQI() && (VecVT.getVectorNumElements() <= 8))
10917     rc = getRegClassFor(MVT::v16i1);
10918   unsigned MaxSift = rc->getSize()*8 - 1;
10919   Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
10920                     DAG.getConstant(MaxSift - IdxVal, dl, MVT::i8));
10921   Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
10922                     DAG.getConstant(MaxSift, dl, MVT::i8));
10923   return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
10924                        DAG.getIntPtrConstant(0, dl));
10925 }
10926
10927 SDValue
10928 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
10929                                            SelectionDAG &DAG) const {
10930   SDLoc dl(Op);
10931   SDValue Vec = Op.getOperand(0);
10932   MVT VecVT = Vec.getSimpleValueType();
10933   SDValue Idx = Op.getOperand(1);
10934
10935   if (Op.getSimpleValueType() == MVT::i1)
10936     return ExtractBitFromMaskVector(Op, DAG);
10937
10938   if (!isa<ConstantSDNode>(Idx)) {
10939     if (VecVT.is512BitVector() ||
10940         (VecVT.is256BitVector() && Subtarget->hasInt256() &&
10941          VecVT.getVectorElementType().getSizeInBits() == 32)) {
10942
10943       MVT MaskEltVT =
10944         MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
10945       MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
10946                                     MaskEltVT.getSizeInBits());
10947
10948       Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
10949       auto PtrVT = getPointerTy(DAG.getDataLayout());
10950       SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
10951                                  getZeroVector(MaskVT, Subtarget, DAG, dl), Idx,
10952                                  DAG.getConstant(0, dl, PtrVT));
10953       SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
10954       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Perm,
10955                          DAG.getConstant(0, dl, PtrVT));
10956     }
10957     return SDValue();
10958   }
10959
10960   // If this is a 256-bit vector result, first extract the 128-bit vector and
10961   // then extract the element from the 128-bit vector.
10962   if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
10963
10964     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10965     // Get the 128-bit vector.
10966     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
10967     MVT EltVT = VecVT.getVectorElementType();
10968
10969     unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
10970
10971     //if (IdxVal >= NumElems/2)
10972     //  IdxVal -= NumElems/2;
10973     IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
10974     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
10975                        DAG.getConstant(IdxVal, dl, MVT::i32));
10976   }
10977
10978   assert(VecVT.is128BitVector() && "Unexpected vector length");
10979
10980   if (Subtarget->hasSSE41())
10981     if (SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG))
10982       return Res;
10983
10984   MVT VT = Op.getSimpleValueType();
10985   // TODO: handle v16i8.
10986   if (VT.getSizeInBits() == 16) {
10987     SDValue Vec = Op.getOperand(0);
10988     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10989     if (Idx == 0)
10990       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
10991                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10992                                      DAG.getBitcast(MVT::v4i32, Vec),
10993                                      Op.getOperand(1)));
10994     // Transform it so it match pextrw which produces a 32-bit result.
10995     MVT EltVT = MVT::i32;
10996     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
10997                                   Op.getOperand(0), Op.getOperand(1));
10998     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
10999                                   DAG.getValueType(VT));
11000     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
11001   }
11002
11003   if (VT.getSizeInBits() == 32) {
11004     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11005     if (Idx == 0)
11006       return Op;
11007
11008     // SHUFPS the element to the lowest double word, then movss.
11009     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
11010     MVT VVT = Op.getOperand(0).getSimpleValueType();
11011     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
11012                                        DAG.getUNDEF(VVT), Mask);
11013     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
11014                        DAG.getIntPtrConstant(0, dl));
11015   }
11016
11017   if (VT.getSizeInBits() == 64) {
11018     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
11019     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
11020     //        to match extract_elt for f64.
11021     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11022     if (Idx == 0)
11023       return Op;
11024
11025     // UNPCKHPD the element to the lowest double word, then movsd.
11026     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
11027     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
11028     int Mask[2] = { 1, -1 };
11029     MVT VVT = Op.getOperand(0).getSimpleValueType();
11030     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
11031                                        DAG.getUNDEF(VVT), Mask);
11032     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
11033                        DAG.getIntPtrConstant(0, dl));
11034   }
11035
11036   return SDValue();
11037 }
11038
11039 /// Insert one bit to mask vector, like v16i1 or v8i1.
11040 /// AVX-512 feature.
11041 SDValue
11042 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
11043   SDLoc dl(Op);
11044   SDValue Vec = Op.getOperand(0);
11045   SDValue Elt = Op.getOperand(1);
11046   SDValue Idx = Op.getOperand(2);
11047   MVT VecVT = Vec.getSimpleValueType();
11048
11049   if (!isa<ConstantSDNode>(Idx)) {
11050     // Non constant index. Extend source and destination,
11051     // insert element and then truncate the result.
11052     MVT ExtVecVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
11053     MVT ExtEltVT = (VecVT == MVT::v8i1 ?  MVT::i64 : MVT::i32);
11054     SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT,
11055       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
11056       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
11057     return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
11058   }
11059
11060   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11061   SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
11062   if (IdxVal)
11063     EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
11064                            DAG.getConstant(IdxVal, dl, MVT::i8));
11065   if (Vec.getOpcode() == ISD::UNDEF)
11066     return EltInVec;
11067   return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
11068 }
11069
11070 SDValue X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
11071                                                   SelectionDAG &DAG) const {
11072   MVT VT = Op.getSimpleValueType();
11073   MVT EltVT = VT.getVectorElementType();
11074
11075   if (EltVT == MVT::i1)
11076     return InsertBitToMaskVector(Op, DAG);
11077
11078   SDLoc dl(Op);
11079   SDValue N0 = Op.getOperand(0);
11080   SDValue N1 = Op.getOperand(1);
11081   SDValue N2 = Op.getOperand(2);
11082   if (!isa<ConstantSDNode>(N2))
11083     return SDValue();
11084   auto *N2C = cast<ConstantSDNode>(N2);
11085   unsigned IdxVal = N2C->getZExtValue();
11086
11087   // If the vector is wider than 128 bits, extract the 128-bit subvector, insert
11088   // into that, and then insert the subvector back into the result.
11089   if (VT.is256BitVector() || VT.is512BitVector()) {
11090     // With a 256-bit vector, we can insert into the zero element efficiently
11091     // using a blend if we have AVX or AVX2 and the right data type.
11092     if (VT.is256BitVector() && IdxVal == 0) {
11093       // TODO: It is worthwhile to cast integer to floating point and back
11094       // and incur a domain crossing penalty if that's what we'll end up
11095       // doing anyway after extracting to a 128-bit vector.
11096       if ((Subtarget->hasAVX() && (EltVT == MVT::f64 || EltVT == MVT::f32)) ||
11097           (Subtarget->hasAVX2() && EltVT == MVT::i32)) {
11098         SDValue N1Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, N1);
11099         N2 = DAG.getIntPtrConstant(1, dl);
11100         return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1Vec, N2);
11101       }
11102     }
11103
11104     // Get the desired 128-bit vector chunk.
11105     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
11106
11107     // Insert the element into the desired chunk.
11108     unsigned NumEltsIn128 = 128 / EltVT.getSizeInBits();
11109     unsigned IdxIn128 = IdxVal - (IdxVal / NumEltsIn128) * NumEltsIn128;
11110
11111     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
11112                     DAG.getConstant(IdxIn128, dl, MVT::i32));
11113
11114     // Insert the changed part back into the bigger vector
11115     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
11116   }
11117   assert(VT.is128BitVector() && "Only 128-bit vector types should be left!");
11118
11119   if (Subtarget->hasSSE41()) {
11120     if (EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) {
11121       unsigned Opc;
11122       if (VT == MVT::v8i16) {
11123         Opc = X86ISD::PINSRW;
11124       } else {
11125         assert(VT == MVT::v16i8);
11126         Opc = X86ISD::PINSRB;
11127       }
11128
11129       // Transform it so it match pinsr{b,w} which expects a GR32 as its second
11130       // argument.
11131       if (N1.getValueType() != MVT::i32)
11132         N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
11133       if (N2.getValueType() != MVT::i32)
11134         N2 = DAG.getIntPtrConstant(IdxVal, dl);
11135       return DAG.getNode(Opc, dl, VT, N0, N1, N2);
11136     }
11137
11138     if (EltVT == MVT::f32) {
11139       // Bits [7:6] of the constant are the source select. This will always be
11140       //   zero here. The DAG Combiner may combine an extract_elt index into
11141       //   these bits. For example (insert (extract, 3), 2) could be matched by
11142       //   putting the '3' into bits [7:6] of X86ISD::INSERTPS.
11143       // Bits [5:4] of the constant are the destination select. This is the
11144       //   value of the incoming immediate.
11145       // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
11146       //   combine either bitwise AND or insert of float 0.0 to set these bits.
11147
11148       bool MinSize = DAG.getMachineFunction().getFunction()->optForMinSize();
11149       if (IdxVal == 0 && (!MinSize || !MayFoldLoad(N1))) {
11150         // If this is an insertion of 32-bits into the low 32-bits of
11151         // a vector, we prefer to generate a blend with immediate rather
11152         // than an insertps. Blends are simpler operations in hardware and so
11153         // will always have equal or better performance than insertps.
11154         // But if optimizing for size and there's a load folding opportunity,
11155         // generate insertps because blendps does not have a 32-bit memory
11156         // operand form.
11157         N2 = DAG.getIntPtrConstant(1, dl);
11158         N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
11159         return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1, N2);
11160       }
11161       N2 = DAG.getIntPtrConstant(IdxVal << 4, dl);
11162       // Create this as a scalar to vector..
11163       N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
11164       return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
11165     }
11166
11167     if (EltVT == MVT::i32 || EltVT == MVT::i64) {
11168       // PINSR* works with constant index.
11169       return Op;
11170     }
11171   }
11172
11173   if (EltVT == MVT::i8)
11174     return SDValue();
11175
11176   if (EltVT.getSizeInBits() == 16) {
11177     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
11178     // as its second argument.
11179     if (N1.getValueType() != MVT::i32)
11180       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
11181     if (N2.getValueType() != MVT::i32)
11182       N2 = DAG.getIntPtrConstant(IdxVal, dl);
11183     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
11184   }
11185   return SDValue();
11186 }
11187
11188 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
11189   SDLoc dl(Op);
11190   MVT OpVT = Op.getSimpleValueType();
11191
11192   // If this is a 256-bit vector result, first insert into a 128-bit
11193   // vector and then insert into the 256-bit vector.
11194   if (!OpVT.is128BitVector()) {
11195     // Insert into a 128-bit vector.
11196     unsigned SizeFactor = OpVT.getSizeInBits()/128;
11197     MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
11198                                  OpVT.getVectorNumElements() / SizeFactor);
11199
11200     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
11201
11202     // Insert the 128-bit vector.
11203     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
11204   }
11205
11206   if (OpVT == MVT::v1i64 &&
11207       Op.getOperand(0).getValueType() == MVT::i64)
11208     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
11209
11210   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
11211   assert(OpVT.is128BitVector() && "Expected an SSE type!");
11212   return DAG.getBitcast(
11213       OpVT, DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, AnyExt));
11214 }
11215
11216 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
11217 // a simple subregister reference or explicit instructions to grab
11218 // upper bits of a vector.
11219 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
11220                                       SelectionDAG &DAG) {
11221   SDLoc dl(Op);
11222   SDValue In =  Op.getOperand(0);
11223   SDValue Idx = Op.getOperand(1);
11224   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11225   MVT ResVT   = Op.getSimpleValueType();
11226   MVT InVT    = In.getSimpleValueType();
11227
11228   if (Subtarget->hasFp256()) {
11229     if (ResVT.is128BitVector() &&
11230         (InVT.is256BitVector() || InVT.is512BitVector()) &&
11231         isa<ConstantSDNode>(Idx)) {
11232       return Extract128BitVector(In, IdxVal, DAG, dl);
11233     }
11234     if (ResVT.is256BitVector() && InVT.is512BitVector() &&
11235         isa<ConstantSDNode>(Idx)) {
11236       return Extract256BitVector(In, IdxVal, DAG, dl);
11237     }
11238   }
11239   return SDValue();
11240 }
11241
11242 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
11243 // simple superregister reference or explicit instructions to insert
11244 // the upper bits of a vector.
11245 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
11246                                      SelectionDAG &DAG) {
11247   if (!Subtarget->hasAVX())
11248     return SDValue();
11249
11250   SDLoc dl(Op);
11251   SDValue Vec = Op.getOperand(0);
11252   SDValue SubVec = Op.getOperand(1);
11253   SDValue Idx = Op.getOperand(2);
11254
11255   if (!isa<ConstantSDNode>(Idx))
11256     return SDValue();
11257
11258   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11259   MVT OpVT = Op.getSimpleValueType();
11260   MVT SubVecVT = SubVec.getSimpleValueType();
11261
11262   // Fold two 16-byte subvector loads into one 32-byte load:
11263   // (insert_subvector (insert_subvector undef, (load addr), 0),
11264   //                   (load addr + 16), Elts/2)
11265   // --> load32 addr
11266   if ((IdxVal == OpVT.getVectorNumElements() / 2) &&
11267       Vec.getOpcode() == ISD::INSERT_SUBVECTOR &&
11268       OpVT.is256BitVector() && SubVecVT.is128BitVector()) {
11269     auto *Idx2 = dyn_cast<ConstantSDNode>(Vec.getOperand(2));
11270     if (Idx2 && Idx2->getZExtValue() == 0) {
11271       SDValue SubVec2 = Vec.getOperand(1);
11272       // If needed, look through a bitcast to get to the load.
11273       if (SubVec2.getNode() && SubVec2.getOpcode() == ISD::BITCAST)
11274         SubVec2 = SubVec2.getOperand(0);
11275       
11276       if (auto *FirstLd = dyn_cast<LoadSDNode>(SubVec2)) {
11277         bool Fast;
11278         unsigned Alignment = FirstLd->getAlignment();
11279         unsigned AS = FirstLd->getAddressSpace();
11280         const X86TargetLowering *TLI = Subtarget->getTargetLowering();
11281         if (TLI->allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(),
11282                                     OpVT, AS, Alignment, &Fast) && Fast) {
11283           SDValue Ops[] = { SubVec2, SubVec };
11284           if (SDValue Ld = EltsFromConsecutiveLoads(OpVT, Ops, dl, DAG, false))
11285             return Ld;
11286         }
11287       }
11288     }
11289   }
11290
11291   if ((OpVT.is256BitVector() || OpVT.is512BitVector()) &&
11292       SubVecVT.is128BitVector())
11293     return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
11294
11295   if (OpVT.is512BitVector() && SubVecVT.is256BitVector())
11296     return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
11297
11298   if (OpVT.getVectorElementType() == MVT::i1) {
11299     if (IdxVal == 0  && Vec.getOpcode() == ISD::UNDEF) // the operation is legal
11300       return Op;
11301     SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
11302     SDValue Undef = DAG.getUNDEF(OpVT);
11303     unsigned NumElems = OpVT.getVectorNumElements();
11304     SDValue ShiftBits = DAG.getConstant(NumElems/2, dl, MVT::i8);
11305
11306     if (IdxVal == OpVT.getVectorNumElements() / 2) {
11307       // Zero upper bits of the Vec
11308       Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
11309       Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
11310
11311       SDValue Vec2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef,
11312                                  SubVec, ZeroIdx);
11313       Vec2 = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec2, ShiftBits);
11314       return DAG.getNode(ISD::OR, dl, OpVT, Vec, Vec2);
11315     }
11316     if (IdxVal == 0) {
11317       SDValue Vec2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef,
11318                                  SubVec, ZeroIdx);
11319       // Zero upper bits of the Vec2
11320       Vec2 = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec2, ShiftBits);
11321       Vec2 = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec2, ShiftBits);
11322       // Zero lower bits of the Vec
11323       Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
11324       Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
11325       // Merge them together
11326       return DAG.getNode(ISD::OR, dl, OpVT, Vec, Vec2);
11327     }
11328   }
11329   return SDValue();
11330 }
11331
11332 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
11333 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
11334 // one of the above mentioned nodes. It has to be wrapped because otherwise
11335 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
11336 // be used to form addressing mode. These wrapped nodes will be selected
11337 // into MOV32ri.
11338 SDValue
11339 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
11340   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
11341
11342   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11343   // global base reg.
11344   unsigned char OpFlag = 0;
11345   unsigned WrapperKind = X86ISD::Wrapper;
11346   CodeModel::Model M = DAG.getTarget().getCodeModel();
11347
11348   if (Subtarget->isPICStyleRIPRel() &&
11349       (M == CodeModel::Small || M == CodeModel::Kernel))
11350     WrapperKind = X86ISD::WrapperRIP;
11351   else if (Subtarget->isPICStyleGOT())
11352     OpFlag = X86II::MO_GOTOFF;
11353   else if (Subtarget->isPICStyleStubPIC())
11354     OpFlag = X86II::MO_PIC_BASE_OFFSET;
11355
11356   auto PtrVT = getPointerTy(DAG.getDataLayout());
11357   SDValue Result = DAG.getTargetConstantPool(
11358       CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(), OpFlag);
11359   SDLoc DL(CP);
11360   Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11361   // With PIC, the address is actually $g + Offset.
11362   if (OpFlag) {
11363     Result =
11364         DAG.getNode(ISD::ADD, DL, PtrVT,
11365                     DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
11366   }
11367
11368   return Result;
11369 }
11370
11371 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
11372   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
11373
11374   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11375   // global base reg.
11376   unsigned char OpFlag = 0;
11377   unsigned WrapperKind = X86ISD::Wrapper;
11378   CodeModel::Model M = DAG.getTarget().getCodeModel();
11379
11380   if (Subtarget->isPICStyleRIPRel() &&
11381       (M == CodeModel::Small || M == CodeModel::Kernel))
11382     WrapperKind = X86ISD::WrapperRIP;
11383   else if (Subtarget->isPICStyleGOT())
11384     OpFlag = X86II::MO_GOTOFF;
11385   else if (Subtarget->isPICStyleStubPIC())
11386     OpFlag = X86II::MO_PIC_BASE_OFFSET;
11387
11388   auto PtrVT = getPointerTy(DAG.getDataLayout());
11389   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, OpFlag);
11390   SDLoc DL(JT);
11391   Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11392
11393   // With PIC, the address is actually $g + Offset.
11394   if (OpFlag)
11395     Result =
11396         DAG.getNode(ISD::ADD, DL, PtrVT,
11397                     DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
11398
11399   return Result;
11400 }
11401
11402 SDValue
11403 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
11404   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
11405
11406   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11407   // global base reg.
11408   unsigned char OpFlag = 0;
11409   unsigned WrapperKind = X86ISD::Wrapper;
11410   CodeModel::Model M = DAG.getTarget().getCodeModel();
11411
11412   if (Subtarget->isPICStyleRIPRel() &&
11413       (M == CodeModel::Small || M == CodeModel::Kernel)) {
11414     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
11415       OpFlag = X86II::MO_GOTPCREL;
11416     WrapperKind = X86ISD::WrapperRIP;
11417   } else if (Subtarget->isPICStyleGOT()) {
11418     OpFlag = X86II::MO_GOT;
11419   } else if (Subtarget->isPICStyleStubPIC()) {
11420     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
11421   } else if (Subtarget->isPICStyleStubNoDynamic()) {
11422     OpFlag = X86II::MO_DARWIN_NONLAZY;
11423   }
11424
11425   auto PtrVT = getPointerTy(DAG.getDataLayout());
11426   SDValue Result = DAG.getTargetExternalSymbol(Sym, PtrVT, OpFlag);
11427
11428   SDLoc DL(Op);
11429   Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11430
11431   // With PIC, the address is actually $g + Offset.
11432   if (DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
11433       !Subtarget->is64Bit()) {
11434     Result =
11435         DAG.getNode(ISD::ADD, DL, PtrVT,
11436                     DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
11437   }
11438
11439   // For symbols that require a load from a stub to get the address, emit the
11440   // load.
11441   if (isGlobalStubReference(OpFlag))
11442     Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
11443                          MachinePointerInfo::getGOT(DAG.getMachineFunction()),
11444                          false, false, false, 0);
11445
11446   return Result;
11447 }
11448
11449 SDValue
11450 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
11451   // Create the TargetBlockAddressAddress node.
11452   unsigned char OpFlags =
11453     Subtarget->ClassifyBlockAddressReference();
11454   CodeModel::Model M = DAG.getTarget().getCodeModel();
11455   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
11456   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
11457   SDLoc dl(Op);
11458   auto PtrVT = getPointerTy(DAG.getDataLayout());
11459   SDValue Result = DAG.getTargetBlockAddress(BA, PtrVT, Offset, OpFlags);
11460
11461   if (Subtarget->isPICStyleRIPRel() &&
11462       (M == CodeModel::Small || M == CodeModel::Kernel))
11463     Result = DAG.getNode(X86ISD::WrapperRIP, dl, PtrVT, Result);
11464   else
11465     Result = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, Result);
11466
11467   // With PIC, the address is actually $g + Offset.
11468   if (isGlobalRelativeToPICBase(OpFlags)) {
11469     Result = DAG.getNode(ISD::ADD, dl, PtrVT,
11470                          DAG.getNode(X86ISD::GlobalBaseReg, dl, PtrVT), Result);
11471   }
11472
11473   return Result;
11474 }
11475
11476 SDValue
11477 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
11478                                       int64_t Offset, SelectionDAG &DAG) const {
11479   // Create the TargetGlobalAddress node, folding in the constant
11480   // offset if it is legal.
11481   unsigned char OpFlags =
11482       Subtarget->ClassifyGlobalReference(GV, DAG.getTarget());
11483   CodeModel::Model M = DAG.getTarget().getCodeModel();
11484   auto PtrVT = getPointerTy(DAG.getDataLayout());
11485   SDValue Result;
11486   if (OpFlags == X86II::MO_NO_FLAG &&
11487       X86::isOffsetSuitableForCodeModel(Offset, M)) {
11488     // A direct static reference to a global.
11489     Result = DAG.getTargetGlobalAddress(GV, dl, PtrVT, Offset);
11490     Offset = 0;
11491   } else {
11492     Result = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, OpFlags);
11493   }
11494
11495   if (Subtarget->isPICStyleRIPRel() &&
11496       (M == CodeModel::Small || M == CodeModel::Kernel))
11497     Result = DAG.getNode(X86ISD::WrapperRIP, dl, PtrVT, Result);
11498   else
11499     Result = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, Result);
11500
11501   // With PIC, the address is actually $g + Offset.
11502   if (isGlobalRelativeToPICBase(OpFlags)) {
11503     Result = DAG.getNode(ISD::ADD, dl, PtrVT,
11504                          DAG.getNode(X86ISD::GlobalBaseReg, dl, PtrVT), Result);
11505   }
11506
11507   // For globals that require a load from a stub to get the address, emit the
11508   // load.
11509   if (isGlobalStubReference(OpFlags))
11510     Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
11511                          MachinePointerInfo::getGOT(DAG.getMachineFunction()),
11512                          false, false, false, 0);
11513
11514   // If there was a non-zero offset that we didn't fold, create an explicit
11515   // addition for it.
11516   if (Offset != 0)
11517     Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result,
11518                          DAG.getConstant(Offset, dl, PtrVT));
11519
11520   return Result;
11521 }
11522
11523 SDValue
11524 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
11525   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
11526   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
11527   return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
11528 }
11529
11530 static SDValue
11531 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
11532            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
11533            unsigned char OperandFlags, bool LocalDynamic = false) {
11534   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11535   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11536   SDLoc dl(GA);
11537   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11538                                            GA->getValueType(0),
11539                                            GA->getOffset(),
11540                                            OperandFlags);
11541
11542   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
11543                                            : X86ISD::TLSADDR;
11544
11545   if (InFlag) {
11546     SDValue Ops[] = { Chain,  TGA, *InFlag };
11547     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11548   } else {
11549     SDValue Ops[]  = { Chain, TGA };
11550     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11551   }
11552
11553   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
11554   MFI->setAdjustsStack(true);
11555   MFI->setHasCalls(true);
11556
11557   SDValue Flag = Chain.getValue(1);
11558   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
11559 }
11560
11561 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
11562 static SDValue
11563 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11564                                 const EVT PtrVT) {
11565   SDValue InFlag;
11566   SDLoc dl(GA);  // ? function entry point might be better
11567   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
11568                                    DAG.getNode(X86ISD::GlobalBaseReg,
11569                                                SDLoc(), PtrVT), InFlag);
11570   InFlag = Chain.getValue(1);
11571
11572   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
11573 }
11574
11575 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
11576 static SDValue
11577 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11578                                 const EVT PtrVT) {
11579   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
11580                     X86::RAX, X86II::MO_TLSGD);
11581 }
11582
11583 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
11584                                            SelectionDAG &DAG,
11585                                            const EVT PtrVT,
11586                                            bool is64Bit) {
11587   SDLoc dl(GA);
11588
11589   // Get the start address of the TLS block for this module.
11590   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
11591       .getInfo<X86MachineFunctionInfo>();
11592   MFI->incNumLocalDynamicTLSAccesses();
11593
11594   SDValue Base;
11595   if (is64Bit) {
11596     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
11597                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
11598   } else {
11599     SDValue InFlag;
11600     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
11601         DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
11602     InFlag = Chain.getValue(1);
11603     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
11604                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
11605   }
11606
11607   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
11608   // of Base.
11609
11610   // Build x@dtpoff.
11611   unsigned char OperandFlags = X86II::MO_DTPOFF;
11612   unsigned WrapperKind = X86ISD::Wrapper;
11613   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11614                                            GA->getValueType(0),
11615                                            GA->getOffset(), OperandFlags);
11616   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
11617
11618   // Add x@dtpoff with the base.
11619   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
11620 }
11621
11622 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
11623 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11624                                    const EVT PtrVT, TLSModel::Model model,
11625                                    bool is64Bit, bool isPIC) {
11626   SDLoc dl(GA);
11627
11628   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
11629   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
11630                                                          is64Bit ? 257 : 256));
11631
11632   SDValue ThreadPointer =
11633       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0, dl),
11634                   MachinePointerInfo(Ptr), false, false, false, 0);
11635
11636   unsigned char OperandFlags = 0;
11637   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
11638   // initialexec.
11639   unsigned WrapperKind = X86ISD::Wrapper;
11640   if (model == TLSModel::LocalExec) {
11641     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
11642   } else if (model == TLSModel::InitialExec) {
11643     if (is64Bit) {
11644       OperandFlags = X86II::MO_GOTTPOFF;
11645       WrapperKind = X86ISD::WrapperRIP;
11646     } else {
11647       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
11648     }
11649   } else {
11650     llvm_unreachable("Unexpected model");
11651   }
11652
11653   // emit "addl x@ntpoff,%eax" (local exec)
11654   // or "addl x@indntpoff,%eax" (initial exec)
11655   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
11656   SDValue TGA =
11657       DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
11658                                  GA->getOffset(), OperandFlags);
11659   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
11660
11661   if (model == TLSModel::InitialExec) {
11662     if (isPIC && !is64Bit) {
11663       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
11664                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
11665                            Offset);
11666     }
11667
11668     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
11669                          MachinePointerInfo::getGOT(DAG.getMachineFunction()),
11670                          false, false, false, 0);
11671   }
11672
11673   // The address of the thread local variable is the add of the thread
11674   // pointer with the offset of the variable.
11675   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
11676 }
11677
11678 SDValue
11679 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
11680
11681   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
11682   const GlobalValue *GV = GA->getGlobal();
11683   auto PtrVT = getPointerTy(DAG.getDataLayout());
11684
11685   if (Subtarget->isTargetELF()) {
11686     if (DAG.getTarget().Options.EmulatedTLS)
11687       return LowerToTLSEmulatedModel(GA, DAG);
11688     TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
11689     switch (model) {
11690       case TLSModel::GeneralDynamic:
11691         if (Subtarget->is64Bit())
11692           return LowerToTLSGeneralDynamicModel64(GA, DAG, PtrVT);
11693         return LowerToTLSGeneralDynamicModel32(GA, DAG, PtrVT);
11694       case TLSModel::LocalDynamic:
11695         return LowerToTLSLocalDynamicModel(GA, DAG, PtrVT,
11696                                            Subtarget->is64Bit());
11697       case TLSModel::InitialExec:
11698       case TLSModel::LocalExec:
11699         return LowerToTLSExecModel(GA, DAG, PtrVT, model, Subtarget->is64Bit(),
11700                                    DAG.getTarget().getRelocationModel() ==
11701                                        Reloc::PIC_);
11702     }
11703     llvm_unreachable("Unknown TLS model.");
11704   }
11705
11706   if (Subtarget->isTargetDarwin()) {
11707     // Darwin only has one model of TLS.  Lower to that.
11708     unsigned char OpFlag = 0;
11709     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
11710                            X86ISD::WrapperRIP : X86ISD::Wrapper;
11711
11712     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11713     // global base reg.
11714     bool PIC32 = (DAG.getTarget().getRelocationModel() == Reloc::PIC_) &&
11715                  !Subtarget->is64Bit();
11716     if (PIC32)
11717       OpFlag = X86II::MO_TLVP_PIC_BASE;
11718     else
11719       OpFlag = X86II::MO_TLVP;
11720     SDLoc DL(Op);
11721     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
11722                                                 GA->getValueType(0),
11723                                                 GA->getOffset(), OpFlag);
11724     SDValue Offset = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11725
11726     // With PIC32, the address is actually $g + Offset.
11727     if (PIC32)
11728       Offset = DAG.getNode(ISD::ADD, DL, PtrVT,
11729                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
11730                            Offset);
11731
11732     // Lowering the machine isd will make sure everything is in the right
11733     // location.
11734     SDValue Chain = DAG.getEntryNode();
11735     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11736     SDValue Args[] = { Chain, Offset };
11737     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
11738
11739     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
11740     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11741     MFI->setAdjustsStack(true);
11742
11743     // And our return value (tls address) is in the standard call return value
11744     // location.
11745     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
11746     return DAG.getCopyFromReg(Chain, DL, Reg, PtrVT, Chain.getValue(1));
11747   }
11748
11749   if (Subtarget->isTargetKnownWindowsMSVC() ||
11750       Subtarget->isTargetWindowsGNU()) {
11751     // Just use the implicit TLS architecture
11752     // Need to generate someting similar to:
11753     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
11754     //                                  ; from TEB
11755     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
11756     //   mov     rcx, qword [rdx+rcx*8]
11757     //   mov     eax, .tls$:tlsvar
11758     //   [rax+rcx] contains the address
11759     // Windows 64bit: gs:0x58
11760     // Windows 32bit: fs:__tls_array
11761
11762     SDLoc dl(GA);
11763     SDValue Chain = DAG.getEntryNode();
11764
11765     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
11766     // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
11767     // use its literal value of 0x2C.
11768     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
11769                                         ? Type::getInt8PtrTy(*DAG.getContext(),
11770                                                              256)
11771                                         : Type::getInt32PtrTy(*DAG.getContext(),
11772                                                               257));
11773
11774     SDValue TlsArray = Subtarget->is64Bit()
11775                            ? DAG.getIntPtrConstant(0x58, dl)
11776                            : (Subtarget->isTargetWindowsGNU()
11777                                   ? DAG.getIntPtrConstant(0x2C, dl)
11778                                   : DAG.getExternalSymbol("_tls_array", PtrVT));
11779
11780     SDValue ThreadPointer =
11781         DAG.getLoad(PtrVT, dl, Chain, TlsArray, MachinePointerInfo(Ptr), false,
11782                     false, false, 0);
11783
11784     SDValue res;
11785     if (GV->getThreadLocalMode() == GlobalVariable::LocalExecTLSModel) {
11786       res = ThreadPointer;
11787     } else {
11788       // Load the _tls_index variable
11789       SDValue IDX = DAG.getExternalSymbol("_tls_index", PtrVT);
11790       if (Subtarget->is64Bit())
11791         IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, PtrVT, Chain, IDX,
11792                              MachinePointerInfo(), MVT::i32, false, false,
11793                              false, 0);
11794       else
11795         IDX = DAG.getLoad(PtrVT, dl, Chain, IDX, MachinePointerInfo(), false,
11796                           false, false, 0);
11797
11798       auto &DL = DAG.getDataLayout();
11799       SDValue Scale =
11800           DAG.getConstant(Log2_64_Ceil(DL.getPointerSize()), dl, PtrVT);
11801       IDX = DAG.getNode(ISD::SHL, dl, PtrVT, IDX, Scale);
11802
11803       res = DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, IDX);
11804     }
11805
11806     res = DAG.getLoad(PtrVT, dl, Chain, res, MachinePointerInfo(), false, false,
11807                       false, 0);
11808
11809     // Get the offset of start of .tls section
11810     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11811                                              GA->getValueType(0),
11812                                              GA->getOffset(), X86II::MO_SECREL);
11813     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, TGA);
11814
11815     // The address of the thread local variable is the add of the thread
11816     // pointer with the offset of the variable.
11817     return DAG.getNode(ISD::ADD, dl, PtrVT, res, Offset);
11818   }
11819
11820   llvm_unreachable("TLS not implemented for this target.");
11821 }
11822
11823 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
11824 /// and take a 2 x i32 value to shift plus a shift amount.
11825 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
11826   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
11827   MVT VT = Op.getSimpleValueType();
11828   unsigned VTBits = VT.getSizeInBits();
11829   SDLoc dl(Op);
11830   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
11831   SDValue ShOpLo = Op.getOperand(0);
11832   SDValue ShOpHi = Op.getOperand(1);
11833   SDValue ShAmt  = Op.getOperand(2);
11834   // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
11835   // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
11836   // during isel.
11837   SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
11838                                   DAG.getConstant(VTBits - 1, dl, MVT::i8));
11839   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
11840                                      DAG.getConstant(VTBits - 1, dl, MVT::i8))
11841                        : DAG.getConstant(0, dl, VT);
11842
11843   SDValue Tmp2, Tmp3;
11844   if (Op.getOpcode() == ISD::SHL_PARTS) {
11845     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
11846     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
11847   } else {
11848     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
11849     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
11850   }
11851
11852   // If the shift amount is larger or equal than the width of a part we can't
11853   // rely on the results of shld/shrd. Insert a test and select the appropriate
11854   // values for large shift amounts.
11855   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
11856                                 DAG.getConstant(VTBits, dl, MVT::i8));
11857   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11858                              AndNode, DAG.getConstant(0, dl, MVT::i8));
11859
11860   SDValue Hi, Lo;
11861   SDValue CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
11862   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
11863   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
11864
11865   if (Op.getOpcode() == ISD::SHL_PARTS) {
11866     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
11867     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
11868   } else {
11869     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
11870     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
11871   }
11872
11873   SDValue Ops[2] = { Lo, Hi };
11874   return DAG.getMergeValues(Ops, dl);
11875 }
11876
11877 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
11878                                            SelectionDAG &DAG) const {
11879   SDValue Src = Op.getOperand(0);
11880   MVT SrcVT = Src.getSimpleValueType();
11881   MVT VT = Op.getSimpleValueType();
11882   SDLoc dl(Op);
11883
11884   if (SrcVT.isVector()) {
11885     if (SrcVT == MVT::v2i32 && VT == MVT::v2f64) {
11886       return DAG.getNode(X86ISD::CVTDQ2PD, dl, VT,
11887                          DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4i32, Src,
11888                          DAG.getUNDEF(SrcVT)));
11889     }
11890     if (SrcVT.getVectorElementType() == MVT::i1) {
11891       MVT IntegerVT = MVT::getVectorVT(MVT::i32, SrcVT.getVectorNumElements());
11892       return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
11893                          DAG.getNode(ISD::SIGN_EXTEND, dl, IntegerVT, Src));
11894     }
11895     return SDValue();
11896   }
11897
11898   assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
11899          "Unknown SINT_TO_FP to lower!");
11900
11901   // These are really Legal; return the operand so the caller accepts it as
11902   // Legal.
11903   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
11904     return Op;
11905   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
11906       Subtarget->is64Bit()) {
11907     return Op;
11908   }
11909
11910   unsigned Size = SrcVT.getSizeInBits()/8;
11911   MachineFunction &MF = DAG.getMachineFunction();
11912   auto PtrVT = getPointerTy(MF.getDataLayout());
11913   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
11914   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
11915   SDValue Chain = DAG.getStore(
11916       DAG.getEntryNode(), dl, Op.getOperand(0), StackSlot,
11917       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI), false,
11918       false, 0);
11919   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
11920 }
11921
11922 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
11923                                      SDValue StackSlot,
11924                                      SelectionDAG &DAG) const {
11925   // Build the FILD
11926   SDLoc DL(Op);
11927   SDVTList Tys;
11928   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
11929   if (useSSE)
11930     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
11931   else
11932     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
11933
11934   unsigned ByteSize = SrcVT.getSizeInBits()/8;
11935
11936   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
11937   MachineMemOperand *MMO;
11938   if (FI) {
11939     int SSFI = FI->getIndex();
11940     MMO = DAG.getMachineFunction().getMachineMemOperand(
11941         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
11942         MachineMemOperand::MOLoad, ByteSize, ByteSize);
11943   } else {
11944     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
11945     StackSlot = StackSlot.getOperand(1);
11946   }
11947   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
11948   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
11949                                            X86ISD::FILD, DL,
11950                                            Tys, Ops, SrcVT, MMO);
11951
11952   if (useSSE) {
11953     Chain = Result.getValue(1);
11954     SDValue InFlag = Result.getValue(2);
11955
11956     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
11957     // shouldn't be necessary except that RFP cannot be live across
11958     // multiple blocks. When stackifier is fixed, they can be uncoupled.
11959     MachineFunction &MF = DAG.getMachineFunction();
11960     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
11961     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
11962     auto PtrVT = getPointerTy(MF.getDataLayout());
11963     SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
11964     Tys = DAG.getVTList(MVT::Other);
11965     SDValue Ops[] = {
11966       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
11967     };
11968     MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
11969         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
11970         MachineMemOperand::MOStore, SSFISize, SSFISize);
11971
11972     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
11973                                     Ops, Op.getValueType(), MMO);
11974     Result = DAG.getLoad(
11975         Op.getValueType(), DL, Chain, StackSlot,
11976         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
11977         false, false, false, 0);
11978   }
11979
11980   return Result;
11981 }
11982
11983 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
11984 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
11985                                                SelectionDAG &DAG) const {
11986   // This algorithm is not obvious. Here it is what we're trying to output:
11987   /*
11988      movq       %rax,  %xmm0
11989      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
11990      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
11991      #ifdef __SSE3__
11992        haddpd   %xmm0, %xmm0
11993      #else
11994        pshufd   $0x4e, %xmm0, %xmm1
11995        addpd    %xmm1, %xmm0
11996      #endif
11997   */
11998
11999   SDLoc dl(Op);
12000   LLVMContext *Context = DAG.getContext();
12001
12002   // Build some magic constants.
12003   static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
12004   Constant *C0 = ConstantDataVector::get(*Context, CV0);
12005   auto PtrVT = getPointerTy(DAG.getDataLayout());
12006   SDValue CPIdx0 = DAG.getConstantPool(C0, PtrVT, 16);
12007
12008   SmallVector<Constant*,2> CV1;
12009   CV1.push_back(
12010     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
12011                                       APInt(64, 0x4330000000000000ULL))));
12012   CV1.push_back(
12013     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
12014                                       APInt(64, 0x4530000000000000ULL))));
12015   Constant *C1 = ConstantVector::get(CV1);
12016   SDValue CPIdx1 = DAG.getConstantPool(C1, PtrVT, 16);
12017
12018   // Load the 64-bit value into an XMM register.
12019   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
12020                             Op.getOperand(0));
12021   SDValue CLod0 =
12022       DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
12023                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
12024                   false, false, false, 16);
12025   SDValue Unpck1 =
12026       getUnpackl(DAG, dl, MVT::v4i32, DAG.getBitcast(MVT::v4i32, XR1), CLod0);
12027
12028   SDValue CLod1 =
12029       DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
12030                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
12031                   false, false, false, 16);
12032   SDValue XR2F = DAG.getBitcast(MVT::v2f64, Unpck1);
12033   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
12034   SDValue Result;
12035
12036   if (Subtarget->hasSSE3()) {
12037     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
12038     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
12039   } else {
12040     SDValue S2F = DAG.getBitcast(MVT::v4i32, Sub);
12041     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
12042                                            S2F, 0x4E, DAG);
12043     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
12044                          DAG.getBitcast(MVT::v2f64, Shuffle), Sub);
12045   }
12046
12047   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
12048                      DAG.getIntPtrConstant(0, dl));
12049 }
12050
12051 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
12052 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
12053                                                SelectionDAG &DAG) const {
12054   SDLoc dl(Op);
12055   // FP constant to bias correct the final result.
12056   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
12057                                    MVT::f64);
12058
12059   // Load the 32-bit value into an XMM register.
12060   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
12061                              Op.getOperand(0));
12062
12063   // Zero out the upper parts of the register.
12064   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
12065
12066   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
12067                      DAG.getBitcast(MVT::v2f64, Load),
12068                      DAG.getIntPtrConstant(0, dl));
12069
12070   // Or the load with the bias.
12071   SDValue Or = DAG.getNode(
12072       ISD::OR, dl, MVT::v2i64,
12073       DAG.getBitcast(MVT::v2i64,
12074                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, Load)),
12075       DAG.getBitcast(MVT::v2i64,
12076                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, Bias)));
12077   Or =
12078       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
12079                   DAG.getBitcast(MVT::v2f64, Or), DAG.getIntPtrConstant(0, dl));
12080
12081   // Subtract the bias.
12082   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
12083
12084   // Handle final rounding.
12085   EVT DestVT = Op.getValueType();
12086
12087   if (DestVT.bitsLT(MVT::f64))
12088     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
12089                        DAG.getIntPtrConstant(0, dl));
12090   if (DestVT.bitsGT(MVT::f64))
12091     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
12092
12093   // Handle final rounding.
12094   return Sub;
12095 }
12096
12097 static SDValue lowerUINT_TO_FP_vXi32(SDValue Op, SelectionDAG &DAG,
12098                                      const X86Subtarget &Subtarget) {
12099   // The algorithm is the following:
12100   // #ifdef __SSE4_1__
12101   //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
12102   //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
12103   //                                 (uint4) 0x53000000, 0xaa);
12104   // #else
12105   //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
12106   //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
12107   // #endif
12108   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
12109   //     return (float4) lo + fhi;
12110
12111   SDLoc DL(Op);
12112   SDValue V = Op->getOperand(0);
12113   EVT VecIntVT = V.getValueType();
12114   bool Is128 = VecIntVT == MVT::v4i32;
12115   EVT VecFloatVT = Is128 ? MVT::v4f32 : MVT::v8f32;
12116   // If we convert to something else than the supported type, e.g., to v4f64,
12117   // abort early.
12118   if (VecFloatVT != Op->getValueType(0))
12119     return SDValue();
12120
12121   unsigned NumElts = VecIntVT.getVectorNumElements();
12122   assert((VecIntVT == MVT::v4i32 || VecIntVT == MVT::v8i32) &&
12123          "Unsupported custom type");
12124   assert(NumElts <= 8 && "The size of the constant array must be fixed");
12125
12126   // In the #idef/#else code, we have in common:
12127   // - The vector of constants:
12128   // -- 0x4b000000
12129   // -- 0x53000000
12130   // - A shift:
12131   // -- v >> 16
12132
12133   // Create the splat vector for 0x4b000000.
12134   SDValue CstLow = DAG.getConstant(0x4b000000, DL, MVT::i32);
12135   SDValue CstLowArray[] = {CstLow, CstLow, CstLow, CstLow,
12136                            CstLow, CstLow, CstLow, CstLow};
12137   SDValue VecCstLow = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12138                                   makeArrayRef(&CstLowArray[0], NumElts));
12139   // Create the splat vector for 0x53000000.
12140   SDValue CstHigh = DAG.getConstant(0x53000000, DL, MVT::i32);
12141   SDValue CstHighArray[] = {CstHigh, CstHigh, CstHigh, CstHigh,
12142                             CstHigh, CstHigh, CstHigh, CstHigh};
12143   SDValue VecCstHigh = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12144                                    makeArrayRef(&CstHighArray[0], NumElts));
12145
12146   // Create the right shift.
12147   SDValue CstShift = DAG.getConstant(16, DL, MVT::i32);
12148   SDValue CstShiftArray[] = {CstShift, CstShift, CstShift, CstShift,
12149                              CstShift, CstShift, CstShift, CstShift};
12150   SDValue VecCstShift = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12151                                     makeArrayRef(&CstShiftArray[0], NumElts));
12152   SDValue HighShift = DAG.getNode(ISD::SRL, DL, VecIntVT, V, VecCstShift);
12153
12154   SDValue Low, High;
12155   if (Subtarget.hasSSE41()) {
12156     EVT VecI16VT = Is128 ? MVT::v8i16 : MVT::v16i16;
12157     //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
12158     SDValue VecCstLowBitcast = DAG.getBitcast(VecI16VT, VecCstLow);
12159     SDValue VecBitcast = DAG.getBitcast(VecI16VT, V);
12160     // Low will be bitcasted right away, so do not bother bitcasting back to its
12161     // original type.
12162     Low = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecBitcast,
12163                       VecCstLowBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
12164     //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
12165     //                                 (uint4) 0x53000000, 0xaa);
12166     SDValue VecCstHighBitcast = DAG.getBitcast(VecI16VT, VecCstHigh);
12167     SDValue VecShiftBitcast = DAG.getBitcast(VecI16VT, HighShift);
12168     // High will be bitcasted right away, so do not bother bitcasting back to
12169     // its original type.
12170     High = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecShiftBitcast,
12171                        VecCstHighBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
12172   } else {
12173     SDValue CstMask = DAG.getConstant(0xffff, DL, MVT::i32);
12174     SDValue VecCstMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT, CstMask,
12175                                      CstMask, CstMask, CstMask);
12176     //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
12177     SDValue LowAnd = DAG.getNode(ISD::AND, DL, VecIntVT, V, VecCstMask);
12178     Low = DAG.getNode(ISD::OR, DL, VecIntVT, LowAnd, VecCstLow);
12179
12180     //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
12181     High = DAG.getNode(ISD::OR, DL, VecIntVT, HighShift, VecCstHigh);
12182   }
12183
12184   // Create the vector constant for -(0x1.0p39f + 0x1.0p23f).
12185   SDValue CstFAdd = DAG.getConstantFP(
12186       APFloat(APFloat::IEEEsingle, APInt(32, 0xD3000080)), DL, MVT::f32);
12187   SDValue CstFAddArray[] = {CstFAdd, CstFAdd, CstFAdd, CstFAdd,
12188                             CstFAdd, CstFAdd, CstFAdd, CstFAdd};
12189   SDValue VecCstFAdd = DAG.getNode(ISD::BUILD_VECTOR, DL, VecFloatVT,
12190                                    makeArrayRef(&CstFAddArray[0], NumElts));
12191
12192   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
12193   SDValue HighBitcast = DAG.getBitcast(VecFloatVT, High);
12194   SDValue FHigh =
12195       DAG.getNode(ISD::FADD, DL, VecFloatVT, HighBitcast, VecCstFAdd);
12196   //     return (float4) lo + fhi;
12197   SDValue LowBitcast = DAG.getBitcast(VecFloatVT, Low);
12198   return DAG.getNode(ISD::FADD, DL, VecFloatVT, LowBitcast, FHigh);
12199 }
12200
12201 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
12202                                                SelectionDAG &DAG) const {
12203   SDValue N0 = Op.getOperand(0);
12204   MVT SVT = N0.getSimpleValueType();
12205   SDLoc dl(Op);
12206
12207   switch (SVT.SimpleTy) {
12208   default:
12209     llvm_unreachable("Custom UINT_TO_FP is not supported!");
12210   case MVT::v4i8:
12211   case MVT::v4i16:
12212   case MVT::v8i8:
12213   case MVT::v8i16: {
12214     MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
12215     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
12216                        DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
12217   }
12218   case MVT::v4i32:
12219   case MVT::v8i32:
12220     return lowerUINT_TO_FP_vXi32(Op, DAG, *Subtarget);
12221   case MVT::v16i8:
12222   case MVT::v16i16:
12223     if (Subtarget->hasAVX512())
12224       return DAG.getNode(ISD::UINT_TO_FP, dl, Op.getValueType(),
12225                          DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v16i32, N0));
12226   }
12227   llvm_unreachable(nullptr);
12228 }
12229
12230 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
12231                                            SelectionDAG &DAG) const {
12232   SDValue N0 = Op.getOperand(0);
12233   SDLoc dl(Op);
12234   auto PtrVT = getPointerTy(DAG.getDataLayout());
12235
12236   if (Op.getValueType().isVector())
12237     return lowerUINT_TO_FP_vec(Op, DAG);
12238
12239   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
12240   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
12241   // the optimization here.
12242   if (DAG.SignBitIsZero(N0))
12243     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
12244
12245   MVT SrcVT = N0.getSimpleValueType();
12246   MVT DstVT = Op.getSimpleValueType();
12247   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
12248     return LowerUINT_TO_FP_i64(Op, DAG);
12249   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
12250     return LowerUINT_TO_FP_i32(Op, DAG);
12251   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
12252     return SDValue();
12253
12254   // Make a 64-bit buffer, and use it to build an FILD.
12255   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
12256   if (SrcVT == MVT::i32) {
12257     SDValue WordOff = DAG.getConstant(4, dl, PtrVT);
12258     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, WordOff);
12259     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
12260                                   StackSlot, MachinePointerInfo(),
12261                                   false, false, 0);
12262     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, dl, MVT::i32),
12263                                   OffsetSlot, MachinePointerInfo(),
12264                                   false, false, 0);
12265     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
12266     return Fild;
12267   }
12268
12269   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
12270   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
12271                                StackSlot, MachinePointerInfo(),
12272                                false, false, 0);
12273   // For i64 source, we need to add the appropriate power of 2 if the input
12274   // was negative.  This is the same as the optimization in
12275   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
12276   // we must be careful to do the computation in x87 extended precision, not
12277   // in SSE. (The generic code can't know it's OK to do this, or how to.)
12278   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
12279   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
12280       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
12281       MachineMemOperand::MOLoad, 8, 8);
12282
12283   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
12284   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
12285   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
12286                                          MVT::i64, MMO);
12287
12288   APInt FF(32, 0x5F800000ULL);
12289
12290   // Check whether the sign bit is set.
12291   SDValue SignSet = DAG.getSetCC(
12292       dl, getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i64),
12293       Op.getOperand(0), DAG.getConstant(0, dl, MVT::i64), ISD::SETLT);
12294
12295   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
12296   SDValue FudgePtr = DAG.getConstantPool(
12297       ConstantInt::get(*DAG.getContext(), FF.zext(64)), PtrVT);
12298
12299   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
12300   SDValue Zero = DAG.getIntPtrConstant(0, dl);
12301   SDValue Four = DAG.getIntPtrConstant(4, dl);
12302   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
12303                                Zero, Four);
12304   FudgePtr = DAG.getNode(ISD::ADD, dl, PtrVT, FudgePtr, Offset);
12305
12306   // Load the value out, extending it from f32 to f80.
12307   // FIXME: Avoid the extend by constructing the right constant pool?
12308   SDValue Fudge = DAG.getExtLoad(
12309       ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(), FudgePtr,
12310       MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), MVT::f32,
12311       false, false, false, 4);
12312   // Extend everything to 80 bits to force it to be done on x87.
12313   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
12314   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add,
12315                      DAG.getIntPtrConstant(0, dl));
12316 }
12317
12318 std::pair<SDValue,SDValue>
12319 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
12320                                     bool IsSigned, bool IsReplace) const {
12321   SDLoc DL(Op);
12322
12323   EVT DstTy = Op.getValueType();
12324   auto PtrVT = getPointerTy(DAG.getDataLayout());
12325
12326   if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
12327     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
12328     DstTy = MVT::i64;
12329   }
12330
12331   assert(DstTy.getSimpleVT() <= MVT::i64 &&
12332          DstTy.getSimpleVT() >= MVT::i16 &&
12333          "Unknown FP_TO_INT to lower!");
12334
12335   // These are really Legal.
12336   if (DstTy == MVT::i32 &&
12337       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
12338     return std::make_pair(SDValue(), SDValue());
12339   if (Subtarget->is64Bit() &&
12340       DstTy == MVT::i64 &&
12341       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
12342     return std::make_pair(SDValue(), SDValue());
12343
12344   // We lower FP->int64 either into FISTP64 followed by a load from a temporary
12345   // stack slot, or into the FTOL runtime function.
12346   MachineFunction &MF = DAG.getMachineFunction();
12347   unsigned MemSize = DstTy.getSizeInBits()/8;
12348   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
12349   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12350
12351   unsigned Opc;
12352   if (!IsSigned && isIntegerTypeFTOL(DstTy))
12353     Opc = X86ISD::WIN_FTOL;
12354   else
12355     switch (DstTy.getSimpleVT().SimpleTy) {
12356     default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
12357     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
12358     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
12359     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
12360     }
12361
12362   SDValue Chain = DAG.getEntryNode();
12363   SDValue Value = Op.getOperand(0);
12364   EVT TheVT = Op.getOperand(0).getValueType();
12365   // FIXME This causes a redundant load/store if the SSE-class value is already
12366   // in memory, such as if it is on the callstack.
12367   if (isScalarFPTypeInSSEReg(TheVT)) {
12368     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
12369     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
12370                          MachinePointerInfo::getFixedStack(MF, SSFI), false,
12371                          false, 0);
12372     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
12373     SDValue Ops[] = {
12374       Chain, StackSlot, DAG.getValueType(TheVT)
12375     };
12376
12377     MachineMemOperand *MMO =
12378         MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, SSFI),
12379                                 MachineMemOperand::MOLoad, MemSize, MemSize);
12380     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
12381     Chain = Value.getValue(1);
12382     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
12383     StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12384   }
12385
12386   MachineMemOperand *MMO =
12387       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, SSFI),
12388                               MachineMemOperand::MOStore, MemSize, MemSize);
12389
12390   if (Opc != X86ISD::WIN_FTOL) {
12391     // Build the FP_TO_INT*_IN_MEM
12392     SDValue Ops[] = { Chain, Value, StackSlot };
12393     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
12394                                            Ops, DstTy, MMO);
12395     return std::make_pair(FIST, StackSlot);
12396   } else {
12397     SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
12398       DAG.getVTList(MVT::Other, MVT::Glue),
12399       Chain, Value);
12400     SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
12401       MVT::i32, ftol.getValue(1));
12402     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
12403       MVT::i32, eax.getValue(2));
12404     SDValue Ops[] = { eax, edx };
12405     SDValue pair = IsReplace
12406       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops)
12407       : DAG.getMergeValues(Ops, DL);
12408     return std::make_pair(pair, SDValue());
12409   }
12410 }
12411
12412 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
12413                               const X86Subtarget *Subtarget) {
12414   MVT VT = Op->getSimpleValueType(0);
12415   SDValue In = Op->getOperand(0);
12416   MVT InVT = In.getSimpleValueType();
12417   SDLoc dl(Op);
12418
12419   if (VT.is512BitVector() || InVT.getScalarType() == MVT::i1)
12420     return DAG.getNode(ISD::ZERO_EXTEND, dl, VT, In);
12421
12422   // Optimize vectors in AVX mode:
12423   //
12424   //   v8i16 -> v8i32
12425   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
12426   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
12427   //   Concat upper and lower parts.
12428   //
12429   //   v4i32 -> v4i64
12430   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
12431   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
12432   //   Concat upper and lower parts.
12433   //
12434
12435   if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
12436       ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
12437       ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
12438     return SDValue();
12439
12440   if (Subtarget->hasInt256())
12441     return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
12442
12443   SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
12444   SDValue Undef = DAG.getUNDEF(InVT);
12445   bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
12446   SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
12447   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
12448
12449   MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
12450                              VT.getVectorNumElements()/2);
12451
12452   OpLo = DAG.getBitcast(HVT, OpLo);
12453   OpHi = DAG.getBitcast(HVT, OpHi);
12454
12455   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
12456 }
12457
12458 static  SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
12459                   const X86Subtarget *Subtarget, SelectionDAG &DAG) {
12460   MVT VT = Op->getSimpleValueType(0);
12461   SDValue In = Op->getOperand(0);
12462   MVT InVT = In.getSimpleValueType();
12463   SDLoc DL(Op);
12464   unsigned int NumElts = VT.getVectorNumElements();
12465   if (NumElts != 8 && NumElts != 16 && !Subtarget->hasBWI())
12466     return SDValue();
12467
12468   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
12469     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
12470
12471   assert(InVT.getVectorElementType() == MVT::i1);
12472   MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
12473   SDValue One =
12474    DAG.getConstant(APInt(ExtVT.getScalarSizeInBits(), 1), DL, ExtVT);
12475   SDValue Zero =
12476    DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), DL, ExtVT);
12477
12478   SDValue V = DAG.getNode(ISD::VSELECT, DL, ExtVT, In, One, Zero);
12479   if (VT.is512BitVector())
12480     return V;
12481   return DAG.getNode(X86ISD::VTRUNC, DL, VT, V);
12482 }
12483
12484 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
12485                                SelectionDAG &DAG) {
12486   if (Subtarget->hasFp256())
12487     if (SDValue Res = LowerAVXExtend(Op, DAG, Subtarget))
12488       return Res;
12489
12490   return SDValue();
12491 }
12492
12493 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
12494                                 SelectionDAG &DAG) {
12495   SDLoc DL(Op);
12496   MVT VT = Op.getSimpleValueType();
12497   SDValue In = Op.getOperand(0);
12498   MVT SVT = In.getSimpleValueType();
12499
12500   if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
12501     return LowerZERO_EXTEND_AVX512(Op, Subtarget, DAG);
12502
12503   if (Subtarget->hasFp256())
12504     if (SDValue Res = LowerAVXExtend(Op, DAG, Subtarget))
12505       return Res;
12506
12507   assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
12508          VT.getVectorNumElements() != SVT.getVectorNumElements());
12509   return SDValue();
12510 }
12511
12512 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
12513   SDLoc DL(Op);
12514   MVT VT = Op.getSimpleValueType();
12515   SDValue In = Op.getOperand(0);
12516   MVT InVT = In.getSimpleValueType();
12517
12518   if (VT == MVT::i1) {
12519     assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
12520            "Invalid scalar TRUNCATE operation");
12521     if (InVT.getSizeInBits() >= 32)
12522       return SDValue();
12523     In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
12524     return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
12525   }
12526   assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
12527          "Invalid TRUNCATE operation");
12528
12529   // move vector to mask - truncate solution for SKX
12530   if (VT.getVectorElementType() == MVT::i1) {
12531     if (InVT.is512BitVector() && InVT.getScalarSizeInBits() <= 16 &&
12532         Subtarget->hasBWI())
12533       return Op; // legal, will go to VPMOVB2M, VPMOVW2M
12534     if ((InVT.is256BitVector() || InVT.is128BitVector())
12535         && InVT.getScalarSizeInBits() <= 16 &&
12536         Subtarget->hasBWI() && Subtarget->hasVLX())
12537       return Op; // legal, will go to VPMOVB2M, VPMOVW2M
12538     if (InVT.is512BitVector() && InVT.getScalarSizeInBits() >= 32 &&
12539         Subtarget->hasDQI())
12540       return Op; // legal, will go to VPMOVD2M, VPMOVQ2M
12541     if ((InVT.is256BitVector() || InVT.is128BitVector())
12542         && InVT.getScalarSizeInBits() >= 32 &&
12543         Subtarget->hasDQI() && Subtarget->hasVLX())
12544       return Op; // legal, will go to VPMOVB2M, VPMOVQ2M
12545   }
12546
12547   if (VT.getVectorElementType() == MVT::i1) {
12548     assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
12549     unsigned NumElts = InVT.getVectorNumElements();
12550     assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
12551     if (InVT.getSizeInBits() < 512) {
12552       MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
12553       In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
12554       InVT = ExtVT;
12555     }
12556
12557     SDValue OneV =
12558      DAG.getConstant(APInt::getSignBit(InVT.getScalarSizeInBits()), DL, InVT);
12559     SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
12560     return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
12561   }
12562
12563   // vpmovqb/w/d, vpmovdb/w, vpmovwb
12564   if (((!InVT.is512BitVector() && Subtarget->hasVLX()) || InVT.is512BitVector()) &&
12565       (InVT.getVectorElementType() != MVT::i16 || Subtarget->hasBWI()))
12566     return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
12567
12568   if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
12569     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
12570     if (Subtarget->hasInt256()) {
12571       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
12572       In = DAG.getBitcast(MVT::v8i32, In);
12573       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
12574                                 ShufMask);
12575       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
12576                          DAG.getIntPtrConstant(0, DL));
12577     }
12578
12579     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12580                                DAG.getIntPtrConstant(0, DL));
12581     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12582                                DAG.getIntPtrConstant(2, DL));
12583     OpLo = DAG.getBitcast(MVT::v4i32, OpLo);
12584     OpHi = DAG.getBitcast(MVT::v4i32, OpHi);
12585     static const int ShufMask[] = {0, 2, 4, 6};
12586     return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
12587   }
12588
12589   if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
12590     // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
12591     if (Subtarget->hasInt256()) {
12592       In = DAG.getBitcast(MVT::v32i8, In);
12593
12594       SmallVector<SDValue,32> pshufbMask;
12595       for (unsigned i = 0; i < 2; ++i) {
12596         pshufbMask.push_back(DAG.getConstant(0x0, DL, MVT::i8));
12597         pshufbMask.push_back(DAG.getConstant(0x1, DL, MVT::i8));
12598         pshufbMask.push_back(DAG.getConstant(0x4, DL, MVT::i8));
12599         pshufbMask.push_back(DAG.getConstant(0x5, DL, MVT::i8));
12600         pshufbMask.push_back(DAG.getConstant(0x8, DL, MVT::i8));
12601         pshufbMask.push_back(DAG.getConstant(0x9, DL, MVT::i8));
12602         pshufbMask.push_back(DAG.getConstant(0xc, DL, MVT::i8));
12603         pshufbMask.push_back(DAG.getConstant(0xd, DL, MVT::i8));
12604         for (unsigned j = 0; j < 8; ++j)
12605           pshufbMask.push_back(DAG.getConstant(0x80, DL, MVT::i8));
12606       }
12607       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
12608       In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
12609       In = DAG.getBitcast(MVT::v4i64, In);
12610
12611       static const int ShufMask[] = {0,  2,  -1,  -1};
12612       In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, DAG.getUNDEF(MVT::v4i64),
12613                                 &ShufMask[0]);
12614       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12615                        DAG.getIntPtrConstant(0, DL));
12616       return DAG.getBitcast(VT, In);
12617     }
12618
12619     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
12620                                DAG.getIntPtrConstant(0, DL));
12621
12622     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
12623                                DAG.getIntPtrConstant(4, DL));
12624
12625     OpLo = DAG.getBitcast(MVT::v16i8, OpLo);
12626     OpHi = DAG.getBitcast(MVT::v16i8, OpHi);
12627
12628     // The PSHUFB mask:
12629     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
12630                                    -1, -1, -1, -1, -1, -1, -1, -1};
12631
12632     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
12633     OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
12634     OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
12635
12636     OpLo = DAG.getBitcast(MVT::v4i32, OpLo);
12637     OpHi = DAG.getBitcast(MVT::v4i32, OpHi);
12638
12639     // The MOVLHPS Mask:
12640     static const int ShufMask2[] = {0, 1, 4, 5};
12641     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
12642     return DAG.getBitcast(MVT::v8i16, res);
12643   }
12644
12645   // Handle truncation of V256 to V128 using shuffles.
12646   if (!VT.is128BitVector() || !InVT.is256BitVector())
12647     return SDValue();
12648
12649   assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
12650
12651   unsigned NumElems = VT.getVectorNumElements();
12652   MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
12653
12654   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
12655   // Prepare truncation shuffle mask
12656   for (unsigned i = 0; i != NumElems; ++i)
12657     MaskVec[i] = i * 2;
12658   SDValue V = DAG.getVectorShuffle(NVT, DL, DAG.getBitcast(NVT, In),
12659                                    DAG.getUNDEF(NVT), &MaskVec[0]);
12660   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
12661                      DAG.getIntPtrConstant(0, DL));
12662 }
12663
12664 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
12665                                            SelectionDAG &DAG) const {
12666   assert(!Op.getSimpleValueType().isVector());
12667
12668   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
12669     /*IsSigned=*/ true, /*IsReplace=*/ false);
12670   SDValue FIST = Vals.first, StackSlot = Vals.second;
12671   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
12672   if (!FIST.getNode()) return Op;
12673
12674   if (StackSlot.getNode())
12675     // Load the result.
12676     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
12677                        FIST, StackSlot, MachinePointerInfo(),
12678                        false, false, false, 0);
12679
12680   // The node is the result.
12681   return FIST;
12682 }
12683
12684 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
12685                                            SelectionDAG &DAG) const {
12686   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
12687     /*IsSigned=*/ false, /*IsReplace=*/ false);
12688   SDValue FIST = Vals.first, StackSlot = Vals.second;
12689   assert(FIST.getNode() && "Unexpected failure");
12690
12691   if (StackSlot.getNode())
12692     // Load the result.
12693     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
12694                        FIST, StackSlot, MachinePointerInfo(),
12695                        false, false, false, 0);
12696
12697   // The node is the result.
12698   return FIST;
12699 }
12700
12701 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
12702   SDLoc DL(Op);
12703   MVT VT = Op.getSimpleValueType();
12704   SDValue In = Op.getOperand(0);
12705   MVT SVT = In.getSimpleValueType();
12706
12707   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
12708
12709   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
12710                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
12711                                  In, DAG.getUNDEF(SVT)));
12712 }
12713
12714 /// The only differences between FABS and FNEG are the mask and the logic op.
12715 /// FNEG also has a folding opportunity for FNEG(FABS(x)).
12716 static SDValue LowerFABSorFNEG(SDValue Op, SelectionDAG &DAG) {
12717   assert((Op.getOpcode() == ISD::FABS || Op.getOpcode() == ISD::FNEG) &&
12718          "Wrong opcode for lowering FABS or FNEG.");
12719
12720   bool IsFABS = (Op.getOpcode() == ISD::FABS);
12721
12722   // If this is a FABS and it has an FNEG user, bail out to fold the combination
12723   // into an FNABS. We'll lower the FABS after that if it is still in use.
12724   if (IsFABS)
12725     for (SDNode *User : Op->uses())
12726       if (User->getOpcode() == ISD::FNEG)
12727         return Op;
12728
12729   SDLoc dl(Op);
12730   MVT VT = Op.getSimpleValueType();
12731
12732   // FIXME: Use function attribute "OptimizeForSize" and/or CodeGenOpt::Level to
12733   // decide if we should generate a 16-byte constant mask when we only need 4 or
12734   // 8 bytes for the scalar case.
12735
12736   MVT LogicVT;
12737   MVT EltVT;
12738   unsigned NumElts;
12739
12740   if (VT.isVector()) {
12741     LogicVT = VT;
12742     EltVT = VT.getVectorElementType();
12743     NumElts = VT.getVectorNumElements();
12744   } else {
12745     // There are no scalar bitwise logical SSE/AVX instructions, so we
12746     // generate a 16-byte vector constant and logic op even for the scalar case.
12747     // Using a 16-byte mask allows folding the load of the mask with
12748     // the logic op, so it can save (~4 bytes) on code size.
12749     LogicVT = (VT == MVT::f64) ? MVT::v2f64 : MVT::v4f32;
12750     EltVT = VT;
12751     NumElts = (VT == MVT::f64) ? 2 : 4;
12752   }
12753
12754   unsigned EltBits = EltVT.getSizeInBits();
12755   LLVMContext *Context = DAG.getContext();
12756   // For FABS, mask is 0x7f...; for FNEG, mask is 0x80...
12757   APInt MaskElt =
12758     IsFABS ? APInt::getSignedMaxValue(EltBits) : APInt::getSignBit(EltBits);
12759   Constant *C = ConstantInt::get(*Context, MaskElt);
12760   C = ConstantVector::getSplat(NumElts, C);
12761   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12762   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(DAG.getDataLayout()));
12763   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
12764   SDValue Mask =
12765       DAG.getLoad(LogicVT, dl, DAG.getEntryNode(), CPIdx,
12766                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
12767                   false, false, false, Alignment);
12768
12769   SDValue Op0 = Op.getOperand(0);
12770   bool IsFNABS = !IsFABS && (Op0.getOpcode() == ISD::FABS);
12771   unsigned LogicOp =
12772     IsFABS ? X86ISD::FAND : IsFNABS ? X86ISD::FOR : X86ISD::FXOR;
12773   SDValue Operand = IsFNABS ? Op0.getOperand(0) : Op0;
12774
12775   if (VT.isVector())
12776     return DAG.getNode(LogicOp, dl, LogicVT, Operand, Mask);
12777
12778   // For the scalar case extend to a 128-bit vector, perform the logic op,
12779   // and extract the scalar result back out.
12780   Operand = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Operand);
12781   SDValue LogicNode = DAG.getNode(LogicOp, dl, LogicVT, Operand, Mask);
12782   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, LogicNode,
12783                      DAG.getIntPtrConstant(0, dl));
12784 }
12785
12786 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
12787   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12788   LLVMContext *Context = DAG.getContext();
12789   SDValue Op0 = Op.getOperand(0);
12790   SDValue Op1 = Op.getOperand(1);
12791   SDLoc dl(Op);
12792   MVT VT = Op.getSimpleValueType();
12793   MVT SrcVT = Op1.getSimpleValueType();
12794
12795   // If second operand is smaller, extend it first.
12796   if (SrcVT.bitsLT(VT)) {
12797     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
12798     SrcVT = VT;
12799   }
12800   // And if it is bigger, shrink it first.
12801   if (SrcVT.bitsGT(VT)) {
12802     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1, dl));
12803     SrcVT = VT;
12804   }
12805
12806   // At this point the operands and the result should have the same
12807   // type, and that won't be f80 since that is not custom lowered.
12808
12809   const fltSemantics &Sem =
12810       VT == MVT::f64 ? APFloat::IEEEdouble : APFloat::IEEEsingle;
12811   const unsigned SizeInBits = VT.getSizeInBits();
12812
12813   SmallVector<Constant *, 4> CV(
12814       VT == MVT::f64 ? 2 : 4,
12815       ConstantFP::get(*Context, APFloat(Sem, APInt(SizeInBits, 0))));
12816
12817   // First, clear all bits but the sign bit from the second operand (sign).
12818   CV[0] = ConstantFP::get(*Context,
12819                           APFloat(Sem, APInt::getHighBitsSet(SizeInBits, 1)));
12820   Constant *C = ConstantVector::get(CV);
12821   auto PtrVT = TLI.getPointerTy(DAG.getDataLayout());
12822   SDValue CPIdx = DAG.getConstantPool(C, PtrVT, 16);
12823
12824   // Perform all logic operations as 16-byte vectors because there are no
12825   // scalar FP logic instructions in SSE. This allows load folding of the
12826   // constants into the logic instructions.
12827   MVT LogicVT = (VT == MVT::f64) ? MVT::v2f64 : MVT::v4f32;
12828   SDValue Mask1 =
12829       DAG.getLoad(LogicVT, dl, DAG.getEntryNode(), CPIdx,
12830                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
12831                   false, false, false, 16);
12832   Op1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Op1);
12833   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, LogicVT, Op1, Mask1);
12834
12835   // Next, clear the sign bit from the first operand (magnitude).
12836   // If it's a constant, we can clear it here.
12837   if (ConstantFPSDNode *Op0CN = dyn_cast<ConstantFPSDNode>(Op0)) {
12838     APFloat APF = Op0CN->getValueAPF();
12839     // If the magnitude is a positive zero, the sign bit alone is enough.
12840     if (APF.isPosZero())
12841       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SrcVT, SignBit,
12842                          DAG.getIntPtrConstant(0, dl));
12843     APF.clearSign();
12844     CV[0] = ConstantFP::get(*Context, APF);
12845   } else {
12846     CV[0] = ConstantFP::get(
12847         *Context,
12848         APFloat(Sem, APInt::getLowBitsSet(SizeInBits, SizeInBits - 1)));
12849   }
12850   C = ConstantVector::get(CV);
12851   CPIdx = DAG.getConstantPool(C, PtrVT, 16);
12852   SDValue Val =
12853       DAG.getLoad(LogicVT, dl, DAG.getEntryNode(), CPIdx,
12854                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
12855                   false, false, false, 16);
12856   // If the magnitude operand wasn't a constant, we need to AND out the sign.
12857   if (!isa<ConstantFPSDNode>(Op0)) {
12858     Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Op0);
12859     Val = DAG.getNode(X86ISD::FAND, dl, LogicVT, Op0, Val);
12860   }
12861   // OR the magnitude value with the sign bit.
12862   Val = DAG.getNode(X86ISD::FOR, dl, LogicVT, Val, SignBit);
12863   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SrcVT, Val,
12864                      DAG.getIntPtrConstant(0, dl));
12865 }
12866
12867 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
12868   SDValue N0 = Op.getOperand(0);
12869   SDLoc dl(Op);
12870   MVT VT = Op.getSimpleValueType();
12871
12872   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
12873   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
12874                                   DAG.getConstant(1, dl, VT));
12875   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, dl, VT));
12876 }
12877
12878 // Check whether an OR'd tree is PTEST-able.
12879 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
12880                                       SelectionDAG &DAG) {
12881   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
12882
12883   if (!Subtarget->hasSSE41())
12884     return SDValue();
12885
12886   if (!Op->hasOneUse())
12887     return SDValue();
12888
12889   SDNode *N = Op.getNode();
12890   SDLoc DL(N);
12891
12892   SmallVector<SDValue, 8> Opnds;
12893   DenseMap<SDValue, unsigned> VecInMap;
12894   SmallVector<SDValue, 8> VecIns;
12895   EVT VT = MVT::Other;
12896
12897   // Recognize a special case where a vector is casted into wide integer to
12898   // test all 0s.
12899   Opnds.push_back(N->getOperand(0));
12900   Opnds.push_back(N->getOperand(1));
12901
12902   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
12903     SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
12904     // BFS traverse all OR'd operands.
12905     if (I->getOpcode() == ISD::OR) {
12906       Opnds.push_back(I->getOperand(0));
12907       Opnds.push_back(I->getOperand(1));
12908       // Re-evaluate the number of nodes to be traversed.
12909       e += 2; // 2 more nodes (LHS and RHS) are pushed.
12910       continue;
12911     }
12912
12913     // Quit if a non-EXTRACT_VECTOR_ELT
12914     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
12915       return SDValue();
12916
12917     // Quit if without a constant index.
12918     SDValue Idx = I->getOperand(1);
12919     if (!isa<ConstantSDNode>(Idx))
12920       return SDValue();
12921
12922     SDValue ExtractedFromVec = I->getOperand(0);
12923     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
12924     if (M == VecInMap.end()) {
12925       VT = ExtractedFromVec.getValueType();
12926       // Quit if not 128/256-bit vector.
12927       if (!VT.is128BitVector() && !VT.is256BitVector())
12928         return SDValue();
12929       // Quit if not the same type.
12930       if (VecInMap.begin() != VecInMap.end() &&
12931           VT != VecInMap.begin()->first.getValueType())
12932         return SDValue();
12933       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
12934       VecIns.push_back(ExtractedFromVec);
12935     }
12936     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
12937   }
12938
12939   assert((VT.is128BitVector() || VT.is256BitVector()) &&
12940          "Not extracted from 128-/256-bit vector.");
12941
12942   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
12943
12944   for (DenseMap<SDValue, unsigned>::const_iterator
12945         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
12946     // Quit if not all elements are used.
12947     if (I->second != FullMask)
12948       return SDValue();
12949   }
12950
12951   EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
12952
12953   // Cast all vectors into TestVT for PTEST.
12954   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
12955     VecIns[i] = DAG.getBitcast(TestVT, VecIns[i]);
12956
12957   // If more than one full vectors are evaluated, OR them first before PTEST.
12958   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
12959     // Each iteration will OR 2 nodes and append the result until there is only
12960     // 1 node left, i.e. the final OR'd value of all vectors.
12961     SDValue LHS = VecIns[Slot];
12962     SDValue RHS = VecIns[Slot + 1];
12963     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
12964   }
12965
12966   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
12967                      VecIns.back(), VecIns.back());
12968 }
12969
12970 /// \brief return true if \c Op has a use that doesn't just read flags.
12971 static bool hasNonFlagsUse(SDValue Op) {
12972   for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
12973        ++UI) {
12974     SDNode *User = *UI;
12975     unsigned UOpNo = UI.getOperandNo();
12976     if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
12977       // Look pass truncate.
12978       UOpNo = User->use_begin().getOperandNo();
12979       User = *User->use_begin();
12980     }
12981
12982     if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
12983         !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
12984       return true;
12985   }
12986   return false;
12987 }
12988
12989 /// Emit nodes that will be selected as "test Op0,Op0", or something
12990 /// equivalent.
12991 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
12992                                     SelectionDAG &DAG) const {
12993   if (Op.getValueType() == MVT::i1) {
12994     SDValue ExtOp = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i8, Op);
12995     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, ExtOp,
12996                        DAG.getConstant(0, dl, MVT::i8));
12997   }
12998   // CF and OF aren't always set the way we want. Determine which
12999   // of these we need.
13000   bool NeedCF = false;
13001   bool NeedOF = false;
13002   switch (X86CC) {
13003   default: break;
13004   case X86::COND_A: case X86::COND_AE:
13005   case X86::COND_B: case X86::COND_BE:
13006     NeedCF = true;
13007     break;
13008   case X86::COND_G: case X86::COND_GE:
13009   case X86::COND_L: case X86::COND_LE:
13010   case X86::COND_O: case X86::COND_NO: {
13011     // Check if we really need to set the
13012     // Overflow flag. If NoSignedWrap is present
13013     // that is not actually needed.
13014     switch (Op->getOpcode()) {
13015     case ISD::ADD:
13016     case ISD::SUB:
13017     case ISD::MUL:
13018     case ISD::SHL: {
13019       const auto *BinNode = cast<BinaryWithFlagsSDNode>(Op.getNode());
13020       if (BinNode->Flags.hasNoSignedWrap())
13021         break;
13022     }
13023     default:
13024       NeedOF = true;
13025       break;
13026     }
13027     break;
13028   }
13029   }
13030   // See if we can use the EFLAGS value from the operand instead of
13031   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
13032   // we prove that the arithmetic won't overflow, we can't use OF or CF.
13033   if (Op.getResNo() != 0 || NeedOF || NeedCF) {
13034     // Emit a CMP with 0, which is the TEST pattern.
13035     //if (Op.getValueType() == MVT::i1)
13036     //  return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
13037     //                     DAG.getConstant(0, MVT::i1));
13038     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
13039                        DAG.getConstant(0, dl, Op.getValueType()));
13040   }
13041   unsigned Opcode = 0;
13042   unsigned NumOperands = 0;
13043
13044   // Truncate operations may prevent the merge of the SETCC instruction
13045   // and the arithmetic instruction before it. Attempt to truncate the operands
13046   // of the arithmetic instruction and use a reduced bit-width instruction.
13047   bool NeedTruncation = false;
13048   SDValue ArithOp = Op;
13049   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
13050     SDValue Arith = Op->getOperand(0);
13051     // Both the trunc and the arithmetic op need to have one user each.
13052     if (Arith->hasOneUse())
13053       switch (Arith.getOpcode()) {
13054         default: break;
13055         case ISD::ADD:
13056         case ISD::SUB:
13057         case ISD::AND:
13058         case ISD::OR:
13059         case ISD::XOR: {
13060           NeedTruncation = true;
13061           ArithOp = Arith;
13062         }
13063       }
13064   }
13065
13066   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
13067   // which may be the result of a CAST.  We use the variable 'Op', which is the
13068   // non-casted variable when we check for possible users.
13069   switch (ArithOp.getOpcode()) {
13070   case ISD::ADD:
13071     // Due to an isel shortcoming, be conservative if this add is likely to be
13072     // selected as part of a load-modify-store instruction. When the root node
13073     // in a match is a store, isel doesn't know how to remap non-chain non-flag
13074     // uses of other nodes in the match, such as the ADD in this case. This
13075     // leads to the ADD being left around and reselected, with the result being
13076     // two adds in the output.  Alas, even if none our users are stores, that
13077     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
13078     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
13079     // climbing the DAG back to the root, and it doesn't seem to be worth the
13080     // effort.
13081     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
13082          UE = Op.getNode()->use_end(); UI != UE; ++UI)
13083       if (UI->getOpcode() != ISD::CopyToReg &&
13084           UI->getOpcode() != ISD::SETCC &&
13085           UI->getOpcode() != ISD::STORE)
13086         goto default_case;
13087
13088     if (ConstantSDNode *C =
13089         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
13090       // An add of one will be selected as an INC.
13091       if (C->getAPIntValue() == 1 && !Subtarget->slowIncDec()) {
13092         Opcode = X86ISD::INC;
13093         NumOperands = 1;
13094         break;
13095       }
13096
13097       // An add of negative one (subtract of one) will be selected as a DEC.
13098       if (C->getAPIntValue().isAllOnesValue() && !Subtarget->slowIncDec()) {
13099         Opcode = X86ISD::DEC;
13100         NumOperands = 1;
13101         break;
13102       }
13103     }
13104
13105     // Otherwise use a regular EFLAGS-setting add.
13106     Opcode = X86ISD::ADD;
13107     NumOperands = 2;
13108     break;
13109   case ISD::SHL:
13110   case ISD::SRL:
13111     // If we have a constant logical shift that's only used in a comparison
13112     // against zero turn it into an equivalent AND. This allows turning it into
13113     // a TEST instruction later.
13114     if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
13115         isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
13116       EVT VT = Op.getValueType();
13117       unsigned BitWidth = VT.getSizeInBits();
13118       unsigned ShAmt = Op->getConstantOperandVal(1);
13119       if (ShAmt >= BitWidth) // Avoid undefined shifts.
13120         break;
13121       APInt Mask = ArithOp.getOpcode() == ISD::SRL
13122                        ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
13123                        : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
13124       if (!Mask.isSignedIntN(32)) // Avoid large immediates.
13125         break;
13126       SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
13127                                 DAG.getConstant(Mask, dl, VT));
13128       DAG.ReplaceAllUsesWith(Op, New);
13129       Op = New;
13130     }
13131     break;
13132
13133   case ISD::AND:
13134     // If the primary and result isn't used, don't bother using X86ISD::AND,
13135     // because a TEST instruction will be better.
13136     if (!hasNonFlagsUse(Op))
13137       break;
13138     // FALL THROUGH
13139   case ISD::SUB:
13140   case ISD::OR:
13141   case ISD::XOR:
13142     // Due to the ISEL shortcoming noted above, be conservative if this op is
13143     // likely to be selected as part of a load-modify-store instruction.
13144     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
13145            UE = Op.getNode()->use_end(); UI != UE; ++UI)
13146       if (UI->getOpcode() == ISD::STORE)
13147         goto default_case;
13148
13149     // Otherwise use a regular EFLAGS-setting instruction.
13150     switch (ArithOp.getOpcode()) {
13151     default: llvm_unreachable("unexpected operator!");
13152     case ISD::SUB: Opcode = X86ISD::SUB; break;
13153     case ISD::XOR: Opcode = X86ISD::XOR; break;
13154     case ISD::AND: Opcode = X86ISD::AND; break;
13155     case ISD::OR: {
13156       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
13157         SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
13158         if (EFLAGS.getNode())
13159           return EFLAGS;
13160       }
13161       Opcode = X86ISD::OR;
13162       break;
13163     }
13164     }
13165
13166     NumOperands = 2;
13167     break;
13168   case X86ISD::ADD:
13169   case X86ISD::SUB:
13170   case X86ISD::INC:
13171   case X86ISD::DEC:
13172   case X86ISD::OR:
13173   case X86ISD::XOR:
13174   case X86ISD::AND:
13175     return SDValue(Op.getNode(), 1);
13176   default:
13177   default_case:
13178     break;
13179   }
13180
13181   // If we found that truncation is beneficial, perform the truncation and
13182   // update 'Op'.
13183   if (NeedTruncation) {
13184     EVT VT = Op.getValueType();
13185     SDValue WideVal = Op->getOperand(0);
13186     EVT WideVT = WideVal.getValueType();
13187     unsigned ConvertedOp = 0;
13188     // Use a target machine opcode to prevent further DAGCombine
13189     // optimizations that may separate the arithmetic operations
13190     // from the setcc node.
13191     switch (WideVal.getOpcode()) {
13192       default: break;
13193       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
13194       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
13195       case ISD::AND: ConvertedOp = X86ISD::AND; break;
13196       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
13197       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
13198     }
13199
13200     if (ConvertedOp) {
13201       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13202       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
13203         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
13204         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
13205         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
13206       }
13207     }
13208   }
13209
13210   if (Opcode == 0)
13211     // Emit a CMP with 0, which is the TEST pattern.
13212     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
13213                        DAG.getConstant(0, dl, Op.getValueType()));
13214
13215   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
13216   SmallVector<SDValue, 4> Ops(Op->op_begin(), Op->op_begin() + NumOperands);
13217
13218   SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
13219   DAG.ReplaceAllUsesWith(Op, New);
13220   return SDValue(New.getNode(), 1);
13221 }
13222
13223 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
13224 /// equivalent.
13225 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
13226                                    SDLoc dl, SelectionDAG &DAG) const {
13227   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
13228     if (C->getAPIntValue() == 0)
13229       return EmitTest(Op0, X86CC, dl, DAG);
13230
13231      if (Op0.getValueType() == MVT::i1)
13232        llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
13233   }
13234
13235   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
13236        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
13237     // Do the comparison at i32 if it's smaller, besides the Atom case.
13238     // This avoids subregister aliasing issues. Keep the smaller reference
13239     // if we're optimizing for size, however, as that'll allow better folding
13240     // of memory operations.
13241     if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
13242         !DAG.getMachineFunction().getFunction()->optForMinSize() &&
13243         !Subtarget->isAtom()) {
13244       unsigned ExtendOp =
13245           isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
13246       Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
13247       Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
13248     }
13249     // Use SUB instead of CMP to enable CSE between SUB and CMP.
13250     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
13251     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
13252                               Op0, Op1);
13253     return SDValue(Sub.getNode(), 1);
13254   }
13255   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
13256 }
13257
13258 /// Convert a comparison if required by the subtarget.
13259 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
13260                                                  SelectionDAG &DAG) const {
13261   // If the subtarget does not support the FUCOMI instruction, floating-point
13262   // comparisons have to be converted.
13263   if (Subtarget->hasCMov() ||
13264       Cmp.getOpcode() != X86ISD::CMP ||
13265       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
13266       !Cmp.getOperand(1).getValueType().isFloatingPoint())
13267     return Cmp;
13268
13269   // The instruction selector will select an FUCOM instruction instead of
13270   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
13271   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
13272   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
13273   SDLoc dl(Cmp);
13274   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
13275   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
13276   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
13277                             DAG.getConstant(8, dl, MVT::i8));
13278   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
13279   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
13280 }
13281
13282 /// The minimum architected relative accuracy is 2^-12. We need one
13283 /// Newton-Raphson step to have a good float result (24 bits of precision).
13284 SDValue X86TargetLowering::getRsqrtEstimate(SDValue Op,
13285                                             DAGCombinerInfo &DCI,
13286                                             unsigned &RefinementSteps,
13287                                             bool &UseOneConstNR) const {
13288   EVT VT = Op.getValueType();
13289   const char *RecipOp;
13290
13291   // SSE1 has rsqrtss and rsqrtps. AVX adds a 256-bit variant for rsqrtps.
13292   // TODO: Add support for AVX512 (v16f32).
13293   // It is likely not profitable to do this for f64 because a double-precision
13294   // rsqrt estimate with refinement on x86 prior to FMA requires at least 16
13295   // instructions: convert to single, rsqrtss, convert back to double, refine
13296   // (3 steps = at least 13 insts). If an 'rsqrtsd' variant was added to the ISA
13297   // along with FMA, this could be a throughput win.
13298   if (VT == MVT::f32 && Subtarget->hasSSE1())
13299     RecipOp = "sqrtf";
13300   else if ((VT == MVT::v4f32 && Subtarget->hasSSE1()) ||
13301            (VT == MVT::v8f32 && Subtarget->hasAVX()))
13302     RecipOp = "vec-sqrtf";
13303   else
13304     return SDValue();
13305
13306   TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
13307   if (!Recips.isEnabled(RecipOp))
13308     return SDValue();
13309
13310   RefinementSteps = Recips.getRefinementSteps(RecipOp);
13311   UseOneConstNR = false;
13312   return DCI.DAG.getNode(X86ISD::FRSQRT, SDLoc(Op), VT, Op);
13313 }
13314
13315 /// The minimum architected relative accuracy is 2^-12. We need one
13316 /// Newton-Raphson step to have a good float result (24 bits of precision).
13317 SDValue X86TargetLowering::getRecipEstimate(SDValue Op,
13318                                             DAGCombinerInfo &DCI,
13319                                             unsigned &RefinementSteps) const {
13320   EVT VT = Op.getValueType();
13321   const char *RecipOp;
13322
13323   // SSE1 has rcpss and rcpps. AVX adds a 256-bit variant for rcpps.
13324   // TODO: Add support for AVX512 (v16f32).
13325   // It is likely not profitable to do this for f64 because a double-precision
13326   // reciprocal estimate with refinement on x86 prior to FMA requires
13327   // 15 instructions: convert to single, rcpss, convert back to double, refine
13328   // (3 steps = 12 insts). If an 'rcpsd' variant was added to the ISA
13329   // along with FMA, this could be a throughput win.
13330   if (VT == MVT::f32 && Subtarget->hasSSE1())
13331     RecipOp = "divf";
13332   else if ((VT == MVT::v4f32 && Subtarget->hasSSE1()) ||
13333            (VT == MVT::v8f32 && Subtarget->hasAVX()))
13334     RecipOp = "vec-divf";
13335   else
13336     return SDValue();
13337
13338   TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
13339   if (!Recips.isEnabled(RecipOp))
13340     return SDValue();
13341
13342   RefinementSteps = Recips.getRefinementSteps(RecipOp);
13343   return DCI.DAG.getNode(X86ISD::FRCP, SDLoc(Op), VT, Op);
13344 }
13345
13346 /// If we have at least two divisions that use the same divisor, convert to
13347 /// multplication by a reciprocal. This may need to be adjusted for a given
13348 /// CPU if a division's cost is not at least twice the cost of a multiplication.
13349 /// This is because we still need one division to calculate the reciprocal and
13350 /// then we need two multiplies by that reciprocal as replacements for the
13351 /// original divisions.
13352 unsigned X86TargetLowering::combineRepeatedFPDivisors() const {
13353   return 2;
13354 }
13355
13356 static bool isAllOnes(SDValue V) {
13357   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
13358   return C && C->isAllOnesValue();
13359 }
13360
13361 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
13362 /// if it's possible.
13363 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
13364                                      SDLoc dl, SelectionDAG &DAG) const {
13365   SDValue Op0 = And.getOperand(0);
13366   SDValue Op1 = And.getOperand(1);
13367   if (Op0.getOpcode() == ISD::TRUNCATE)
13368     Op0 = Op0.getOperand(0);
13369   if (Op1.getOpcode() == ISD::TRUNCATE)
13370     Op1 = Op1.getOperand(0);
13371
13372   SDValue LHS, RHS;
13373   if (Op1.getOpcode() == ISD::SHL)
13374     std::swap(Op0, Op1);
13375   if (Op0.getOpcode() == ISD::SHL) {
13376     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
13377       if (And00C->getZExtValue() == 1) {
13378         // If we looked past a truncate, check that it's only truncating away
13379         // known zeros.
13380         unsigned BitWidth = Op0.getValueSizeInBits();
13381         unsigned AndBitWidth = And.getValueSizeInBits();
13382         if (BitWidth > AndBitWidth) {
13383           APInt Zeros, Ones;
13384           DAG.computeKnownBits(Op0, Zeros, Ones);
13385           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
13386             return SDValue();
13387         }
13388         LHS = Op1;
13389         RHS = Op0.getOperand(1);
13390       }
13391   } else if (Op1.getOpcode() == ISD::Constant) {
13392     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
13393     uint64_t AndRHSVal = AndRHS->getZExtValue();
13394     SDValue AndLHS = Op0;
13395
13396     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
13397       LHS = AndLHS.getOperand(0);
13398       RHS = AndLHS.getOperand(1);
13399     }
13400
13401     // Use BT if the immediate can't be encoded in a TEST instruction.
13402     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
13403       LHS = AndLHS;
13404       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), dl, LHS.getValueType());
13405     }
13406   }
13407
13408   if (LHS.getNode()) {
13409     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
13410     // instruction.  Since the shift amount is in-range-or-undefined, we know
13411     // that doing a bittest on the i32 value is ok.  We extend to i32 because
13412     // the encoding for the i16 version is larger than the i32 version.
13413     // Also promote i16 to i32 for performance / code size reason.
13414     if (LHS.getValueType() == MVT::i8 ||
13415         LHS.getValueType() == MVT::i16)
13416       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
13417
13418     // If the operand types disagree, extend the shift amount to match.  Since
13419     // BT ignores high bits (like shifts) we can use anyextend.
13420     if (LHS.getValueType() != RHS.getValueType())
13421       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
13422
13423     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
13424     X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
13425     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13426                        DAG.getConstant(Cond, dl, MVT::i8), BT);
13427   }
13428
13429   return SDValue();
13430 }
13431
13432 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
13433 /// mask CMPs.
13434 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
13435                               SDValue &Op1) {
13436   unsigned SSECC;
13437   bool Swap = false;
13438
13439   // SSE Condition code mapping:
13440   //  0 - EQ
13441   //  1 - LT
13442   //  2 - LE
13443   //  3 - UNORD
13444   //  4 - NEQ
13445   //  5 - NLT
13446   //  6 - NLE
13447   //  7 - ORD
13448   switch (SetCCOpcode) {
13449   default: llvm_unreachable("Unexpected SETCC condition");
13450   case ISD::SETOEQ:
13451   case ISD::SETEQ:  SSECC = 0; break;
13452   case ISD::SETOGT:
13453   case ISD::SETGT:  Swap = true; // Fallthrough
13454   case ISD::SETLT:
13455   case ISD::SETOLT: SSECC = 1; break;
13456   case ISD::SETOGE:
13457   case ISD::SETGE:  Swap = true; // Fallthrough
13458   case ISD::SETLE:
13459   case ISD::SETOLE: SSECC = 2; break;
13460   case ISD::SETUO:  SSECC = 3; break;
13461   case ISD::SETUNE:
13462   case ISD::SETNE:  SSECC = 4; break;
13463   case ISD::SETULE: Swap = true; // Fallthrough
13464   case ISD::SETUGE: SSECC = 5; break;
13465   case ISD::SETULT: Swap = true; // Fallthrough
13466   case ISD::SETUGT: SSECC = 6; break;
13467   case ISD::SETO:   SSECC = 7; break;
13468   case ISD::SETUEQ:
13469   case ISD::SETONE: SSECC = 8; break;
13470   }
13471   if (Swap)
13472     std::swap(Op0, Op1);
13473
13474   return SSECC;
13475 }
13476
13477 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
13478 // ones, and then concatenate the result back.
13479 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
13480   MVT VT = Op.getSimpleValueType();
13481
13482   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
13483          "Unsupported value type for operation");
13484
13485   unsigned NumElems = VT.getVectorNumElements();
13486   SDLoc dl(Op);
13487   SDValue CC = Op.getOperand(2);
13488
13489   // Extract the LHS vectors
13490   SDValue LHS = Op.getOperand(0);
13491   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
13492   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
13493
13494   // Extract the RHS vectors
13495   SDValue RHS = Op.getOperand(1);
13496   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
13497   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
13498
13499   // Issue the operation on the smaller types and concatenate the result back
13500   MVT EltVT = VT.getVectorElementType();
13501   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13502   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
13503                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
13504                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
13505 }
13506
13507 static SDValue LowerBoolVSETCC_AVX512(SDValue Op, SelectionDAG &DAG) {
13508   SDValue Op0 = Op.getOperand(0);
13509   SDValue Op1 = Op.getOperand(1);
13510   SDValue CC = Op.getOperand(2);
13511   MVT VT = Op.getSimpleValueType();
13512   SDLoc dl(Op);
13513
13514   assert(Op0.getValueType().getVectorElementType() == MVT::i1 &&
13515          "Unexpected type for boolean compare operation");
13516   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13517   SDValue NotOp0 = DAG.getNode(ISD::XOR, dl, VT, Op0,
13518                                DAG.getConstant(-1, dl, VT));
13519   SDValue NotOp1 = DAG.getNode(ISD::XOR, dl, VT, Op1,
13520                                DAG.getConstant(-1, dl, VT));
13521   switch (SetCCOpcode) {
13522   default: llvm_unreachable("Unexpected SETCC condition");
13523   case ISD::SETEQ:
13524     // (x == y) -> ~(x ^ y)
13525     return DAG.getNode(ISD::XOR, dl, VT,
13526                        DAG.getNode(ISD::XOR, dl, VT, Op0, Op1),
13527                        DAG.getConstant(-1, dl, VT));
13528   case ISD::SETNE:
13529     // (x != y) -> (x ^ y)
13530     return DAG.getNode(ISD::XOR, dl, VT, Op0, Op1);
13531   case ISD::SETUGT:
13532   case ISD::SETGT:
13533     // (x > y) -> (x & ~y)
13534     return DAG.getNode(ISD::AND, dl, VT, Op0, NotOp1);
13535   case ISD::SETULT:
13536   case ISD::SETLT:
13537     // (x < y) -> (~x & y)
13538     return DAG.getNode(ISD::AND, dl, VT, NotOp0, Op1);
13539   case ISD::SETULE:
13540   case ISD::SETLE:
13541     // (x <= y) -> (~x | y)
13542     return DAG.getNode(ISD::OR, dl, VT, NotOp0, Op1);
13543   case ISD::SETUGE:
13544   case ISD::SETGE:
13545     // (x >=y) -> (x | ~y)
13546     return DAG.getNode(ISD::OR, dl, VT, Op0, NotOp1);
13547   }
13548 }
13549
13550 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
13551                                      const X86Subtarget *Subtarget) {
13552   SDValue Op0 = Op.getOperand(0);
13553   SDValue Op1 = Op.getOperand(1);
13554   SDValue CC = Op.getOperand(2);
13555   MVT VT = Op.getSimpleValueType();
13556   SDLoc dl(Op);
13557
13558   assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 8 &&
13559          Op.getValueType().getScalarType() == MVT::i1 &&
13560          "Cannot set masked compare for this operation");
13561
13562   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13563   unsigned  Opc = 0;
13564   bool Unsigned = false;
13565   bool Swap = false;
13566   unsigned SSECC;
13567   switch (SetCCOpcode) {
13568   default: llvm_unreachable("Unexpected SETCC condition");
13569   case ISD::SETNE:  SSECC = 4; break;
13570   case ISD::SETEQ:  Opc = X86ISD::PCMPEQM; break;
13571   case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
13572   case ISD::SETLT:  Swap = true; //fall-through
13573   case ISD::SETGT:  Opc = X86ISD::PCMPGTM; break;
13574   case ISD::SETULT: SSECC = 1; Unsigned = true; break;
13575   case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
13576   case ISD::SETGE:  Swap = true; SSECC = 2; break; // LE + swap
13577   case ISD::SETULE: Unsigned = true; //fall-through
13578   case ISD::SETLE:  SSECC = 2; break;
13579   }
13580
13581   if (Swap)
13582     std::swap(Op0, Op1);
13583   if (Opc)
13584     return DAG.getNode(Opc, dl, VT, Op0, Op1);
13585   Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
13586   return DAG.getNode(Opc, dl, VT, Op0, Op1,
13587                      DAG.getConstant(SSECC, dl, MVT::i8));
13588 }
13589
13590 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
13591 /// operand \p Op1.  If non-trivial (for example because it's not constant)
13592 /// return an empty value.
13593 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
13594 {
13595   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
13596   if (!BV)
13597     return SDValue();
13598
13599   MVT VT = Op1.getSimpleValueType();
13600   MVT EVT = VT.getVectorElementType();
13601   unsigned n = VT.getVectorNumElements();
13602   SmallVector<SDValue, 8> ULTOp1;
13603
13604   for (unsigned i = 0; i < n; ++i) {
13605     ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
13606     if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
13607       return SDValue();
13608
13609     // Avoid underflow.
13610     APInt Val = Elt->getAPIntValue();
13611     if (Val == 0)
13612       return SDValue();
13613
13614     ULTOp1.push_back(DAG.getConstant(Val - 1, dl, EVT));
13615   }
13616
13617   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
13618 }
13619
13620 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
13621                            SelectionDAG &DAG) {
13622   SDValue Op0 = Op.getOperand(0);
13623   SDValue Op1 = Op.getOperand(1);
13624   SDValue CC = Op.getOperand(2);
13625   MVT VT = Op.getSimpleValueType();
13626   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13627   bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
13628   SDLoc dl(Op);
13629
13630   if (isFP) {
13631 #ifndef NDEBUG
13632     MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
13633     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
13634 #endif
13635
13636     unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
13637     unsigned Opc = X86ISD::CMPP;
13638     if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
13639       assert(VT.getVectorNumElements() <= 16);
13640       Opc = X86ISD::CMPM;
13641     }
13642     // In the two special cases we can't handle, emit two comparisons.
13643     if (SSECC == 8) {
13644       unsigned CC0, CC1;
13645       unsigned CombineOpc;
13646       if (SetCCOpcode == ISD::SETUEQ) {
13647         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
13648       } else {
13649         assert(SetCCOpcode == ISD::SETONE);
13650         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
13651       }
13652
13653       SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
13654                                  DAG.getConstant(CC0, dl, MVT::i8));
13655       SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
13656                                  DAG.getConstant(CC1, dl, MVT::i8));
13657       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
13658     }
13659     // Handle all other FP comparisons here.
13660     return DAG.getNode(Opc, dl, VT, Op0, Op1,
13661                        DAG.getConstant(SSECC, dl, MVT::i8));
13662   }
13663
13664   // Break 256-bit integer vector compare into smaller ones.
13665   if (VT.is256BitVector() && !Subtarget->hasInt256())
13666     return Lower256IntVSETCC(Op, DAG);
13667
13668   EVT OpVT = Op1.getValueType();
13669   if (OpVT.getVectorElementType() == MVT::i1)
13670     return LowerBoolVSETCC_AVX512(Op, DAG);
13671
13672   bool MaskResult = (VT.getVectorElementType() == MVT::i1);
13673   if (Subtarget->hasAVX512()) {
13674     if (Op1.getValueType().is512BitVector() ||
13675         (Subtarget->hasBWI() && Subtarget->hasVLX()) ||
13676         (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
13677       return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
13678
13679     // In AVX-512 architecture setcc returns mask with i1 elements,
13680     // But there is no compare instruction for i8 and i16 elements in KNL.
13681     // We are not talking about 512-bit operands in this case, these
13682     // types are illegal.
13683     if (MaskResult &&
13684         (OpVT.getVectorElementType().getSizeInBits() < 32 &&
13685          OpVT.getVectorElementType().getSizeInBits() >= 8))
13686       return DAG.getNode(ISD::TRUNCATE, dl, VT,
13687                          DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
13688   }
13689
13690   // We are handling one of the integer comparisons here.  Since SSE only has
13691   // GT and EQ comparisons for integer, swapping operands and multiple
13692   // operations may be required for some comparisons.
13693   unsigned Opc;
13694   bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
13695   bool Subus = false;
13696
13697   switch (SetCCOpcode) {
13698   default: llvm_unreachable("Unexpected SETCC condition");
13699   case ISD::SETNE:  Invert = true;
13700   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
13701   case ISD::SETLT:  Swap = true;
13702   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
13703   case ISD::SETGE:  Swap = true;
13704   case ISD::SETLE:  Opc = X86ISD::PCMPGT;
13705                     Invert = true; break;
13706   case ISD::SETULT: Swap = true;
13707   case ISD::SETUGT: Opc = X86ISD::PCMPGT;
13708                     FlipSigns = true; break;
13709   case ISD::SETUGE: Swap = true;
13710   case ISD::SETULE: Opc = X86ISD::PCMPGT;
13711                     FlipSigns = true; Invert = true; break;
13712   }
13713
13714   // Special case: Use min/max operations for SETULE/SETUGE
13715   MVT VET = VT.getVectorElementType();
13716   bool hasMinMax =
13717        (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
13718     || (Subtarget->hasSSE2()  && (VET == MVT::i8));
13719
13720   if (hasMinMax) {
13721     switch (SetCCOpcode) {
13722     default: break;
13723     case ISD::SETULE: Opc = ISD::UMIN; MinMax = true; break;
13724     case ISD::SETUGE: Opc = ISD::UMAX; MinMax = true; break;
13725     }
13726
13727     if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
13728   }
13729
13730   bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
13731   if (!MinMax && hasSubus) {
13732     // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
13733     // Op0 u<= Op1:
13734     //   t = psubus Op0, Op1
13735     //   pcmpeq t, <0..0>
13736     switch (SetCCOpcode) {
13737     default: break;
13738     case ISD::SETULT: {
13739       // If the comparison is against a constant we can turn this into a
13740       // setule.  With psubus, setule does not require a swap.  This is
13741       // beneficial because the constant in the register is no longer
13742       // destructed as the destination so it can be hoisted out of a loop.
13743       // Only do this pre-AVX since vpcmp* is no longer destructive.
13744       if (Subtarget->hasAVX())
13745         break;
13746       SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
13747       if (ULEOp1.getNode()) {
13748         Op1 = ULEOp1;
13749         Subus = true; Invert = false; Swap = false;
13750       }
13751       break;
13752     }
13753     // Psubus is better than flip-sign because it requires no inversion.
13754     case ISD::SETUGE: Subus = true; Invert = false; Swap = true;  break;
13755     case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
13756     }
13757
13758     if (Subus) {
13759       Opc = X86ISD::SUBUS;
13760       FlipSigns = false;
13761     }
13762   }
13763
13764   if (Swap)
13765     std::swap(Op0, Op1);
13766
13767   // Check that the operation in question is available (most are plain SSE2,
13768   // but PCMPGTQ and PCMPEQQ have different requirements).
13769   if (VT == MVT::v2i64) {
13770     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
13771       assert(Subtarget->hasSSE2() && "Don't know how to lower!");
13772
13773       // First cast everything to the right type.
13774       Op0 = DAG.getBitcast(MVT::v4i32, Op0);
13775       Op1 = DAG.getBitcast(MVT::v4i32, Op1);
13776
13777       // Since SSE has no unsigned integer comparisons, we need to flip the sign
13778       // bits of the inputs before performing those operations. The lower
13779       // compare is always unsigned.
13780       SDValue SB;
13781       if (FlipSigns) {
13782         SB = DAG.getConstant(0x80000000U, dl, MVT::v4i32);
13783       } else {
13784         SDValue Sign = DAG.getConstant(0x80000000U, dl, MVT::i32);
13785         SDValue Zero = DAG.getConstant(0x00000000U, dl, MVT::i32);
13786         SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
13787                          Sign, Zero, Sign, Zero);
13788       }
13789       Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
13790       Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
13791
13792       // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
13793       SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
13794       SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
13795
13796       // Create masks for only the low parts/high parts of the 64 bit integers.
13797       static const int MaskHi[] = { 1, 1, 3, 3 };
13798       static const int MaskLo[] = { 0, 0, 2, 2 };
13799       SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
13800       SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
13801       SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
13802
13803       SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
13804       Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
13805
13806       if (Invert)
13807         Result = DAG.getNOT(dl, Result, MVT::v4i32);
13808
13809       return DAG.getBitcast(VT, Result);
13810     }
13811
13812     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
13813       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
13814       // pcmpeqd + pshufd + pand.
13815       assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
13816
13817       // First cast everything to the right type.
13818       Op0 = DAG.getBitcast(MVT::v4i32, Op0);
13819       Op1 = DAG.getBitcast(MVT::v4i32, Op1);
13820
13821       // Do the compare.
13822       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
13823
13824       // Make sure the lower and upper halves are both all-ones.
13825       static const int Mask[] = { 1, 0, 3, 2 };
13826       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
13827       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
13828
13829       if (Invert)
13830         Result = DAG.getNOT(dl, Result, MVT::v4i32);
13831
13832       return DAG.getBitcast(VT, Result);
13833     }
13834   }
13835
13836   // Since SSE has no unsigned integer comparisons, we need to flip the sign
13837   // bits of the inputs before performing those operations.
13838   if (FlipSigns) {
13839     EVT EltVT = VT.getVectorElementType();
13840     SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), dl,
13841                                  VT);
13842     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
13843     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
13844   }
13845
13846   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
13847
13848   // If the logical-not of the result is required, perform that now.
13849   if (Invert)
13850     Result = DAG.getNOT(dl, Result, VT);
13851
13852   if (MinMax)
13853     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
13854
13855   if (Subus)
13856     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
13857                          getZeroVector(VT, Subtarget, DAG, dl));
13858
13859   return Result;
13860 }
13861
13862 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
13863
13864   MVT VT = Op.getSimpleValueType();
13865
13866   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
13867
13868   assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
13869          && "SetCC type must be 8-bit or 1-bit integer");
13870   SDValue Op0 = Op.getOperand(0);
13871   SDValue Op1 = Op.getOperand(1);
13872   SDLoc dl(Op);
13873   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
13874
13875   // Optimize to BT if possible.
13876   // Lower (X & (1 << N)) == 0 to BT(X, N).
13877   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
13878   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
13879   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
13880       Op1.getOpcode() == ISD::Constant &&
13881       cast<ConstantSDNode>(Op1)->isNullValue() &&
13882       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13883     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
13884     if (NewSetCC.getNode()) {
13885       if (VT == MVT::i1)
13886         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewSetCC);
13887       return NewSetCC;
13888     }
13889   }
13890
13891   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
13892   // these.
13893   if (Op1.getOpcode() == ISD::Constant &&
13894       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
13895        cast<ConstantSDNode>(Op1)->isNullValue()) &&
13896       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13897
13898     // If the input is a setcc, then reuse the input setcc or use a new one with
13899     // the inverted condition.
13900     if (Op0.getOpcode() == X86ISD::SETCC) {
13901       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
13902       bool Invert = (CC == ISD::SETNE) ^
13903         cast<ConstantSDNode>(Op1)->isNullValue();
13904       if (!Invert)
13905         return Op0;
13906
13907       CCode = X86::GetOppositeBranchCondition(CCode);
13908       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13909                                   DAG.getConstant(CCode, dl, MVT::i8),
13910                                   Op0.getOperand(1));
13911       if (VT == MVT::i1)
13912         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
13913       return SetCC;
13914     }
13915   }
13916   if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
13917       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
13918       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13919
13920     ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
13921     return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, dl, MVT::i1), NewCC);
13922   }
13923
13924   bool isFP = Op1.getSimpleValueType().isFloatingPoint();
13925   unsigned X86CC = TranslateX86CC(CC, dl, isFP, Op0, Op1, DAG);
13926   if (X86CC == X86::COND_INVALID)
13927     return SDValue();
13928
13929   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
13930   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
13931   SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13932                               DAG.getConstant(X86CC, dl, MVT::i8), EFLAGS);
13933   if (VT == MVT::i1)
13934     return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
13935   return SetCC;
13936 }
13937
13938 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
13939 static bool isX86LogicalCmp(SDValue Op) {
13940   unsigned Opc = Op.getNode()->getOpcode();
13941   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
13942       Opc == X86ISD::SAHF)
13943     return true;
13944   if (Op.getResNo() == 1 &&
13945       (Opc == X86ISD::ADD ||
13946        Opc == X86ISD::SUB ||
13947        Opc == X86ISD::ADC ||
13948        Opc == X86ISD::SBB ||
13949        Opc == X86ISD::SMUL ||
13950        Opc == X86ISD::UMUL ||
13951        Opc == X86ISD::INC ||
13952        Opc == X86ISD::DEC ||
13953        Opc == X86ISD::OR ||
13954        Opc == X86ISD::XOR ||
13955        Opc == X86ISD::AND))
13956     return true;
13957
13958   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
13959     return true;
13960
13961   return false;
13962 }
13963
13964 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
13965   if (V.getOpcode() != ISD::TRUNCATE)
13966     return false;
13967
13968   SDValue VOp0 = V.getOperand(0);
13969   unsigned InBits = VOp0.getValueSizeInBits();
13970   unsigned Bits = V.getValueSizeInBits();
13971   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
13972 }
13973
13974 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
13975   bool addTest = true;
13976   SDValue Cond  = Op.getOperand(0);
13977   SDValue Op1 = Op.getOperand(1);
13978   SDValue Op2 = Op.getOperand(2);
13979   SDLoc DL(Op);
13980   EVT VT = Op1.getValueType();
13981   SDValue CC;
13982
13983   // Lower FP selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
13984   // are available or VBLENDV if AVX is available.
13985   // Otherwise FP cmovs get lowered into a less efficient branch sequence later.
13986   if (Cond.getOpcode() == ISD::SETCC &&
13987       ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
13988        (Subtarget->hasSSE1() && VT == MVT::f32)) &&
13989       VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
13990     SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
13991     int SSECC = translateX86FSETCC(
13992         cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
13993
13994     if (SSECC != 8) {
13995       if (Subtarget->hasAVX512()) {
13996         SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
13997                                   DAG.getConstant(SSECC, DL, MVT::i8));
13998         return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
13999       }
14000
14001       SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
14002                                 DAG.getConstant(SSECC, DL, MVT::i8));
14003
14004       // If we have AVX, we can use a variable vector select (VBLENDV) instead
14005       // of 3 logic instructions for size savings and potentially speed.
14006       // Unfortunately, there is no scalar form of VBLENDV.
14007
14008       // If either operand is a constant, don't try this. We can expect to
14009       // optimize away at least one of the logic instructions later in that
14010       // case, so that sequence would be faster than a variable blend.
14011
14012       // BLENDV was introduced with SSE 4.1, but the 2 register form implicitly
14013       // uses XMM0 as the selection register. That may need just as many
14014       // instructions as the AND/ANDN/OR sequence due to register moves, so
14015       // don't bother.
14016
14017       if (Subtarget->hasAVX() &&
14018           !isa<ConstantFPSDNode>(Op1) && !isa<ConstantFPSDNode>(Op2)) {
14019
14020         // Convert to vectors, do a VSELECT, and convert back to scalar.
14021         // All of the conversions should be optimized away.
14022
14023         EVT VecVT = VT == MVT::f32 ? MVT::v4f32 : MVT::v2f64;
14024         SDValue VOp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op1);
14025         SDValue VOp2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op2);
14026         SDValue VCmp = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Cmp);
14027
14028         EVT VCmpVT = VT == MVT::f32 ? MVT::v4i32 : MVT::v2i64;
14029         VCmp = DAG.getBitcast(VCmpVT, VCmp);
14030
14031         SDValue VSel = DAG.getNode(ISD::VSELECT, DL, VecVT, VCmp, VOp1, VOp2);
14032
14033         return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
14034                            VSel, DAG.getIntPtrConstant(0, DL));
14035       }
14036       SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
14037       SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
14038       return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
14039     }
14040   }
14041
14042   if (VT.isVector() && VT.getScalarType() == MVT::i1) {
14043     SDValue Op1Scalar;
14044     if (ISD::isBuildVectorOfConstantSDNodes(Op1.getNode()))
14045       Op1Scalar = ConvertI1VectorToInteger(Op1, DAG);
14046     else if (Op1.getOpcode() == ISD::BITCAST && Op1.getOperand(0))
14047       Op1Scalar = Op1.getOperand(0);
14048     SDValue Op2Scalar;
14049     if (ISD::isBuildVectorOfConstantSDNodes(Op2.getNode()))
14050       Op2Scalar = ConvertI1VectorToInteger(Op2, DAG);
14051     else if (Op2.getOpcode() == ISD::BITCAST && Op2.getOperand(0))
14052       Op2Scalar = Op2.getOperand(0);
14053     if (Op1Scalar.getNode() && Op2Scalar.getNode()) {
14054       SDValue newSelect = DAG.getNode(ISD::SELECT, DL,
14055                                       Op1Scalar.getValueType(),
14056                                       Cond, Op1Scalar, Op2Scalar);
14057       if (newSelect.getValueSizeInBits() == VT.getSizeInBits())
14058         return DAG.getBitcast(VT, newSelect);
14059       SDValue ExtVec = DAG.getBitcast(MVT::v8i1, newSelect);
14060       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, ExtVec,
14061                          DAG.getIntPtrConstant(0, DL));
14062     }
14063   }
14064
14065   if (VT == MVT::v4i1 || VT == MVT::v2i1) {
14066     SDValue zeroConst = DAG.getIntPtrConstant(0, DL);
14067     Op1 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
14068                       DAG.getUNDEF(MVT::v8i1), Op1, zeroConst);
14069     Op2 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
14070                       DAG.getUNDEF(MVT::v8i1), Op2, zeroConst);
14071     SDValue newSelect = DAG.getNode(ISD::SELECT, DL, MVT::v8i1,
14072                                     Cond, Op1, Op2);
14073     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, newSelect, zeroConst);
14074   }
14075
14076   if (Cond.getOpcode() == ISD::SETCC) {
14077     SDValue NewCond = LowerSETCC(Cond, DAG);
14078     if (NewCond.getNode())
14079       Cond = NewCond;
14080   }
14081
14082   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
14083   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
14084   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
14085   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
14086   if (Cond.getOpcode() == X86ISD::SETCC &&
14087       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
14088       isZero(Cond.getOperand(1).getOperand(1))) {
14089     SDValue Cmp = Cond.getOperand(1);
14090
14091     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
14092
14093     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
14094         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
14095       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
14096
14097       SDValue CmpOp0 = Cmp.getOperand(0);
14098       // Apply further optimizations for special cases
14099       // (select (x != 0), -1, 0) -> neg & sbb
14100       // (select (x == 0), 0, -1) -> neg & sbb
14101       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
14102         if (YC->isNullValue() &&
14103             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
14104           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
14105           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
14106                                     DAG.getConstant(0, DL,
14107                                                     CmpOp0.getValueType()),
14108                                     CmpOp0);
14109           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
14110                                     DAG.getConstant(X86::COND_B, DL, MVT::i8),
14111                                     SDValue(Neg.getNode(), 1));
14112           return Res;
14113         }
14114
14115       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
14116                         CmpOp0, DAG.getConstant(1, DL, CmpOp0.getValueType()));
14117       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14118
14119       SDValue Res =   // Res = 0 or -1.
14120         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
14121                     DAG.getConstant(X86::COND_B, DL, MVT::i8), Cmp);
14122
14123       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
14124         Res = DAG.getNOT(DL, Res, Res.getValueType());
14125
14126       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
14127       if (!N2C || !N2C->isNullValue())
14128         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
14129       return Res;
14130     }
14131   }
14132
14133   // Look past (and (setcc_carry (cmp ...)), 1).
14134   if (Cond.getOpcode() == ISD::AND &&
14135       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
14136     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
14137     if (C && C->getAPIntValue() == 1)
14138       Cond = Cond.getOperand(0);
14139   }
14140
14141   // If condition flag is set by a X86ISD::CMP, then use it as the condition
14142   // setting operand in place of the X86ISD::SETCC.
14143   unsigned CondOpcode = Cond.getOpcode();
14144   if (CondOpcode == X86ISD::SETCC ||
14145       CondOpcode == X86ISD::SETCC_CARRY) {
14146     CC = Cond.getOperand(0);
14147
14148     SDValue Cmp = Cond.getOperand(1);
14149     unsigned Opc = Cmp.getOpcode();
14150     MVT VT = Op.getSimpleValueType();
14151
14152     bool IllegalFPCMov = false;
14153     if (VT.isFloatingPoint() && !VT.isVector() &&
14154         !isScalarFPTypeInSSEReg(VT))  // FPStack?
14155       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
14156
14157     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
14158         Opc == X86ISD::BT) { // FIXME
14159       Cond = Cmp;
14160       addTest = false;
14161     }
14162   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
14163              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
14164              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
14165               Cond.getOperand(0).getValueType() != MVT::i8)) {
14166     SDValue LHS = Cond.getOperand(0);
14167     SDValue RHS = Cond.getOperand(1);
14168     unsigned X86Opcode;
14169     unsigned X86Cond;
14170     SDVTList VTs;
14171     switch (CondOpcode) {
14172     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
14173     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
14174     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
14175     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
14176     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
14177     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
14178     default: llvm_unreachable("unexpected overflowing operator");
14179     }
14180     if (CondOpcode == ISD::UMULO)
14181       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
14182                           MVT::i32);
14183     else
14184       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
14185
14186     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
14187
14188     if (CondOpcode == ISD::UMULO)
14189       Cond = X86Op.getValue(2);
14190     else
14191       Cond = X86Op.getValue(1);
14192
14193     CC = DAG.getConstant(X86Cond, DL, MVT::i8);
14194     addTest = false;
14195   }
14196
14197   if (addTest) {
14198     // Look past the truncate if the high bits are known zero.
14199     if (isTruncWithZeroHighBitsInput(Cond, DAG))
14200       Cond = Cond.getOperand(0);
14201
14202     // We know the result of AND is compared against zero. Try to match
14203     // it to BT.
14204     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
14205       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
14206       if (NewSetCC.getNode()) {
14207         CC = NewSetCC.getOperand(0);
14208         Cond = NewSetCC.getOperand(1);
14209         addTest = false;
14210       }
14211     }
14212   }
14213
14214   if (addTest) {
14215     CC = DAG.getConstant(X86::COND_NE, DL, MVT::i8);
14216     Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
14217   }
14218
14219   // a <  b ? -1 :  0 -> RES = ~setcc_carry
14220   // a <  b ?  0 : -1 -> RES = setcc_carry
14221   // a >= b ? -1 :  0 -> RES = setcc_carry
14222   // a >= b ?  0 : -1 -> RES = ~setcc_carry
14223   if (Cond.getOpcode() == X86ISD::SUB) {
14224     Cond = ConvertCmpIfNecessary(Cond, DAG);
14225     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
14226
14227     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
14228         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
14229       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
14230                                 DAG.getConstant(X86::COND_B, DL, MVT::i8),
14231                                 Cond);
14232       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
14233         return DAG.getNOT(DL, Res, Res.getValueType());
14234       return Res;
14235     }
14236   }
14237
14238   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
14239   // widen the cmov and push the truncate through. This avoids introducing a new
14240   // branch during isel and doesn't add any extensions.
14241   if (Op.getValueType() == MVT::i8 &&
14242       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
14243     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
14244     if (T1.getValueType() == T2.getValueType() &&
14245         // Blacklist CopyFromReg to avoid partial register stalls.
14246         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
14247       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
14248       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
14249       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
14250     }
14251   }
14252
14253   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
14254   // condition is true.
14255   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
14256   SDValue Ops[] = { Op2, Op1, CC, Cond };
14257   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
14258 }
14259
14260 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op,
14261                                        const X86Subtarget *Subtarget,
14262                                        SelectionDAG &DAG) {
14263   MVT VT = Op->getSimpleValueType(0);
14264   SDValue In = Op->getOperand(0);
14265   MVT InVT = In.getSimpleValueType();
14266   MVT VTElt = VT.getVectorElementType();
14267   MVT InVTElt = InVT.getVectorElementType();
14268   SDLoc dl(Op);
14269
14270   // SKX processor
14271   if ((InVTElt == MVT::i1) &&
14272       (((Subtarget->hasBWI() && Subtarget->hasVLX() &&
14273         VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() <= 16)) ||
14274
14275        ((Subtarget->hasBWI() && VT.is512BitVector() &&
14276         VTElt.getSizeInBits() <= 16)) ||
14277
14278        ((Subtarget->hasDQI() && Subtarget->hasVLX() &&
14279         VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() >= 32)) ||
14280
14281        ((Subtarget->hasDQI() && VT.is512BitVector() &&
14282         VTElt.getSizeInBits() >= 32))))
14283     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14284
14285   unsigned int NumElts = VT.getVectorNumElements();
14286
14287   if (NumElts != 8 && NumElts != 16 && !Subtarget->hasBWI())
14288     return SDValue();
14289
14290   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1) {
14291     if (In.getOpcode() == X86ISD::VSEXT || In.getOpcode() == X86ISD::VZEXT)
14292       return DAG.getNode(In.getOpcode(), dl, VT, In.getOperand(0));
14293     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14294   }
14295
14296   assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
14297   MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
14298   SDValue NegOne =
14299    DAG.getConstant(APInt::getAllOnesValue(ExtVT.getScalarSizeInBits()), dl,
14300                    ExtVT);
14301   SDValue Zero =
14302    DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), dl, ExtVT);
14303
14304   SDValue V = DAG.getNode(ISD::VSELECT, dl, ExtVT, In, NegOne, Zero);
14305   if (VT.is512BitVector())
14306     return V;
14307   return DAG.getNode(X86ISD::VTRUNC, dl, VT, V);
14308 }
14309
14310 static SDValue LowerSIGN_EXTEND_VECTOR_INREG(SDValue Op,
14311                                              const X86Subtarget *Subtarget,
14312                                              SelectionDAG &DAG) {
14313   SDValue In = Op->getOperand(0);
14314   MVT VT = Op->getSimpleValueType(0);
14315   MVT InVT = In.getSimpleValueType();
14316   assert(VT.getSizeInBits() == InVT.getSizeInBits());
14317
14318   MVT InSVT = InVT.getScalarType();
14319   assert(VT.getScalarType().getScalarSizeInBits() > InSVT.getScalarSizeInBits());
14320
14321   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
14322     return SDValue();
14323   if (InSVT != MVT::i32 && InSVT != MVT::i16 && InSVT != MVT::i8)
14324     return SDValue();
14325
14326   SDLoc dl(Op);
14327
14328   // SSE41 targets can use the pmovsx* instructions directly.
14329   if (Subtarget->hasSSE41())
14330     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14331
14332   // pre-SSE41 targets unpack lower lanes and then sign-extend using SRAI.
14333   SDValue Curr = In;
14334   MVT CurrVT = InVT;
14335
14336   // As SRAI is only available on i16/i32 types, we expand only up to i32
14337   // and handle i64 separately.
14338   while (CurrVT != VT && CurrVT.getScalarType() != MVT::i32) {
14339     Curr = DAG.getNode(X86ISD::UNPCKL, dl, CurrVT, DAG.getUNDEF(CurrVT), Curr);
14340     MVT CurrSVT = MVT::getIntegerVT(CurrVT.getScalarSizeInBits() * 2);
14341     CurrVT = MVT::getVectorVT(CurrSVT, CurrVT.getVectorNumElements() / 2);
14342     Curr = DAG.getBitcast(CurrVT, Curr);
14343   }
14344
14345   SDValue SignExt = Curr;
14346   if (CurrVT != InVT) {
14347     unsigned SignExtShift =
14348         CurrVT.getScalarSizeInBits() - InSVT.getScalarSizeInBits();
14349     SignExt = DAG.getNode(X86ISD::VSRAI, dl, CurrVT, Curr,
14350                           DAG.getConstant(SignExtShift, dl, MVT::i8));
14351   }
14352
14353   if (CurrVT == VT)
14354     return SignExt;
14355
14356   if (VT == MVT::v2i64 && CurrVT == MVT::v4i32) {
14357     SDValue Sign = DAG.getNode(X86ISD::VSRAI, dl, CurrVT, Curr,
14358                                DAG.getConstant(31, dl, MVT::i8));
14359     SDValue Ext = DAG.getVectorShuffle(CurrVT, dl, SignExt, Sign, {0, 4, 1, 5});
14360     return DAG.getBitcast(VT, Ext);
14361   }
14362
14363   return SDValue();
14364 }
14365
14366 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
14367                                 SelectionDAG &DAG) {
14368   MVT VT = Op->getSimpleValueType(0);
14369   SDValue In = Op->getOperand(0);
14370   MVT InVT = In.getSimpleValueType();
14371   SDLoc dl(Op);
14372
14373   if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
14374     return LowerSIGN_EXTEND_AVX512(Op, Subtarget, DAG);
14375
14376   if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
14377       (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
14378       (VT != MVT::v16i16 || InVT != MVT::v16i8))
14379     return SDValue();
14380
14381   if (Subtarget->hasInt256())
14382     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14383
14384   // Optimize vectors in AVX mode
14385   // Sign extend  v8i16 to v8i32 and
14386   //              v4i32 to v4i64
14387   //
14388   // Divide input vector into two parts
14389   // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
14390   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
14391   // concat the vectors to original VT
14392
14393   unsigned NumElems = InVT.getVectorNumElements();
14394   SDValue Undef = DAG.getUNDEF(InVT);
14395
14396   SmallVector<int,8> ShufMask1(NumElems, -1);
14397   for (unsigned i = 0; i != NumElems/2; ++i)
14398     ShufMask1[i] = i;
14399
14400   SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
14401
14402   SmallVector<int,8> ShufMask2(NumElems, -1);
14403   for (unsigned i = 0; i != NumElems/2; ++i)
14404     ShufMask2[i] = i + NumElems/2;
14405
14406   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
14407
14408   MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
14409                                 VT.getVectorNumElements()/2);
14410
14411   OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
14412   OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
14413
14414   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
14415 }
14416
14417 // Lower vector extended loads using a shuffle. If SSSE3 is not available we
14418 // may emit an illegal shuffle but the expansion is still better than scalar
14419 // code. We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise
14420 // we'll emit a shuffle and a arithmetic shift.
14421 // FIXME: Is the expansion actually better than scalar code? It doesn't seem so.
14422 // TODO: It is possible to support ZExt by zeroing the undef values during
14423 // the shuffle phase or after the shuffle.
14424 static SDValue LowerExtendedLoad(SDValue Op, const X86Subtarget *Subtarget,
14425                                  SelectionDAG &DAG) {
14426   MVT RegVT = Op.getSimpleValueType();
14427   assert(RegVT.isVector() && "We only custom lower vector sext loads.");
14428   assert(RegVT.isInteger() &&
14429          "We only custom lower integer vector sext loads.");
14430
14431   // Nothing useful we can do without SSE2 shuffles.
14432   assert(Subtarget->hasSSE2() && "We only custom lower sext loads with SSE2.");
14433
14434   LoadSDNode *Ld = cast<LoadSDNode>(Op.getNode());
14435   SDLoc dl(Ld);
14436   EVT MemVT = Ld->getMemoryVT();
14437   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14438   unsigned RegSz = RegVT.getSizeInBits();
14439
14440   ISD::LoadExtType Ext = Ld->getExtensionType();
14441
14442   assert((Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)
14443          && "Only anyext and sext are currently implemented.");
14444   assert(MemVT != RegVT && "Cannot extend to the same type");
14445   assert(MemVT.isVector() && "Must load a vector from memory");
14446
14447   unsigned NumElems = RegVT.getVectorNumElements();
14448   unsigned MemSz = MemVT.getSizeInBits();
14449   assert(RegSz > MemSz && "Register size must be greater than the mem size");
14450
14451   if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256()) {
14452     // The only way in which we have a legal 256-bit vector result but not the
14453     // integer 256-bit operations needed to directly lower a sextload is if we
14454     // have AVX1 but not AVX2. In that case, we can always emit a sextload to
14455     // a 128-bit vector and a normal sign_extend to 256-bits that should get
14456     // correctly legalized. We do this late to allow the canonical form of
14457     // sextload to persist throughout the rest of the DAG combiner -- it wants
14458     // to fold together any extensions it can, and so will fuse a sign_extend
14459     // of an sextload into a sextload targeting a wider value.
14460     SDValue Load;
14461     if (MemSz == 128) {
14462       // Just switch this to a normal load.
14463       assert(TLI.isTypeLegal(MemVT) && "If the memory type is a 128-bit type, "
14464                                        "it must be a legal 128-bit vector "
14465                                        "type!");
14466       Load = DAG.getLoad(MemVT, dl, Ld->getChain(), Ld->getBasePtr(),
14467                   Ld->getPointerInfo(), Ld->isVolatile(), Ld->isNonTemporal(),
14468                   Ld->isInvariant(), Ld->getAlignment());
14469     } else {
14470       assert(MemSz < 128 &&
14471              "Can't extend a type wider than 128 bits to a 256 bit vector!");
14472       // Do an sext load to a 128-bit vector type. We want to use the same
14473       // number of elements, but elements half as wide. This will end up being
14474       // recursively lowered by this routine, but will succeed as we definitely
14475       // have all the necessary features if we're using AVX1.
14476       EVT HalfEltVT =
14477           EVT::getIntegerVT(*DAG.getContext(), RegVT.getScalarSizeInBits() / 2);
14478       EVT HalfVecVT = EVT::getVectorVT(*DAG.getContext(), HalfEltVT, NumElems);
14479       Load =
14480           DAG.getExtLoad(Ext, dl, HalfVecVT, Ld->getChain(), Ld->getBasePtr(),
14481                          Ld->getPointerInfo(), MemVT, Ld->isVolatile(),
14482                          Ld->isNonTemporal(), Ld->isInvariant(),
14483                          Ld->getAlignment());
14484     }
14485
14486     // Replace chain users with the new chain.
14487     assert(Load->getNumValues() == 2 && "Loads must carry a chain!");
14488     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Load.getValue(1));
14489
14490     // Finally, do a normal sign-extend to the desired register.
14491     return DAG.getSExtOrTrunc(Load, dl, RegVT);
14492   }
14493
14494   // All sizes must be a power of two.
14495   assert(isPowerOf2_32(RegSz * MemSz * NumElems) &&
14496          "Non-power-of-two elements are not custom lowered!");
14497
14498   // Attempt to load the original value using scalar loads.
14499   // Find the largest scalar type that divides the total loaded size.
14500   MVT SclrLoadTy = MVT::i8;
14501   for (MVT Tp : MVT::integer_valuetypes()) {
14502     if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
14503       SclrLoadTy = Tp;
14504     }
14505   }
14506
14507   // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
14508   if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
14509       (64 <= MemSz))
14510     SclrLoadTy = MVT::f64;
14511
14512   // Calculate the number of scalar loads that we need to perform
14513   // in order to load our vector from memory.
14514   unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
14515
14516   assert((Ext != ISD::SEXTLOAD || NumLoads == 1) &&
14517          "Can only lower sext loads with a single scalar load!");
14518
14519   unsigned loadRegZize = RegSz;
14520   if (Ext == ISD::SEXTLOAD && RegSz >= 256)
14521     loadRegZize = 128;
14522
14523   // Represent our vector as a sequence of elements which are the
14524   // largest scalar that we can load.
14525   EVT LoadUnitVecVT = EVT::getVectorVT(
14526       *DAG.getContext(), SclrLoadTy, loadRegZize / SclrLoadTy.getSizeInBits());
14527
14528   // Represent the data using the same element type that is stored in
14529   // memory. In practice, we ''widen'' MemVT.
14530   EVT WideVecVT =
14531       EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
14532                        loadRegZize / MemVT.getScalarType().getSizeInBits());
14533
14534   assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
14535          "Invalid vector type");
14536
14537   // We can't shuffle using an illegal type.
14538   assert(TLI.isTypeLegal(WideVecVT) &&
14539          "We only lower types that form legal widened vector types");
14540
14541   SmallVector<SDValue, 8> Chains;
14542   SDValue Ptr = Ld->getBasePtr();
14543   SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits() / 8, dl,
14544                                       TLI.getPointerTy(DAG.getDataLayout()));
14545   SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
14546
14547   for (unsigned i = 0; i < NumLoads; ++i) {
14548     // Perform a single load.
14549     SDValue ScalarLoad =
14550         DAG.getLoad(SclrLoadTy, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
14551                     Ld->isVolatile(), Ld->isNonTemporal(), Ld->isInvariant(),
14552                     Ld->getAlignment());
14553     Chains.push_back(ScalarLoad.getValue(1));
14554     // Create the first element type using SCALAR_TO_VECTOR in order to avoid
14555     // another round of DAGCombining.
14556     if (i == 0)
14557       Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
14558     else
14559       Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
14560                         ScalarLoad, DAG.getIntPtrConstant(i, dl));
14561
14562     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
14563   }
14564
14565   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
14566
14567   // Bitcast the loaded value to a vector of the original element type, in
14568   // the size of the target vector type.
14569   SDValue SlicedVec = DAG.getBitcast(WideVecVT, Res);
14570   unsigned SizeRatio = RegSz / MemSz;
14571
14572   if (Ext == ISD::SEXTLOAD) {
14573     // If we have SSE4.1, we can directly emit a VSEXT node.
14574     if (Subtarget->hasSSE41()) {
14575       SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
14576       DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14577       return Sext;
14578     }
14579
14580     // Otherwise we'll shuffle the small elements in the high bits of the
14581     // larger type and perform an arithmetic shift. If the shift is not legal
14582     // it's better to scalarize.
14583     assert(TLI.isOperationLegalOrCustom(ISD::SRA, RegVT) &&
14584            "We can't implement a sext load without an arithmetic right shift!");
14585
14586     // Redistribute the loaded elements into the different locations.
14587     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
14588     for (unsigned i = 0; i != NumElems; ++i)
14589       ShuffleVec[i * SizeRatio + SizeRatio - 1] = i;
14590
14591     SDValue Shuff = DAG.getVectorShuffle(
14592         WideVecVT, dl, SlicedVec, DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
14593
14594     Shuff = DAG.getBitcast(RegVT, Shuff);
14595
14596     // Build the arithmetic shift.
14597     unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
14598                    MemVT.getVectorElementType().getSizeInBits();
14599     Shuff =
14600         DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
14601                     DAG.getConstant(Amt, dl, RegVT));
14602
14603     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14604     return Shuff;
14605   }
14606
14607   // Redistribute the loaded elements into the different locations.
14608   SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
14609   for (unsigned i = 0; i != NumElems; ++i)
14610     ShuffleVec[i * SizeRatio] = i;
14611
14612   SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
14613                                        DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
14614
14615   // Bitcast to the requested type.
14616   Shuff = DAG.getBitcast(RegVT, Shuff);
14617   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14618   return Shuff;
14619 }
14620
14621 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
14622 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
14623 // from the AND / OR.
14624 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
14625   Opc = Op.getOpcode();
14626   if (Opc != ISD::OR && Opc != ISD::AND)
14627     return false;
14628   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
14629           Op.getOperand(0).hasOneUse() &&
14630           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
14631           Op.getOperand(1).hasOneUse());
14632 }
14633
14634 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
14635 // 1 and that the SETCC node has a single use.
14636 static bool isXor1OfSetCC(SDValue Op) {
14637   if (Op.getOpcode() != ISD::XOR)
14638     return false;
14639   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
14640   if (N1C && N1C->getAPIntValue() == 1) {
14641     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
14642       Op.getOperand(0).hasOneUse();
14643   }
14644   return false;
14645 }
14646
14647 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
14648   bool addTest = true;
14649   SDValue Chain = Op.getOperand(0);
14650   SDValue Cond  = Op.getOperand(1);
14651   SDValue Dest  = Op.getOperand(2);
14652   SDLoc dl(Op);
14653   SDValue CC;
14654   bool Inverted = false;
14655
14656   if (Cond.getOpcode() == ISD::SETCC) {
14657     // Check for setcc([su]{add,sub,mul}o == 0).
14658     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
14659         isa<ConstantSDNode>(Cond.getOperand(1)) &&
14660         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
14661         Cond.getOperand(0).getResNo() == 1 &&
14662         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
14663          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
14664          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
14665          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
14666          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
14667          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
14668       Inverted = true;
14669       Cond = Cond.getOperand(0);
14670     } else {
14671       SDValue NewCond = LowerSETCC(Cond, DAG);
14672       if (NewCond.getNode())
14673         Cond = NewCond;
14674     }
14675   }
14676 #if 0
14677   // FIXME: LowerXALUO doesn't handle these!!
14678   else if (Cond.getOpcode() == X86ISD::ADD  ||
14679            Cond.getOpcode() == X86ISD::SUB  ||
14680            Cond.getOpcode() == X86ISD::SMUL ||
14681            Cond.getOpcode() == X86ISD::UMUL)
14682     Cond = LowerXALUO(Cond, DAG);
14683 #endif
14684
14685   // Look pass (and (setcc_carry (cmp ...)), 1).
14686   if (Cond.getOpcode() == ISD::AND &&
14687       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
14688     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
14689     if (C && C->getAPIntValue() == 1)
14690       Cond = Cond.getOperand(0);
14691   }
14692
14693   // If condition flag is set by a X86ISD::CMP, then use it as the condition
14694   // setting operand in place of the X86ISD::SETCC.
14695   unsigned CondOpcode = Cond.getOpcode();
14696   if (CondOpcode == X86ISD::SETCC ||
14697       CondOpcode == X86ISD::SETCC_CARRY) {
14698     CC = Cond.getOperand(0);
14699
14700     SDValue Cmp = Cond.getOperand(1);
14701     unsigned Opc = Cmp.getOpcode();
14702     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
14703     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
14704       Cond = Cmp;
14705       addTest = false;
14706     } else {
14707       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
14708       default: break;
14709       case X86::COND_O:
14710       case X86::COND_B:
14711         // These can only come from an arithmetic instruction with overflow,
14712         // e.g. SADDO, UADDO.
14713         Cond = Cond.getNode()->getOperand(1);
14714         addTest = false;
14715         break;
14716       }
14717     }
14718   }
14719   CondOpcode = Cond.getOpcode();
14720   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
14721       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
14722       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
14723        Cond.getOperand(0).getValueType() != MVT::i8)) {
14724     SDValue LHS = Cond.getOperand(0);
14725     SDValue RHS = Cond.getOperand(1);
14726     unsigned X86Opcode;
14727     unsigned X86Cond;
14728     SDVTList VTs;
14729     // Keep this in sync with LowerXALUO, otherwise we might create redundant
14730     // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
14731     // X86ISD::INC).
14732     switch (CondOpcode) {
14733     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
14734     case ISD::SADDO:
14735       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
14736         if (C->isOne()) {
14737           X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
14738           break;
14739         }
14740       X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
14741     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
14742     case ISD::SSUBO:
14743       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
14744         if (C->isOne()) {
14745           X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
14746           break;
14747         }
14748       X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
14749     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
14750     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
14751     default: llvm_unreachable("unexpected overflowing operator");
14752     }
14753     if (Inverted)
14754       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
14755     if (CondOpcode == ISD::UMULO)
14756       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
14757                           MVT::i32);
14758     else
14759       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
14760
14761     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
14762
14763     if (CondOpcode == ISD::UMULO)
14764       Cond = X86Op.getValue(2);
14765     else
14766       Cond = X86Op.getValue(1);
14767
14768     CC = DAG.getConstant(X86Cond, dl, MVT::i8);
14769     addTest = false;
14770   } else {
14771     unsigned CondOpc;
14772     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
14773       SDValue Cmp = Cond.getOperand(0).getOperand(1);
14774       if (CondOpc == ISD::OR) {
14775         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
14776         // two branches instead of an explicit OR instruction with a
14777         // separate test.
14778         if (Cmp == Cond.getOperand(1).getOperand(1) &&
14779             isX86LogicalCmp(Cmp)) {
14780           CC = Cond.getOperand(0).getOperand(0);
14781           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14782                               Chain, Dest, CC, Cmp);
14783           CC = Cond.getOperand(1).getOperand(0);
14784           Cond = Cmp;
14785           addTest = false;
14786         }
14787       } else { // ISD::AND
14788         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
14789         // two branches instead of an explicit AND instruction with a
14790         // separate test. However, we only do this if this block doesn't
14791         // have a fall-through edge, because this requires an explicit
14792         // jmp when the condition is false.
14793         if (Cmp == Cond.getOperand(1).getOperand(1) &&
14794             isX86LogicalCmp(Cmp) &&
14795             Op.getNode()->hasOneUse()) {
14796           X86::CondCode CCode =
14797             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
14798           CCode = X86::GetOppositeBranchCondition(CCode);
14799           CC = DAG.getConstant(CCode, dl, MVT::i8);
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             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14813                                 Chain, Dest, CC, Cmp);
14814             X86::CondCode CCode =
14815               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
14816             CCode = X86::GetOppositeBranchCondition(CCode);
14817             CC = DAG.getConstant(CCode, dl, MVT::i8);
14818             Cond = Cmp;
14819             addTest = false;
14820           }
14821         }
14822       }
14823     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
14824       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
14825       // It should be transformed during dag combiner except when the condition
14826       // is set by a arithmetics with overflow node.
14827       X86::CondCode CCode =
14828         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
14829       CCode = X86::GetOppositeBranchCondition(CCode);
14830       CC = DAG.getConstant(CCode, dl, MVT::i8);
14831       Cond = Cond.getOperand(0).getOperand(1);
14832       addTest = false;
14833     } else if (Cond.getOpcode() == ISD::SETCC &&
14834                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
14835       // For FCMP_OEQ, we can emit
14836       // two branches instead of an explicit AND instruction with a
14837       // separate test. However, we only do this if this block doesn't
14838       // have a fall-through edge, because this requires an explicit
14839       // jmp when the condition is false.
14840       if (Op.getNode()->hasOneUse()) {
14841         SDNode *User = *Op.getNode()->use_begin();
14842         // Look for an unconditional branch following this conditional branch.
14843         // We need this because we need to reverse the successors in order
14844         // to implement FCMP_OEQ.
14845         if (User->getOpcode() == ISD::BR) {
14846           SDValue FalseBB = User->getOperand(1);
14847           SDNode *NewBR =
14848             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14849           assert(NewBR == User);
14850           (void)NewBR;
14851           Dest = FalseBB;
14852
14853           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
14854                                     Cond.getOperand(0), Cond.getOperand(1));
14855           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14856           CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
14857           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14858                               Chain, Dest, CC, Cmp);
14859           CC = DAG.getConstant(X86::COND_P, dl, MVT::i8);
14860           Cond = Cmp;
14861           addTest = false;
14862         }
14863       }
14864     } else if (Cond.getOpcode() == ISD::SETCC &&
14865                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
14866       // For FCMP_UNE, we can emit
14867       // two branches instead of an explicit AND instruction with a
14868       // separate test. However, we only do this if this block doesn't
14869       // have a fall-through edge, because this requires an explicit
14870       // jmp when the condition is false.
14871       if (Op.getNode()->hasOneUse()) {
14872         SDNode *User = *Op.getNode()->use_begin();
14873         // Look for an unconditional branch following this conditional branch.
14874         // We need this because we need to reverse the successors in order
14875         // to implement FCMP_UNE.
14876         if (User->getOpcode() == ISD::BR) {
14877           SDValue FalseBB = User->getOperand(1);
14878           SDNode *NewBR =
14879             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14880           assert(NewBR == User);
14881           (void)NewBR;
14882
14883           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
14884                                     Cond.getOperand(0), Cond.getOperand(1));
14885           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14886           CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
14887           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14888                               Chain, Dest, CC, Cmp);
14889           CC = DAG.getConstant(X86::COND_NP, dl, MVT::i8);
14890           Cond = Cmp;
14891           addTest = false;
14892           Dest = FalseBB;
14893         }
14894       }
14895     }
14896   }
14897
14898   if (addTest) {
14899     // Look pass the truncate if the high bits are known zero.
14900     if (isTruncWithZeroHighBitsInput(Cond, DAG))
14901         Cond = Cond.getOperand(0);
14902
14903     // We know the result of AND is compared against zero. Try to match
14904     // it to BT.
14905     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
14906       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
14907       if (NewSetCC.getNode()) {
14908         CC = NewSetCC.getOperand(0);
14909         Cond = NewSetCC.getOperand(1);
14910         addTest = false;
14911       }
14912     }
14913   }
14914
14915   if (addTest) {
14916     X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
14917     CC = DAG.getConstant(X86Cond, dl, MVT::i8);
14918     Cond = EmitTest(Cond, X86Cond, dl, DAG);
14919   }
14920   Cond = ConvertCmpIfNecessary(Cond, DAG);
14921   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14922                      Chain, Dest, CC, Cond);
14923 }
14924
14925 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
14926 // Calls to _alloca are needed to probe the stack when allocating more than 4k
14927 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
14928 // that the guard pages used by the OS virtual memory manager are allocated in
14929 // correct sequence.
14930 SDValue
14931 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
14932                                            SelectionDAG &DAG) const {
14933   MachineFunction &MF = DAG.getMachineFunction();
14934   bool SplitStack = MF.shouldSplitStack();
14935   bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMachO()) ||
14936                SplitStack;
14937   SDLoc dl(Op);
14938
14939   if (!Lower) {
14940     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14941     SDNode* Node = Op.getNode();
14942
14943     unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
14944     assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
14945         " not tell us which reg is the stack pointer!");
14946     EVT VT = Node->getValueType(0);
14947     SDValue Tmp1 = SDValue(Node, 0);
14948     SDValue Tmp2 = SDValue(Node, 1);
14949     SDValue Tmp3 = Node->getOperand(2);
14950     SDValue Chain = Tmp1.getOperand(0);
14951
14952     // Chain the dynamic stack allocation so that it doesn't modify the stack
14953     // pointer when other instructions are using the stack.
14954     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, dl, true),
14955         SDLoc(Node));
14956
14957     SDValue Size = Tmp2.getOperand(1);
14958     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
14959     Chain = SP.getValue(1);
14960     unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
14961     const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
14962     unsigned StackAlign = TFI.getStackAlignment();
14963     Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
14964     if (Align > StackAlign)
14965       Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
14966           DAG.getConstant(-(uint64_t)Align, dl, VT));
14967     Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
14968
14969     Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, dl, true),
14970         DAG.getIntPtrConstant(0, dl, true), SDValue(),
14971         SDLoc(Node));
14972
14973     SDValue Ops[2] = { Tmp1, Tmp2 };
14974     return DAG.getMergeValues(Ops, dl);
14975   }
14976
14977   // Get the inputs.
14978   SDValue Chain = Op.getOperand(0);
14979   SDValue Size  = Op.getOperand(1);
14980   unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
14981   EVT VT = Op.getNode()->getValueType(0);
14982
14983   bool Is64Bit = Subtarget->is64Bit();
14984   MVT SPTy = getPointerTy(DAG.getDataLayout());
14985
14986   if (SplitStack) {
14987     MachineRegisterInfo &MRI = MF.getRegInfo();
14988
14989     if (Is64Bit) {
14990       // The 64 bit implementation of segmented stacks needs to clobber both r10
14991       // r11. This makes it impossible to use it along with nested parameters.
14992       const Function *F = MF.getFunction();
14993
14994       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
14995            I != E; ++I)
14996         if (I->hasNestAttr())
14997           report_fatal_error("Cannot use segmented stacks with functions that "
14998                              "have nested arguments.");
14999     }
15000
15001     const TargetRegisterClass *AddrRegClass = getRegClassFor(SPTy);
15002     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
15003     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
15004     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
15005                                 DAG.getRegister(Vreg, SPTy));
15006     SDValue Ops1[2] = { Value, Chain };
15007     return DAG.getMergeValues(Ops1, dl);
15008   } else {
15009     SDValue Flag;
15010     const unsigned Reg = (Subtarget->isTarget64BitLP64() ? X86::RAX : X86::EAX);
15011
15012     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
15013     Flag = Chain.getValue(1);
15014     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
15015
15016     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
15017
15018     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15019     unsigned SPReg = RegInfo->getStackRegister();
15020     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
15021     Chain = SP.getValue(1);
15022
15023     if (Align) {
15024       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
15025                        DAG.getConstant(-(uint64_t)Align, dl, VT));
15026       Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
15027     }
15028
15029     SDValue Ops1[2] = { SP, Chain };
15030     return DAG.getMergeValues(Ops1, dl);
15031   }
15032 }
15033
15034 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
15035   MachineFunction &MF = DAG.getMachineFunction();
15036   auto PtrVT = getPointerTy(MF.getDataLayout());
15037   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
15038
15039   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
15040   SDLoc DL(Op);
15041
15042   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
15043     // vastart just stores the address of the VarArgsFrameIndex slot into the
15044     // memory location argument.
15045     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
15046     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
15047                         MachinePointerInfo(SV), false, false, 0);
15048   }
15049
15050   // __va_list_tag:
15051   //   gp_offset         (0 - 6 * 8)
15052   //   fp_offset         (48 - 48 + 8 * 16)
15053   //   overflow_arg_area (point to parameters coming in memory).
15054   //   reg_save_area
15055   SmallVector<SDValue, 8> MemOps;
15056   SDValue FIN = Op.getOperand(1);
15057   // Store gp_offset
15058   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
15059                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
15060                                                DL, MVT::i32),
15061                                FIN, MachinePointerInfo(SV), false, false, 0);
15062   MemOps.push_back(Store);
15063
15064   // Store fp_offset
15065   FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(4, DL));
15066   Store = DAG.getStore(Op.getOperand(0), DL,
15067                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(), DL,
15068                                        MVT::i32),
15069                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
15070   MemOps.push_back(Store);
15071
15072   // Store ptr to overflow_arg_area
15073   FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(4, DL));
15074   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
15075   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
15076                        MachinePointerInfo(SV, 8),
15077                        false, false, 0);
15078   MemOps.push_back(Store);
15079
15080   // Store ptr to reg_save_area.
15081   FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(8, DL));
15082   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(), PtrVT);
15083   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
15084                        MachinePointerInfo(SV, 16), false, false, 0);
15085   MemOps.push_back(Store);
15086   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
15087 }
15088
15089 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
15090   assert(Subtarget->is64Bit() &&
15091          "LowerVAARG only handles 64-bit va_arg!");
15092   assert((Subtarget->isTargetLinux() ||
15093           Subtarget->isTargetDarwin()) &&
15094           "Unhandled target in LowerVAARG");
15095   assert(Op.getNode()->getNumOperands() == 4);
15096   SDValue Chain = Op.getOperand(0);
15097   SDValue SrcPtr = Op.getOperand(1);
15098   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
15099   unsigned Align = Op.getConstantOperandVal(3);
15100   SDLoc dl(Op);
15101
15102   EVT ArgVT = Op.getNode()->getValueType(0);
15103   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
15104   uint32_t ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy);
15105   uint8_t ArgMode;
15106
15107   // Decide which area this value should be read from.
15108   // TODO: Implement the AMD64 ABI in its entirety. This simple
15109   // selection mechanism works only for the basic types.
15110   if (ArgVT == MVT::f80) {
15111     llvm_unreachable("va_arg for f80 not yet implemented");
15112   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
15113     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
15114   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
15115     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
15116   } else {
15117     llvm_unreachable("Unhandled argument type in LowerVAARG");
15118   }
15119
15120   if (ArgMode == 2) {
15121     // Sanity Check: Make sure using fp_offset makes sense.
15122     assert(!Subtarget->useSoftFloat() &&
15123            !(DAG.getMachineFunction().getFunction()->hasFnAttribute(
15124                Attribute::NoImplicitFloat)) &&
15125            Subtarget->hasSSE1());
15126   }
15127
15128   // Insert VAARG_64 node into the DAG
15129   // VAARG_64 returns two values: Variable Argument Address, Chain
15130   SDValue InstOps[] = {Chain, SrcPtr, DAG.getConstant(ArgSize, dl, MVT::i32),
15131                        DAG.getConstant(ArgMode, dl, MVT::i8),
15132                        DAG.getConstant(Align, dl, MVT::i32)};
15133   SDVTList VTs = DAG.getVTList(getPointerTy(DAG.getDataLayout()), MVT::Other);
15134   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
15135                                           VTs, InstOps, MVT::i64,
15136                                           MachinePointerInfo(SV),
15137                                           /*Align=*/0,
15138                                           /*Volatile=*/false,
15139                                           /*ReadMem=*/true,
15140                                           /*WriteMem=*/true);
15141   Chain = VAARG.getValue(1);
15142
15143   // Load the next argument and return it
15144   return DAG.getLoad(ArgVT, dl,
15145                      Chain,
15146                      VAARG,
15147                      MachinePointerInfo(),
15148                      false, false, false, 0);
15149 }
15150
15151 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
15152                            SelectionDAG &DAG) {
15153   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
15154   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
15155   SDValue Chain = Op.getOperand(0);
15156   SDValue DstPtr = Op.getOperand(1);
15157   SDValue SrcPtr = Op.getOperand(2);
15158   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
15159   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
15160   SDLoc DL(Op);
15161
15162   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
15163                        DAG.getIntPtrConstant(24, DL), 8, /*isVolatile*/false,
15164                        false, false,
15165                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
15166 }
15167
15168 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
15169 // amount is a constant. Takes immediate version of shift as input.
15170 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
15171                                           SDValue SrcOp, uint64_t ShiftAmt,
15172                                           SelectionDAG &DAG) {
15173   MVT ElementType = VT.getVectorElementType();
15174
15175   // Fold this packed shift into its first operand if ShiftAmt is 0.
15176   if (ShiftAmt == 0)
15177     return SrcOp;
15178
15179   // Check for ShiftAmt >= element width
15180   if (ShiftAmt >= ElementType.getSizeInBits()) {
15181     if (Opc == X86ISD::VSRAI)
15182       ShiftAmt = ElementType.getSizeInBits() - 1;
15183     else
15184       return DAG.getConstant(0, dl, VT);
15185   }
15186
15187   assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
15188          && "Unknown target vector shift-by-constant node");
15189
15190   // Fold this packed vector shift into a build vector if SrcOp is a
15191   // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
15192   if (VT == SrcOp.getSimpleValueType() &&
15193       ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
15194     SmallVector<SDValue, 8> Elts;
15195     unsigned NumElts = SrcOp->getNumOperands();
15196     ConstantSDNode *ND;
15197
15198     switch(Opc) {
15199     default: llvm_unreachable(nullptr);
15200     case X86ISD::VSHLI:
15201       for (unsigned i=0; i!=NumElts; ++i) {
15202         SDValue CurrentOp = SrcOp->getOperand(i);
15203         if (CurrentOp->getOpcode() == ISD::UNDEF) {
15204           Elts.push_back(CurrentOp);
15205           continue;
15206         }
15207         ND = cast<ConstantSDNode>(CurrentOp);
15208         const APInt &C = ND->getAPIntValue();
15209         Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), dl, ElementType));
15210       }
15211       break;
15212     case X86ISD::VSRLI:
15213       for (unsigned i=0; i!=NumElts; ++i) {
15214         SDValue CurrentOp = SrcOp->getOperand(i);
15215         if (CurrentOp->getOpcode() == ISD::UNDEF) {
15216           Elts.push_back(CurrentOp);
15217           continue;
15218         }
15219         ND = cast<ConstantSDNode>(CurrentOp);
15220         const APInt &C = ND->getAPIntValue();
15221         Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), dl, ElementType));
15222       }
15223       break;
15224     case X86ISD::VSRAI:
15225       for (unsigned i=0; i!=NumElts; ++i) {
15226         SDValue CurrentOp = SrcOp->getOperand(i);
15227         if (CurrentOp->getOpcode() == ISD::UNDEF) {
15228           Elts.push_back(CurrentOp);
15229           continue;
15230         }
15231         ND = cast<ConstantSDNode>(CurrentOp);
15232         const APInt &C = ND->getAPIntValue();
15233         Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), dl, ElementType));
15234       }
15235       break;
15236     }
15237
15238     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
15239   }
15240
15241   return DAG.getNode(Opc, dl, VT, SrcOp,
15242                      DAG.getConstant(ShiftAmt, dl, MVT::i8));
15243 }
15244
15245 // getTargetVShiftNode - Handle vector element shifts where the shift amount
15246 // may or may not be a constant. Takes immediate version of shift as input.
15247 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
15248                                    SDValue SrcOp, SDValue ShAmt,
15249                                    SelectionDAG &DAG) {
15250   MVT SVT = ShAmt.getSimpleValueType();
15251   assert((SVT == MVT::i32 || SVT == MVT::i64) && "Unexpected value type!");
15252
15253   // Catch shift-by-constant.
15254   if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
15255     return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
15256                                       CShAmt->getZExtValue(), DAG);
15257
15258   // Change opcode to non-immediate version
15259   switch (Opc) {
15260     default: llvm_unreachable("Unknown target vector shift node");
15261     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
15262     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
15263     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
15264   }
15265
15266   const X86Subtarget &Subtarget =
15267       static_cast<const X86Subtarget &>(DAG.getSubtarget());
15268   if (Subtarget.hasSSE41() && ShAmt.getOpcode() == ISD::ZERO_EXTEND &&
15269       ShAmt.getOperand(0).getSimpleValueType() == MVT::i16) {
15270     // Let the shuffle legalizer expand this shift amount node.
15271     SDValue Op0 = ShAmt.getOperand(0);
15272     Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(Op0), MVT::v8i16, Op0);
15273     ShAmt = getShuffleVectorZeroOrUndef(Op0, 0, true, &Subtarget, DAG);
15274   } else {
15275     // Need to build a vector containing shift amount.
15276     // SSE/AVX packed shifts only use the lower 64-bit of the shift count.
15277     SmallVector<SDValue, 4> ShOps;
15278     ShOps.push_back(ShAmt);
15279     if (SVT == MVT::i32) {
15280       ShOps.push_back(DAG.getConstant(0, dl, SVT));
15281       ShOps.push_back(DAG.getUNDEF(SVT));
15282     }
15283     ShOps.push_back(DAG.getUNDEF(SVT));
15284
15285     MVT BVT = SVT == MVT::i32 ? MVT::v4i32 : MVT::v2i64;
15286     ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, BVT, ShOps);
15287   }
15288
15289   // The return type has to be a 128-bit type with the same element
15290   // type as the input type.
15291   MVT EltVT = VT.getVectorElementType();
15292   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
15293
15294   ShAmt = DAG.getBitcast(ShVT, ShAmt);
15295   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
15296 }
15297
15298 /// \brief Return (and \p Op, \p Mask) for compare instructions or
15299 /// (vselect \p Mask, \p Op, \p PreservedSrc) for others along with the
15300 /// necessary casting or extending for \p Mask when lowering masking intrinsics
15301 static SDValue getVectorMaskingNode(SDValue Op, SDValue Mask,
15302                                     SDValue PreservedSrc,
15303                                     const X86Subtarget *Subtarget,
15304                                     SelectionDAG &DAG) {
15305     EVT VT = Op.getValueType();
15306     EVT MaskVT = EVT::getVectorVT(*DAG.getContext(),
15307                                   MVT::i1, VT.getVectorNumElements());
15308     SDValue VMask = SDValue();
15309     unsigned OpcodeSelect = ISD::VSELECT;
15310     SDLoc dl(Op);
15311
15312     assert(MaskVT.isSimple() && "invalid mask type");
15313
15314     if (isAllOnes(Mask))
15315       return Op;
15316
15317     if (MaskVT.bitsGT(Mask.getValueType())) {
15318       EVT newMaskVT =  EVT::getIntegerVT(*DAG.getContext(),
15319                                          MaskVT.getSizeInBits());
15320       VMask = DAG.getBitcast(MaskVT,
15321                              DAG.getNode(ISD::ANY_EXTEND, dl, newMaskVT, Mask));
15322     } else {
15323       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15324                                        Mask.getValueType().getSizeInBits());
15325       // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
15326       // are extracted by EXTRACT_SUBVECTOR.
15327       VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15328                           DAG.getBitcast(BitcastVT, Mask),
15329                           DAG.getIntPtrConstant(0, dl));
15330     }
15331
15332     switch (Op.getOpcode()) {
15333       default: break;
15334       case X86ISD::PCMPEQM:
15335       case X86ISD::PCMPGTM:
15336       case X86ISD::CMPM:
15337       case X86ISD::CMPMU:
15338         return DAG.getNode(ISD::AND, dl, VT, Op, VMask);
15339       case X86ISD::VTRUNC:
15340       case X86ISD::VTRUNCS:
15341       case X86ISD::VTRUNCUS:
15342         // We can't use ISD::VSELECT here because it is not always "Legal"
15343         // for the destination type. For example vpmovqb require only AVX512
15344         // and vselect that can operate on byte element type require BWI
15345         OpcodeSelect = X86ISD::SELECT;
15346         break;
15347     }
15348     if (PreservedSrc.getOpcode() == ISD::UNDEF)
15349       PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
15350     return DAG.getNode(OpcodeSelect, dl, VT, VMask, Op, PreservedSrc);
15351 }
15352
15353 /// \brief Creates an SDNode for a predicated scalar operation.
15354 /// \returns (X86vselect \p Mask, \p Op, \p PreservedSrc).
15355 /// The mask is coming as MVT::i8 and it should be truncated
15356 /// to MVT::i1 while lowering masking intrinsics.
15357 /// The main difference between ScalarMaskingNode and VectorMaskingNode is using
15358 /// "X86select" instead of "vselect". We just can't create the "vselect" node
15359 /// for a scalar instruction.
15360 static SDValue getScalarMaskingNode(SDValue Op, SDValue Mask,
15361                                     SDValue PreservedSrc,
15362                                     const X86Subtarget *Subtarget,
15363                                     SelectionDAG &DAG) {
15364     if (isAllOnes(Mask))
15365       return Op;
15366
15367     EVT VT = Op.getValueType();
15368     SDLoc dl(Op);
15369     // The mask should be of type MVT::i1
15370     SDValue IMask = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Mask);
15371
15372     if (PreservedSrc.getOpcode() == ISD::UNDEF)
15373       PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
15374     return DAG.getNode(X86ISD::SELECT, dl, VT, IMask, Op, PreservedSrc);
15375 }
15376
15377 static int getSEHRegistrationNodeSize(const Function *Fn) {
15378   if (!Fn->hasPersonalityFn())
15379     report_fatal_error(
15380         "querying registration node size for function without personality");
15381   // The RegNodeSize is 6 32-bit words for SEH and 4 for C++ EH. See
15382   // WinEHStatePass for the full struct definition.
15383   switch (classifyEHPersonality(Fn->getPersonalityFn())) {
15384   case EHPersonality::MSVC_X86SEH: return 24;
15385   case EHPersonality::MSVC_CXX: return 16;
15386   default: break;
15387   }
15388   report_fatal_error("can only recover FP for MSVC EH personality functions");
15389 }
15390
15391 /// When the 32-bit MSVC runtime transfers control to us, either to an outlined
15392 /// function or when returning to a parent frame after catching an exception, we
15393 /// recover the parent frame pointer by doing arithmetic on the incoming EBP.
15394 /// Here's the math:
15395 ///   RegNodeBase = EntryEBP - RegNodeSize
15396 ///   ParentFP = RegNodeBase - RegNodeFrameOffset
15397 /// Subtracting RegNodeSize takes us to the offset of the registration node, and
15398 /// subtracting the offset (negative on x86) takes us back to the parent FP.
15399 static SDValue recoverFramePointer(SelectionDAG &DAG, const Function *Fn,
15400                                    SDValue EntryEBP) {
15401   MachineFunction &MF = DAG.getMachineFunction();
15402   SDLoc dl;
15403
15404   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15405   MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
15406
15407   // It's possible that the parent function no longer has a personality function
15408   // if the exceptional code was optimized away, in which case we just return
15409   // the incoming EBP.
15410   if (!Fn->hasPersonalityFn())
15411     return EntryEBP;
15412
15413   int RegNodeSize = getSEHRegistrationNodeSize(Fn);
15414
15415   // Get an MCSymbol that will ultimately resolve to the frame offset of the EH
15416   // registration.
15417   MCSymbol *OffsetSym =
15418       MF.getMMI().getContext().getOrCreateParentFrameOffsetSymbol(
15419           GlobalValue::getRealLinkageName(Fn->getName()));
15420   SDValue OffsetSymVal = DAG.getMCSymbol(OffsetSym, PtrVT);
15421   SDValue RegNodeFrameOffset =
15422       DAG.getNode(ISD::LOCAL_RECOVER, dl, PtrVT, OffsetSymVal);
15423
15424   // RegNodeBase = EntryEBP - RegNodeSize
15425   // ParentFP = RegNodeBase - RegNodeFrameOffset
15426   SDValue RegNodeBase = DAG.getNode(ISD::SUB, dl, PtrVT, EntryEBP,
15427                                     DAG.getConstant(RegNodeSize, dl, PtrVT));
15428   return DAG.getNode(ISD::SUB, dl, PtrVT, RegNodeBase, RegNodeFrameOffset);
15429 }
15430
15431 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
15432                                        SelectionDAG &DAG) {
15433   SDLoc dl(Op);
15434   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15435   EVT VT = Op.getValueType();
15436   const IntrinsicData* IntrData = getIntrinsicWithoutChain(IntNo);
15437   if (IntrData) {
15438     switch(IntrData->Type) {
15439     case INTR_TYPE_1OP:
15440       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1));
15441     case INTR_TYPE_2OP:
15442       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
15443         Op.getOperand(2));
15444     case INTR_TYPE_3OP:
15445       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
15446         Op.getOperand(2), Op.getOperand(3));
15447     case INTR_TYPE_4OP:
15448       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
15449         Op.getOperand(2), Op.getOperand(3), Op.getOperand(4));
15450     case INTR_TYPE_1OP_MASK_RM: {
15451       SDValue Src = Op.getOperand(1);
15452       SDValue PassThru = Op.getOperand(2);
15453       SDValue Mask = Op.getOperand(3);
15454       SDValue RoundingMode;
15455       // We allways add rounding mode to the Node.
15456       // If the rounding mode is not specified, we add the
15457       // "current direction" mode.
15458       if (Op.getNumOperands() == 4)
15459         RoundingMode =
15460           DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
15461       else
15462         RoundingMode = Op.getOperand(4);
15463       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15464       if (IntrWithRoundingModeOpcode != 0)
15465         if (cast<ConstantSDNode>(RoundingMode)->getZExtValue() !=
15466             X86::STATIC_ROUNDING::CUR_DIRECTION)
15467           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15468                                       dl, Op.getValueType(), Src, RoundingMode),
15469                                       Mask, PassThru, Subtarget, DAG);
15470       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src,
15471                                               RoundingMode),
15472                                   Mask, PassThru, Subtarget, DAG);
15473     }
15474     case INTR_TYPE_1OP_MASK: {
15475       SDValue Src = Op.getOperand(1);
15476       SDValue PassThru = Op.getOperand(2);
15477       SDValue Mask = Op.getOperand(3);
15478       // We add rounding mode to the Node when
15479       //   - RM Opcode is specified and
15480       //   - RM is not "current direction".
15481       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15482       if (IntrWithRoundingModeOpcode != 0) {
15483         SDValue Rnd = Op.getOperand(4);
15484         unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
15485         if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
15486           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15487                                       dl, Op.getValueType(),
15488                                       Src, Rnd),
15489                                       Mask, PassThru, Subtarget, DAG);
15490         }
15491       }
15492       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src),
15493                                   Mask, PassThru, Subtarget, DAG);
15494     }
15495     case INTR_TYPE_SCALAR_MASK_RM: {
15496       SDValue Src1 = Op.getOperand(1);
15497       SDValue Src2 = Op.getOperand(2);
15498       SDValue Src0 = Op.getOperand(3);
15499       SDValue Mask = Op.getOperand(4);
15500       // There are 2 kinds of intrinsics in this group:
15501       // (1) With suppress-all-exceptions (sae) or rounding mode- 6 operands
15502       // (2) With rounding mode and sae - 7 operands.
15503       if (Op.getNumOperands() == 6) {
15504         SDValue Sae  = Op.getOperand(5);
15505         unsigned Opc = IntrData->Opc1 ? IntrData->Opc1 : IntrData->Opc0;
15506         return getScalarMaskingNode(DAG.getNode(Opc, dl, VT, Src1, Src2,
15507                                                 Sae),
15508                                     Mask, Src0, Subtarget, DAG);
15509       }
15510       assert(Op.getNumOperands() == 7 && "Unexpected intrinsic form");
15511       SDValue RoundingMode  = Op.getOperand(5);
15512       SDValue Sae  = Op.getOperand(6);
15513       return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2,
15514                                               RoundingMode, Sae),
15515                                   Mask, Src0, Subtarget, DAG);
15516     }
15517     case INTR_TYPE_2OP_MASK: {
15518       SDValue Src1 = Op.getOperand(1);
15519       SDValue Src2 = Op.getOperand(2);
15520       SDValue PassThru = Op.getOperand(3);
15521       SDValue Mask = Op.getOperand(4);
15522       // We specify 2 possible opcodes for intrinsics with rounding modes.
15523       // First, we check if the intrinsic may have non-default rounding mode,
15524       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15525       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15526       if (IntrWithRoundingModeOpcode != 0) {
15527         SDValue Rnd = Op.getOperand(5);
15528         unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
15529         if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
15530           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15531                                       dl, Op.getValueType(),
15532                                       Src1, Src2, Rnd),
15533                                       Mask, PassThru, Subtarget, DAG);
15534         }
15535       }
15536       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15537                                               Src1,Src2),
15538                                   Mask, PassThru, Subtarget, DAG);
15539     }
15540     case INTR_TYPE_2OP_MASK_RM: {
15541       SDValue Src1 = Op.getOperand(1);
15542       SDValue Src2 = Op.getOperand(2);
15543       SDValue PassThru = Op.getOperand(3);
15544       SDValue Mask = Op.getOperand(4);
15545       // We specify 2 possible modes for intrinsics, with/without rounding modes.
15546       // First, we check if the intrinsic have rounding mode (6 operands),
15547       // if not, we set rounding mode to "current".
15548       SDValue Rnd;
15549       if (Op.getNumOperands() == 6)
15550         Rnd = Op.getOperand(5);
15551       else
15552         Rnd = DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
15553       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15554                                               Src1, Src2, Rnd),
15555                                   Mask, PassThru, Subtarget, DAG);
15556     }
15557     case INTR_TYPE_3OP_MASK_RM: {
15558       SDValue Src1 = Op.getOperand(1);
15559       SDValue Src2 = Op.getOperand(2);
15560       SDValue Imm = Op.getOperand(3);
15561       SDValue PassThru = Op.getOperand(4);
15562       SDValue Mask = Op.getOperand(5);
15563       // We specify 2 possible modes for intrinsics, with/without rounding modes.
15564       // First, we check if the intrinsic have rounding mode (7 operands),
15565       // if not, we set rounding mode to "current".
15566       SDValue Rnd;
15567       if (Op.getNumOperands() == 7)
15568         Rnd = Op.getOperand(6);
15569       else
15570         Rnd = DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
15571       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15572         Src1, Src2, Imm, Rnd),
15573         Mask, PassThru, Subtarget, DAG);
15574     }
15575     case INTR_TYPE_3OP_MASK: {
15576       SDValue Src1 = Op.getOperand(1);
15577       SDValue Src2 = Op.getOperand(2);
15578       SDValue Src3 = Op.getOperand(3);
15579       SDValue PassThru = Op.getOperand(4);
15580       SDValue Mask = Op.getOperand(5);
15581       // We specify 2 possible opcodes for intrinsics with rounding modes.
15582       // First, we check if the intrinsic may have non-default rounding mode,
15583       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15584       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15585       if (IntrWithRoundingModeOpcode != 0) {
15586         SDValue Rnd = Op.getOperand(6);
15587         unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
15588         if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
15589           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15590                                       dl, Op.getValueType(),
15591                                       Src1, Src2, Src3, Rnd),
15592                                       Mask, PassThru, Subtarget, DAG);
15593         }
15594       }
15595       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15596                                               Src1, Src2, Src3),
15597                                   Mask, PassThru, Subtarget, DAG);
15598     }
15599     case VPERM_3OP_MASKZ:
15600     case VPERM_3OP_MASK:
15601     case FMA_OP_MASK3:
15602     case FMA_OP_MASKZ:
15603     case FMA_OP_MASK: {
15604       SDValue Src1 = Op.getOperand(1);
15605       SDValue Src2 = Op.getOperand(2);
15606       SDValue Src3 = Op.getOperand(3);
15607       SDValue Mask = Op.getOperand(4);
15608       EVT VT = Op.getValueType();
15609       SDValue PassThru = SDValue();
15610
15611       // set PassThru element
15612       if (IntrData->Type == VPERM_3OP_MASKZ || IntrData->Type == FMA_OP_MASKZ)
15613         PassThru = getZeroVector(VT, Subtarget, DAG, dl);
15614       else if (IntrData->Type == FMA_OP_MASK3)
15615         PassThru = Src3;
15616       else
15617         PassThru = Src1;
15618
15619       // We specify 2 possible opcodes for intrinsics with rounding modes.
15620       // First, we check if the intrinsic may have non-default rounding mode,
15621       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15622       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15623       if (IntrWithRoundingModeOpcode != 0) {
15624         SDValue Rnd = Op.getOperand(5);
15625         if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
15626             X86::STATIC_ROUNDING::CUR_DIRECTION)
15627           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15628                                                   dl, Op.getValueType(),
15629                                                   Src1, Src2, Src3, Rnd),
15630                                       Mask, PassThru, Subtarget, DAG);
15631       }
15632       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0,
15633                                               dl, Op.getValueType(),
15634                                               Src1, Src2, Src3),
15635                                   Mask, PassThru, Subtarget, DAG);
15636     }
15637     case CMP_MASK:
15638     case CMP_MASK_CC: {
15639       // Comparison intrinsics with masks.
15640       // Example of transformation:
15641       // (i8 (int_x86_avx512_mask_pcmpeq_q_128
15642       //             (v2i64 %a), (v2i64 %b), (i8 %mask))) ->
15643       // (i8 (bitcast
15644       //   (v8i1 (insert_subvector undef,
15645       //           (v2i1 (and (PCMPEQM %a, %b),
15646       //                      (extract_subvector
15647       //                         (v8i1 (bitcast %mask)), 0))), 0))))
15648       EVT VT = Op.getOperand(1).getValueType();
15649       EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15650                                     VT.getVectorNumElements());
15651       SDValue Mask = Op.getOperand((IntrData->Type == CMP_MASK_CC) ? 4 : 3);
15652       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15653                                        Mask.getValueType().getSizeInBits());
15654       SDValue Cmp;
15655       if (IntrData->Type == CMP_MASK_CC) {
15656         SDValue CC = Op.getOperand(3);
15657         CC = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, CC);
15658         // We specify 2 possible opcodes for intrinsics with rounding modes.
15659         // First, we check if the intrinsic may have non-default rounding mode,
15660         // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15661         if (IntrData->Opc1 != 0) {
15662           SDValue Rnd = Op.getOperand(5);
15663           if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
15664               X86::STATIC_ROUNDING::CUR_DIRECTION)
15665             Cmp = DAG.getNode(IntrData->Opc1, dl, MaskVT, Op.getOperand(1),
15666                               Op.getOperand(2), CC, Rnd);
15667         }
15668         //default rounding mode
15669         if(!Cmp.getNode())
15670             Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
15671                               Op.getOperand(2), CC);
15672
15673       } else {
15674         assert(IntrData->Type == CMP_MASK && "Unexpected intrinsic type!");
15675         Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
15676                           Op.getOperand(2));
15677       }
15678       SDValue CmpMask = getVectorMaskingNode(Cmp, Mask,
15679                                              DAG.getTargetConstant(0, dl,
15680                                                                    MaskVT),
15681                                              Subtarget, DAG);
15682       SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, BitcastVT,
15683                                 DAG.getUNDEF(BitcastVT), CmpMask,
15684                                 DAG.getIntPtrConstant(0, dl));
15685       return DAG.getBitcast(Op.getValueType(), Res);
15686     }
15687     case COMI: { // Comparison intrinsics
15688       ISD::CondCode CC = (ISD::CondCode)IntrData->Opc1;
15689       SDValue LHS = Op.getOperand(1);
15690       SDValue RHS = Op.getOperand(2);
15691       unsigned X86CC = TranslateX86CC(CC, dl, true, LHS, RHS, DAG);
15692       assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
15693       SDValue Cond = DAG.getNode(IntrData->Opc0, dl, MVT::i32, LHS, RHS);
15694       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15695                                   DAG.getConstant(X86CC, dl, MVT::i8), Cond);
15696       return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15697     }
15698     case VSHIFT:
15699       return getTargetVShiftNode(IntrData->Opc0, dl, Op.getSimpleValueType(),
15700                                  Op.getOperand(1), Op.getOperand(2), DAG);
15701     case VSHIFT_MASK:
15702       return getVectorMaskingNode(getTargetVShiftNode(IntrData->Opc0, dl,
15703                                                       Op.getSimpleValueType(),
15704                                                       Op.getOperand(1),
15705                                                       Op.getOperand(2), DAG),
15706                                   Op.getOperand(4), Op.getOperand(3), Subtarget,
15707                                   DAG);
15708     case COMPRESS_EXPAND_IN_REG: {
15709       SDValue Mask = Op.getOperand(3);
15710       SDValue DataToCompress = Op.getOperand(1);
15711       SDValue PassThru = Op.getOperand(2);
15712       if (isAllOnes(Mask)) // return data as is
15713         return Op.getOperand(1);
15714
15715       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15716                                               DataToCompress),
15717                                   Mask, PassThru, Subtarget, DAG);
15718     }
15719     case BLEND: {
15720       SDValue Mask = Op.getOperand(3);
15721       EVT VT = Op.getValueType();
15722       EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15723                                     VT.getVectorNumElements());
15724       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15725                                        Mask.getValueType().getSizeInBits());
15726       SDLoc dl(Op);
15727       SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15728                                   DAG.getBitcast(BitcastVT, Mask),
15729                                   DAG.getIntPtrConstant(0, dl));
15730       return DAG.getNode(IntrData->Opc0, dl, VT, VMask, Op.getOperand(1),
15731                          Op.getOperand(2));
15732     }
15733     default:
15734       break;
15735     }
15736   }
15737
15738   switch (IntNo) {
15739   default: return SDValue();    // Don't custom lower most intrinsics.
15740
15741   case Intrinsic::x86_avx2_permd:
15742   case Intrinsic::x86_avx2_permps:
15743     // Operands intentionally swapped. Mask is last operand to intrinsic,
15744     // but second operand for node/instruction.
15745     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
15746                        Op.getOperand(2), Op.getOperand(1));
15747
15748   // ptest and testp intrinsics. The intrinsic these come from are designed to
15749   // return an integer value, not just an instruction so lower it to the ptest
15750   // or testp pattern and a setcc for the result.
15751   case Intrinsic::x86_sse41_ptestz:
15752   case Intrinsic::x86_sse41_ptestc:
15753   case Intrinsic::x86_sse41_ptestnzc:
15754   case Intrinsic::x86_avx_ptestz_256:
15755   case Intrinsic::x86_avx_ptestc_256:
15756   case Intrinsic::x86_avx_ptestnzc_256:
15757   case Intrinsic::x86_avx_vtestz_ps:
15758   case Intrinsic::x86_avx_vtestc_ps:
15759   case Intrinsic::x86_avx_vtestnzc_ps:
15760   case Intrinsic::x86_avx_vtestz_pd:
15761   case Intrinsic::x86_avx_vtestc_pd:
15762   case Intrinsic::x86_avx_vtestnzc_pd:
15763   case Intrinsic::x86_avx_vtestz_ps_256:
15764   case Intrinsic::x86_avx_vtestc_ps_256:
15765   case Intrinsic::x86_avx_vtestnzc_ps_256:
15766   case Intrinsic::x86_avx_vtestz_pd_256:
15767   case Intrinsic::x86_avx_vtestc_pd_256:
15768   case Intrinsic::x86_avx_vtestnzc_pd_256: {
15769     bool IsTestPacked = false;
15770     unsigned X86CC;
15771     switch (IntNo) {
15772     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
15773     case Intrinsic::x86_avx_vtestz_ps:
15774     case Intrinsic::x86_avx_vtestz_pd:
15775     case Intrinsic::x86_avx_vtestz_ps_256:
15776     case Intrinsic::x86_avx_vtestz_pd_256:
15777       IsTestPacked = true; // Fallthrough
15778     case Intrinsic::x86_sse41_ptestz:
15779     case Intrinsic::x86_avx_ptestz_256:
15780       // ZF = 1
15781       X86CC = X86::COND_E;
15782       break;
15783     case Intrinsic::x86_avx_vtestc_ps:
15784     case Intrinsic::x86_avx_vtestc_pd:
15785     case Intrinsic::x86_avx_vtestc_ps_256:
15786     case Intrinsic::x86_avx_vtestc_pd_256:
15787       IsTestPacked = true; // Fallthrough
15788     case Intrinsic::x86_sse41_ptestc:
15789     case Intrinsic::x86_avx_ptestc_256:
15790       // CF = 1
15791       X86CC = X86::COND_B;
15792       break;
15793     case Intrinsic::x86_avx_vtestnzc_ps:
15794     case Intrinsic::x86_avx_vtestnzc_pd:
15795     case Intrinsic::x86_avx_vtestnzc_ps_256:
15796     case Intrinsic::x86_avx_vtestnzc_pd_256:
15797       IsTestPacked = true; // Fallthrough
15798     case Intrinsic::x86_sse41_ptestnzc:
15799     case Intrinsic::x86_avx_ptestnzc_256:
15800       // ZF and CF = 0
15801       X86CC = X86::COND_A;
15802       break;
15803     }
15804
15805     SDValue LHS = Op.getOperand(1);
15806     SDValue RHS = Op.getOperand(2);
15807     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
15808     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
15809     SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
15810     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
15811     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15812   }
15813   case Intrinsic::x86_avx512_kortestz_w:
15814   case Intrinsic::x86_avx512_kortestc_w: {
15815     unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
15816     SDValue LHS = DAG.getBitcast(MVT::v16i1, Op.getOperand(1));
15817     SDValue RHS = DAG.getBitcast(MVT::v16i1, Op.getOperand(2));
15818     SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
15819     SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
15820     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
15821     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15822   }
15823
15824   case Intrinsic::x86_sse42_pcmpistria128:
15825   case Intrinsic::x86_sse42_pcmpestria128:
15826   case Intrinsic::x86_sse42_pcmpistric128:
15827   case Intrinsic::x86_sse42_pcmpestric128:
15828   case Intrinsic::x86_sse42_pcmpistrio128:
15829   case Intrinsic::x86_sse42_pcmpestrio128:
15830   case Intrinsic::x86_sse42_pcmpistris128:
15831   case Intrinsic::x86_sse42_pcmpestris128:
15832   case Intrinsic::x86_sse42_pcmpistriz128:
15833   case Intrinsic::x86_sse42_pcmpestriz128: {
15834     unsigned Opcode;
15835     unsigned X86CC;
15836     switch (IntNo) {
15837     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
15838     case Intrinsic::x86_sse42_pcmpistria128:
15839       Opcode = X86ISD::PCMPISTRI;
15840       X86CC = X86::COND_A;
15841       break;
15842     case Intrinsic::x86_sse42_pcmpestria128:
15843       Opcode = X86ISD::PCMPESTRI;
15844       X86CC = X86::COND_A;
15845       break;
15846     case Intrinsic::x86_sse42_pcmpistric128:
15847       Opcode = X86ISD::PCMPISTRI;
15848       X86CC = X86::COND_B;
15849       break;
15850     case Intrinsic::x86_sse42_pcmpestric128:
15851       Opcode = X86ISD::PCMPESTRI;
15852       X86CC = X86::COND_B;
15853       break;
15854     case Intrinsic::x86_sse42_pcmpistrio128:
15855       Opcode = X86ISD::PCMPISTRI;
15856       X86CC = X86::COND_O;
15857       break;
15858     case Intrinsic::x86_sse42_pcmpestrio128:
15859       Opcode = X86ISD::PCMPESTRI;
15860       X86CC = X86::COND_O;
15861       break;
15862     case Intrinsic::x86_sse42_pcmpistris128:
15863       Opcode = X86ISD::PCMPISTRI;
15864       X86CC = X86::COND_S;
15865       break;
15866     case Intrinsic::x86_sse42_pcmpestris128:
15867       Opcode = X86ISD::PCMPESTRI;
15868       X86CC = X86::COND_S;
15869       break;
15870     case Intrinsic::x86_sse42_pcmpistriz128:
15871       Opcode = X86ISD::PCMPISTRI;
15872       X86CC = X86::COND_E;
15873       break;
15874     case Intrinsic::x86_sse42_pcmpestriz128:
15875       Opcode = X86ISD::PCMPESTRI;
15876       X86CC = X86::COND_E;
15877       break;
15878     }
15879     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
15880     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
15881     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
15882     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15883                                 DAG.getConstant(X86CC, dl, MVT::i8),
15884                                 SDValue(PCMP.getNode(), 1));
15885     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15886   }
15887
15888   case Intrinsic::x86_sse42_pcmpistri128:
15889   case Intrinsic::x86_sse42_pcmpestri128: {
15890     unsigned Opcode;
15891     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
15892       Opcode = X86ISD::PCMPISTRI;
15893     else
15894       Opcode = X86ISD::PCMPESTRI;
15895
15896     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
15897     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
15898     return DAG.getNode(Opcode, dl, VTs, NewOps);
15899   }
15900
15901   case Intrinsic::x86_seh_lsda: {
15902     // Compute the symbol for the LSDA. We know it'll get emitted later.
15903     MachineFunction &MF = DAG.getMachineFunction();
15904     SDValue Op1 = Op.getOperand(1);
15905     auto *Fn = cast<Function>(cast<GlobalAddressSDNode>(Op1)->getGlobal());
15906     MCSymbol *LSDASym = MF.getMMI().getContext().getOrCreateLSDASymbol(
15907         GlobalValue::getRealLinkageName(Fn->getName()));
15908
15909     // Generate a simple absolute symbol reference. This intrinsic is only
15910     // supported on 32-bit Windows, which isn't PIC.
15911     SDValue Result = DAG.getMCSymbol(LSDASym, VT);
15912     return DAG.getNode(X86ISD::Wrapper, dl, VT, Result);
15913   }
15914
15915   case Intrinsic::x86_seh_recoverfp: {
15916     SDValue FnOp = Op.getOperand(1);
15917     SDValue IncomingFPOp = Op.getOperand(2);
15918     GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(FnOp);
15919     auto *Fn = dyn_cast_or_null<Function>(GSD ? GSD->getGlobal() : nullptr);
15920     if (!Fn)
15921       report_fatal_error(
15922           "llvm.x86.seh.recoverfp must take a function as the first argument");
15923     return recoverFramePointer(DAG, Fn, IncomingFPOp);
15924   }
15925
15926   case Intrinsic::localaddress: {
15927     // Returns one of the stack, base, or frame pointer registers, depending on
15928     // which is used to reference local variables.
15929     MachineFunction &MF = DAG.getMachineFunction();
15930     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15931     unsigned Reg;
15932     if (RegInfo->hasBasePointer(MF))
15933       Reg = RegInfo->getBaseRegister();
15934     else // This function handles the SP or FP case.
15935       Reg = RegInfo->getPtrSizedFrameRegister(MF);
15936     return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
15937   }
15938   }
15939 }
15940
15941 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15942                               SDValue Src, SDValue Mask, SDValue Base,
15943                               SDValue Index, SDValue ScaleOp, SDValue Chain,
15944                               const X86Subtarget * Subtarget) {
15945   SDLoc dl(Op);
15946   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15947   if (!C)
15948     llvm_unreachable("Invalid scale type");
15949   unsigned ScaleVal = C->getZExtValue();
15950   if (ScaleVal > 2 && ScaleVal != 4 && ScaleVal != 8)
15951     llvm_unreachable("Valid scale values are 1, 2, 4, 8");
15952
15953   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
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(Op.getValueType(), MaskVT, MVT::Other);
15971   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
15972   SDValue Segment = DAG.getRegister(0, MVT::i32);
15973   if (Src.getOpcode() == ISD::UNDEF)
15974     Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
15975   SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
15976   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
15977   SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
15978   return DAG.getMergeValues(RetOps, dl);
15979 }
15980
15981 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15982                                SDValue Src, SDValue Mask, SDValue Base,
15983                                SDValue Index, SDValue ScaleOp, SDValue Chain) {
15984   SDLoc dl(Op);
15985   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15986   if (!C)
15987     llvm_unreachable("Invalid scale type");
15988   unsigned ScaleVal = C->getZExtValue();
15989   if (ScaleVal > 2 && ScaleVal != 4 && ScaleVal != 8)
15990     llvm_unreachable("Valid scale values are 1, 2, 4, 8");
15991
15992   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
15993   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
15994   SDValue Segment = DAG.getRegister(0, MVT::i32);
15995   EVT MaskVT = MVT::getVectorVT(MVT::i1,
15996                              Index.getSimpleValueType().getVectorNumElements());
15997   SDValue MaskInReg;
15998   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15999   if (MaskC)
16000     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
16001   else {
16002     EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16003                                      Mask.getValueType().getSizeInBits());
16004
16005     // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
16006     // are extracted by EXTRACT_SUBVECTOR.
16007     MaskInReg = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
16008                             DAG.getBitcast(BitcastVT, Mask),
16009                             DAG.getIntPtrConstant(0, dl));
16010   }
16011   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
16012   SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
16013   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
16014   return SDValue(Res, 1);
16015 }
16016
16017 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
16018                                SDValue Mask, SDValue Base, SDValue Index,
16019                                SDValue ScaleOp, SDValue Chain) {
16020   SDLoc dl(Op);
16021   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
16022   assert(C && "Invalid scale type");
16023   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
16024   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
16025   SDValue Segment = DAG.getRegister(0, MVT::i32);
16026   EVT MaskVT =
16027     MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
16028   SDValue MaskInReg;
16029   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
16030   if (MaskC)
16031     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
16032   else
16033     MaskInReg = DAG.getBitcast(MaskVT, Mask);
16034   //SDVTList VTs = DAG.getVTList(MVT::Other);
16035   SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
16036   SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
16037   return SDValue(Res, 0);
16038 }
16039
16040 // getReadPerformanceCounter - Handles the lowering of builtin intrinsics that
16041 // read performance monitor counters (x86_rdpmc).
16042 static void getReadPerformanceCounter(SDNode *N, SDLoc DL,
16043                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
16044                               SmallVectorImpl<SDValue> &Results) {
16045   assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
16046   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
16047   SDValue LO, HI;
16048
16049   // The ECX register is used to select the index of the performance counter
16050   // to read.
16051   SDValue Chain = DAG.getCopyToReg(N->getOperand(0), DL, X86::ECX,
16052                                    N->getOperand(2));
16053   SDValue rd = DAG.getNode(X86ISD::RDPMC_DAG, DL, Tys, Chain);
16054
16055   // Reads the content of a 64-bit performance counter and returns it in the
16056   // registers EDX:EAX.
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   Chain = HI.getValue(1);
16067
16068   if (Subtarget->is64Bit()) {
16069     // The EAX register is loaded with the low-order 32 bits. The EDX register
16070     // is loaded with the supported high-order bits of the counter.
16071     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
16072                               DAG.getConstant(32, DL, MVT::i8));
16073     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
16074     Results.push_back(Chain);
16075     return;
16076   }
16077
16078   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
16079   SDValue Ops[] = { LO, HI };
16080   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
16081   Results.push_back(Pair);
16082   Results.push_back(Chain);
16083 }
16084
16085 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
16086 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
16087 // also used to custom lower READCYCLECOUNTER nodes.
16088 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
16089                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
16090                               SmallVectorImpl<SDValue> &Results) {
16091   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
16092   SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
16093   SDValue LO, HI;
16094
16095   // The processor's time-stamp counter (a 64-bit MSR) is stored into the
16096   // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
16097   // and the EAX register is loaded with the low-order 32 bits.
16098   if (Subtarget->is64Bit()) {
16099     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
16100     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
16101                             LO.getValue(2));
16102   } else {
16103     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
16104     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
16105                             LO.getValue(2));
16106   }
16107   SDValue Chain = HI.getValue(1);
16108
16109   if (Opcode == X86ISD::RDTSCP_DAG) {
16110     assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
16111
16112     // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
16113     // the ECX register. Add 'ecx' explicitly to the chain.
16114     SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
16115                                      HI.getValue(2));
16116     // Explicitly store the content of ECX at the location passed in input
16117     // to the 'rdtscp' intrinsic.
16118     Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
16119                          MachinePointerInfo(), false, false, 0);
16120   }
16121
16122   if (Subtarget->is64Bit()) {
16123     // The EDX register is loaded with the high-order 32 bits of the MSR, and
16124     // the EAX register is loaded with the low-order 32 bits.
16125     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
16126                               DAG.getConstant(32, DL, MVT::i8));
16127     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
16128     Results.push_back(Chain);
16129     return;
16130   }
16131
16132   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
16133   SDValue Ops[] = { LO, HI };
16134   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
16135   Results.push_back(Pair);
16136   Results.push_back(Chain);
16137 }
16138
16139 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
16140                                      SelectionDAG &DAG) {
16141   SmallVector<SDValue, 2> Results;
16142   SDLoc DL(Op);
16143   getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
16144                           Results);
16145   return DAG.getMergeValues(Results, DL);
16146 }
16147
16148 static SDValue LowerSEHRESTOREFRAME(SDValue Op, const X86Subtarget *Subtarget,
16149                                     SelectionDAG &DAG) {
16150   MachineFunction &MF = DAG.getMachineFunction();
16151   const Function *Fn = MF.getFunction();
16152   SDLoc dl(Op);
16153   SDValue Chain = Op.getOperand(0);
16154
16155   assert(Subtarget->getFrameLowering()->hasFP(MF) &&
16156          "using llvm.x86.seh.restoreframe requires a frame pointer");
16157
16158   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16159   MVT VT = TLI.getPointerTy(DAG.getDataLayout());
16160
16161   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16162   unsigned FrameReg =
16163       RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
16164   unsigned SPReg = RegInfo->getStackRegister();
16165   unsigned SlotSize = RegInfo->getSlotSize();
16166
16167   // Get incoming EBP.
16168   SDValue IncomingEBP =
16169       DAG.getCopyFromReg(Chain, dl, FrameReg, VT);
16170
16171   // SP is saved in the first field of every registration node, so load
16172   // [EBP-RegNodeSize] into SP.
16173   int RegNodeSize = getSEHRegistrationNodeSize(Fn);
16174   SDValue SPAddr = DAG.getNode(ISD::ADD, dl, VT, IncomingEBP,
16175                                DAG.getConstant(-RegNodeSize, dl, VT));
16176   SDValue NewSP =
16177       DAG.getLoad(VT, dl, Chain, SPAddr, MachinePointerInfo(), false, false,
16178                   false, VT.getScalarSizeInBits() / 8);
16179   Chain = DAG.getCopyToReg(Chain, dl, SPReg, NewSP);
16180
16181   if (!RegInfo->needsStackRealignment(MF)) {
16182     // Adjust EBP to point back to the original frame position.
16183     SDValue NewFP = recoverFramePointer(DAG, Fn, IncomingEBP);
16184     Chain = DAG.getCopyToReg(Chain, dl, FrameReg, NewFP);
16185   } else {
16186     assert(RegInfo->hasBasePointer(MF) &&
16187            "functions with Win32 EH must use frame or base pointer register");
16188
16189     // Reload the base pointer (ESI) with the adjusted incoming EBP.
16190     SDValue NewBP = recoverFramePointer(DAG, Fn, IncomingEBP);
16191     Chain = DAG.getCopyToReg(Chain, dl, RegInfo->getBaseRegister(), NewBP);
16192
16193     // Reload the spilled EBP value, now that the stack and base pointers are
16194     // set up.
16195     X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
16196     X86FI->setHasSEHFramePtrSave(true);
16197     int FI = MF.getFrameInfo()->CreateSpillStackObject(SlotSize, SlotSize);
16198     X86FI->setSEHFramePtrSaveIndex(FI);
16199     SDValue NewFP = DAG.getLoad(VT, dl, Chain, DAG.getFrameIndex(FI, VT),
16200                                 MachinePointerInfo(), false, false, false,
16201                                 VT.getScalarSizeInBits() / 8);
16202     Chain = DAG.getCopyToReg(NewFP, dl, FrameReg, NewFP);
16203   }
16204
16205   return Chain;
16206 }
16207
16208 /// \brief Lower intrinsics for TRUNCATE_TO_MEM case
16209 /// return truncate Store/MaskedStore Node
16210 static SDValue LowerINTRINSIC_TRUNCATE_TO_MEM(const SDValue & Op,
16211                                                SelectionDAG &DAG,
16212                                                MVT ElementType) {
16213   SDLoc dl(Op);
16214   SDValue Mask = Op.getOperand(4);
16215   SDValue DataToTruncate = Op.getOperand(3);
16216   SDValue Addr = Op.getOperand(2);
16217   SDValue Chain = Op.getOperand(0);
16218
16219   EVT VT  = DataToTruncate.getValueType();
16220   EVT SVT = EVT::getVectorVT(*DAG.getContext(),
16221                              ElementType, VT.getVectorNumElements());
16222
16223   if (isAllOnes(Mask)) // return just a truncate store
16224     return DAG.getTruncStore(Chain, dl, DataToTruncate, Addr,
16225                              MachinePointerInfo(), SVT, false, false,
16226                              SVT.getScalarSizeInBits()/8);
16227
16228   EVT MaskVT = EVT::getVectorVT(*DAG.getContext(),
16229                                 MVT::i1, VT.getVectorNumElements());
16230   EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16231                                    Mask.getValueType().getSizeInBits());
16232   // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
16233   // are extracted by EXTRACT_SUBVECTOR.
16234   SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
16235                               DAG.getBitcast(BitcastVT, Mask),
16236                               DAG.getIntPtrConstant(0, dl));
16237
16238   MachineMemOperand *MMO = DAG.getMachineFunction().
16239     getMachineMemOperand(MachinePointerInfo(),
16240                          MachineMemOperand::MOStore, SVT.getStoreSize(),
16241                          SVT.getScalarSizeInBits()/8);
16242
16243   return DAG.getMaskedStore(Chain, dl, DataToTruncate, Addr,
16244                             VMask, SVT, MMO, true);
16245 }
16246
16247 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
16248                                       SelectionDAG &DAG) {
16249   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
16250
16251   const IntrinsicData* IntrData = getIntrinsicWithChain(IntNo);
16252   if (!IntrData) {
16253     if (IntNo == llvm::Intrinsic::x86_seh_restoreframe)
16254       return LowerSEHRESTOREFRAME(Op, Subtarget, DAG);
16255     return SDValue();
16256   }
16257
16258   SDLoc dl(Op);
16259   switch(IntrData->Type) {
16260   default:
16261     llvm_unreachable("Unknown Intrinsic Type");
16262     break;
16263   case RDSEED:
16264   case RDRAND: {
16265     // Emit the node with the right value type.
16266     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
16267     SDValue Result = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
16268
16269     // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
16270     // Otherwise return the value from Rand, which is always 0, casted to i32.
16271     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
16272                       DAG.getConstant(1, dl, Op->getValueType(1)),
16273                       DAG.getConstant(X86::COND_B, dl, MVT::i32),
16274                       SDValue(Result.getNode(), 1) };
16275     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
16276                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
16277                                   Ops);
16278
16279     // Return { result, isValid, chain }.
16280     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
16281                        SDValue(Result.getNode(), 2));
16282   }
16283   case GATHER: {
16284   //gather(v1, mask, index, base, scale);
16285     SDValue Chain = Op.getOperand(0);
16286     SDValue Src   = Op.getOperand(2);
16287     SDValue Base  = Op.getOperand(3);
16288     SDValue Index = Op.getOperand(4);
16289     SDValue Mask  = Op.getOperand(5);
16290     SDValue Scale = Op.getOperand(6);
16291     return getGatherNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index, Scale,
16292                          Chain, Subtarget);
16293   }
16294   case SCATTER: {
16295   //scatter(base, mask, index, v1, scale);
16296     SDValue Chain = Op.getOperand(0);
16297     SDValue Base  = Op.getOperand(2);
16298     SDValue Mask  = Op.getOperand(3);
16299     SDValue Index = Op.getOperand(4);
16300     SDValue Src   = Op.getOperand(5);
16301     SDValue Scale = Op.getOperand(6);
16302     return getScatterNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index,
16303                           Scale, Chain);
16304   }
16305   case PREFETCH: {
16306     SDValue Hint = Op.getOperand(6);
16307     unsigned HintVal = cast<ConstantSDNode>(Hint)->getZExtValue();
16308     assert(HintVal < 2 && "Wrong prefetch hint in intrinsic: should be 0 or 1");
16309     unsigned Opcode = (HintVal ? IntrData->Opc1 : IntrData->Opc0);
16310     SDValue Chain = Op.getOperand(0);
16311     SDValue Mask  = Op.getOperand(2);
16312     SDValue Index = Op.getOperand(3);
16313     SDValue Base  = Op.getOperand(4);
16314     SDValue Scale = Op.getOperand(5);
16315     return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
16316   }
16317   // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
16318   case RDTSC: {
16319     SmallVector<SDValue, 2> Results;
16320     getReadTimeStampCounter(Op.getNode(), dl, IntrData->Opc0, DAG, Subtarget,
16321                             Results);
16322     return DAG.getMergeValues(Results, dl);
16323   }
16324   // Read Performance Monitoring Counters.
16325   case RDPMC: {
16326     SmallVector<SDValue, 2> Results;
16327     getReadPerformanceCounter(Op.getNode(), dl, DAG, Subtarget, Results);
16328     return DAG.getMergeValues(Results, dl);
16329   }
16330   // XTEST intrinsics.
16331   case XTEST: {
16332     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
16333     SDValue InTrans = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
16334     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16335                                 DAG.getConstant(X86::COND_NE, dl, MVT::i8),
16336                                 InTrans);
16337     SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
16338     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
16339                        Ret, SDValue(InTrans.getNode(), 1));
16340   }
16341   // ADC/ADCX/SBB
16342   case ADX: {
16343     SmallVector<SDValue, 2> Results;
16344     SDVTList CFVTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
16345     SDVTList VTs = DAG.getVTList(Op.getOperand(3)->getValueType(0), MVT::Other);
16346     SDValue GenCF = DAG.getNode(X86ISD::ADD, dl, CFVTs, Op.getOperand(2),
16347                                 DAG.getConstant(-1, dl, MVT::i8));
16348     SDValue Res = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(3),
16349                               Op.getOperand(4), GenCF.getValue(1));
16350     SDValue Store = DAG.getStore(Op.getOperand(0), dl, Res.getValue(0),
16351                                  Op.getOperand(5), MachinePointerInfo(),
16352                                  false, false, 0);
16353     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16354                                 DAG.getConstant(X86::COND_B, dl, MVT::i8),
16355                                 Res.getValue(1));
16356     Results.push_back(SetCC);
16357     Results.push_back(Store);
16358     return DAG.getMergeValues(Results, dl);
16359   }
16360   case COMPRESS_TO_MEM: {
16361     SDLoc dl(Op);
16362     SDValue Mask = Op.getOperand(4);
16363     SDValue DataToCompress = Op.getOperand(3);
16364     SDValue Addr = Op.getOperand(2);
16365     SDValue Chain = Op.getOperand(0);
16366
16367     EVT VT = DataToCompress.getValueType();
16368     if (isAllOnes(Mask)) // return just a store
16369       return DAG.getStore(Chain, dl, DataToCompress, Addr,
16370                           MachinePointerInfo(), false, false,
16371                           VT.getScalarSizeInBits()/8);
16372
16373     SDValue Compressed =
16374       getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, DataToCompress),
16375                            Mask, DAG.getUNDEF(VT), Subtarget, DAG);
16376     return DAG.getStore(Chain, dl, Compressed, Addr,
16377                         MachinePointerInfo(), false, false,
16378                         VT.getScalarSizeInBits()/8);
16379   }
16380   case TRUNCATE_TO_MEM_VI8:
16381     return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i8);
16382   case TRUNCATE_TO_MEM_VI16:
16383     return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i16);
16384   case TRUNCATE_TO_MEM_VI32:
16385     return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i32);
16386   case EXPAND_FROM_MEM: {
16387     SDLoc dl(Op);
16388     SDValue Mask = Op.getOperand(4);
16389     SDValue PassThru = Op.getOperand(3);
16390     SDValue Addr = Op.getOperand(2);
16391     SDValue Chain = Op.getOperand(0);
16392     EVT VT = Op.getValueType();
16393
16394     if (isAllOnes(Mask)) // return just a load
16395       return DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(), false, false,
16396                          false, VT.getScalarSizeInBits()/8);
16397
16398     SDValue DataToExpand = DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(),
16399                                        false, false, false,
16400                                        VT.getScalarSizeInBits()/8);
16401
16402     SDValue Results[] = {
16403       getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, DataToExpand),
16404                            Mask, PassThru, Subtarget, DAG), Chain};
16405     return DAG.getMergeValues(Results, dl);
16406   }
16407   }
16408 }
16409
16410 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
16411                                            SelectionDAG &DAG) const {
16412   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
16413   MFI->setReturnAddressIsTaken(true);
16414
16415   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
16416     return SDValue();
16417
16418   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16419   SDLoc dl(Op);
16420   EVT PtrVT = getPointerTy(DAG.getDataLayout());
16421
16422   if (Depth > 0) {
16423     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
16424     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16425     SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), dl, PtrVT);
16426     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
16427                        DAG.getNode(ISD::ADD, dl, PtrVT,
16428                                    FrameAddr, Offset),
16429                        MachinePointerInfo(), false, false, false, 0);
16430   }
16431
16432   // Just load the return address.
16433   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
16434   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
16435                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
16436 }
16437
16438 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
16439   MachineFunction &MF = DAG.getMachineFunction();
16440   MachineFrameInfo *MFI = MF.getFrameInfo();
16441   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
16442   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16443   EVT VT = Op.getValueType();
16444
16445   MFI->setFrameAddressIsTaken(true);
16446
16447   if (MF.getTarget().getMCAsmInfo()->usesWindowsCFI()) {
16448     // Depth > 0 makes no sense on targets which use Windows unwind codes.  It
16449     // is not possible to crawl up the stack without looking at the unwind codes
16450     // simultaneously.
16451     int FrameAddrIndex = FuncInfo->getFAIndex();
16452     if (!FrameAddrIndex) {
16453       // Set up a frame object for the return address.
16454       unsigned SlotSize = RegInfo->getSlotSize();
16455       FrameAddrIndex = MF.getFrameInfo()->CreateFixedObject(
16456           SlotSize, /*Offset=*/0, /*IsImmutable=*/false);
16457       FuncInfo->setFAIndex(FrameAddrIndex);
16458     }
16459     return DAG.getFrameIndex(FrameAddrIndex, VT);
16460   }
16461
16462   unsigned FrameReg =
16463       RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
16464   SDLoc dl(Op);  // FIXME probably not meaningful
16465   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16466   assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
16467           (FrameReg == X86::EBP && VT == MVT::i32)) &&
16468          "Invalid Frame Register!");
16469   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
16470   while (Depth--)
16471     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
16472                             MachinePointerInfo(),
16473                             false, false, false, 0);
16474   return FrameAddr;
16475 }
16476
16477 // FIXME? Maybe this could be a TableGen attribute on some registers and
16478 // this table could be generated automatically from RegInfo.
16479 unsigned X86TargetLowering::getRegisterByName(const char* RegName, EVT VT,
16480                                               SelectionDAG &DAG) const {
16481   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
16482   const MachineFunction &MF = DAG.getMachineFunction();
16483
16484   unsigned Reg = StringSwitch<unsigned>(RegName)
16485                        .Case("esp", X86::ESP)
16486                        .Case("rsp", X86::RSP)
16487                        .Case("ebp", X86::EBP)
16488                        .Case("rbp", X86::RBP)
16489                        .Default(0);
16490
16491   if (Reg == X86::EBP || Reg == X86::RBP) {
16492     if (!TFI.hasFP(MF))
16493       report_fatal_error("register " + StringRef(RegName) +
16494                          " is allocatable: function has no frame pointer");
16495 #ifndef NDEBUG
16496     else {
16497       const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16498       unsigned FrameReg =
16499           RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
16500       assert((FrameReg == X86::EBP || FrameReg == X86::RBP) &&
16501              "Invalid Frame Register!");
16502     }
16503 #endif
16504   }
16505
16506   if (Reg)
16507     return Reg;
16508
16509   report_fatal_error("Invalid register name global variable");
16510 }
16511
16512 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
16513                                                      SelectionDAG &DAG) const {
16514   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16515   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize(), SDLoc(Op));
16516 }
16517
16518 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
16519   SDValue Chain     = Op.getOperand(0);
16520   SDValue Offset    = Op.getOperand(1);
16521   SDValue Handler   = Op.getOperand(2);
16522   SDLoc dl      (Op);
16523
16524   EVT PtrVT = getPointerTy(DAG.getDataLayout());
16525   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16526   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
16527   assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
16528           (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
16529          "Invalid Frame Register!");
16530   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
16531   unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
16532
16533   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
16534                                  DAG.getIntPtrConstant(RegInfo->getSlotSize(),
16535                                                        dl));
16536   StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
16537   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
16538                        false, false, 0);
16539   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
16540
16541   return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
16542                      DAG.getRegister(StoreAddrReg, PtrVT));
16543 }
16544
16545 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
16546                                                SelectionDAG &DAG) const {
16547   SDLoc DL(Op);
16548   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
16549                      DAG.getVTList(MVT::i32, MVT::Other),
16550                      Op.getOperand(0), Op.getOperand(1));
16551 }
16552
16553 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
16554                                                 SelectionDAG &DAG) const {
16555   SDLoc DL(Op);
16556   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
16557                      Op.getOperand(0), Op.getOperand(1));
16558 }
16559
16560 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
16561   return Op.getOperand(0);
16562 }
16563
16564 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
16565                                                 SelectionDAG &DAG) const {
16566   SDValue Root = Op.getOperand(0);
16567   SDValue Trmp = Op.getOperand(1); // trampoline
16568   SDValue FPtr = Op.getOperand(2); // nested function
16569   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
16570   SDLoc dl (Op);
16571
16572   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
16573   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
16574
16575   if (Subtarget->is64Bit()) {
16576     SDValue OutChains[6];
16577
16578     // Large code-model.
16579     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
16580     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
16581
16582     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
16583     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
16584
16585     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
16586
16587     // Load the pointer to the nested function into R11.
16588     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
16589     SDValue Addr = Trmp;
16590     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
16591                                 Addr, MachinePointerInfo(TrmpAddr),
16592                                 false, false, 0);
16593
16594     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16595                        DAG.getConstant(2, dl, MVT::i64));
16596     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
16597                                 MachinePointerInfo(TrmpAddr, 2),
16598                                 false, false, 2);
16599
16600     // Load the 'nest' parameter value into R10.
16601     // R10 is specified in X86CallingConv.td
16602     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
16603     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16604                        DAG.getConstant(10, dl, MVT::i64));
16605     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
16606                                 Addr, MachinePointerInfo(TrmpAddr, 10),
16607                                 false, false, 0);
16608
16609     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16610                        DAG.getConstant(12, dl, MVT::i64));
16611     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
16612                                 MachinePointerInfo(TrmpAddr, 12),
16613                                 false, false, 2);
16614
16615     // Jump to the nested function.
16616     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
16617     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16618                        DAG.getConstant(20, dl, MVT::i64));
16619     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
16620                                 Addr, MachinePointerInfo(TrmpAddr, 20),
16621                                 false, false, 0);
16622
16623     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
16624     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16625                        DAG.getConstant(22, dl, MVT::i64));
16626     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, dl, MVT::i8),
16627                                 Addr, MachinePointerInfo(TrmpAddr, 22),
16628                                 false, false, 0);
16629
16630     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
16631   } else {
16632     const Function *Func =
16633       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
16634     CallingConv::ID CC = Func->getCallingConv();
16635     unsigned NestReg;
16636
16637     switch (CC) {
16638     default:
16639       llvm_unreachable("Unsupported calling convention");
16640     case CallingConv::C:
16641     case CallingConv::X86_StdCall: {
16642       // Pass 'nest' parameter in ECX.
16643       // Must be kept in sync with X86CallingConv.td
16644       NestReg = X86::ECX;
16645
16646       // Check that ECX wasn't needed by an 'inreg' parameter.
16647       FunctionType *FTy = Func->getFunctionType();
16648       const AttributeSet &Attrs = Func->getAttributes();
16649
16650       if (!Attrs.isEmpty() && !Func->isVarArg()) {
16651         unsigned InRegCount = 0;
16652         unsigned Idx = 1;
16653
16654         for (FunctionType::param_iterator I = FTy->param_begin(),
16655              E = FTy->param_end(); I != E; ++I, ++Idx)
16656           if (Attrs.hasAttribute(Idx, Attribute::InReg)) {
16657             auto &DL = DAG.getDataLayout();
16658             // FIXME: should only count parameters that are lowered to integers.
16659             InRegCount += (DL.getTypeSizeInBits(*I) + 31) / 32;
16660           }
16661
16662         if (InRegCount > 2) {
16663           report_fatal_error("Nest register in use - reduce number of inreg"
16664                              " parameters!");
16665         }
16666       }
16667       break;
16668     }
16669     case CallingConv::X86_FastCall:
16670     case CallingConv::X86_ThisCall:
16671     case CallingConv::Fast:
16672       // Pass 'nest' parameter in EAX.
16673       // Must be kept in sync with X86CallingConv.td
16674       NestReg = X86::EAX;
16675       break;
16676     }
16677
16678     SDValue OutChains[4];
16679     SDValue Addr, Disp;
16680
16681     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
16682                        DAG.getConstant(10, dl, MVT::i32));
16683     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
16684
16685     // This is storing the opcode for MOV32ri.
16686     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
16687     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
16688     OutChains[0] = DAG.getStore(Root, dl,
16689                                 DAG.getConstant(MOV32ri|N86Reg, dl, MVT::i8),
16690                                 Trmp, MachinePointerInfo(TrmpAddr),
16691                                 false, false, 0);
16692
16693     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
16694                        DAG.getConstant(1, dl, MVT::i32));
16695     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
16696                                 MachinePointerInfo(TrmpAddr, 1),
16697                                 false, false, 1);
16698
16699     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
16700     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
16701                        DAG.getConstant(5, dl, MVT::i32));
16702     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, dl, MVT::i8),
16703                                 Addr, MachinePointerInfo(TrmpAddr, 5),
16704                                 false, false, 1);
16705
16706     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
16707                        DAG.getConstant(6, dl, MVT::i32));
16708     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
16709                                 MachinePointerInfo(TrmpAddr, 6),
16710                                 false, false, 1);
16711
16712     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
16713   }
16714 }
16715
16716 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
16717                                             SelectionDAG &DAG) const {
16718   /*
16719    The rounding mode is in bits 11:10 of FPSR, and has the following
16720    settings:
16721      00 Round to nearest
16722      01 Round to -inf
16723      10 Round to +inf
16724      11 Round to 0
16725
16726   FLT_ROUNDS, on the other hand, expects the following:
16727     -1 Undefined
16728      0 Round to 0
16729      1 Round to nearest
16730      2 Round to +inf
16731      3 Round to -inf
16732
16733   To perform the conversion, we do:
16734     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
16735   */
16736
16737   MachineFunction &MF = DAG.getMachineFunction();
16738   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
16739   unsigned StackAlignment = TFI.getStackAlignment();
16740   MVT VT = Op.getSimpleValueType();
16741   SDLoc DL(Op);
16742
16743   // Save FP Control Word to stack slot
16744   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
16745   SDValue StackSlot =
16746       DAG.getFrameIndex(SSFI, getPointerTy(DAG.getDataLayout()));
16747
16748   MachineMemOperand *MMO =
16749       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, SSFI),
16750                               MachineMemOperand::MOStore, 2, 2);
16751
16752   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
16753   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
16754                                           DAG.getVTList(MVT::Other),
16755                                           Ops, MVT::i16, MMO);
16756
16757   // Load FP Control Word from stack slot
16758   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
16759                             MachinePointerInfo(), false, false, false, 0);
16760
16761   // Transform as necessary
16762   SDValue CWD1 =
16763     DAG.getNode(ISD::SRL, DL, MVT::i16,
16764                 DAG.getNode(ISD::AND, DL, MVT::i16,
16765                             CWD, DAG.getConstant(0x800, DL, MVT::i16)),
16766                 DAG.getConstant(11, DL, MVT::i8));
16767   SDValue CWD2 =
16768     DAG.getNode(ISD::SRL, DL, MVT::i16,
16769                 DAG.getNode(ISD::AND, DL, MVT::i16,
16770                             CWD, DAG.getConstant(0x400, DL, MVT::i16)),
16771                 DAG.getConstant(9, DL, MVT::i8));
16772
16773   SDValue RetVal =
16774     DAG.getNode(ISD::AND, DL, MVT::i16,
16775                 DAG.getNode(ISD::ADD, DL, MVT::i16,
16776                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
16777                             DAG.getConstant(1, DL, MVT::i16)),
16778                 DAG.getConstant(3, DL, MVT::i16));
16779
16780   return DAG.getNode((VT.getSizeInBits() < 16 ?
16781                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
16782 }
16783
16784 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
16785   MVT VT = Op.getSimpleValueType();
16786   EVT OpVT = VT;
16787   unsigned NumBits = VT.getSizeInBits();
16788   SDLoc dl(Op);
16789
16790   Op = Op.getOperand(0);
16791   if (VT == MVT::i8) {
16792     // Zero extend to i32 since there is not an i8 bsr.
16793     OpVT = MVT::i32;
16794     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
16795   }
16796
16797   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
16798   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
16799   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
16800
16801   // If src is zero (i.e. bsr sets ZF), returns NumBits.
16802   SDValue Ops[] = {
16803     Op,
16804     DAG.getConstant(NumBits + NumBits - 1, dl, OpVT),
16805     DAG.getConstant(X86::COND_E, dl, MVT::i8),
16806     Op.getValue(1)
16807   };
16808   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
16809
16810   // Finally xor with NumBits-1.
16811   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
16812                    DAG.getConstant(NumBits - 1, dl, OpVT));
16813
16814   if (VT == MVT::i8)
16815     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
16816   return Op;
16817 }
16818
16819 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
16820   MVT VT = Op.getSimpleValueType();
16821   EVT OpVT = VT;
16822   unsigned NumBits = VT.getSizeInBits();
16823   SDLoc dl(Op);
16824
16825   Op = Op.getOperand(0);
16826   if (VT == MVT::i8) {
16827     // Zero extend to i32 since there is not an i8 bsr.
16828     OpVT = MVT::i32;
16829     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
16830   }
16831
16832   // Issue a bsr (scan bits in reverse).
16833   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
16834   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
16835
16836   // And xor with NumBits-1.
16837   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
16838                    DAG.getConstant(NumBits - 1, dl, OpVT));
16839
16840   if (VT == MVT::i8)
16841     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
16842   return Op;
16843 }
16844
16845 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
16846   MVT VT = Op.getSimpleValueType();
16847   unsigned NumBits = VT.getSizeInBits();
16848   SDLoc dl(Op);
16849   Op = Op.getOperand(0);
16850
16851   // Issue a bsf (scan bits forward) which also sets EFLAGS.
16852   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
16853   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
16854
16855   // If src is zero (i.e. bsf sets ZF), returns NumBits.
16856   SDValue Ops[] = {
16857     Op,
16858     DAG.getConstant(NumBits, dl, VT),
16859     DAG.getConstant(X86::COND_E, dl, MVT::i8),
16860     Op.getValue(1)
16861   };
16862   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
16863 }
16864
16865 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
16866 // ones, and then concatenate the result back.
16867 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
16868   MVT VT = Op.getSimpleValueType();
16869
16870   assert(VT.is256BitVector() && VT.isInteger() &&
16871          "Unsupported value type for operation");
16872
16873   unsigned NumElems = VT.getVectorNumElements();
16874   SDLoc dl(Op);
16875
16876   // Extract the LHS vectors
16877   SDValue LHS = Op.getOperand(0);
16878   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
16879   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
16880
16881   // Extract the RHS vectors
16882   SDValue RHS = Op.getOperand(1);
16883   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
16884   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
16885
16886   MVT EltVT = VT.getVectorElementType();
16887   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
16888
16889   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
16890                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
16891                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
16892 }
16893
16894 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
16895   if (Op.getValueType() == MVT::i1)
16896     return DAG.getNode(ISD::XOR, SDLoc(Op), Op.getValueType(),
16897                        Op.getOperand(0), Op.getOperand(1));
16898   assert(Op.getSimpleValueType().is256BitVector() &&
16899          Op.getSimpleValueType().isInteger() &&
16900          "Only handle AVX 256-bit vector integer operation");
16901   return Lower256IntArith(Op, DAG);
16902 }
16903
16904 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
16905   if (Op.getValueType() == MVT::i1)
16906     return DAG.getNode(ISD::XOR, SDLoc(Op), Op.getValueType(),
16907                        Op.getOperand(0), Op.getOperand(1));
16908   assert(Op.getSimpleValueType().is256BitVector() &&
16909          Op.getSimpleValueType().isInteger() &&
16910          "Only handle AVX 256-bit vector integer operation");
16911   return Lower256IntArith(Op, DAG);
16912 }
16913
16914 static SDValue LowerMINMAX(SDValue Op, SelectionDAG &DAG) {
16915   assert(Op.getSimpleValueType().is256BitVector() &&
16916          Op.getSimpleValueType().isInteger() &&
16917          "Only handle AVX 256-bit vector integer operation");
16918   return Lower256IntArith(Op, DAG);
16919 }
16920
16921 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
16922                         SelectionDAG &DAG) {
16923   SDLoc dl(Op);
16924   MVT VT = Op.getSimpleValueType();
16925
16926   if (VT == MVT::i1)
16927     return DAG.getNode(ISD::AND, dl, VT, Op.getOperand(0), Op.getOperand(1));
16928
16929   // Decompose 256-bit ops into smaller 128-bit ops.
16930   if (VT.is256BitVector() && !Subtarget->hasInt256())
16931     return Lower256IntArith(Op, DAG);
16932
16933   SDValue A = Op.getOperand(0);
16934   SDValue B = Op.getOperand(1);
16935
16936   // Lower v16i8/v32i8 mul as promotion to v8i16/v16i16 vector
16937   // pairs, multiply and truncate.
16938   if (VT == MVT::v16i8 || VT == MVT::v32i8) {
16939     if (Subtarget->hasInt256()) {
16940       if (VT == MVT::v32i8) {
16941         MVT SubVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() / 2);
16942         SDValue Lo = DAG.getIntPtrConstant(0, dl);
16943         SDValue Hi = DAG.getIntPtrConstant(VT.getVectorNumElements() / 2, dl);
16944         SDValue ALo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Lo);
16945         SDValue BLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Lo);
16946         SDValue AHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Hi);
16947         SDValue BHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Hi);
16948         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
16949                            DAG.getNode(ISD::MUL, dl, SubVT, ALo, BLo),
16950                            DAG.getNode(ISD::MUL, dl, SubVT, AHi, BHi));
16951       }
16952
16953       MVT ExVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements());
16954       return DAG.getNode(
16955           ISD::TRUNCATE, dl, VT,
16956           DAG.getNode(ISD::MUL, dl, ExVT,
16957                       DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, A),
16958                       DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, B)));
16959     }
16960
16961     assert(VT == MVT::v16i8 &&
16962            "Pre-AVX2 support only supports v16i8 multiplication");
16963     MVT ExVT = MVT::v8i16;
16964
16965     // Extract the lo parts and sign extend to i16
16966     SDValue ALo, BLo;
16967     if (Subtarget->hasSSE41()) {
16968       ALo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, A);
16969       BLo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, B);
16970     } else {
16971       const int ShufMask[] = {-1, 0, -1, 1, -1, 2, -1, 3,
16972                               -1, 4, -1, 5, -1, 6, -1, 7};
16973       ALo = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
16974       BLo = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
16975       ALo = DAG.getBitcast(ExVT, ALo);
16976       BLo = DAG.getBitcast(ExVT, BLo);
16977       ALo = DAG.getNode(ISD::SRA, dl, ExVT, ALo, DAG.getConstant(8, dl, ExVT));
16978       BLo = DAG.getNode(ISD::SRA, dl, ExVT, BLo, DAG.getConstant(8, dl, ExVT));
16979     }
16980
16981     // Extract the hi parts and sign extend to i16
16982     SDValue AHi, BHi;
16983     if (Subtarget->hasSSE41()) {
16984       const int ShufMask[] = {8,  9,  10, 11, 12, 13, 14, 15,
16985                               -1, -1, -1, -1, -1, -1, -1, -1};
16986       AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
16987       BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
16988       AHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, AHi);
16989       BHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, BHi);
16990     } else {
16991       const int ShufMask[] = {-1, 8,  -1, 9,  -1, 10, -1, 11,
16992                               -1, 12, -1, 13, -1, 14, -1, 15};
16993       AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
16994       BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
16995       AHi = DAG.getBitcast(ExVT, AHi);
16996       BHi = DAG.getBitcast(ExVT, BHi);
16997       AHi = DAG.getNode(ISD::SRA, dl, ExVT, AHi, DAG.getConstant(8, dl, ExVT));
16998       BHi = DAG.getNode(ISD::SRA, dl, ExVT, BHi, DAG.getConstant(8, dl, ExVT));
16999     }
17000
17001     // Multiply, mask the lower 8bits of the lo/hi results and pack
17002     SDValue RLo = DAG.getNode(ISD::MUL, dl, ExVT, ALo, BLo);
17003     SDValue RHi = DAG.getNode(ISD::MUL, dl, ExVT, AHi, BHi);
17004     RLo = DAG.getNode(ISD::AND, dl, ExVT, RLo, DAG.getConstant(255, dl, ExVT));
17005     RHi = DAG.getNode(ISD::AND, dl, ExVT, RHi, DAG.getConstant(255, dl, ExVT));
17006     return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
17007   }
17008
17009   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
17010   if (VT == MVT::v4i32) {
17011     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
17012            "Should not custom lower when pmuldq is available!");
17013
17014     // Extract the odd parts.
17015     static const int UnpackMask[] = { 1, -1, 3, -1 };
17016     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
17017     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
17018
17019     // Multiply the even parts.
17020     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
17021     // Now multiply odd parts.
17022     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
17023
17024     Evens = DAG.getBitcast(VT, Evens);
17025     Odds = DAG.getBitcast(VT, Odds);
17026
17027     // Merge the two vectors back together with a shuffle. This expands into 2
17028     // shuffles.
17029     static const int ShufMask[] = { 0, 4, 2, 6 };
17030     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
17031   }
17032
17033   assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
17034          "Only know how to lower V2I64/V4I64/V8I64 multiply");
17035
17036   //  Ahi = psrlqi(a, 32);
17037   //  Bhi = psrlqi(b, 32);
17038   //
17039   //  AloBlo = pmuludq(a, b);
17040   //  AloBhi = pmuludq(a, Bhi);
17041   //  AhiBlo = pmuludq(Ahi, b);
17042
17043   //  AloBhi = psllqi(AloBhi, 32);
17044   //  AhiBlo = psllqi(AhiBlo, 32);
17045   //  return AloBlo + AloBhi + AhiBlo;
17046
17047   SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
17048   SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
17049
17050   SDValue AhiBlo = Ahi;
17051   SDValue AloBhi = Bhi;
17052   // Bit cast to 32-bit vectors for MULUDQ
17053   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
17054                                   (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
17055   A = DAG.getBitcast(MulVT, A);
17056   B = DAG.getBitcast(MulVT, B);
17057   Ahi = DAG.getBitcast(MulVT, Ahi);
17058   Bhi = DAG.getBitcast(MulVT, Bhi);
17059
17060   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
17061   // After shifting right const values the result may be all-zero.
17062   if (!ISD::isBuildVectorAllZeros(Ahi.getNode())) {
17063     AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
17064     AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
17065   }
17066   if (!ISD::isBuildVectorAllZeros(Bhi.getNode())) {
17067     AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
17068     AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
17069   }
17070
17071   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
17072   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
17073 }
17074
17075 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
17076   assert(Subtarget->isTargetWin64() && "Unexpected target");
17077   EVT VT = Op.getValueType();
17078   assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
17079          "Unexpected return type for lowering");
17080
17081   RTLIB::Libcall LC;
17082   bool isSigned;
17083   switch (Op->getOpcode()) {
17084   default: llvm_unreachable("Unexpected request for libcall!");
17085   case ISD::SDIV:      isSigned = true;  LC = RTLIB::SDIV_I128;    break;
17086   case ISD::UDIV:      isSigned = false; LC = RTLIB::UDIV_I128;    break;
17087   case ISD::SREM:      isSigned = true;  LC = RTLIB::SREM_I128;    break;
17088   case ISD::UREM:      isSigned = false; LC = RTLIB::UREM_I128;    break;
17089   case ISD::SDIVREM:   isSigned = true;  LC = RTLIB::SDIVREM_I128; break;
17090   case ISD::UDIVREM:   isSigned = false; LC = RTLIB::UDIVREM_I128; break;
17091   }
17092
17093   SDLoc dl(Op);
17094   SDValue InChain = DAG.getEntryNode();
17095
17096   TargetLowering::ArgListTy Args;
17097   TargetLowering::ArgListEntry Entry;
17098   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
17099     EVT ArgVT = Op->getOperand(i).getValueType();
17100     assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
17101            "Unexpected argument type for lowering");
17102     SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
17103     Entry.Node = StackPtr;
17104     InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
17105                            false, false, 16);
17106     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
17107     Entry.Ty = PointerType::get(ArgTy,0);
17108     Entry.isSExt = false;
17109     Entry.isZExt = false;
17110     Args.push_back(Entry);
17111   }
17112
17113   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
17114                                          getPointerTy(DAG.getDataLayout()));
17115
17116   TargetLowering::CallLoweringInfo CLI(DAG);
17117   CLI.setDebugLoc(dl).setChain(InChain)
17118     .setCallee(getLibcallCallingConv(LC),
17119                static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
17120                Callee, std::move(Args), 0)
17121     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
17122
17123   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
17124   return DAG.getBitcast(VT, CallInfo.first);
17125 }
17126
17127 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
17128                              SelectionDAG &DAG) {
17129   SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
17130   EVT VT = Op0.getValueType();
17131   SDLoc dl(Op);
17132
17133   assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
17134          (VT == MVT::v8i32 && Subtarget->hasInt256()));
17135
17136   // PMULxD operations multiply each even value (starting at 0) of LHS with
17137   // the related value of RHS and produce a widen result.
17138   // E.g., PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
17139   // => <2 x i64> <ae|cg>
17140   //
17141   // In other word, to have all the results, we need to perform two PMULxD:
17142   // 1. one with the even values.
17143   // 2. one with the odd values.
17144   // To achieve #2, with need to place the odd values at an even position.
17145   //
17146   // Place the odd value at an even position (basically, shift all values 1
17147   // step to the left):
17148   const int Mask[] = {1, -1, 3, -1, 5, -1, 7, -1};
17149   // <a|b|c|d> => <b|undef|d|undef>
17150   SDValue Odd0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
17151   // <e|f|g|h> => <f|undef|h|undef>
17152   SDValue Odd1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
17153
17154   // Emit two multiplies, one for the lower 2 ints and one for the higher 2
17155   // ints.
17156   MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
17157   bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
17158   unsigned Opcode =
17159       (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
17160   // PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
17161   // => <2 x i64> <ae|cg>
17162   SDValue Mul1 = DAG.getBitcast(VT, DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
17163   // PMULUDQ <4 x i32> <b|undef|d|undef>, <4 x i32> <f|undef|h|undef>
17164   // => <2 x i64> <bf|dh>
17165   SDValue Mul2 = DAG.getBitcast(VT, DAG.getNode(Opcode, dl, MulVT, Odd0, Odd1));
17166
17167   // Shuffle it back into the right order.
17168   SDValue Highs, Lows;
17169   if (VT == MVT::v8i32) {
17170     const int HighMask[] = {1, 9, 3, 11, 5, 13, 7, 15};
17171     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
17172     const int LowMask[] = {0, 8, 2, 10, 4, 12, 6, 14};
17173     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
17174   } else {
17175     const int HighMask[] = {1, 5, 3, 7};
17176     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
17177     const int LowMask[] = {0, 4, 2, 6};
17178     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
17179   }
17180
17181   // If we have a signed multiply but no PMULDQ fix up the high parts of a
17182   // unsigned multiply.
17183   if (IsSigned && !Subtarget->hasSSE41()) {
17184     SDValue ShAmt = DAG.getConstant(
17185         31, dl,
17186         DAG.getTargetLoweringInfo().getShiftAmountTy(VT, DAG.getDataLayout()));
17187     SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
17188                              DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
17189     SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
17190                              DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
17191
17192     SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
17193     Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
17194   }
17195
17196   // The first result of MUL_LOHI is actually the low value, followed by the
17197   // high value.
17198   SDValue Ops[] = {Lows, Highs};
17199   return DAG.getMergeValues(Ops, dl);
17200 }
17201
17202 // Return true if the required (according to Opcode) shift-imm form is natively
17203 // supported by the Subtarget
17204 static bool SupportedVectorShiftWithImm(MVT VT, const X86Subtarget *Subtarget,
17205                                         unsigned Opcode) {
17206   if (VT.getScalarSizeInBits() < 16)
17207     return false;
17208
17209   if (VT.is512BitVector() &&
17210       (VT.getScalarSizeInBits() > 16 || Subtarget->hasBWI()))
17211     return true;
17212
17213   bool LShift = VT.is128BitVector() ||
17214     (VT.is256BitVector() && Subtarget->hasInt256());
17215
17216   bool AShift = LShift && (Subtarget->hasVLX() ||
17217     (VT != MVT::v2i64 && VT != MVT::v4i64));
17218   return (Opcode == ISD::SRA) ? AShift : LShift;
17219 }
17220
17221 // The shift amount is a variable, but it is the same for all vector lanes.
17222 // These instructions are defined together with shift-immediate.
17223 static
17224 bool SupportedVectorShiftWithBaseAmnt(MVT VT, const X86Subtarget *Subtarget,
17225                                       unsigned Opcode) {
17226   return SupportedVectorShiftWithImm(VT, Subtarget, Opcode);
17227 }
17228
17229 // Return true if the required (according to Opcode) variable-shift form is
17230 // natively supported by the Subtarget
17231 static bool SupportedVectorVarShift(MVT VT, const X86Subtarget *Subtarget,
17232                                     unsigned Opcode) {
17233
17234   if (!Subtarget->hasInt256() || VT.getScalarSizeInBits() < 16)
17235     return false;
17236
17237   // vXi16 supported only on AVX-512, BWI
17238   if (VT.getScalarSizeInBits() == 16 && !Subtarget->hasBWI())
17239     return false;
17240
17241   if (VT.is512BitVector() || Subtarget->hasVLX())
17242     return true;
17243
17244   bool LShift = VT.is128BitVector() || VT.is256BitVector();
17245   bool AShift = LShift &&  VT != MVT::v2i64 && VT != MVT::v4i64;
17246   return (Opcode == ISD::SRA) ? AShift : LShift;
17247 }
17248
17249 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
17250                                          const X86Subtarget *Subtarget) {
17251   MVT VT = Op.getSimpleValueType();
17252   SDLoc dl(Op);
17253   SDValue R = Op.getOperand(0);
17254   SDValue Amt = Op.getOperand(1);
17255
17256   unsigned X86Opc = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHLI :
17257     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRLI : X86ISD::VSRAI;
17258
17259   auto ArithmeticShiftRight64 = [&](uint64_t ShiftAmt) {
17260     assert((VT == MVT::v2i64 || VT == MVT::v4i64) && "Unexpected SRA type");
17261     MVT ExVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() * 2);
17262     SDValue Ex = DAG.getBitcast(ExVT, R);
17263
17264     if (ShiftAmt >= 32) {
17265       // Splat sign to upper i32 dst, and SRA upper i32 src to lower i32.
17266       SDValue Upper =
17267           getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex, 31, DAG);
17268       SDValue Lower = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex,
17269                                                  ShiftAmt - 32, DAG);
17270       if (VT == MVT::v2i64)
17271         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower, {5, 1, 7, 3});
17272       if (VT == MVT::v4i64)
17273         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower,
17274                                   {9, 1, 11, 3, 13, 5, 15, 7});
17275     } else {
17276       // SRA upper i32, SHL whole i64 and select lower i32.
17277       SDValue Upper = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex,
17278                                                  ShiftAmt, DAG);
17279       SDValue Lower =
17280           getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt, DAG);
17281       Lower = DAG.getBitcast(ExVT, Lower);
17282       if (VT == MVT::v2i64)
17283         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower, {4, 1, 6, 3});
17284       if (VT == MVT::v4i64)
17285         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower,
17286                                   {8, 1, 10, 3, 12, 5, 14, 7});
17287     }
17288     return DAG.getBitcast(VT, Ex);
17289   };
17290
17291   // Optimize shl/srl/sra with constant shift amount.
17292   if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
17293     if (auto *ShiftConst = BVAmt->getConstantSplatNode()) {
17294       uint64_t ShiftAmt = ShiftConst->getZExtValue();
17295
17296       if (SupportedVectorShiftWithImm(VT, Subtarget, Op.getOpcode()))
17297         return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
17298
17299       // i64 SRA needs to be performed as partial shifts.
17300       if ((VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
17301           Op.getOpcode() == ISD::SRA)
17302         return ArithmeticShiftRight64(ShiftAmt);
17303
17304       if (VT == MVT::v16i8 || (Subtarget->hasInt256() && VT == MVT::v32i8)) {
17305         unsigned NumElts = VT.getVectorNumElements();
17306         MVT ShiftVT = MVT::getVectorVT(MVT::i16, NumElts / 2);
17307
17308         if (Op.getOpcode() == ISD::SHL) {
17309           // Simple i8 add case
17310           if (ShiftAmt == 1)
17311             return DAG.getNode(ISD::ADD, dl, VT, R, R);
17312
17313           // Make a large shift.
17314           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, ShiftVT,
17315                                                    R, ShiftAmt, DAG);
17316           SHL = DAG.getBitcast(VT, SHL);
17317           // Zero out the rightmost bits.
17318           SmallVector<SDValue, 32> V(
17319               NumElts, DAG.getConstant(uint8_t(-1U << ShiftAmt), dl, MVT::i8));
17320           return DAG.getNode(ISD::AND, dl, VT, SHL,
17321                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
17322         }
17323         if (Op.getOpcode() == ISD::SRL) {
17324           // Make a large shift.
17325           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ShiftVT,
17326                                                    R, ShiftAmt, DAG);
17327           SRL = DAG.getBitcast(VT, SRL);
17328           // Zero out the leftmost bits.
17329           SmallVector<SDValue, 32> V(
17330               NumElts, DAG.getConstant(uint8_t(-1U) >> ShiftAmt, dl, MVT::i8));
17331           return DAG.getNode(ISD::AND, dl, VT, SRL,
17332                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
17333         }
17334         if (Op.getOpcode() == ISD::SRA) {
17335           if (ShiftAmt == 7) {
17336             // ashr(R, 7)  === cmp_slt(R, 0)
17337             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
17338             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
17339           }
17340
17341           // ashr(R, Amt) === sub(xor(lshr(R, Amt), Mask), Mask)
17342           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
17343           SmallVector<SDValue, 32> V(NumElts,
17344                                      DAG.getConstant(128 >> ShiftAmt, dl,
17345                                                      MVT::i8));
17346           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
17347           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
17348           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
17349           return Res;
17350         }
17351         llvm_unreachable("Unknown shift opcode.");
17352       }
17353     }
17354   }
17355
17356   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
17357   if (!Subtarget->is64Bit() &&
17358       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64))) {
17359
17360     // Peek through any splat that was introduced for i64 shift vectorization.
17361     int SplatIndex = -1;
17362     if (ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(Amt.getNode()))
17363       if (SVN->isSplat()) {
17364         SplatIndex = SVN->getSplatIndex();
17365         Amt = Amt.getOperand(0);
17366         assert(SplatIndex < (int)VT.getVectorNumElements() &&
17367                "Splat shuffle referencing second operand");
17368       }
17369
17370     if (Amt.getOpcode() != ISD::BITCAST ||
17371         Amt.getOperand(0).getOpcode() != ISD::BUILD_VECTOR)
17372       return SDValue();
17373
17374     Amt = Amt.getOperand(0);
17375     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
17376                      VT.getVectorNumElements();
17377     unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
17378     uint64_t ShiftAmt = 0;
17379     unsigned BaseOp = (SplatIndex < 0 ? 0 : SplatIndex * Ratio);
17380     for (unsigned i = 0; i != Ratio; ++i) {
17381       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i + BaseOp));
17382       if (!C)
17383         return SDValue();
17384       // 6 == Log2(64)
17385       ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
17386     }
17387
17388     // Check remaining shift amounts (if not a splat).
17389     if (SplatIndex < 0) {
17390       for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
17391         uint64_t ShAmt = 0;
17392         for (unsigned j = 0; j != Ratio; ++j) {
17393           ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
17394           if (!C)
17395             return SDValue();
17396           // 6 == Log2(64)
17397           ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
17398         }
17399         if (ShAmt != ShiftAmt)
17400           return SDValue();
17401       }
17402     }
17403
17404     if (SupportedVectorShiftWithImm(VT, Subtarget, Op.getOpcode()))
17405       return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
17406
17407     if (Op.getOpcode() == ISD::SRA)
17408       return ArithmeticShiftRight64(ShiftAmt);
17409   }
17410
17411   return SDValue();
17412 }
17413
17414 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
17415                                         const X86Subtarget* Subtarget) {
17416   MVT VT = Op.getSimpleValueType();
17417   SDLoc dl(Op);
17418   SDValue R = Op.getOperand(0);
17419   SDValue Amt = Op.getOperand(1);
17420
17421   unsigned X86OpcI = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHLI :
17422     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRLI : X86ISD::VSRAI;
17423
17424   unsigned X86OpcV = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHL :
17425     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRL : X86ISD::VSRA;
17426
17427   if (SupportedVectorShiftWithBaseAmnt(VT, Subtarget, Op.getOpcode())) {
17428     SDValue BaseShAmt;
17429     EVT EltVT = VT.getVectorElementType();
17430
17431     if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Amt)) {
17432       // Check if this build_vector node is doing a splat.
17433       // If so, then set BaseShAmt equal to the splat value.
17434       BaseShAmt = BV->getSplatValue();
17435       if (BaseShAmt && BaseShAmt.getOpcode() == ISD::UNDEF)
17436         BaseShAmt = SDValue();
17437     } else {
17438       if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
17439         Amt = Amt.getOperand(0);
17440
17441       ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(Amt);
17442       if (SVN && SVN->isSplat()) {
17443         unsigned SplatIdx = (unsigned)SVN->getSplatIndex();
17444         SDValue InVec = Amt.getOperand(0);
17445         if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
17446           assert((SplatIdx < InVec.getValueType().getVectorNumElements()) &&
17447                  "Unexpected shuffle index found!");
17448           BaseShAmt = InVec.getOperand(SplatIdx);
17449         } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
17450            if (ConstantSDNode *C =
17451                dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
17452              if (C->getZExtValue() == SplatIdx)
17453                BaseShAmt = InVec.getOperand(1);
17454            }
17455         }
17456
17457         if (!BaseShAmt)
17458           // Avoid introducing an extract element from a shuffle.
17459           BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, InVec,
17460                                   DAG.getIntPtrConstant(SplatIdx, dl));
17461       }
17462     }
17463
17464     if (BaseShAmt.getNode()) {
17465       assert(EltVT.bitsLE(MVT::i64) && "Unexpected element type!");
17466       if (EltVT != MVT::i64 && EltVT.bitsGT(MVT::i32))
17467         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, BaseShAmt);
17468       else if (EltVT.bitsLT(MVT::i32))
17469         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
17470
17471       return getTargetVShiftNode(X86OpcI, dl, VT, R, BaseShAmt, DAG);
17472     }
17473   }
17474
17475   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
17476   if (!Subtarget->is64Bit() && VT == MVT::v2i64  &&
17477       Amt.getOpcode() == ISD::BITCAST &&
17478       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
17479     Amt = Amt.getOperand(0);
17480     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
17481                      VT.getVectorNumElements();
17482     std::vector<SDValue> Vals(Ratio);
17483     for (unsigned i = 0; i != Ratio; ++i)
17484       Vals[i] = Amt.getOperand(i);
17485     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
17486       for (unsigned j = 0; j != Ratio; ++j)
17487         if (Vals[j] != Amt.getOperand(i + j))
17488           return SDValue();
17489     }
17490
17491     if (SupportedVectorShiftWithBaseAmnt(VT, Subtarget, Op.getOpcode()))
17492       return DAG.getNode(X86OpcV, dl, VT, R, Op.getOperand(1));
17493   }
17494   return SDValue();
17495 }
17496
17497 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
17498                           SelectionDAG &DAG) {
17499   MVT VT = Op.getSimpleValueType();
17500   SDLoc dl(Op);
17501   SDValue R = Op.getOperand(0);
17502   SDValue Amt = Op.getOperand(1);
17503
17504   assert(VT.isVector() && "Custom lowering only for vector shifts!");
17505   assert(Subtarget->hasSSE2() && "Only custom lower when we have SSE2!");
17506
17507   if (SDValue V = LowerScalarImmediateShift(Op, DAG, Subtarget))
17508     return V;
17509
17510   if (SDValue V = LowerScalarVariableShift(Op, DAG, Subtarget))
17511       return V;
17512
17513   if (SupportedVectorVarShift(VT, Subtarget, Op.getOpcode()))
17514     return Op;
17515
17516   // 2i64 vector logical shifts can efficiently avoid scalarization - do the
17517   // shifts per-lane and then shuffle the partial results back together.
17518   if (VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) {
17519     // Splat the shift amounts so the scalar shifts above will catch it.
17520     SDValue Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {0, 0});
17521     SDValue Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {1, 1});
17522     SDValue R0 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt0);
17523     SDValue R1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt1);
17524     return DAG.getVectorShuffle(VT, dl, R0, R1, {0, 3});
17525   }
17526
17527   // i64 vector arithmetic shift can be emulated with the transform:
17528   // M = lshr(SIGN_BIT, Amt)
17529   // ashr(R, Amt) === sub(xor(lshr(R, Amt), M), M)
17530   if ((VT == MVT::v2i64 || (VT == MVT::v4i64 && Subtarget->hasInt256())) &&
17531       Op.getOpcode() == ISD::SRA) {
17532     SDValue S = DAG.getConstant(APInt::getSignBit(64), dl, VT);
17533     SDValue M = DAG.getNode(ISD::SRL, dl, VT, S, Amt);
17534     R = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
17535     R = DAG.getNode(ISD::XOR, dl, VT, R, M);
17536     R = DAG.getNode(ISD::SUB, dl, VT, R, M);
17537     return R;
17538   }
17539
17540   // If possible, lower this packed shift into a vector multiply instead of
17541   // expanding it into a sequence of scalar shifts.
17542   // Do this only if the vector shift count is a constant build_vector.
17543   if (Op.getOpcode() == ISD::SHL &&
17544       (VT == MVT::v8i16 || VT == MVT::v4i32 ||
17545        (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
17546       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
17547     SmallVector<SDValue, 8> Elts;
17548     EVT SVT = VT.getScalarType();
17549     unsigned SVTBits = SVT.getSizeInBits();
17550     const APInt &One = APInt(SVTBits, 1);
17551     unsigned NumElems = VT.getVectorNumElements();
17552
17553     for (unsigned i=0; i !=NumElems; ++i) {
17554       SDValue Op = Amt->getOperand(i);
17555       if (Op->getOpcode() == ISD::UNDEF) {
17556         Elts.push_back(Op);
17557         continue;
17558       }
17559
17560       ConstantSDNode *ND = cast<ConstantSDNode>(Op);
17561       const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
17562       uint64_t ShAmt = C.getZExtValue();
17563       if (ShAmt >= SVTBits) {
17564         Elts.push_back(DAG.getUNDEF(SVT));
17565         continue;
17566       }
17567       Elts.push_back(DAG.getConstant(One.shl(ShAmt), dl, SVT));
17568     }
17569     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
17570     return DAG.getNode(ISD::MUL, dl, VT, R, BV);
17571   }
17572
17573   // Lower SHL with variable shift amount.
17574   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
17575     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, dl, VT));
17576
17577     Op = DAG.getNode(ISD::ADD, dl, VT, Op,
17578                      DAG.getConstant(0x3f800000U, dl, VT));
17579     Op = DAG.getBitcast(MVT::v4f32, Op);
17580     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
17581     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
17582   }
17583
17584   // If possible, lower this shift as a sequence of two shifts by
17585   // constant plus a MOVSS/MOVSD instead of scalarizing it.
17586   // Example:
17587   //   (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
17588   //
17589   // Could be rewritten as:
17590   //   (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
17591   //
17592   // The advantage is that the two shifts from the example would be
17593   // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
17594   // the vector shift into four scalar shifts plus four pairs of vector
17595   // insert/extract.
17596   if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
17597       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
17598     unsigned TargetOpcode = X86ISD::MOVSS;
17599     bool CanBeSimplified;
17600     // The splat value for the first packed shift (the 'X' from the example).
17601     SDValue Amt1 = Amt->getOperand(0);
17602     // The splat value for the second packed shift (the 'Y' from the example).
17603     SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
17604                                         Amt->getOperand(2);
17605
17606     // See if it is possible to replace this node with a sequence of
17607     // two shifts followed by a MOVSS/MOVSD
17608     if (VT == MVT::v4i32) {
17609       // Check if it is legal to use a MOVSS.
17610       CanBeSimplified = Amt2 == Amt->getOperand(2) &&
17611                         Amt2 == Amt->getOperand(3);
17612       if (!CanBeSimplified) {
17613         // Otherwise, check if we can still simplify this node using a MOVSD.
17614         CanBeSimplified = Amt1 == Amt->getOperand(1) &&
17615                           Amt->getOperand(2) == Amt->getOperand(3);
17616         TargetOpcode = X86ISD::MOVSD;
17617         Amt2 = Amt->getOperand(2);
17618       }
17619     } else {
17620       // Do similar checks for the case where the machine value type
17621       // is MVT::v8i16.
17622       CanBeSimplified = Amt1 == Amt->getOperand(1);
17623       for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
17624         CanBeSimplified = Amt2 == Amt->getOperand(i);
17625
17626       if (!CanBeSimplified) {
17627         TargetOpcode = X86ISD::MOVSD;
17628         CanBeSimplified = true;
17629         Amt2 = Amt->getOperand(4);
17630         for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
17631           CanBeSimplified = Amt1 == Amt->getOperand(i);
17632         for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
17633           CanBeSimplified = Amt2 == Amt->getOperand(j);
17634       }
17635     }
17636
17637     if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
17638         isa<ConstantSDNode>(Amt2)) {
17639       // Replace this node with two shifts followed by a MOVSS/MOVSD.
17640       EVT CastVT = MVT::v4i32;
17641       SDValue Splat1 =
17642         DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), dl, VT);
17643       SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
17644       SDValue Splat2 =
17645         DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), dl, VT);
17646       SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
17647       if (TargetOpcode == X86ISD::MOVSD)
17648         CastVT = MVT::v2i64;
17649       SDValue BitCast1 = DAG.getBitcast(CastVT, Shift1);
17650       SDValue BitCast2 = DAG.getBitcast(CastVT, Shift2);
17651       SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
17652                                             BitCast1, DAG);
17653       return DAG.getBitcast(VT, Result);
17654     }
17655   }
17656
17657   // v4i32 Non Uniform Shifts.
17658   // If the shift amount is constant we can shift each lane using the SSE2
17659   // immediate shifts, else we need to zero-extend each lane to the lower i64
17660   // and shift using the SSE2 variable shifts.
17661   // The separate results can then be blended together.
17662   if (VT == MVT::v4i32) {
17663     unsigned Opc = Op.getOpcode();
17664     SDValue Amt0, Amt1, Amt2, Amt3;
17665     if (ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
17666       Amt0 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {0, 0, 0, 0});
17667       Amt1 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {1, 1, 1, 1});
17668       Amt2 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {2, 2, 2, 2});
17669       Amt3 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {3, 3, 3, 3});
17670     } else {
17671       // ISD::SHL is handled above but we include it here for completeness.
17672       switch (Opc) {
17673       default:
17674         llvm_unreachable("Unknown target vector shift node");
17675       case ISD::SHL:
17676         Opc = X86ISD::VSHL;
17677         break;
17678       case ISD::SRL:
17679         Opc = X86ISD::VSRL;
17680         break;
17681       case ISD::SRA:
17682         Opc = X86ISD::VSRA;
17683         break;
17684       }
17685       // The SSE2 shifts use the lower i64 as the same shift amount for
17686       // all lanes and the upper i64 is ignored. These shuffle masks
17687       // optimally zero-extend each lanes on SSE2/SSE41/AVX targets.
17688       SDValue Z = getZeroVector(VT, Subtarget, DAG, dl);
17689       Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Z, {0, 4, -1, -1});
17690       Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Z, {1, 5, -1, -1});
17691       Amt2 = DAG.getVectorShuffle(VT, dl, Amt, Z, {2, 6, -1, -1});
17692       Amt3 = DAG.getVectorShuffle(VT, dl, Amt, Z, {3, 7, -1, -1});
17693     }
17694
17695     SDValue R0 = DAG.getNode(Opc, dl, VT, R, Amt0);
17696     SDValue R1 = DAG.getNode(Opc, dl, VT, R, Amt1);
17697     SDValue R2 = DAG.getNode(Opc, dl, VT, R, Amt2);
17698     SDValue R3 = DAG.getNode(Opc, dl, VT, R, Amt3);
17699     SDValue R02 = DAG.getVectorShuffle(VT, dl, R0, R2, {0, -1, 6, -1});
17700     SDValue R13 = DAG.getVectorShuffle(VT, dl, R1, R3, {-1, 1, -1, 7});
17701     return DAG.getVectorShuffle(VT, dl, R02, R13, {0, 5, 2, 7});
17702   }
17703
17704   if (VT == MVT::v16i8 || (VT == MVT::v32i8 && Subtarget->hasInt256())) {
17705     MVT ExtVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements() / 2);
17706     unsigned ShiftOpcode = Op->getOpcode();
17707
17708     auto SignBitSelect = [&](MVT SelVT, SDValue Sel, SDValue V0, SDValue V1) {
17709       // On SSE41 targets we make use of the fact that VSELECT lowers
17710       // to PBLENDVB which selects bytes based just on the sign bit.
17711       if (Subtarget->hasSSE41()) {
17712         V0 = DAG.getBitcast(VT, V0);
17713         V1 = DAG.getBitcast(VT, V1);
17714         Sel = DAG.getBitcast(VT, Sel);
17715         return DAG.getBitcast(SelVT,
17716                               DAG.getNode(ISD::VSELECT, dl, VT, Sel, V0, V1));
17717       }
17718       // On pre-SSE41 targets we test for the sign bit by comparing to
17719       // zero - a negative value will set all bits of the lanes to true
17720       // and VSELECT uses that in its OR(AND(V0,C),AND(V1,~C)) lowering.
17721       SDValue Z = getZeroVector(SelVT, Subtarget, DAG, dl);
17722       SDValue C = DAG.getNode(X86ISD::PCMPGT, dl, SelVT, Z, Sel);
17723       return DAG.getNode(ISD::VSELECT, dl, SelVT, C, V0, V1);
17724     };
17725
17726     // Turn 'a' into a mask suitable for VSELECT: a = a << 5;
17727     // We can safely do this using i16 shifts as we're only interested in
17728     // the 3 lower bits of each byte.
17729     Amt = DAG.getBitcast(ExtVT, Amt);
17730     Amt = DAG.getNode(ISD::SHL, dl, ExtVT, Amt, DAG.getConstant(5, dl, ExtVT));
17731     Amt = DAG.getBitcast(VT, Amt);
17732
17733     if (Op->getOpcode() == ISD::SHL || Op->getOpcode() == ISD::SRL) {
17734       // r = VSELECT(r, shift(r, 4), a);
17735       SDValue M =
17736           DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(4, dl, VT));
17737       R = SignBitSelect(VT, Amt, M, R);
17738
17739       // a += a
17740       Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
17741
17742       // r = VSELECT(r, shift(r, 2), a);
17743       M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(2, dl, VT));
17744       R = SignBitSelect(VT, Amt, M, R);
17745
17746       // a += a
17747       Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
17748
17749       // return VSELECT(r, shift(r, 1), a);
17750       M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(1, dl, VT));
17751       R = SignBitSelect(VT, Amt, M, R);
17752       return R;
17753     }
17754
17755     if (Op->getOpcode() == ISD::SRA) {
17756       // For SRA we need to unpack each byte to the higher byte of a i16 vector
17757       // so we can correctly sign extend. We don't care what happens to the
17758       // lower byte.
17759       SDValue ALo = DAG.getNode(X86ISD::UNPCKL, dl, VT, DAG.getUNDEF(VT), Amt);
17760       SDValue AHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, DAG.getUNDEF(VT), Amt);
17761       SDValue RLo = DAG.getNode(X86ISD::UNPCKL, dl, VT, DAG.getUNDEF(VT), R);
17762       SDValue RHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, DAG.getUNDEF(VT), R);
17763       ALo = DAG.getBitcast(ExtVT, ALo);
17764       AHi = DAG.getBitcast(ExtVT, AHi);
17765       RLo = DAG.getBitcast(ExtVT, RLo);
17766       RHi = DAG.getBitcast(ExtVT, RHi);
17767
17768       // r = VSELECT(r, shift(r, 4), a);
17769       SDValue MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
17770                                 DAG.getConstant(4, dl, ExtVT));
17771       SDValue MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
17772                                 DAG.getConstant(4, dl, ExtVT));
17773       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
17774       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
17775
17776       // a += a
17777       ALo = DAG.getNode(ISD::ADD, dl, ExtVT, ALo, ALo);
17778       AHi = DAG.getNode(ISD::ADD, dl, ExtVT, AHi, AHi);
17779
17780       // r = VSELECT(r, shift(r, 2), a);
17781       MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
17782                         DAG.getConstant(2, dl, ExtVT));
17783       MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
17784                         DAG.getConstant(2, dl, ExtVT));
17785       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
17786       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
17787
17788       // a += a
17789       ALo = DAG.getNode(ISD::ADD, dl, ExtVT, ALo, ALo);
17790       AHi = DAG.getNode(ISD::ADD, dl, ExtVT, AHi, AHi);
17791
17792       // r = VSELECT(r, shift(r, 1), a);
17793       MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
17794                         DAG.getConstant(1, dl, ExtVT));
17795       MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
17796                         DAG.getConstant(1, dl, ExtVT));
17797       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
17798       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
17799
17800       // Logical shift the result back to the lower byte, leaving a zero upper
17801       // byte
17802       // meaning that we can safely pack with PACKUSWB.
17803       RLo =
17804           DAG.getNode(ISD::SRL, dl, ExtVT, RLo, DAG.getConstant(8, dl, ExtVT));
17805       RHi =
17806           DAG.getNode(ISD::SRL, dl, ExtVT, RHi, DAG.getConstant(8, dl, ExtVT));
17807       return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
17808     }
17809   }
17810
17811   // It's worth extending once and using the v8i32 shifts for 16-bit types, but
17812   // the extra overheads to get from v16i8 to v8i32 make the existing SSE
17813   // solution better.
17814   if (Subtarget->hasInt256() && VT == MVT::v8i16) {
17815     MVT ExtVT = MVT::v8i32;
17816     unsigned ExtOpc =
17817         Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
17818     R = DAG.getNode(ExtOpc, dl, ExtVT, R);
17819     Amt = DAG.getNode(ISD::ANY_EXTEND, dl, ExtVT, Amt);
17820     return DAG.getNode(ISD::TRUNCATE, dl, VT,
17821                        DAG.getNode(Op.getOpcode(), dl, ExtVT, R, Amt));
17822   }
17823
17824   if (Subtarget->hasInt256() && VT == MVT::v16i16) {
17825     MVT ExtVT = MVT::v8i32;
17826     SDValue Z = getZeroVector(VT, Subtarget, DAG, dl);
17827     SDValue ALo = DAG.getNode(X86ISD::UNPCKL, dl, VT, Amt, Z);
17828     SDValue AHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, Amt, Z);
17829     SDValue RLo = DAG.getNode(X86ISD::UNPCKL, dl, VT, R, R);
17830     SDValue RHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, R, R);
17831     ALo = DAG.getBitcast(ExtVT, ALo);
17832     AHi = DAG.getBitcast(ExtVT, AHi);
17833     RLo = DAG.getBitcast(ExtVT, RLo);
17834     RHi = DAG.getBitcast(ExtVT, RHi);
17835     SDValue Lo = DAG.getNode(Op.getOpcode(), dl, ExtVT, RLo, ALo);
17836     SDValue Hi = DAG.getNode(Op.getOpcode(), dl, ExtVT, RHi, AHi);
17837     Lo = DAG.getNode(ISD::SRL, dl, ExtVT, Lo, DAG.getConstant(16, dl, ExtVT));
17838     Hi = DAG.getNode(ISD::SRL, dl, ExtVT, Hi, DAG.getConstant(16, dl, ExtVT));
17839     return DAG.getNode(X86ISD::PACKUS, dl, VT, Lo, Hi);
17840   }
17841
17842   if (VT == MVT::v8i16) {
17843     unsigned ShiftOpcode = Op->getOpcode();
17844
17845     auto SignBitSelect = [&](SDValue Sel, SDValue V0, SDValue V1) {
17846       // On SSE41 targets we make use of the fact that VSELECT lowers
17847       // to PBLENDVB which selects bytes based just on the sign bit.
17848       if (Subtarget->hasSSE41()) {
17849         MVT ExtVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() * 2);
17850         V0 = DAG.getBitcast(ExtVT, V0);
17851         V1 = DAG.getBitcast(ExtVT, V1);
17852         Sel = DAG.getBitcast(ExtVT, Sel);
17853         return DAG.getBitcast(
17854             VT, DAG.getNode(ISD::VSELECT, dl, ExtVT, Sel, V0, V1));
17855       }
17856       // On pre-SSE41 targets we splat the sign bit - a negative value will
17857       // set all bits of the lanes to true and VSELECT uses that in
17858       // its OR(AND(V0,C),AND(V1,~C)) lowering.
17859       SDValue C =
17860           DAG.getNode(ISD::SRA, dl, VT, Sel, DAG.getConstant(15, dl, VT));
17861       return DAG.getNode(ISD::VSELECT, dl, VT, C, V0, V1);
17862     };
17863
17864     // Turn 'a' into a mask suitable for VSELECT: a = a << 12;
17865     if (Subtarget->hasSSE41()) {
17866       // On SSE41 targets we need to replicate the shift mask in both
17867       // bytes for PBLENDVB.
17868       Amt = DAG.getNode(
17869           ISD::OR, dl, VT,
17870           DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(4, dl, VT)),
17871           DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(12, dl, VT)));
17872     } else {
17873       Amt = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(12, dl, VT));
17874     }
17875
17876     // r = VSELECT(r, shift(r, 8), a);
17877     SDValue M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(8, dl, VT));
17878     R = SignBitSelect(Amt, M, R);
17879
17880     // a += a
17881     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
17882
17883     // r = VSELECT(r, shift(r, 4), a);
17884     M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(4, dl, VT));
17885     R = SignBitSelect(Amt, M, R);
17886
17887     // a += a
17888     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
17889
17890     // r = VSELECT(r, shift(r, 2), a);
17891     M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(2, dl, VT));
17892     R = SignBitSelect(Amt, M, R);
17893
17894     // a += a
17895     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
17896
17897     // return VSELECT(r, shift(r, 1), a);
17898     M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(1, dl, VT));
17899     R = SignBitSelect(Amt, M, R);
17900     return R;
17901   }
17902
17903   // Decompose 256-bit shifts into smaller 128-bit shifts.
17904   if (VT.is256BitVector()) {
17905     unsigned NumElems = VT.getVectorNumElements();
17906     MVT EltVT = VT.getVectorElementType();
17907     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
17908
17909     // Extract the two vectors
17910     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
17911     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
17912
17913     // Recreate the shift amount vectors
17914     SDValue Amt1, Amt2;
17915     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
17916       // Constant shift amount
17917       SmallVector<SDValue, 8> Ops(Amt->op_begin(), Amt->op_begin() + NumElems);
17918       ArrayRef<SDValue> Amt1Csts = makeArrayRef(Ops).slice(0, NumElems / 2);
17919       ArrayRef<SDValue> Amt2Csts = makeArrayRef(Ops).slice(NumElems / 2);
17920
17921       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
17922       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
17923     } else {
17924       // Variable shift amount
17925       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
17926       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
17927     }
17928
17929     // Issue new vector shifts for the smaller types
17930     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
17931     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
17932
17933     // Concatenate the result back
17934     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
17935   }
17936
17937   return SDValue();
17938 }
17939
17940 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
17941   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
17942   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
17943   // looks for this combo and may remove the "setcc" instruction if the "setcc"
17944   // has only one use.
17945   SDNode *N = Op.getNode();
17946   SDValue LHS = N->getOperand(0);
17947   SDValue RHS = N->getOperand(1);
17948   unsigned BaseOp = 0;
17949   unsigned Cond = 0;
17950   SDLoc DL(Op);
17951   switch (Op.getOpcode()) {
17952   default: llvm_unreachable("Unknown ovf instruction!");
17953   case ISD::SADDO:
17954     // A subtract of one will be selected as a INC. Note that INC doesn't
17955     // set CF, so we can't do this for UADDO.
17956     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
17957       if (C->isOne()) {
17958         BaseOp = X86ISD::INC;
17959         Cond = X86::COND_O;
17960         break;
17961       }
17962     BaseOp = X86ISD::ADD;
17963     Cond = X86::COND_O;
17964     break;
17965   case ISD::UADDO:
17966     BaseOp = X86ISD::ADD;
17967     Cond = X86::COND_B;
17968     break;
17969   case ISD::SSUBO:
17970     // A subtract of one will be selected as a DEC. Note that DEC doesn't
17971     // set CF, so we can't do this for USUBO.
17972     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
17973       if (C->isOne()) {
17974         BaseOp = X86ISD::DEC;
17975         Cond = X86::COND_O;
17976         break;
17977       }
17978     BaseOp = X86ISD::SUB;
17979     Cond = X86::COND_O;
17980     break;
17981   case ISD::USUBO:
17982     BaseOp = X86ISD::SUB;
17983     Cond = X86::COND_B;
17984     break;
17985   case ISD::SMULO:
17986     BaseOp = N->getValueType(0) == MVT::i8 ? X86ISD::SMUL8 : X86ISD::SMUL;
17987     Cond = X86::COND_O;
17988     break;
17989   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
17990     if (N->getValueType(0) == MVT::i8) {
17991       BaseOp = X86ISD::UMUL8;
17992       Cond = X86::COND_O;
17993       break;
17994     }
17995     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
17996                                  MVT::i32);
17997     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
17998
17999     SDValue SetCC =
18000       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18001                   DAG.getConstant(X86::COND_O, DL, MVT::i32),
18002                   SDValue(Sum.getNode(), 2));
18003
18004     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
18005   }
18006   }
18007
18008   // Also sets EFLAGS.
18009   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
18010   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
18011
18012   SDValue SetCC =
18013     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
18014                 DAG.getConstant(Cond, DL, MVT::i32),
18015                 SDValue(Sum.getNode(), 1));
18016
18017   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
18018 }
18019
18020 /// Returns true if the operand type is exactly twice the native width, and
18021 /// the corresponding cmpxchg8b or cmpxchg16b instruction is available.
18022 /// Used to know whether to use cmpxchg8/16b when expanding atomic operations
18023 /// (otherwise we leave them alone to become __sync_fetch_and_... calls).
18024 bool X86TargetLowering::needsCmpXchgNb(Type *MemType) const {
18025   unsigned OpWidth = MemType->getPrimitiveSizeInBits();
18026
18027   if (OpWidth == 64)
18028     return !Subtarget->is64Bit(); // FIXME this should be Subtarget.hasCmpxchg8b
18029   else if (OpWidth == 128)
18030     return Subtarget->hasCmpxchg16b();
18031   else
18032     return false;
18033 }
18034
18035 bool X86TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
18036   return needsCmpXchgNb(SI->getValueOperand()->getType());
18037 }
18038
18039 // Note: this turns large loads into lock cmpxchg8b/16b.
18040 // FIXME: On 32 bits x86, fild/movq might be faster than lock cmpxchg8b.
18041 bool X86TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
18042   auto PTy = cast<PointerType>(LI->getPointerOperand()->getType());
18043   return needsCmpXchgNb(PTy->getElementType());
18044 }
18045
18046 TargetLoweringBase::AtomicRMWExpansionKind
18047 X86TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
18048   unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
18049   Type *MemType = AI->getType();
18050
18051   // If the operand is too big, we must see if cmpxchg8/16b is available
18052   // and default to library calls otherwise.
18053   if (MemType->getPrimitiveSizeInBits() > NativeWidth) {
18054     return needsCmpXchgNb(MemType) ? AtomicRMWExpansionKind::CmpXChg
18055                                    : AtomicRMWExpansionKind::None;
18056   }
18057
18058   AtomicRMWInst::BinOp Op = AI->getOperation();
18059   switch (Op) {
18060   default:
18061     llvm_unreachable("Unknown atomic operation");
18062   case AtomicRMWInst::Xchg:
18063   case AtomicRMWInst::Add:
18064   case AtomicRMWInst::Sub:
18065     // It's better to use xadd, xsub or xchg for these in all cases.
18066     return AtomicRMWExpansionKind::None;
18067   case AtomicRMWInst::Or:
18068   case AtomicRMWInst::And:
18069   case AtomicRMWInst::Xor:
18070     // If the atomicrmw's result isn't actually used, we can just add a "lock"
18071     // prefix to a normal instruction for these operations.
18072     return !AI->use_empty() ? AtomicRMWExpansionKind::CmpXChg
18073                             : AtomicRMWExpansionKind::None;
18074   case AtomicRMWInst::Nand:
18075   case AtomicRMWInst::Max:
18076   case AtomicRMWInst::Min:
18077   case AtomicRMWInst::UMax:
18078   case AtomicRMWInst::UMin:
18079     // These always require a non-trivial set of data operations on x86. We must
18080     // use a cmpxchg loop.
18081     return AtomicRMWExpansionKind::CmpXChg;
18082   }
18083 }
18084
18085 static bool hasMFENCE(const X86Subtarget& Subtarget) {
18086   // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
18087   // no-sse2). There isn't any reason to disable it if the target processor
18088   // supports it.
18089   return Subtarget.hasSSE2() || Subtarget.is64Bit();
18090 }
18091
18092 LoadInst *
18093 X86TargetLowering::lowerIdempotentRMWIntoFencedLoad(AtomicRMWInst *AI) const {
18094   unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
18095   Type *MemType = AI->getType();
18096   // Accesses larger than the native width are turned into cmpxchg/libcalls, so
18097   // there is no benefit in turning such RMWs into loads, and it is actually
18098   // harmful as it introduces a mfence.
18099   if (MemType->getPrimitiveSizeInBits() > NativeWidth)
18100     return nullptr;
18101
18102   auto Builder = IRBuilder<>(AI);
18103   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
18104   auto SynchScope = AI->getSynchScope();
18105   // We must restrict the ordering to avoid generating loads with Release or
18106   // ReleaseAcquire orderings.
18107   auto Order = AtomicCmpXchgInst::getStrongestFailureOrdering(AI->getOrdering());
18108   auto Ptr = AI->getPointerOperand();
18109
18110   // Before the load we need a fence. Here is an example lifted from
18111   // http://www.hpl.hp.com/techreports/2012/HPL-2012-68.pdf showing why a fence
18112   // is required:
18113   // Thread 0:
18114   //   x.store(1, relaxed);
18115   //   r1 = y.fetch_add(0, release);
18116   // Thread 1:
18117   //   y.fetch_add(42, acquire);
18118   //   r2 = x.load(relaxed);
18119   // r1 = r2 = 0 is impossible, but becomes possible if the idempotent rmw is
18120   // lowered to just a load without a fence. A mfence flushes the store buffer,
18121   // making the optimization clearly correct.
18122   // FIXME: it is required if isAtLeastRelease(Order) but it is not clear
18123   // otherwise, we might be able to be more aggressive on relaxed idempotent
18124   // rmw. In practice, they do not look useful, so we don't try to be
18125   // especially clever.
18126   if (SynchScope == SingleThread)
18127     // FIXME: we could just insert an X86ISD::MEMBARRIER here, except we are at
18128     // the IR level, so we must wrap it in an intrinsic.
18129     return nullptr;
18130
18131   if (!hasMFENCE(*Subtarget))
18132     // FIXME: it might make sense to use a locked operation here but on a
18133     // different cache-line to prevent cache-line bouncing. In practice it
18134     // is probably a small win, and x86 processors without mfence are rare
18135     // enough that we do not bother.
18136     return nullptr;
18137
18138   Function *MFence =
18139       llvm::Intrinsic::getDeclaration(M, Intrinsic::x86_sse2_mfence);
18140   Builder.CreateCall(MFence, {});
18141
18142   // Finally we can emit the atomic load.
18143   LoadInst *Loaded = Builder.CreateAlignedLoad(Ptr,
18144           AI->getType()->getPrimitiveSizeInBits());
18145   Loaded->setAtomic(Order, SynchScope);
18146   AI->replaceAllUsesWith(Loaded);
18147   AI->eraseFromParent();
18148   return Loaded;
18149 }
18150
18151 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
18152                                  SelectionDAG &DAG) {
18153   SDLoc dl(Op);
18154   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
18155     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
18156   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
18157     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
18158
18159   // The only fence that needs an instruction is a sequentially-consistent
18160   // cross-thread fence.
18161   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
18162     if (hasMFENCE(*Subtarget))
18163       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
18164
18165     SDValue Chain = Op.getOperand(0);
18166     SDValue Zero = DAG.getConstant(0, dl, MVT::i32);
18167     SDValue Ops[] = {
18168       DAG.getRegister(X86::ESP, MVT::i32),     // Base
18169       DAG.getTargetConstant(1, dl, MVT::i8),   // Scale
18170       DAG.getRegister(0, MVT::i32),            // Index
18171       DAG.getTargetConstant(0, dl, MVT::i32),  // Disp
18172       DAG.getRegister(0, MVT::i32),            // Segment.
18173       Zero,
18174       Chain
18175     };
18176     SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
18177     return SDValue(Res, 0);
18178   }
18179
18180   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
18181   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
18182 }
18183
18184 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
18185                              SelectionDAG &DAG) {
18186   MVT T = Op.getSimpleValueType();
18187   SDLoc DL(Op);
18188   unsigned Reg = 0;
18189   unsigned size = 0;
18190   switch(T.SimpleTy) {
18191   default: llvm_unreachable("Invalid value type!");
18192   case MVT::i8:  Reg = X86::AL;  size = 1; break;
18193   case MVT::i16: Reg = X86::AX;  size = 2; break;
18194   case MVT::i32: Reg = X86::EAX; size = 4; break;
18195   case MVT::i64:
18196     assert(Subtarget->is64Bit() && "Node not type legal!");
18197     Reg = X86::RAX; size = 8;
18198     break;
18199   }
18200   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
18201                                   Op.getOperand(2), SDValue());
18202   SDValue Ops[] = { cpIn.getValue(0),
18203                     Op.getOperand(1),
18204                     Op.getOperand(3),
18205                     DAG.getTargetConstant(size, DL, MVT::i8),
18206                     cpIn.getValue(1) };
18207   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
18208   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
18209   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
18210                                            Ops, T, MMO);
18211
18212   SDValue cpOut =
18213     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
18214   SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
18215                                       MVT::i32, cpOut.getValue(2));
18216   SDValue Success = DAG.getNode(X86ISD::SETCC, DL, Op->getValueType(1),
18217                                 DAG.getConstant(X86::COND_E, DL, MVT::i8),
18218                                 EFLAGS);
18219
18220   DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), cpOut);
18221   DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
18222   DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), EFLAGS.getValue(1));
18223   return SDValue();
18224 }
18225
18226 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
18227                             SelectionDAG &DAG) {
18228   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
18229   MVT DstVT = Op.getSimpleValueType();
18230
18231   if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
18232     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
18233     if (DstVT != MVT::f64)
18234       // This conversion needs to be expanded.
18235       return SDValue();
18236
18237     SDValue InVec = Op->getOperand(0);
18238     SDLoc dl(Op);
18239     unsigned NumElts = SrcVT.getVectorNumElements();
18240     EVT SVT = SrcVT.getVectorElementType();
18241
18242     // Widen the vector in input in the case of MVT::v2i32.
18243     // Example: from MVT::v2i32 to MVT::v4i32.
18244     SmallVector<SDValue, 16> Elts;
18245     for (unsigned i = 0, e = NumElts; i != e; ++i)
18246       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
18247                                  DAG.getIntPtrConstant(i, dl)));
18248
18249     // Explicitly mark the extra elements as Undef.
18250     Elts.append(NumElts, DAG.getUNDEF(SVT));
18251
18252     EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
18253     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
18254     SDValue ToV2F64 = DAG.getBitcast(MVT::v2f64, BV);
18255     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
18256                        DAG.getIntPtrConstant(0, dl));
18257   }
18258
18259   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
18260          Subtarget->hasMMX() && "Unexpected custom BITCAST");
18261   assert((DstVT == MVT::i64 ||
18262           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
18263          "Unexpected custom BITCAST");
18264   // i64 <=> MMX conversions are Legal.
18265   if (SrcVT==MVT::i64 && DstVT.isVector())
18266     return Op;
18267   if (DstVT==MVT::i64 && SrcVT.isVector())
18268     return Op;
18269   // MMX <=> MMX conversions are Legal.
18270   if (SrcVT.isVector() && DstVT.isVector())
18271     return Op;
18272   // All other conversions need to be expanded.
18273   return SDValue();
18274 }
18275
18276 /// Compute the horizontal sum of bytes in V for the elements of VT.
18277 ///
18278 /// Requires V to be a byte vector and VT to be an integer vector type with
18279 /// wider elements than V's type. The width of the elements of VT determines
18280 /// how many bytes of V are summed horizontally to produce each element of the
18281 /// result.
18282 static SDValue LowerHorizontalByteSum(SDValue V, MVT VT,
18283                                       const X86Subtarget *Subtarget,
18284                                       SelectionDAG &DAG) {
18285   SDLoc DL(V);
18286   MVT ByteVecVT = V.getSimpleValueType();
18287   MVT EltVT = VT.getVectorElementType();
18288   int NumElts = VT.getVectorNumElements();
18289   assert(ByteVecVT.getVectorElementType() == MVT::i8 &&
18290          "Expected value to have byte element type.");
18291   assert(EltVT != MVT::i8 &&
18292          "Horizontal byte sum only makes sense for wider elements!");
18293   unsigned VecSize = VT.getSizeInBits();
18294   assert(ByteVecVT.getSizeInBits() == VecSize && "Cannot change vector size!");
18295
18296   // PSADBW instruction horizontally add all bytes and leave the result in i64
18297   // chunks, thus directly computes the pop count for v2i64 and v4i64.
18298   if (EltVT == MVT::i64) {
18299     SDValue Zeros = getZeroVector(ByteVecVT, Subtarget, DAG, DL);
18300     V = DAG.getNode(X86ISD::PSADBW, DL, ByteVecVT, V, Zeros);
18301     return DAG.getBitcast(VT, V);
18302   }
18303
18304   if (EltVT == MVT::i32) {
18305     // We unpack the low half and high half into i32s interleaved with zeros so
18306     // that we can use PSADBW to horizontally sum them. The most useful part of
18307     // this is that it lines up the results of two PSADBW instructions to be
18308     // two v2i64 vectors which concatenated are the 4 population counts. We can
18309     // then use PACKUSWB to shrink and concatenate them into a v4i32 again.
18310     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, DL);
18311     SDValue Low = DAG.getNode(X86ISD::UNPCKL, DL, VT, V, Zeros);
18312     SDValue High = DAG.getNode(X86ISD::UNPCKH, DL, VT, V, Zeros);
18313
18314     // Do the horizontal sums into two v2i64s.
18315     Zeros = getZeroVector(ByteVecVT, Subtarget, DAG, DL);
18316     Low = DAG.getNode(X86ISD::PSADBW, DL, ByteVecVT,
18317                       DAG.getBitcast(ByteVecVT, Low), Zeros);
18318     High = DAG.getNode(X86ISD::PSADBW, DL, ByteVecVT,
18319                        DAG.getBitcast(ByteVecVT, High), Zeros);
18320
18321     // Merge them together.
18322     MVT ShortVecVT = MVT::getVectorVT(MVT::i16, VecSize / 16);
18323     V = DAG.getNode(X86ISD::PACKUS, DL, ByteVecVT,
18324                     DAG.getBitcast(ShortVecVT, Low),
18325                     DAG.getBitcast(ShortVecVT, High));
18326
18327     return DAG.getBitcast(VT, V);
18328   }
18329
18330   // The only element type left is i16.
18331   assert(EltVT == MVT::i16 && "Unknown how to handle type");
18332
18333   // To obtain pop count for each i16 element starting from the pop count for
18334   // i8 elements, shift the i16s left by 8, sum as i8s, and then shift as i16s
18335   // right by 8. It is important to shift as i16s as i8 vector shift isn't
18336   // directly supported.
18337   SmallVector<SDValue, 16> Shifters(NumElts, DAG.getConstant(8, DL, EltVT));
18338   SDValue Shifter = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Shifters);
18339   SDValue Shl = DAG.getNode(ISD::SHL, DL, VT, DAG.getBitcast(VT, V), Shifter);
18340   V = DAG.getNode(ISD::ADD, DL, ByteVecVT, DAG.getBitcast(ByteVecVT, Shl),
18341                   DAG.getBitcast(ByteVecVT, V));
18342   return DAG.getNode(ISD::SRL, DL, VT, DAG.getBitcast(VT, V), Shifter);
18343 }
18344
18345 static SDValue LowerVectorCTPOPInRegLUT(SDValue Op, SDLoc DL,
18346                                         const X86Subtarget *Subtarget,
18347                                         SelectionDAG &DAG) {
18348   MVT VT = Op.getSimpleValueType();
18349   MVT EltVT = VT.getVectorElementType();
18350   unsigned VecSize = VT.getSizeInBits();
18351
18352   // Implement a lookup table in register by using an algorithm based on:
18353   // http://wm.ite.pl/articles/sse-popcount.html
18354   //
18355   // The general idea is that every lower byte nibble in the input vector is an
18356   // index into a in-register pre-computed pop count table. We then split up the
18357   // input vector in two new ones: (1) a vector with only the shifted-right
18358   // higher nibbles for each byte and (2) a vector with the lower nibbles (and
18359   // masked out higher ones) for each byte. PSHUB is used separately with both
18360   // to index the in-register table. Next, both are added and the result is a
18361   // i8 vector where each element contains the pop count for input byte.
18362   //
18363   // To obtain the pop count for elements != i8, we follow up with the same
18364   // approach and use additional tricks as described below.
18365   //
18366   const int LUT[16] = {/* 0 */ 0, /* 1 */ 1, /* 2 */ 1, /* 3 */ 2,
18367                        /* 4 */ 1, /* 5 */ 2, /* 6 */ 2, /* 7 */ 3,
18368                        /* 8 */ 1, /* 9 */ 2, /* a */ 2, /* b */ 3,
18369                        /* c */ 2, /* d */ 3, /* e */ 3, /* f */ 4};
18370
18371   int NumByteElts = VecSize / 8;
18372   MVT ByteVecVT = MVT::getVectorVT(MVT::i8, NumByteElts);
18373   SDValue In = DAG.getBitcast(ByteVecVT, Op);
18374   SmallVector<SDValue, 16> LUTVec;
18375   for (int i = 0; i < NumByteElts; ++i)
18376     LUTVec.push_back(DAG.getConstant(LUT[i % 16], DL, MVT::i8));
18377   SDValue InRegLUT = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, LUTVec);
18378   SmallVector<SDValue, 16> Mask0F(NumByteElts,
18379                                   DAG.getConstant(0x0F, DL, MVT::i8));
18380   SDValue M0F = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, Mask0F);
18381
18382   // High nibbles
18383   SmallVector<SDValue, 16> Four(NumByteElts, DAG.getConstant(4, DL, MVT::i8));
18384   SDValue FourV = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, Four);
18385   SDValue HighNibbles = DAG.getNode(ISD::SRL, DL, ByteVecVT, In, FourV);
18386
18387   // Low nibbles
18388   SDValue LowNibbles = DAG.getNode(ISD::AND, DL, ByteVecVT, In, M0F);
18389
18390   // The input vector is used as the shuffle mask that index elements into the
18391   // LUT. After counting low and high nibbles, add the vector to obtain the
18392   // final pop count per i8 element.
18393   SDValue HighPopCnt =
18394       DAG.getNode(X86ISD::PSHUFB, DL, ByteVecVT, InRegLUT, HighNibbles);
18395   SDValue LowPopCnt =
18396       DAG.getNode(X86ISD::PSHUFB, DL, ByteVecVT, InRegLUT, LowNibbles);
18397   SDValue PopCnt = DAG.getNode(ISD::ADD, DL, ByteVecVT, HighPopCnt, LowPopCnt);
18398
18399   if (EltVT == MVT::i8)
18400     return PopCnt;
18401
18402   return LowerHorizontalByteSum(PopCnt, VT, Subtarget, DAG);
18403 }
18404
18405 static SDValue LowerVectorCTPOPBitmath(SDValue Op, SDLoc DL,
18406                                        const X86Subtarget *Subtarget,
18407                                        SelectionDAG &DAG) {
18408   MVT VT = Op.getSimpleValueType();
18409   assert(VT.is128BitVector() &&
18410          "Only 128-bit vector bitmath lowering supported.");
18411
18412   int VecSize = VT.getSizeInBits();
18413   MVT EltVT = VT.getVectorElementType();
18414   int Len = EltVT.getSizeInBits();
18415
18416   // This is the vectorized version of the "best" algorithm from
18417   // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
18418   // with a minor tweak to use a series of adds + shifts instead of vector
18419   // multiplications. Implemented for all integer vector types. We only use
18420   // this when we don't have SSSE3 which allows a LUT-based lowering that is
18421   // much faster, even faster than using native popcnt instructions.
18422
18423   auto GetShift = [&](unsigned OpCode, SDValue V, int Shifter) {
18424     MVT VT = V.getSimpleValueType();
18425     SmallVector<SDValue, 32> Shifters(
18426         VT.getVectorNumElements(),
18427         DAG.getConstant(Shifter, DL, VT.getVectorElementType()));
18428     return DAG.getNode(OpCode, DL, VT, V,
18429                        DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Shifters));
18430   };
18431   auto GetMask = [&](SDValue V, APInt Mask) {
18432     MVT VT = V.getSimpleValueType();
18433     SmallVector<SDValue, 32> Masks(
18434         VT.getVectorNumElements(),
18435         DAG.getConstant(Mask, DL, VT.getVectorElementType()));
18436     return DAG.getNode(ISD::AND, DL, VT, V,
18437                        DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Masks));
18438   };
18439
18440   // We don't want to incur the implicit masks required to SRL vNi8 vectors on
18441   // x86, so set the SRL type to have elements at least i16 wide. This is
18442   // correct because all of our SRLs are followed immediately by a mask anyways
18443   // that handles any bits that sneak into the high bits of the byte elements.
18444   MVT SrlVT = Len > 8 ? VT : MVT::getVectorVT(MVT::i16, VecSize / 16);
18445
18446   SDValue V = Op;
18447
18448   // v = v - ((v >> 1) & 0x55555555...)
18449   SDValue Srl =
18450       DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 1));
18451   SDValue And = GetMask(Srl, APInt::getSplat(Len, APInt(8, 0x55)));
18452   V = DAG.getNode(ISD::SUB, DL, VT, V, And);
18453
18454   // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...)
18455   SDValue AndLHS = GetMask(V, APInt::getSplat(Len, APInt(8, 0x33)));
18456   Srl = DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 2));
18457   SDValue AndRHS = GetMask(Srl, APInt::getSplat(Len, APInt(8, 0x33)));
18458   V = DAG.getNode(ISD::ADD, DL, VT, AndLHS, AndRHS);
18459
18460   // v = (v + (v >> 4)) & 0x0F0F0F0F...
18461   Srl = DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 4));
18462   SDValue Add = DAG.getNode(ISD::ADD, DL, VT, V, Srl);
18463   V = GetMask(Add, APInt::getSplat(Len, APInt(8, 0x0F)));
18464
18465   // At this point, V contains the byte-wise population count, and we are
18466   // merely doing a horizontal sum if necessary to get the wider element
18467   // counts.
18468   if (EltVT == MVT::i8)
18469     return V;
18470
18471   return LowerHorizontalByteSum(
18472       DAG.getBitcast(MVT::getVectorVT(MVT::i8, VecSize / 8), V), VT, Subtarget,
18473       DAG);
18474 }
18475
18476 static SDValue LowerVectorCTPOP(SDValue Op, const X86Subtarget *Subtarget,
18477                                 SelectionDAG &DAG) {
18478   MVT VT = Op.getSimpleValueType();
18479   // FIXME: Need to add AVX-512 support here!
18480   assert((VT.is256BitVector() || VT.is128BitVector()) &&
18481          "Unknown CTPOP type to handle");
18482   SDLoc DL(Op.getNode());
18483   SDValue Op0 = Op.getOperand(0);
18484
18485   if (!Subtarget->hasSSSE3()) {
18486     // We can't use the fast LUT approach, so fall back on vectorized bitmath.
18487     assert(VT.is128BitVector() && "Only 128-bit vectors supported in SSE!");
18488     return LowerVectorCTPOPBitmath(Op0, DL, Subtarget, DAG);
18489   }
18490
18491   if (VT.is256BitVector() && !Subtarget->hasInt256()) {
18492     unsigned NumElems = VT.getVectorNumElements();
18493
18494     // Extract each 128-bit vector, compute pop count and concat the result.
18495     SDValue LHS = Extract128BitVector(Op0, 0, DAG, DL);
18496     SDValue RHS = Extract128BitVector(Op0, NumElems/2, DAG, DL);
18497
18498     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT,
18499                        LowerVectorCTPOPInRegLUT(LHS, DL, Subtarget, DAG),
18500                        LowerVectorCTPOPInRegLUT(RHS, DL, Subtarget, DAG));
18501   }
18502
18503   return LowerVectorCTPOPInRegLUT(Op0, DL, Subtarget, DAG);
18504 }
18505
18506 static SDValue LowerCTPOP(SDValue Op, const X86Subtarget *Subtarget,
18507                           SelectionDAG &DAG) {
18508   assert(Op.getValueType().isVector() &&
18509          "We only do custom lowering for vector population count.");
18510   return LowerVectorCTPOP(Op, Subtarget, DAG);
18511 }
18512
18513 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
18514   SDNode *Node = Op.getNode();
18515   SDLoc dl(Node);
18516   EVT T = Node->getValueType(0);
18517   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
18518                               DAG.getConstant(0, dl, T), Node->getOperand(2));
18519   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
18520                        cast<AtomicSDNode>(Node)->getMemoryVT(),
18521                        Node->getOperand(0),
18522                        Node->getOperand(1), negOp,
18523                        cast<AtomicSDNode>(Node)->getMemOperand(),
18524                        cast<AtomicSDNode>(Node)->getOrdering(),
18525                        cast<AtomicSDNode>(Node)->getSynchScope());
18526 }
18527
18528 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
18529   SDNode *Node = Op.getNode();
18530   SDLoc dl(Node);
18531   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
18532
18533   // Convert seq_cst store -> xchg
18534   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
18535   // FIXME: On 32-bit, store -> fist or movq would be more efficient
18536   //        (The only way to get a 16-byte store is cmpxchg16b)
18537   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
18538   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
18539       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
18540     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
18541                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
18542                                  Node->getOperand(0),
18543                                  Node->getOperand(1), Node->getOperand(2),
18544                                  cast<AtomicSDNode>(Node)->getMemOperand(),
18545                                  cast<AtomicSDNode>(Node)->getOrdering(),
18546                                  cast<AtomicSDNode>(Node)->getSynchScope());
18547     return Swap.getValue(1);
18548   }
18549   // Other atomic stores have a simple pattern.
18550   return Op;
18551 }
18552
18553 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
18554   EVT VT = Op.getNode()->getSimpleValueType(0);
18555
18556   // Let legalize expand this if it isn't a legal type yet.
18557   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
18558     return SDValue();
18559
18560   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
18561
18562   unsigned Opc;
18563   bool ExtraOp = false;
18564   switch (Op.getOpcode()) {
18565   default: llvm_unreachable("Invalid code");
18566   case ISD::ADDC: Opc = X86ISD::ADD; break;
18567   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
18568   case ISD::SUBC: Opc = X86ISD::SUB; break;
18569   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
18570   }
18571
18572   if (!ExtraOp)
18573     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
18574                        Op.getOperand(1));
18575   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
18576                      Op.getOperand(1), Op.getOperand(2));
18577 }
18578
18579 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
18580                             SelectionDAG &DAG) {
18581   assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
18582
18583   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
18584   // which returns the values as { float, float } (in XMM0) or
18585   // { double, double } (which is returned in XMM0, XMM1).
18586   SDLoc dl(Op);
18587   SDValue Arg = Op.getOperand(0);
18588   EVT ArgVT = Arg.getValueType();
18589   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
18590
18591   TargetLowering::ArgListTy Args;
18592   TargetLowering::ArgListEntry Entry;
18593
18594   Entry.Node = Arg;
18595   Entry.Ty = ArgTy;
18596   Entry.isSExt = false;
18597   Entry.isZExt = false;
18598   Args.push_back(Entry);
18599
18600   bool isF64 = ArgVT == MVT::f64;
18601   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
18602   // the small struct {f32, f32} is returned in (eax, edx). For f64,
18603   // the results are returned via SRet in memory.
18604   const char *LibcallName =  isF64 ? "__sincos_stret" : "__sincosf_stret";
18605   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18606   SDValue Callee =
18607       DAG.getExternalSymbol(LibcallName, TLI.getPointerTy(DAG.getDataLayout()));
18608
18609   Type *RetTy = isF64
18610     ? (Type*)StructType::get(ArgTy, ArgTy, nullptr)
18611     : (Type*)VectorType::get(ArgTy, 4);
18612
18613   TargetLowering::CallLoweringInfo CLI(DAG);
18614   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
18615     .setCallee(CallingConv::C, RetTy, Callee, std::move(Args), 0);
18616
18617   std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
18618
18619   if (isF64)
18620     // Returned in xmm0 and xmm1.
18621     return CallResult.first;
18622
18623   // Returned in bits 0:31 and 32:64 xmm0.
18624   SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
18625                                CallResult.first, DAG.getIntPtrConstant(0, dl));
18626   SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
18627                                CallResult.first, DAG.getIntPtrConstant(1, dl));
18628   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
18629   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
18630 }
18631
18632 static SDValue LowerMSCATTER(SDValue Op, const X86Subtarget *Subtarget,
18633                              SelectionDAG &DAG) {
18634   assert(Subtarget->hasAVX512() &&
18635          "MGATHER/MSCATTER are supported on AVX-512 arch only");
18636
18637   MaskedScatterSDNode *N = cast<MaskedScatterSDNode>(Op.getNode());
18638   EVT VT = N->getValue().getValueType();
18639   assert(VT.getScalarSizeInBits() >= 32 && "Unsupported scatter op");
18640   SDLoc dl(Op);
18641
18642   // X86 scatter kills mask register, so its type should be added to
18643   // the list of return values
18644   if (N->getNumValues() == 1) {
18645     SDValue Index = N->getIndex();
18646     if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
18647         !Index.getValueType().is512BitVector())
18648       Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
18649
18650     SDVTList VTs = DAG.getVTList(N->getMask().getValueType(), MVT::Other);
18651     SDValue Ops[] = { N->getOperand(0), N->getOperand(1),  N->getOperand(2),
18652                       N->getOperand(3), Index };
18653
18654     SDValue NewScatter = DAG.getMaskedScatter(VTs, VT, dl, Ops, N->getMemOperand());
18655     DAG.ReplaceAllUsesWith(Op, SDValue(NewScatter.getNode(), 1));
18656     return SDValue(NewScatter.getNode(), 0);
18657   }
18658   return Op;
18659 }
18660
18661 static SDValue LowerMGATHER(SDValue Op, const X86Subtarget *Subtarget,
18662                             SelectionDAG &DAG) {
18663   assert(Subtarget->hasAVX512() &&
18664          "MGATHER/MSCATTER are supported on AVX-512 arch only");
18665
18666   MaskedGatherSDNode *N = cast<MaskedGatherSDNode>(Op.getNode());
18667   EVT VT = Op.getValueType();
18668   assert(VT.getScalarSizeInBits() >= 32 && "Unsupported gather op");
18669   SDLoc dl(Op);
18670
18671   SDValue Index = N->getIndex();
18672   if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
18673       !Index.getValueType().is512BitVector()) {
18674     Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
18675     SDValue Ops[] = { N->getOperand(0), N->getOperand(1),  N->getOperand(2),
18676                       N->getOperand(3), Index };
18677     DAG.UpdateNodeOperands(N, Ops);
18678   }
18679   return Op;
18680 }
18681
18682 SDValue X86TargetLowering::LowerGC_TRANSITION_START(SDValue Op,
18683                                                     SelectionDAG &DAG) const {
18684   // TODO: Eventually, the lowering of these nodes should be informed by or
18685   // deferred to the GC strategy for the function in which they appear. For
18686   // now, however, they must be lowered to something. Since they are logically
18687   // no-ops in the case of a null GC strategy (or a GC strategy which does not
18688   // require special handling for these nodes), lower them as literal NOOPs for
18689   // the time being.
18690   SmallVector<SDValue, 2> Ops;
18691
18692   Ops.push_back(Op.getOperand(0));
18693   if (Op->getGluedNode())
18694     Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
18695
18696   SDLoc OpDL(Op);
18697   SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
18698   SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
18699
18700   return NOOP;
18701 }
18702
18703 SDValue X86TargetLowering::LowerGC_TRANSITION_END(SDValue Op,
18704                                                   SelectionDAG &DAG) const {
18705   // TODO: Eventually, the lowering of these nodes should be informed by or
18706   // deferred to the GC strategy for the function in which they appear. For
18707   // now, however, they must be lowered to something. Since they are logically
18708   // no-ops in the case of a null GC strategy (or a GC strategy which does not
18709   // require special handling for these nodes), lower them as literal NOOPs for
18710   // the time being.
18711   SmallVector<SDValue, 2> Ops;
18712
18713   Ops.push_back(Op.getOperand(0));
18714   if (Op->getGluedNode())
18715     Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
18716
18717   SDLoc OpDL(Op);
18718   SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
18719   SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
18720
18721   return NOOP;
18722 }
18723
18724 /// LowerOperation - Provide custom lowering hooks for some operations.
18725 ///
18726 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
18727   switch (Op.getOpcode()) {
18728   default: llvm_unreachable("Should not custom lower this!");
18729   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
18730   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
18731     return LowerCMP_SWAP(Op, Subtarget, DAG);
18732   case ISD::CTPOP:              return LowerCTPOP(Op, Subtarget, DAG);
18733   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
18734   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
18735   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
18736   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, Subtarget, DAG);
18737   case ISD::VECTOR_SHUFFLE:     return lowerVectorShuffle(Op, Subtarget, DAG);
18738   case ISD::VSELECT:            return LowerVSELECT(Op, DAG);
18739   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
18740   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
18741   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
18742   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
18743   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
18744   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
18745   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
18746   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
18747   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
18748   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
18749   case ISD::SHL_PARTS:
18750   case ISD::SRA_PARTS:
18751   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
18752   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
18753   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
18754   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
18755   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, Subtarget, DAG);
18756   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, Subtarget, DAG);
18757   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, Subtarget, DAG);
18758   case ISD::SIGN_EXTEND_VECTOR_INREG:
18759     return LowerSIGN_EXTEND_VECTOR_INREG(Op, Subtarget, DAG);
18760   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
18761   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
18762   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
18763   case ISD::LOAD:               return LowerExtendedLoad(Op, Subtarget, DAG);
18764   case ISD::FABS:
18765   case ISD::FNEG:               return LowerFABSorFNEG(Op, DAG);
18766   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
18767   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
18768   case ISD::SETCC:              return LowerSETCC(Op, DAG);
18769   case ISD::SELECT:             return LowerSELECT(Op, DAG);
18770   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
18771   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
18772   case ISD::VASTART:            return LowerVASTART(Op, DAG);
18773   case ISD::VAARG:              return LowerVAARG(Op, DAG);
18774   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
18775   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, Subtarget, DAG);
18776   case ISD::INTRINSIC_VOID:
18777   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
18778   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
18779   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
18780   case ISD::FRAME_TO_ARGS_OFFSET:
18781                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
18782   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
18783   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
18784   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
18785   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
18786   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
18787   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
18788   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
18789   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
18790   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
18791   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
18792   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
18793   case ISD::UMUL_LOHI:
18794   case ISD::SMUL_LOHI:          return LowerMUL_LOHI(Op, Subtarget, DAG);
18795   case ISD::SRA:
18796   case ISD::SRL:
18797   case ISD::SHL:                return LowerShift(Op, Subtarget, DAG);
18798   case ISD::SADDO:
18799   case ISD::UADDO:
18800   case ISD::SSUBO:
18801   case ISD::USUBO:
18802   case ISD::SMULO:
18803   case ISD::UMULO:              return LowerXALUO(Op, DAG);
18804   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
18805   case ISD::BITCAST:            return LowerBITCAST(Op, Subtarget, DAG);
18806   case ISD::ADDC:
18807   case ISD::ADDE:
18808   case ISD::SUBC:
18809   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
18810   case ISD::ADD:                return LowerADD(Op, DAG);
18811   case ISD::SUB:                return LowerSUB(Op, DAG);
18812   case ISD::SMAX:
18813   case ISD::SMIN:
18814   case ISD::UMAX:
18815   case ISD::UMIN:               return LowerMINMAX(Op, DAG);
18816   case ISD::FSINCOS:            return LowerFSINCOS(Op, Subtarget, DAG);
18817   case ISD::MGATHER:            return LowerMGATHER(Op, Subtarget, DAG);
18818   case ISD::MSCATTER:           return LowerMSCATTER(Op, Subtarget, DAG);
18819   case ISD::GC_TRANSITION_START:
18820                                 return LowerGC_TRANSITION_START(Op, DAG);
18821   case ISD::GC_TRANSITION_END:  return LowerGC_TRANSITION_END(Op, DAG);
18822   }
18823 }
18824
18825 /// ReplaceNodeResults - Replace a node with an illegal result type
18826 /// with a new node built out of custom code.
18827 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
18828                                            SmallVectorImpl<SDValue>&Results,
18829                                            SelectionDAG &DAG) const {
18830   SDLoc dl(N);
18831   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18832   switch (N->getOpcode()) {
18833   default:
18834     llvm_unreachable("Do not know how to custom type legalize this operation!");
18835   // We might have generated v2f32 FMIN/FMAX operations. Widen them to v4f32.
18836   case X86ISD::FMINC:
18837   case X86ISD::FMIN:
18838   case X86ISD::FMAXC:
18839   case X86ISD::FMAX: {
18840     EVT VT = N->getValueType(0);
18841     if (VT != MVT::v2f32)
18842       llvm_unreachable("Unexpected type (!= v2f32) on FMIN/FMAX.");
18843     SDValue UNDEF = DAG.getUNDEF(VT);
18844     SDValue LHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
18845                               N->getOperand(0), UNDEF);
18846     SDValue RHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
18847                               N->getOperand(1), UNDEF);
18848     Results.push_back(DAG.getNode(N->getOpcode(), dl, MVT::v4f32, LHS, RHS));
18849     return;
18850   }
18851   case ISD::SIGN_EXTEND_INREG:
18852   case ISD::ADDC:
18853   case ISD::ADDE:
18854   case ISD::SUBC:
18855   case ISD::SUBE:
18856     // We don't want to expand or promote these.
18857     return;
18858   case ISD::SDIV:
18859   case ISD::UDIV:
18860   case ISD::SREM:
18861   case ISD::UREM:
18862   case ISD::SDIVREM:
18863   case ISD::UDIVREM: {
18864     SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
18865     Results.push_back(V);
18866     return;
18867   }
18868   case ISD::FP_TO_SINT:
18869     // FP_TO_INT*_IN_MEM is not legal for f16 inputs.  Do not convert
18870     // (FP_TO_SINT (load f16)) to FP_TO_INT*.
18871     if (N->getOperand(0).getValueType() == MVT::f16)
18872       break;
18873     // fallthrough
18874   case ISD::FP_TO_UINT: {
18875     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
18876
18877     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
18878       return;
18879
18880     std::pair<SDValue,SDValue> Vals =
18881         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
18882     SDValue FIST = Vals.first, StackSlot = Vals.second;
18883     if (FIST.getNode()) {
18884       EVT VT = N->getValueType(0);
18885       // Return a load from the stack slot.
18886       if (StackSlot.getNode())
18887         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
18888                                       MachinePointerInfo(),
18889                                       false, false, false, 0));
18890       else
18891         Results.push_back(FIST);
18892     }
18893     return;
18894   }
18895   case ISD::UINT_TO_FP: {
18896     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
18897     if (N->getOperand(0).getValueType() != MVT::v2i32 ||
18898         N->getValueType(0) != MVT::v2f32)
18899       return;
18900     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
18901                                  N->getOperand(0));
18902     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
18903                                      MVT::f64);
18904     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
18905     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
18906                              DAG.getBitcast(MVT::v2i64, VBias));
18907     Or = DAG.getBitcast(MVT::v2f64, Or);
18908     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
18909     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
18910     return;
18911   }
18912   case ISD::FP_ROUND: {
18913     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
18914         return;
18915     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
18916     Results.push_back(V);
18917     return;
18918   }
18919   case ISD::FP_EXTEND: {
18920     // Right now, only MVT::v2f32 has OperationAction for FP_EXTEND.
18921     // No other ValueType for FP_EXTEND should reach this point.
18922     assert(N->getValueType(0) == MVT::v2f32 &&
18923            "Do not know how to legalize this Node");
18924     return;
18925   }
18926   case ISD::INTRINSIC_W_CHAIN: {
18927     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
18928     switch (IntNo) {
18929     default : llvm_unreachable("Do not know how to custom type "
18930                                "legalize this intrinsic operation!");
18931     case Intrinsic::x86_rdtsc:
18932       return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
18933                                      Results);
18934     case Intrinsic::x86_rdtscp:
18935       return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
18936                                      Results);
18937     case Intrinsic::x86_rdpmc:
18938       return getReadPerformanceCounter(N, dl, DAG, Subtarget, Results);
18939     }
18940   }
18941   case ISD::READCYCLECOUNTER: {
18942     return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
18943                                    Results);
18944   }
18945   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
18946     EVT T = N->getValueType(0);
18947     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
18948     bool Regs64bit = T == MVT::i128;
18949     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
18950     SDValue cpInL, cpInH;
18951     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
18952                         DAG.getConstant(0, dl, HalfT));
18953     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
18954                         DAG.getConstant(1, dl, HalfT));
18955     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
18956                              Regs64bit ? X86::RAX : X86::EAX,
18957                              cpInL, SDValue());
18958     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
18959                              Regs64bit ? X86::RDX : X86::EDX,
18960                              cpInH, cpInL.getValue(1));
18961     SDValue swapInL, swapInH;
18962     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
18963                           DAG.getConstant(0, dl, HalfT));
18964     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
18965                           DAG.getConstant(1, dl, HalfT));
18966     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
18967                                Regs64bit ? X86::RBX : X86::EBX,
18968                                swapInL, cpInH.getValue(1));
18969     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
18970                                Regs64bit ? X86::RCX : X86::ECX,
18971                                swapInH, swapInL.getValue(1));
18972     SDValue Ops[] = { swapInH.getValue(0),
18973                       N->getOperand(1),
18974                       swapInH.getValue(1) };
18975     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
18976     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
18977     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
18978                                   X86ISD::LCMPXCHG8_DAG;
18979     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
18980     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
18981                                         Regs64bit ? X86::RAX : X86::EAX,
18982                                         HalfT, Result.getValue(1));
18983     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
18984                                         Regs64bit ? X86::RDX : X86::EDX,
18985                                         HalfT, cpOutL.getValue(2));
18986     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
18987
18988     SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
18989                                         MVT::i32, cpOutH.getValue(2));
18990     SDValue Success =
18991         DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
18992                     DAG.getConstant(X86::COND_E, dl, MVT::i8), EFLAGS);
18993     Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
18994
18995     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
18996     Results.push_back(Success);
18997     Results.push_back(EFLAGS.getValue(1));
18998     return;
18999   }
19000   case ISD::ATOMIC_SWAP:
19001   case ISD::ATOMIC_LOAD_ADD:
19002   case ISD::ATOMIC_LOAD_SUB:
19003   case ISD::ATOMIC_LOAD_AND:
19004   case ISD::ATOMIC_LOAD_OR:
19005   case ISD::ATOMIC_LOAD_XOR:
19006   case ISD::ATOMIC_LOAD_NAND:
19007   case ISD::ATOMIC_LOAD_MIN:
19008   case ISD::ATOMIC_LOAD_MAX:
19009   case ISD::ATOMIC_LOAD_UMIN:
19010   case ISD::ATOMIC_LOAD_UMAX:
19011   case ISD::ATOMIC_LOAD: {
19012     // Delegate to generic TypeLegalization. Situations we can really handle
19013     // should have already been dealt with by AtomicExpandPass.cpp.
19014     break;
19015   }
19016   case ISD::BITCAST: {
19017     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
19018     EVT DstVT = N->getValueType(0);
19019     EVT SrcVT = N->getOperand(0)->getValueType(0);
19020
19021     if (SrcVT != MVT::f64 ||
19022         (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
19023       return;
19024
19025     unsigned NumElts = DstVT.getVectorNumElements();
19026     EVT SVT = DstVT.getVectorElementType();
19027     EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
19028     SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
19029                                    MVT::v2f64, N->getOperand(0));
19030     SDValue ToVecInt = DAG.getBitcast(WiderVT, Expanded);
19031
19032     if (ExperimentalVectorWideningLegalization) {
19033       // If we are legalizing vectors by widening, we already have the desired
19034       // legal vector type, just return it.
19035       Results.push_back(ToVecInt);
19036       return;
19037     }
19038
19039     SmallVector<SDValue, 8> Elts;
19040     for (unsigned i = 0, e = NumElts; i != e; ++i)
19041       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
19042                                    ToVecInt, DAG.getIntPtrConstant(i, dl)));
19043
19044     Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
19045   }
19046   }
19047 }
19048
19049 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
19050   switch ((X86ISD::NodeType)Opcode) {
19051   case X86ISD::FIRST_NUMBER:       break;
19052   case X86ISD::BSF:                return "X86ISD::BSF";
19053   case X86ISD::BSR:                return "X86ISD::BSR";
19054   case X86ISD::SHLD:               return "X86ISD::SHLD";
19055   case X86ISD::SHRD:               return "X86ISD::SHRD";
19056   case X86ISD::FAND:               return "X86ISD::FAND";
19057   case X86ISD::FANDN:              return "X86ISD::FANDN";
19058   case X86ISD::FOR:                return "X86ISD::FOR";
19059   case X86ISD::FXOR:               return "X86ISD::FXOR";
19060   case X86ISD::FILD:               return "X86ISD::FILD";
19061   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
19062   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
19063   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
19064   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
19065   case X86ISD::FLD:                return "X86ISD::FLD";
19066   case X86ISD::FST:                return "X86ISD::FST";
19067   case X86ISD::CALL:               return "X86ISD::CALL";
19068   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
19069   case X86ISD::RDTSCP_DAG:         return "X86ISD::RDTSCP_DAG";
19070   case X86ISD::RDPMC_DAG:          return "X86ISD::RDPMC_DAG";
19071   case X86ISD::BT:                 return "X86ISD::BT";
19072   case X86ISD::CMP:                return "X86ISD::CMP";
19073   case X86ISD::COMI:               return "X86ISD::COMI";
19074   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
19075   case X86ISD::CMPM:               return "X86ISD::CMPM";
19076   case X86ISD::CMPMU:              return "X86ISD::CMPMU";
19077   case X86ISD::CMPM_RND:           return "X86ISD::CMPM_RND";
19078   case X86ISD::SETCC:              return "X86ISD::SETCC";
19079   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
19080   case X86ISD::FSETCC:             return "X86ISD::FSETCC";
19081   case X86ISD::FGETSIGNx86:        return "X86ISD::FGETSIGNx86";
19082   case X86ISD::CMOV:               return "X86ISD::CMOV";
19083   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
19084   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
19085   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
19086   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
19087   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
19088   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
19089   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
19090   case X86ISD::MOVDQ2Q:            return "X86ISD::MOVDQ2Q";
19091   case X86ISD::MMX_MOVD2W:         return "X86ISD::MMX_MOVD2W";
19092   case X86ISD::MMX_MOVW2D:         return "X86ISD::MMX_MOVW2D";
19093   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
19094   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
19095   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
19096   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
19097   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
19098   case X86ISD::MMX_PINSRW:         return "X86ISD::MMX_PINSRW";
19099   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
19100   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
19101   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
19102   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
19103   case X86ISD::SHRUNKBLEND:        return "X86ISD::SHRUNKBLEND";
19104   case X86ISD::ADDUS:              return "X86ISD::ADDUS";
19105   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
19106   case X86ISD::HADD:               return "X86ISD::HADD";
19107   case X86ISD::HSUB:               return "X86ISD::HSUB";
19108   case X86ISD::FHADD:              return "X86ISD::FHADD";
19109   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
19110   case X86ISD::ABS:                return "X86ISD::ABS";
19111   case X86ISD::FMAX:               return "X86ISD::FMAX";
19112   case X86ISD::FMAX_RND:           return "X86ISD::FMAX_RND";
19113   case X86ISD::FMIN:               return "X86ISD::FMIN";
19114   case X86ISD::FMIN_RND:           return "X86ISD::FMIN_RND";
19115   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
19116   case X86ISD::FMINC:              return "X86ISD::FMINC";
19117   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
19118   case X86ISD::FRCP:               return "X86ISD::FRCP";
19119   case X86ISD::EXTRQI:             return "X86ISD::EXTRQI";
19120   case X86ISD::INSERTQI:           return "X86ISD::INSERTQI";
19121   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
19122   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
19123   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
19124   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
19125   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
19126   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
19127   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
19128   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
19129   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
19130   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
19131   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
19132   case X86ISD::LCMPXCHG16_DAG:     return "X86ISD::LCMPXCHG16_DAG";
19133   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
19134   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
19135   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
19136   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
19137   case X86ISD::VTRUNC:             return "X86ISD::VTRUNC";
19138   case X86ISD::VTRUNCS:            return "X86ISD::VTRUNCS";
19139   case X86ISD::VTRUNCUS:           return "X86ISD::VTRUNCUS";
19140   case X86ISD::VINSERT:            return "X86ISD::VINSERT";
19141   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
19142   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
19143   case X86ISD::CVTDQ2PD:           return "X86ISD::CVTDQ2PD";
19144   case X86ISD::CVTUDQ2PD:          return "X86ISD::CVTUDQ2PD";
19145   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
19146   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
19147   case X86ISD::VSHL:               return "X86ISD::VSHL";
19148   case X86ISD::VSRL:               return "X86ISD::VSRL";
19149   case X86ISD::VSRA:               return "X86ISD::VSRA";
19150   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
19151   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
19152   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
19153   case X86ISD::CMPP:               return "X86ISD::CMPP";
19154   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
19155   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
19156   case X86ISD::PCMPEQM:            return "X86ISD::PCMPEQM";
19157   case X86ISD::PCMPGTM:            return "X86ISD::PCMPGTM";
19158   case X86ISD::ADD:                return "X86ISD::ADD";
19159   case X86ISD::SUB:                return "X86ISD::SUB";
19160   case X86ISD::ADC:                return "X86ISD::ADC";
19161   case X86ISD::SBB:                return "X86ISD::SBB";
19162   case X86ISD::SMUL:               return "X86ISD::SMUL";
19163   case X86ISD::UMUL:               return "X86ISD::UMUL";
19164   case X86ISD::SMUL8:              return "X86ISD::SMUL8";
19165   case X86ISD::UMUL8:              return "X86ISD::UMUL8";
19166   case X86ISD::SDIVREM8_SEXT_HREG: return "X86ISD::SDIVREM8_SEXT_HREG";
19167   case X86ISD::UDIVREM8_ZEXT_HREG: return "X86ISD::UDIVREM8_ZEXT_HREG";
19168   case X86ISD::INC:                return "X86ISD::INC";
19169   case X86ISD::DEC:                return "X86ISD::DEC";
19170   case X86ISD::OR:                 return "X86ISD::OR";
19171   case X86ISD::XOR:                return "X86ISD::XOR";
19172   case X86ISD::AND:                return "X86ISD::AND";
19173   case X86ISD::BEXTR:              return "X86ISD::BEXTR";
19174   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
19175   case X86ISD::PTEST:              return "X86ISD::PTEST";
19176   case X86ISD::TESTP:              return "X86ISD::TESTP";
19177   case X86ISD::TESTM:              return "X86ISD::TESTM";
19178   case X86ISD::TESTNM:             return "X86ISD::TESTNM";
19179   case X86ISD::KORTEST:            return "X86ISD::KORTEST";
19180   case X86ISD::PACKSS:             return "X86ISD::PACKSS";
19181   case X86ISD::PACKUS:             return "X86ISD::PACKUS";
19182   case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
19183   case X86ISD::VALIGN:             return "X86ISD::VALIGN";
19184   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
19185   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
19186   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
19187   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
19188   case X86ISD::SHUF128:            return "X86ISD::SHUF128";
19189   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
19190   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
19191   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
19192   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
19193   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
19194   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
19195   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
19196   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
19197   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
19198   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
19199   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
19200   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
19201   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
19202   case X86ISD::SUBV_BROADCAST:     return "X86ISD::SUBV_BROADCAST";
19203   case X86ISD::VEXTRACT:           return "X86ISD::VEXTRACT";
19204   case X86ISD::VPERMILPV:          return "X86ISD::VPERMILPV";
19205   case X86ISD::VPERMILPI:          return "X86ISD::VPERMILPI";
19206   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
19207   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
19208   case X86ISD::VPERMV3:            return "X86ISD::VPERMV3";
19209   case X86ISD::VPERMIV3:           return "X86ISD::VPERMIV3";
19210   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
19211   case X86ISD::VFIXUPIMM:          return "X86ISD::VFIXUPIMM";
19212   case X86ISD::VRANGE:             return "X86ISD::VRANGE";
19213   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
19214   case X86ISD::PMULDQ:             return "X86ISD::PMULDQ";
19215   case X86ISD::PSADBW:             return "X86ISD::PSADBW";
19216   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
19217   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
19218   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
19219   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
19220   case X86ISD::MFENCE:             return "X86ISD::MFENCE";
19221   case X86ISD::SFENCE:             return "X86ISD::SFENCE";
19222   case X86ISD::LFENCE:             return "X86ISD::LFENCE";
19223   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
19224   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
19225   case X86ISD::SAHF:               return "X86ISD::SAHF";
19226   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
19227   case X86ISD::RDSEED:             return "X86ISD::RDSEED";
19228   case X86ISD::VPMADDUBSW:         return "X86ISD::VPMADDUBSW";
19229   case X86ISD::VPMADDWD:           return "X86ISD::VPMADDWD";
19230   case X86ISD::FMADD:              return "X86ISD::FMADD";
19231   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
19232   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
19233   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
19234   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
19235   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
19236   case X86ISD::FMADD_RND:          return "X86ISD::FMADD_RND";
19237   case X86ISD::FNMADD_RND:         return "X86ISD::FNMADD_RND";
19238   case X86ISD::FMSUB_RND:          return "X86ISD::FMSUB_RND";
19239   case X86ISD::FNMSUB_RND:         return "X86ISD::FNMSUB_RND";
19240   case X86ISD::FMADDSUB_RND:       return "X86ISD::FMADDSUB_RND";
19241   case X86ISD::FMSUBADD_RND:       return "X86ISD::FMSUBADD_RND";
19242   case X86ISD::VRNDSCALE:          return "X86ISD::VRNDSCALE";
19243   case X86ISD::VREDUCE:            return "X86ISD::VREDUCE";
19244   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
19245   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
19246   case X86ISD::XTEST:              return "X86ISD::XTEST";
19247   case X86ISD::COMPRESS:           return "X86ISD::COMPRESS";
19248   case X86ISD::EXPAND:             return "X86ISD::EXPAND";
19249   case X86ISD::SELECT:             return "X86ISD::SELECT";
19250   case X86ISD::ADDSUB:             return "X86ISD::ADDSUB";
19251   case X86ISD::RCP28:              return "X86ISD::RCP28";
19252   case X86ISD::EXP2:               return "X86ISD::EXP2";
19253   case X86ISD::RSQRT28:            return "X86ISD::RSQRT28";
19254   case X86ISD::FADD_RND:           return "X86ISD::FADD_RND";
19255   case X86ISD::FSUB_RND:           return "X86ISD::FSUB_RND";
19256   case X86ISD::FMUL_RND:           return "X86ISD::FMUL_RND";
19257   case X86ISD::FDIV_RND:           return "X86ISD::FDIV_RND";
19258   case X86ISD::FSQRT_RND:          return "X86ISD::FSQRT_RND";
19259   case X86ISD::FGETEXP_RND:        return "X86ISD::FGETEXP_RND";
19260   case X86ISD::SCALEF:             return "X86ISD::SCALEF";
19261   case X86ISD::ADDS:               return "X86ISD::ADDS";
19262   case X86ISD::SUBS:               return "X86ISD::SUBS";
19263   case X86ISD::AVG:                return "X86ISD::AVG";
19264   case X86ISD::MULHRS:             return "X86ISD::MULHRS";
19265   case X86ISD::SINT_TO_FP_RND:     return "X86ISD::SINT_TO_FP_RND";
19266   case X86ISD::UINT_TO_FP_RND:     return "X86ISD::UINT_TO_FP_RND";
19267   case X86ISD::FP_TO_SINT_RND:     return "X86ISD::FP_TO_SINT_RND";
19268   case X86ISD::FP_TO_UINT_RND:     return "X86ISD::FP_TO_UINT_RND";
19269   }
19270   return nullptr;
19271 }
19272
19273 // isLegalAddressingMode - Return true if the addressing mode represented
19274 // by AM is legal for this target, for a load/store of the specified type.
19275 bool X86TargetLowering::isLegalAddressingMode(const DataLayout &DL,
19276                                               const AddrMode &AM, Type *Ty,
19277                                               unsigned AS) const {
19278   // X86 supports extremely general addressing modes.
19279   CodeModel::Model M = getTargetMachine().getCodeModel();
19280   Reloc::Model R = getTargetMachine().getRelocationModel();
19281
19282   // X86 allows a sign-extended 32-bit immediate field as a displacement.
19283   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
19284     return false;
19285
19286   if (AM.BaseGV) {
19287     unsigned GVFlags =
19288       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
19289
19290     // If a reference to this global requires an extra load, we can't fold it.
19291     if (isGlobalStubReference(GVFlags))
19292       return false;
19293
19294     // If BaseGV requires a register for the PIC base, we cannot also have a
19295     // BaseReg specified.
19296     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
19297       return false;
19298
19299     // If lower 4G is not available, then we must use rip-relative addressing.
19300     if ((M != CodeModel::Small || R != Reloc::Static) &&
19301         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
19302       return false;
19303   }
19304
19305   switch (AM.Scale) {
19306   case 0:
19307   case 1:
19308   case 2:
19309   case 4:
19310   case 8:
19311     // These scales always work.
19312     break;
19313   case 3:
19314   case 5:
19315   case 9:
19316     // These scales are formed with basereg+scalereg.  Only accept if there is
19317     // no basereg yet.
19318     if (AM.HasBaseReg)
19319       return false;
19320     break;
19321   default:  // Other stuff never works.
19322     return false;
19323   }
19324
19325   return true;
19326 }
19327
19328 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
19329   unsigned Bits = Ty->getScalarSizeInBits();
19330
19331   // 8-bit shifts are always expensive, but versions with a scalar amount aren't
19332   // particularly cheaper than those without.
19333   if (Bits == 8)
19334     return false;
19335
19336   // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
19337   // variable shifts just as cheap as scalar ones.
19338   if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
19339     return false;
19340
19341   // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
19342   // fully general vector.
19343   return true;
19344 }
19345
19346 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
19347   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
19348     return false;
19349   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
19350   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
19351   return NumBits1 > NumBits2;
19352 }
19353
19354 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
19355   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
19356     return false;
19357
19358   if (!isTypeLegal(EVT::getEVT(Ty1)))
19359     return false;
19360
19361   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
19362
19363   // Assuming the caller doesn't have a zeroext or signext return parameter,
19364   // truncation all the way down to i1 is valid.
19365   return true;
19366 }
19367
19368 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
19369   return isInt<32>(Imm);
19370 }
19371
19372 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
19373   // Can also use sub to handle negated immediates.
19374   return isInt<32>(Imm);
19375 }
19376
19377 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
19378   if (!VT1.isInteger() || !VT2.isInteger())
19379     return false;
19380   unsigned NumBits1 = VT1.getSizeInBits();
19381   unsigned NumBits2 = VT2.getSizeInBits();
19382   return NumBits1 > NumBits2;
19383 }
19384
19385 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
19386   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
19387   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
19388 }
19389
19390 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
19391   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
19392   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
19393 }
19394
19395 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
19396   EVT VT1 = Val.getValueType();
19397   if (isZExtFree(VT1, VT2))
19398     return true;
19399
19400   if (Val.getOpcode() != ISD::LOAD)
19401     return false;
19402
19403   if (!VT1.isSimple() || !VT1.isInteger() ||
19404       !VT2.isSimple() || !VT2.isInteger())
19405     return false;
19406
19407   switch (VT1.getSimpleVT().SimpleTy) {
19408   default: break;
19409   case MVT::i8:
19410   case MVT::i16:
19411   case MVT::i32:
19412     // X86 has 8, 16, and 32-bit zero-extending loads.
19413     return true;
19414   }
19415
19416   return false;
19417 }
19418
19419 bool X86TargetLowering::isVectorLoadExtDesirable(SDValue) const { return true; }
19420
19421 bool
19422 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
19423   if (!(Subtarget->hasFMA() || Subtarget->hasFMA4() || Subtarget->hasAVX512()))
19424     return false;
19425
19426   VT = VT.getScalarType();
19427
19428   if (!VT.isSimple())
19429     return false;
19430
19431   switch (VT.getSimpleVT().SimpleTy) {
19432   case MVT::f32:
19433   case MVT::f64:
19434     return true;
19435   default:
19436     break;
19437   }
19438
19439   return false;
19440 }
19441
19442 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
19443   // i16 instructions are longer (0x66 prefix) and potentially slower.
19444   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
19445 }
19446
19447 /// isShuffleMaskLegal - Targets can use this to indicate that they only
19448 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
19449 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
19450 /// are assumed to be legal.
19451 bool
19452 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
19453                                       EVT VT) const {
19454   if (!VT.isSimple())
19455     return false;
19456
19457   // Not for i1 vectors
19458   if (VT.getScalarType() == MVT::i1)
19459     return false;
19460
19461   // Very little shuffling can be done for 64-bit vectors right now.
19462   if (VT.getSizeInBits() == 64)
19463     return false;
19464
19465   // We only care that the types being shuffled are legal. The lowering can
19466   // handle any possible shuffle mask that results.
19467   return isTypeLegal(VT.getSimpleVT());
19468 }
19469
19470 bool
19471 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
19472                                           EVT VT) const {
19473   // Just delegate to the generic legality, clear masks aren't special.
19474   return isShuffleMaskLegal(Mask, VT);
19475 }
19476
19477 //===----------------------------------------------------------------------===//
19478 //                           X86 Scheduler Hooks
19479 //===----------------------------------------------------------------------===//
19480
19481 /// Utility function to emit xbegin specifying the start of an RTM region.
19482 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
19483                                      const TargetInstrInfo *TII) {
19484   DebugLoc DL = MI->getDebugLoc();
19485
19486   const BasicBlock *BB = MBB->getBasicBlock();
19487   MachineFunction::iterator I = MBB;
19488   ++I;
19489
19490   // For the v = xbegin(), we generate
19491   //
19492   // thisMBB:
19493   //  xbegin sinkMBB
19494   //
19495   // mainMBB:
19496   //  eax = -1
19497   //
19498   // sinkMBB:
19499   //  v = eax
19500
19501   MachineBasicBlock *thisMBB = MBB;
19502   MachineFunction *MF = MBB->getParent();
19503   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
19504   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
19505   MF->insert(I, mainMBB);
19506   MF->insert(I, sinkMBB);
19507
19508   // Transfer the remainder of BB and its successor edges to sinkMBB.
19509   sinkMBB->splice(sinkMBB->begin(), MBB,
19510                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
19511   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
19512
19513   // thisMBB:
19514   //  xbegin sinkMBB
19515   //  # fallthrough to mainMBB
19516   //  # abortion to sinkMBB
19517   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
19518   thisMBB->addSuccessor(mainMBB);
19519   thisMBB->addSuccessor(sinkMBB);
19520
19521   // mainMBB:
19522   //  EAX = -1
19523   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
19524   mainMBB->addSuccessor(sinkMBB);
19525
19526   // sinkMBB:
19527   // EAX is live into the sinkMBB
19528   sinkMBB->addLiveIn(X86::EAX);
19529   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
19530           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
19531     .addReg(X86::EAX);
19532
19533   MI->eraseFromParent();
19534   return sinkMBB;
19535 }
19536
19537 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
19538 // or XMM0_V32I8 in AVX all of this code can be replaced with that
19539 // in the .td file.
19540 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
19541                                        const TargetInstrInfo *TII) {
19542   unsigned Opc;
19543   switch (MI->getOpcode()) {
19544   default: llvm_unreachable("illegal opcode!");
19545   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
19546   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
19547   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
19548   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
19549   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
19550   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
19551   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
19552   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
19553   }
19554
19555   DebugLoc dl = MI->getDebugLoc();
19556   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
19557
19558   unsigned NumArgs = MI->getNumOperands();
19559   for (unsigned i = 1; i < NumArgs; ++i) {
19560     MachineOperand &Op = MI->getOperand(i);
19561     if (!(Op.isReg() && Op.isImplicit()))
19562       MIB.addOperand(Op);
19563   }
19564   if (MI->hasOneMemOperand())
19565     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
19566
19567   BuildMI(*BB, MI, dl,
19568     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
19569     .addReg(X86::XMM0);
19570
19571   MI->eraseFromParent();
19572   return BB;
19573 }
19574
19575 // FIXME: Custom handling because TableGen doesn't support multiple implicit
19576 // defs in an instruction pattern
19577 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
19578                                        const TargetInstrInfo *TII) {
19579   unsigned Opc;
19580   switch (MI->getOpcode()) {
19581   default: llvm_unreachable("illegal opcode!");
19582   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
19583   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
19584   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
19585   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
19586   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
19587   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
19588   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
19589   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
19590   }
19591
19592   DebugLoc dl = MI->getDebugLoc();
19593   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
19594
19595   unsigned NumArgs = MI->getNumOperands(); // remove the results
19596   for (unsigned i = 1; i < NumArgs; ++i) {
19597     MachineOperand &Op = MI->getOperand(i);
19598     if (!(Op.isReg() && Op.isImplicit()))
19599       MIB.addOperand(Op);
19600   }
19601   if (MI->hasOneMemOperand())
19602     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
19603
19604   BuildMI(*BB, MI, dl,
19605     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
19606     .addReg(X86::ECX);
19607
19608   MI->eraseFromParent();
19609   return BB;
19610 }
19611
19612 static MachineBasicBlock *EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
19613                                       const X86Subtarget *Subtarget) {
19614   DebugLoc dl = MI->getDebugLoc();
19615   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19616   // Address into RAX/EAX, other two args into ECX, EDX.
19617   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
19618   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
19619   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
19620   for (int i = 0; i < X86::AddrNumOperands; ++i)
19621     MIB.addOperand(MI->getOperand(i));
19622
19623   unsigned ValOps = X86::AddrNumOperands;
19624   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
19625     .addReg(MI->getOperand(ValOps).getReg());
19626   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
19627     .addReg(MI->getOperand(ValOps+1).getReg());
19628
19629   // The instruction doesn't actually take any operands though.
19630   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
19631
19632   MI->eraseFromParent(); // The pseudo is gone now.
19633   return BB;
19634 }
19635
19636 MachineBasicBlock *
19637 X86TargetLowering::EmitVAARG64WithCustomInserter(MachineInstr *MI,
19638                                                  MachineBasicBlock *MBB) const {
19639   // Emit va_arg instruction on X86-64.
19640
19641   // Operands to this pseudo-instruction:
19642   // 0  ) Output        : destination address (reg)
19643   // 1-5) Input         : va_list address (addr, i64mem)
19644   // 6  ) ArgSize       : Size (in bytes) of vararg type
19645   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
19646   // 8  ) Align         : Alignment of type
19647   // 9  ) EFLAGS (implicit-def)
19648
19649   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
19650   static_assert(X86::AddrNumOperands == 5,
19651                 "VAARG_64 assumes 5 address operands");
19652
19653   unsigned DestReg = MI->getOperand(0).getReg();
19654   MachineOperand &Base = MI->getOperand(1);
19655   MachineOperand &Scale = MI->getOperand(2);
19656   MachineOperand &Index = MI->getOperand(3);
19657   MachineOperand &Disp = MI->getOperand(4);
19658   MachineOperand &Segment = MI->getOperand(5);
19659   unsigned ArgSize = MI->getOperand(6).getImm();
19660   unsigned ArgMode = MI->getOperand(7).getImm();
19661   unsigned Align = MI->getOperand(8).getImm();
19662
19663   // Memory Reference
19664   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
19665   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
19666   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
19667
19668   // Machine Information
19669   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19670   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
19671   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
19672   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
19673   DebugLoc DL = MI->getDebugLoc();
19674
19675   // struct va_list {
19676   //   i32   gp_offset
19677   //   i32   fp_offset
19678   //   i64   overflow_area (address)
19679   //   i64   reg_save_area (address)
19680   // }
19681   // sizeof(va_list) = 24
19682   // alignment(va_list) = 8
19683
19684   unsigned TotalNumIntRegs = 6;
19685   unsigned TotalNumXMMRegs = 8;
19686   bool UseGPOffset = (ArgMode == 1);
19687   bool UseFPOffset = (ArgMode == 2);
19688   unsigned MaxOffset = TotalNumIntRegs * 8 +
19689                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
19690
19691   /* Align ArgSize to a multiple of 8 */
19692   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
19693   bool NeedsAlign = (Align > 8);
19694
19695   MachineBasicBlock *thisMBB = MBB;
19696   MachineBasicBlock *overflowMBB;
19697   MachineBasicBlock *offsetMBB;
19698   MachineBasicBlock *endMBB;
19699
19700   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
19701   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
19702   unsigned OffsetReg = 0;
19703
19704   if (!UseGPOffset && !UseFPOffset) {
19705     // If we only pull from the overflow region, we don't create a branch.
19706     // We don't need to alter control flow.
19707     OffsetDestReg = 0; // unused
19708     OverflowDestReg = DestReg;
19709
19710     offsetMBB = nullptr;
19711     overflowMBB = thisMBB;
19712     endMBB = thisMBB;
19713   } else {
19714     // First emit code to check if gp_offset (or fp_offset) is below the bound.
19715     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
19716     // If not, pull from overflow_area. (branch to overflowMBB)
19717     //
19718     //       thisMBB
19719     //         |     .
19720     //         |        .
19721     //     offsetMBB   overflowMBB
19722     //         |        .
19723     //         |     .
19724     //        endMBB
19725
19726     // Registers for the PHI in endMBB
19727     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
19728     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
19729
19730     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
19731     MachineFunction *MF = MBB->getParent();
19732     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
19733     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
19734     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
19735
19736     MachineFunction::iterator MBBIter = MBB;
19737     ++MBBIter;
19738
19739     // Insert the new basic blocks
19740     MF->insert(MBBIter, offsetMBB);
19741     MF->insert(MBBIter, overflowMBB);
19742     MF->insert(MBBIter, endMBB);
19743
19744     // Transfer the remainder of MBB and its successor edges to endMBB.
19745     endMBB->splice(endMBB->begin(), thisMBB,
19746                    std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
19747     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
19748
19749     // Make offsetMBB and overflowMBB successors of thisMBB
19750     thisMBB->addSuccessor(offsetMBB);
19751     thisMBB->addSuccessor(overflowMBB);
19752
19753     // endMBB is a successor of both offsetMBB and overflowMBB
19754     offsetMBB->addSuccessor(endMBB);
19755     overflowMBB->addSuccessor(endMBB);
19756
19757     // Load the offset value into a register
19758     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
19759     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
19760       .addOperand(Base)
19761       .addOperand(Scale)
19762       .addOperand(Index)
19763       .addDisp(Disp, UseFPOffset ? 4 : 0)
19764       .addOperand(Segment)
19765       .setMemRefs(MMOBegin, MMOEnd);
19766
19767     // Check if there is enough room left to pull this argument.
19768     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
19769       .addReg(OffsetReg)
19770       .addImm(MaxOffset + 8 - ArgSizeA8);
19771
19772     // Branch to "overflowMBB" if offset >= max
19773     // Fall through to "offsetMBB" otherwise
19774     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
19775       .addMBB(overflowMBB);
19776   }
19777
19778   // In offsetMBB, emit code to use the reg_save_area.
19779   if (offsetMBB) {
19780     assert(OffsetReg != 0);
19781
19782     // Read the reg_save_area address.
19783     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
19784     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
19785       .addOperand(Base)
19786       .addOperand(Scale)
19787       .addOperand(Index)
19788       .addDisp(Disp, 16)
19789       .addOperand(Segment)
19790       .setMemRefs(MMOBegin, MMOEnd);
19791
19792     // Zero-extend the offset
19793     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
19794       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
19795         .addImm(0)
19796         .addReg(OffsetReg)
19797         .addImm(X86::sub_32bit);
19798
19799     // Add the offset to the reg_save_area to get the final address.
19800     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
19801       .addReg(OffsetReg64)
19802       .addReg(RegSaveReg);
19803
19804     // Compute the offset for the next argument
19805     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
19806     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
19807       .addReg(OffsetReg)
19808       .addImm(UseFPOffset ? 16 : 8);
19809
19810     // Store it back into the va_list.
19811     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
19812       .addOperand(Base)
19813       .addOperand(Scale)
19814       .addOperand(Index)
19815       .addDisp(Disp, UseFPOffset ? 4 : 0)
19816       .addOperand(Segment)
19817       .addReg(NextOffsetReg)
19818       .setMemRefs(MMOBegin, MMOEnd);
19819
19820     // Jump to endMBB
19821     BuildMI(offsetMBB, DL, TII->get(X86::JMP_1))
19822       .addMBB(endMBB);
19823   }
19824
19825   //
19826   // Emit code to use overflow area
19827   //
19828
19829   // Load the overflow_area address into a register.
19830   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
19831   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
19832     .addOperand(Base)
19833     .addOperand(Scale)
19834     .addOperand(Index)
19835     .addDisp(Disp, 8)
19836     .addOperand(Segment)
19837     .setMemRefs(MMOBegin, MMOEnd);
19838
19839   // If we need to align it, do so. Otherwise, just copy the address
19840   // to OverflowDestReg.
19841   if (NeedsAlign) {
19842     // Align the overflow address
19843     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
19844     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
19845
19846     // aligned_addr = (addr + (align-1)) & ~(align-1)
19847     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
19848       .addReg(OverflowAddrReg)
19849       .addImm(Align-1);
19850
19851     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
19852       .addReg(TmpReg)
19853       .addImm(~(uint64_t)(Align-1));
19854   } else {
19855     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
19856       .addReg(OverflowAddrReg);
19857   }
19858
19859   // Compute the next overflow address after this argument.
19860   // (the overflow address should be kept 8-byte aligned)
19861   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
19862   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
19863     .addReg(OverflowDestReg)
19864     .addImm(ArgSizeA8);
19865
19866   // Store the new overflow address.
19867   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
19868     .addOperand(Base)
19869     .addOperand(Scale)
19870     .addOperand(Index)
19871     .addDisp(Disp, 8)
19872     .addOperand(Segment)
19873     .addReg(NextAddrReg)
19874     .setMemRefs(MMOBegin, MMOEnd);
19875
19876   // If we branched, emit the PHI to the front of endMBB.
19877   if (offsetMBB) {
19878     BuildMI(*endMBB, endMBB->begin(), DL,
19879             TII->get(X86::PHI), DestReg)
19880       .addReg(OffsetDestReg).addMBB(offsetMBB)
19881       .addReg(OverflowDestReg).addMBB(overflowMBB);
19882   }
19883
19884   // Erase the pseudo instruction
19885   MI->eraseFromParent();
19886
19887   return endMBB;
19888 }
19889
19890 MachineBasicBlock *
19891 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
19892                                                  MachineInstr *MI,
19893                                                  MachineBasicBlock *MBB) const {
19894   // Emit code to save XMM registers to the stack. The ABI says that the
19895   // number of registers to save is given in %al, so it's theoretically
19896   // possible to do an indirect jump trick to avoid saving all of them,
19897   // however this code takes a simpler approach and just executes all
19898   // of the stores if %al is non-zero. It's less code, and it's probably
19899   // easier on the hardware branch predictor, and stores aren't all that
19900   // expensive anyway.
19901
19902   // Create the new basic blocks. One block contains all the XMM stores,
19903   // and one block is the final destination regardless of whether any
19904   // stores were performed.
19905   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
19906   MachineFunction *F = MBB->getParent();
19907   MachineFunction::iterator MBBIter = MBB;
19908   ++MBBIter;
19909   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
19910   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
19911   F->insert(MBBIter, XMMSaveMBB);
19912   F->insert(MBBIter, EndMBB);
19913
19914   // Transfer the remainder of MBB and its successor edges to EndMBB.
19915   EndMBB->splice(EndMBB->begin(), MBB,
19916                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
19917   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
19918
19919   // The original block will now fall through to the XMM save block.
19920   MBB->addSuccessor(XMMSaveMBB);
19921   // The XMMSaveMBB will fall through to the end block.
19922   XMMSaveMBB->addSuccessor(EndMBB);
19923
19924   // Now add the instructions.
19925   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19926   DebugLoc DL = MI->getDebugLoc();
19927
19928   unsigned CountReg = MI->getOperand(0).getReg();
19929   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
19930   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
19931
19932   if (!Subtarget->isTargetWin64()) {
19933     // If %al is 0, branch around the XMM save block.
19934     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
19935     BuildMI(MBB, DL, TII->get(X86::JE_1)).addMBB(EndMBB);
19936     MBB->addSuccessor(EndMBB);
19937   }
19938
19939   // Make sure the last operand is EFLAGS, which gets clobbered by the branch
19940   // that was just emitted, but clearly shouldn't be "saved".
19941   assert((MI->getNumOperands() <= 3 ||
19942           !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
19943           MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
19944          && "Expected last argument to be EFLAGS");
19945   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
19946   // In the XMM save block, save all the XMM argument registers.
19947   for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
19948     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
19949     MachineMemOperand *MMO = F->getMachineMemOperand(
19950         MachinePointerInfo::getFixedStack(*F, RegSaveFrameIndex, Offset),
19951         MachineMemOperand::MOStore,
19952         /*Size=*/16, /*Align=*/16);
19953     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
19954       .addFrameIndex(RegSaveFrameIndex)
19955       .addImm(/*Scale=*/1)
19956       .addReg(/*IndexReg=*/0)
19957       .addImm(/*Disp=*/Offset)
19958       .addReg(/*Segment=*/0)
19959       .addReg(MI->getOperand(i).getReg())
19960       .addMemOperand(MMO);
19961   }
19962
19963   MI->eraseFromParent();   // The pseudo instruction is gone now.
19964
19965   return EndMBB;
19966 }
19967
19968 // The EFLAGS operand of SelectItr might be missing a kill marker
19969 // because there were multiple uses of EFLAGS, and ISel didn't know
19970 // which to mark. Figure out whether SelectItr should have had a
19971 // kill marker, and set it if it should. Returns the correct kill
19972 // marker value.
19973 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
19974                                      MachineBasicBlock* BB,
19975                                      const TargetRegisterInfo* TRI) {
19976   // Scan forward through BB for a use/def of EFLAGS.
19977   MachineBasicBlock::iterator miI(std::next(SelectItr));
19978   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
19979     const MachineInstr& mi = *miI;
19980     if (mi.readsRegister(X86::EFLAGS))
19981       return false;
19982     if (mi.definesRegister(X86::EFLAGS))
19983       break; // Should have kill-flag - update below.
19984   }
19985
19986   // If we hit the end of the block, check whether EFLAGS is live into a
19987   // successor.
19988   if (miI == BB->end()) {
19989     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
19990                                           sEnd = BB->succ_end();
19991          sItr != sEnd; ++sItr) {
19992       MachineBasicBlock* succ = *sItr;
19993       if (succ->isLiveIn(X86::EFLAGS))
19994         return false;
19995     }
19996   }
19997
19998   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
19999   // out. SelectMI should have a kill flag on EFLAGS.
20000   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
20001   return true;
20002 }
20003
20004 // Return true if it is OK for this CMOV pseudo-opcode to be cascaded
20005 // together with other CMOV pseudo-opcodes into a single basic-block with
20006 // conditional jump around it.
20007 static bool isCMOVPseudo(MachineInstr *MI) {
20008   switch (MI->getOpcode()) {
20009   case X86::CMOV_FR32:
20010   case X86::CMOV_FR64:
20011   case X86::CMOV_GR8:
20012   case X86::CMOV_GR16:
20013   case X86::CMOV_GR32:
20014   case X86::CMOV_RFP32:
20015   case X86::CMOV_RFP64:
20016   case X86::CMOV_RFP80:
20017   case X86::CMOV_V2F64:
20018   case X86::CMOV_V2I64:
20019   case X86::CMOV_V4F32:
20020   case X86::CMOV_V4F64:
20021   case X86::CMOV_V4I64:
20022   case X86::CMOV_V16F32:
20023   case X86::CMOV_V8F32:
20024   case X86::CMOV_V8F64:
20025   case X86::CMOV_V8I64:
20026   case X86::CMOV_V8I1:
20027   case X86::CMOV_V16I1:
20028   case X86::CMOV_V32I1:
20029   case X86::CMOV_V64I1:
20030     return true;
20031
20032   default:
20033     return false;
20034   }
20035 }
20036
20037 MachineBasicBlock *
20038 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
20039                                      MachineBasicBlock *BB) const {
20040   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20041   DebugLoc DL = MI->getDebugLoc();
20042
20043   // To "insert" a SELECT_CC instruction, we actually have to insert the
20044   // diamond control-flow pattern.  The incoming instruction knows the
20045   // destination vreg to set, the condition code register to branch on, the
20046   // true/false values to select between, and a branch opcode to use.
20047   const BasicBlock *LLVM_BB = BB->getBasicBlock();
20048   MachineFunction::iterator It = BB;
20049   ++It;
20050
20051   //  thisMBB:
20052   //  ...
20053   //   TrueVal = ...
20054   //   cmpTY ccX, r1, r2
20055   //   bCC copy1MBB
20056   //   fallthrough --> copy0MBB
20057   MachineBasicBlock *thisMBB = BB;
20058   MachineFunction *F = BB->getParent();
20059
20060   // This code lowers all pseudo-CMOV instructions. Generally it lowers these
20061   // as described above, by inserting a BB, and then making a PHI at the join
20062   // point to select the true and false operands of the CMOV in the PHI.
20063   //
20064   // The code also handles two different cases of multiple CMOV opcodes
20065   // in a row.
20066   //
20067   // Case 1:
20068   // In this case, there are multiple CMOVs in a row, all which are based on
20069   // the same condition setting (or the exact opposite condition setting).
20070   // In this case we can lower all the CMOVs using a single inserted BB, and
20071   // then make a number of PHIs at the join point to model the CMOVs. The only
20072   // trickiness here, is that in a case like:
20073   //
20074   // t2 = CMOV cond1 t1, f1
20075   // t3 = CMOV cond1 t2, f2
20076   //
20077   // when rewriting this into PHIs, we have to perform some renaming on the
20078   // temps since you cannot have a PHI operand refer to a PHI result earlier
20079   // in the same block.  The "simple" but wrong lowering would be:
20080   //
20081   // t2 = PHI t1(BB1), f1(BB2)
20082   // t3 = PHI t2(BB1), f2(BB2)
20083   //
20084   // but clearly t2 is not defined in BB1, so that is incorrect. The proper
20085   // renaming is to note that on the path through BB1, t2 is really just a
20086   // copy of t1, and do that renaming, properly generating:
20087   //
20088   // t2 = PHI t1(BB1), f1(BB2)
20089   // t3 = PHI t1(BB1), f2(BB2)
20090   //
20091   // Case 2, we lower cascaded CMOVs such as
20092   //
20093   //   (CMOV (CMOV F, T, cc1), T, cc2)
20094   //
20095   // to two successives branches.  For that, we look for another CMOV as the
20096   // following instruction.
20097   //
20098   // Without this, we would add a PHI between the two jumps, which ends up
20099   // creating a few copies all around. For instance, for
20100   //
20101   //    (sitofp (zext (fcmp une)))
20102   //
20103   // we would generate:
20104   //
20105   //         ucomiss %xmm1, %xmm0
20106   //         movss  <1.0f>, %xmm0
20107   //         movaps  %xmm0, %xmm1
20108   //         jne     .LBB5_2
20109   //         xorps   %xmm1, %xmm1
20110   // .LBB5_2:
20111   //         jp      .LBB5_4
20112   //         movaps  %xmm1, %xmm0
20113   // .LBB5_4:
20114   //         retq
20115   //
20116   // because this custom-inserter would have generated:
20117   //
20118   //   A
20119   //   | \
20120   //   |  B
20121   //   | /
20122   //   C
20123   //   | \
20124   //   |  D
20125   //   | /
20126   //   E
20127   //
20128   // A: X = ...; Y = ...
20129   // B: empty
20130   // C: Z = PHI [X, A], [Y, B]
20131   // D: empty
20132   // E: PHI [X, C], [Z, D]
20133   //
20134   // If we lower both CMOVs in a single step, we can instead generate:
20135   //
20136   //   A
20137   //   | \
20138   //   |  C
20139   //   | /|
20140   //   |/ |
20141   //   |  |
20142   //   |  D
20143   //   | /
20144   //   E
20145   //
20146   // A: X = ...; Y = ...
20147   // D: empty
20148   // E: PHI [X, A], [X, C], [Y, D]
20149   //
20150   // Which, in our sitofp/fcmp example, gives us something like:
20151   //
20152   //         ucomiss %xmm1, %xmm0
20153   //         movss  <1.0f>, %xmm0
20154   //         jne     .LBB5_4
20155   //         jp      .LBB5_4
20156   //         xorps   %xmm0, %xmm0
20157   // .LBB5_4:
20158   //         retq
20159   //
20160   MachineInstr *CascadedCMOV = nullptr;
20161   MachineInstr *LastCMOV = MI;
20162   X86::CondCode CC = X86::CondCode(MI->getOperand(3).getImm());
20163   X86::CondCode OppCC = X86::GetOppositeBranchCondition(CC);
20164   MachineBasicBlock::iterator NextMIIt =
20165       std::next(MachineBasicBlock::iterator(MI));
20166
20167   // Check for case 1, where there are multiple CMOVs with the same condition
20168   // first.  Of the two cases of multiple CMOV lowerings, case 1 reduces the
20169   // number of jumps the most.
20170
20171   if (isCMOVPseudo(MI)) {
20172     // See if we have a string of CMOVS with the same condition.
20173     while (NextMIIt != BB->end() &&
20174            isCMOVPseudo(NextMIIt) &&
20175            (NextMIIt->getOperand(3).getImm() == CC ||
20176             NextMIIt->getOperand(3).getImm() == OppCC)) {
20177       LastCMOV = &*NextMIIt;
20178       ++NextMIIt;
20179     }
20180   }
20181
20182   // This checks for case 2, but only do this if we didn't already find
20183   // case 1, as indicated by LastCMOV == MI.
20184   if (LastCMOV == MI &&
20185       NextMIIt != BB->end() && NextMIIt->getOpcode() == MI->getOpcode() &&
20186       NextMIIt->getOperand(2).getReg() == MI->getOperand(2).getReg() &&
20187       NextMIIt->getOperand(1).getReg() == MI->getOperand(0).getReg()) {
20188     CascadedCMOV = &*NextMIIt;
20189   }
20190
20191   MachineBasicBlock *jcc1MBB = nullptr;
20192
20193   // If we have a cascaded CMOV, we lower it to two successive branches to
20194   // the same block.  EFLAGS is used by both, so mark it as live in the second.
20195   if (CascadedCMOV) {
20196     jcc1MBB = F->CreateMachineBasicBlock(LLVM_BB);
20197     F->insert(It, jcc1MBB);
20198     jcc1MBB->addLiveIn(X86::EFLAGS);
20199   }
20200
20201   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
20202   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
20203   F->insert(It, copy0MBB);
20204   F->insert(It, sinkMBB);
20205
20206   // If the EFLAGS register isn't dead in the terminator, then claim that it's
20207   // live into the sink and copy blocks.
20208   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
20209
20210   MachineInstr *LastEFLAGSUser = CascadedCMOV ? CascadedCMOV : LastCMOV;
20211   if (!LastEFLAGSUser->killsRegister(X86::EFLAGS) &&
20212       !checkAndUpdateEFLAGSKill(LastEFLAGSUser, BB, TRI)) {
20213     copy0MBB->addLiveIn(X86::EFLAGS);
20214     sinkMBB->addLiveIn(X86::EFLAGS);
20215   }
20216
20217   // Transfer the remainder of BB and its successor edges to sinkMBB.
20218   sinkMBB->splice(sinkMBB->begin(), BB,
20219                   std::next(MachineBasicBlock::iterator(LastCMOV)), BB->end());
20220   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
20221
20222   // Add the true and fallthrough blocks as its successors.
20223   if (CascadedCMOV) {
20224     // The fallthrough block may be jcc1MBB, if we have a cascaded CMOV.
20225     BB->addSuccessor(jcc1MBB);
20226
20227     // In that case, jcc1MBB will itself fallthrough the copy0MBB, and
20228     // jump to the sinkMBB.
20229     jcc1MBB->addSuccessor(copy0MBB);
20230     jcc1MBB->addSuccessor(sinkMBB);
20231   } else {
20232     BB->addSuccessor(copy0MBB);
20233   }
20234
20235   // The true block target of the first (or only) branch is always sinkMBB.
20236   BB->addSuccessor(sinkMBB);
20237
20238   // Create the conditional branch instruction.
20239   unsigned Opc = X86::GetCondBranchFromCond(CC);
20240   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
20241
20242   if (CascadedCMOV) {
20243     unsigned Opc2 = X86::GetCondBranchFromCond(
20244         (X86::CondCode)CascadedCMOV->getOperand(3).getImm());
20245     BuildMI(jcc1MBB, DL, TII->get(Opc2)).addMBB(sinkMBB);
20246   }
20247
20248   //  copy0MBB:
20249   //   %FalseValue = ...
20250   //   # fallthrough to sinkMBB
20251   copy0MBB->addSuccessor(sinkMBB);
20252
20253   //  sinkMBB:
20254   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
20255   //  ...
20256   MachineBasicBlock::iterator MIItBegin = MachineBasicBlock::iterator(MI);
20257   MachineBasicBlock::iterator MIItEnd =
20258     std::next(MachineBasicBlock::iterator(LastCMOV));
20259   MachineBasicBlock::iterator SinkInsertionPoint = sinkMBB->begin();
20260   DenseMap<unsigned, std::pair<unsigned, unsigned>> RegRewriteTable;
20261   MachineInstrBuilder MIB;
20262
20263   // As we are creating the PHIs, we have to be careful if there is more than
20264   // one.  Later CMOVs may reference the results of earlier CMOVs, but later
20265   // PHIs have to reference the individual true/false inputs from earlier PHIs.
20266   // That also means that PHI construction must work forward from earlier to
20267   // later, and that the code must maintain a mapping from earlier PHI's
20268   // destination registers, and the registers that went into the PHI.
20269
20270   for (MachineBasicBlock::iterator MIIt = MIItBegin; MIIt != MIItEnd; ++MIIt) {
20271     unsigned DestReg = MIIt->getOperand(0).getReg();
20272     unsigned Op1Reg = MIIt->getOperand(1).getReg();
20273     unsigned Op2Reg = MIIt->getOperand(2).getReg();
20274
20275     // If this CMOV we are generating is the opposite condition from
20276     // the jump we generated, then we have to swap the operands for the
20277     // PHI that is going to be generated.
20278     if (MIIt->getOperand(3).getImm() == OppCC)
20279         std::swap(Op1Reg, Op2Reg);
20280
20281     if (RegRewriteTable.find(Op1Reg) != RegRewriteTable.end())
20282       Op1Reg = RegRewriteTable[Op1Reg].first;
20283
20284     if (RegRewriteTable.find(Op2Reg) != RegRewriteTable.end())
20285       Op2Reg = RegRewriteTable[Op2Reg].second;
20286
20287     MIB = BuildMI(*sinkMBB, SinkInsertionPoint, DL,
20288                   TII->get(X86::PHI), DestReg)
20289           .addReg(Op1Reg).addMBB(copy0MBB)
20290           .addReg(Op2Reg).addMBB(thisMBB);
20291
20292     // Add this PHI to the rewrite table.
20293     RegRewriteTable[DestReg] = std::make_pair(Op1Reg, Op2Reg);
20294   }
20295
20296   // If we have a cascaded CMOV, the second Jcc provides the same incoming
20297   // value as the first Jcc (the True operand of the SELECT_CC/CMOV nodes).
20298   if (CascadedCMOV) {
20299     MIB.addReg(MI->getOperand(2).getReg()).addMBB(jcc1MBB);
20300     // Copy the PHI result to the register defined by the second CMOV.
20301     BuildMI(*sinkMBB, std::next(MachineBasicBlock::iterator(MIB.getInstr())),
20302             DL, TII->get(TargetOpcode::COPY),
20303             CascadedCMOV->getOperand(0).getReg())
20304         .addReg(MI->getOperand(0).getReg());
20305     CascadedCMOV->eraseFromParent();
20306   }
20307
20308   // Now remove the CMOV(s).
20309   for (MachineBasicBlock::iterator MIIt = MIItBegin; MIIt != MIItEnd; )
20310     (MIIt++)->eraseFromParent();
20311
20312   return sinkMBB;
20313 }
20314
20315 MachineBasicBlock *
20316 X86TargetLowering::EmitLoweredAtomicFP(MachineInstr *MI,
20317                                        MachineBasicBlock *BB) const {
20318   // Combine the following atomic floating-point modification pattern:
20319   //   a.store(reg OP a.load(acquire), release)
20320   // Transform them into:
20321   //   OPss (%gpr), %xmm
20322   //   movss %xmm, (%gpr)
20323   // Or sd equivalent for 64-bit operations.
20324   unsigned MOp, FOp;
20325   switch (MI->getOpcode()) {
20326   default: llvm_unreachable("unexpected instr type for EmitLoweredAtomicFP");
20327   case X86::RELEASE_FADD32mr: MOp = X86::MOVSSmr; FOp = X86::ADDSSrm; break;
20328   case X86::RELEASE_FADD64mr: MOp = X86::MOVSDmr; FOp = X86::ADDSDrm; break;
20329   }
20330   const X86InstrInfo *TII = Subtarget->getInstrInfo();
20331   DebugLoc DL = MI->getDebugLoc();
20332   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
20333   unsigned MSrc = MI->getOperand(0).getReg();
20334   unsigned VSrc = MI->getOperand(5).getReg();
20335   MachineInstrBuilder MIM = BuildMI(*BB, MI, DL, TII->get(MOp))
20336                                 .addReg(/*Base=*/MSrc)
20337                                 .addImm(/*Scale=*/1)
20338                                 .addReg(/*Index=*/0)
20339                                 .addImm(0)
20340                                 .addReg(0);
20341   MachineInstr *MIO = BuildMI(*BB, (MachineInstr *)MIM, DL, TII->get(FOp),
20342                               MRI.createVirtualRegister(MRI.getRegClass(VSrc)))
20343                           .addReg(VSrc)
20344                           .addReg(/*Base=*/MSrc)
20345                           .addImm(/*Scale=*/1)
20346                           .addReg(/*Index=*/0)
20347                           .addImm(/*Disp=*/0)
20348                           .addReg(/*Segment=*/0);
20349   MIM.addReg(MIO->getOperand(0).getReg(), RegState::Kill);
20350   MI->eraseFromParent(); // The pseudo instruction is gone now.
20351   return BB;
20352 }
20353
20354 MachineBasicBlock *
20355 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI,
20356                                         MachineBasicBlock *BB) const {
20357   MachineFunction *MF = BB->getParent();
20358   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20359   DebugLoc DL = MI->getDebugLoc();
20360   const BasicBlock *LLVM_BB = BB->getBasicBlock();
20361
20362   assert(MF->shouldSplitStack());
20363
20364   const bool Is64Bit = Subtarget->is64Bit();
20365   const bool IsLP64 = Subtarget->isTarget64BitLP64();
20366
20367   const unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
20368   const unsigned TlsOffset = IsLP64 ? 0x70 : Is64Bit ? 0x40 : 0x30;
20369
20370   // BB:
20371   //  ... [Till the alloca]
20372   // If stacklet is not large enough, jump to mallocMBB
20373   //
20374   // bumpMBB:
20375   //  Allocate by subtracting from RSP
20376   //  Jump to continueMBB
20377   //
20378   // mallocMBB:
20379   //  Allocate by call to runtime
20380   //
20381   // continueMBB:
20382   //  ...
20383   //  [rest of original BB]
20384   //
20385
20386   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20387   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20388   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20389
20390   MachineRegisterInfo &MRI = MF->getRegInfo();
20391   const TargetRegisterClass *AddrRegClass =
20392       getRegClassFor(getPointerTy(MF->getDataLayout()));
20393
20394   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
20395     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
20396     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
20397     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
20398     sizeVReg = MI->getOperand(1).getReg(),
20399     physSPReg = IsLP64 || Subtarget->isTargetNaCl64() ? X86::RSP : X86::ESP;
20400
20401   MachineFunction::iterator MBBIter = BB;
20402   ++MBBIter;
20403
20404   MF->insert(MBBIter, bumpMBB);
20405   MF->insert(MBBIter, mallocMBB);
20406   MF->insert(MBBIter, continueMBB);
20407
20408   continueMBB->splice(continueMBB->begin(), BB,
20409                       std::next(MachineBasicBlock::iterator(MI)), BB->end());
20410   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
20411
20412   // Add code to the main basic block to check if the stack limit has been hit,
20413   // and if so, jump to mallocMBB otherwise to bumpMBB.
20414   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
20415   BuildMI(BB, DL, TII->get(IsLP64 ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
20416     .addReg(tmpSPVReg).addReg(sizeVReg);
20417   BuildMI(BB, DL, TII->get(IsLP64 ? X86::CMP64mr:X86::CMP32mr))
20418     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
20419     .addReg(SPLimitVReg);
20420   BuildMI(BB, DL, TII->get(X86::JG_1)).addMBB(mallocMBB);
20421
20422   // bumpMBB simply decreases the stack pointer, since we know the current
20423   // stacklet has enough space.
20424   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
20425     .addReg(SPLimitVReg);
20426   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
20427     .addReg(SPLimitVReg);
20428   BuildMI(bumpMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
20429
20430   // Calls into a routine in libgcc to allocate more space from the heap.
20431   const uint32_t *RegMask =
20432       Subtarget->getRegisterInfo()->getCallPreservedMask(*MF, CallingConv::C);
20433   if (IsLP64) {
20434     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
20435       .addReg(sizeVReg);
20436     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
20437       .addExternalSymbol("__morestack_allocate_stack_space")
20438       .addRegMask(RegMask)
20439       .addReg(X86::RDI, RegState::Implicit)
20440       .addReg(X86::RAX, RegState::ImplicitDefine);
20441   } else if (Is64Bit) {
20442     BuildMI(mallocMBB, DL, TII->get(X86::MOV32rr), X86::EDI)
20443       .addReg(sizeVReg);
20444     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
20445       .addExternalSymbol("__morestack_allocate_stack_space")
20446       .addRegMask(RegMask)
20447       .addReg(X86::EDI, RegState::Implicit)
20448       .addReg(X86::EAX, RegState::ImplicitDefine);
20449   } else {
20450     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
20451       .addImm(12);
20452     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
20453     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
20454       .addExternalSymbol("__morestack_allocate_stack_space")
20455       .addRegMask(RegMask)
20456       .addReg(X86::EAX, RegState::ImplicitDefine);
20457   }
20458
20459   if (!Is64Bit)
20460     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
20461       .addImm(16);
20462
20463   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
20464     .addReg(IsLP64 ? X86::RAX : X86::EAX);
20465   BuildMI(mallocMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
20466
20467   // Set up the CFG correctly.
20468   BB->addSuccessor(bumpMBB);
20469   BB->addSuccessor(mallocMBB);
20470   mallocMBB->addSuccessor(continueMBB);
20471   bumpMBB->addSuccessor(continueMBB);
20472
20473   // Take care of the PHI nodes.
20474   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
20475           MI->getOperand(0).getReg())
20476     .addReg(mallocPtrVReg).addMBB(mallocMBB)
20477     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
20478
20479   // Delete the original pseudo instruction.
20480   MI->eraseFromParent();
20481
20482   // And we're done.
20483   return continueMBB;
20484 }
20485
20486 MachineBasicBlock *
20487 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
20488                                         MachineBasicBlock *BB) const {
20489   DebugLoc DL = MI->getDebugLoc();
20490
20491   assert(!Subtarget->isTargetMachO());
20492
20493   Subtarget->getFrameLowering()->emitStackProbeCall(*BB->getParent(), *BB, MI,
20494                                                     DL);
20495
20496   MI->eraseFromParent();   // The pseudo instruction is gone now.
20497   return BB;
20498 }
20499
20500 MachineBasicBlock *
20501 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
20502                                       MachineBasicBlock *BB) const {
20503   // This is pretty easy.  We're taking the value that we received from
20504   // our load from the relocation, sticking it in either RDI (x86-64)
20505   // or EAX and doing an indirect call.  The return value will then
20506   // be in the normal return register.
20507   MachineFunction *F = BB->getParent();
20508   const X86InstrInfo *TII = Subtarget->getInstrInfo();
20509   DebugLoc DL = MI->getDebugLoc();
20510
20511   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
20512   assert(MI->getOperand(3).isGlobal() && "This should be a global");
20513
20514   // Get a register mask for the lowered call.
20515   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
20516   // proper register mask.
20517   const uint32_t *RegMask =
20518       Subtarget->getRegisterInfo()->getCallPreservedMask(*F, CallingConv::C);
20519   if (Subtarget->is64Bit()) {
20520     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
20521                                       TII->get(X86::MOV64rm), X86::RDI)
20522     .addReg(X86::RIP)
20523     .addImm(0).addReg(0)
20524     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
20525                       MI->getOperand(3).getTargetFlags())
20526     .addReg(0);
20527     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
20528     addDirectMem(MIB, X86::RDI);
20529     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
20530   } else if (F->getTarget().getRelocationModel() != Reloc::PIC_) {
20531     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
20532                                       TII->get(X86::MOV32rm), X86::EAX)
20533     .addReg(0)
20534     .addImm(0).addReg(0)
20535     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
20536                       MI->getOperand(3).getTargetFlags())
20537     .addReg(0);
20538     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
20539     addDirectMem(MIB, X86::EAX);
20540     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
20541   } else {
20542     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
20543                                       TII->get(X86::MOV32rm), X86::EAX)
20544     .addReg(TII->getGlobalBaseReg(F))
20545     .addImm(0).addReg(0)
20546     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
20547                       MI->getOperand(3).getTargetFlags())
20548     .addReg(0);
20549     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
20550     addDirectMem(MIB, X86::EAX);
20551     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
20552   }
20553
20554   MI->eraseFromParent(); // The pseudo instruction is gone now.
20555   return BB;
20556 }
20557
20558 MachineBasicBlock *
20559 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
20560                                     MachineBasicBlock *MBB) const {
20561   DebugLoc DL = MI->getDebugLoc();
20562   MachineFunction *MF = MBB->getParent();
20563   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20564   MachineRegisterInfo &MRI = MF->getRegInfo();
20565
20566   const BasicBlock *BB = MBB->getBasicBlock();
20567   MachineFunction::iterator I = MBB;
20568   ++I;
20569
20570   // Memory Reference
20571   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
20572   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
20573
20574   unsigned DstReg;
20575   unsigned MemOpndSlot = 0;
20576
20577   unsigned CurOp = 0;
20578
20579   DstReg = MI->getOperand(CurOp++).getReg();
20580   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
20581   assert(RC->hasType(MVT::i32) && "Invalid destination!");
20582   unsigned mainDstReg = MRI.createVirtualRegister(RC);
20583   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
20584
20585   MemOpndSlot = CurOp;
20586
20587   MVT PVT = getPointerTy(MF->getDataLayout());
20588   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
20589          "Invalid Pointer Size!");
20590
20591   // For v = setjmp(buf), we generate
20592   //
20593   // thisMBB:
20594   //  buf[LabelOffset] = restoreMBB
20595   //  SjLjSetup restoreMBB
20596   //
20597   // mainMBB:
20598   //  v_main = 0
20599   //
20600   // sinkMBB:
20601   //  v = phi(main, restore)
20602   //
20603   // restoreMBB:
20604   //  if base pointer being used, load it from frame
20605   //  v_restore = 1
20606
20607   MachineBasicBlock *thisMBB = MBB;
20608   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
20609   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
20610   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
20611   MF->insert(I, mainMBB);
20612   MF->insert(I, sinkMBB);
20613   MF->push_back(restoreMBB);
20614
20615   MachineInstrBuilder MIB;
20616
20617   // Transfer the remainder of BB and its successor edges to sinkMBB.
20618   sinkMBB->splice(sinkMBB->begin(), MBB,
20619                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
20620   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
20621
20622   // thisMBB:
20623   unsigned PtrStoreOpc = 0;
20624   unsigned LabelReg = 0;
20625   const int64_t LabelOffset = 1 * PVT.getStoreSize();
20626   Reloc::Model RM = MF->getTarget().getRelocationModel();
20627   bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
20628                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
20629
20630   // Prepare IP either in reg or imm.
20631   if (!UseImmLabel) {
20632     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
20633     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
20634     LabelReg = MRI.createVirtualRegister(PtrRC);
20635     if (Subtarget->is64Bit()) {
20636       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
20637               .addReg(X86::RIP)
20638               .addImm(0)
20639               .addReg(0)
20640               .addMBB(restoreMBB)
20641               .addReg(0);
20642     } else {
20643       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
20644       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
20645               .addReg(XII->getGlobalBaseReg(MF))
20646               .addImm(0)
20647               .addReg(0)
20648               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
20649               .addReg(0);
20650     }
20651   } else
20652     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
20653   // Store IP
20654   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
20655   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
20656     if (i == X86::AddrDisp)
20657       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
20658     else
20659       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
20660   }
20661   if (!UseImmLabel)
20662     MIB.addReg(LabelReg);
20663   else
20664     MIB.addMBB(restoreMBB);
20665   MIB.setMemRefs(MMOBegin, MMOEnd);
20666   // Setup
20667   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
20668           .addMBB(restoreMBB);
20669
20670   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
20671   MIB.addRegMask(RegInfo->getNoPreservedMask());
20672   thisMBB->addSuccessor(mainMBB);
20673   thisMBB->addSuccessor(restoreMBB);
20674
20675   // mainMBB:
20676   //  EAX = 0
20677   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
20678   mainMBB->addSuccessor(sinkMBB);
20679
20680   // sinkMBB:
20681   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
20682           TII->get(X86::PHI), DstReg)
20683     .addReg(mainDstReg).addMBB(mainMBB)
20684     .addReg(restoreDstReg).addMBB(restoreMBB);
20685
20686   // restoreMBB:
20687   if (RegInfo->hasBasePointer(*MF)) {
20688     const bool Uses64BitFramePtr =
20689         Subtarget->isTarget64BitLP64() || Subtarget->isTargetNaCl64();
20690     X86MachineFunctionInfo *X86FI = MF->getInfo<X86MachineFunctionInfo>();
20691     X86FI->setRestoreBasePointer(MF);
20692     unsigned FramePtr = RegInfo->getFrameRegister(*MF);
20693     unsigned BasePtr = RegInfo->getBaseRegister();
20694     unsigned Opm = Uses64BitFramePtr ? X86::MOV64rm : X86::MOV32rm;
20695     addRegOffset(BuildMI(restoreMBB, DL, TII->get(Opm), BasePtr),
20696                  FramePtr, true, X86FI->getRestoreBasePointerOffset())
20697       .setMIFlag(MachineInstr::FrameSetup);
20698   }
20699   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
20700   BuildMI(restoreMBB, DL, TII->get(X86::JMP_1)).addMBB(sinkMBB);
20701   restoreMBB->addSuccessor(sinkMBB);
20702
20703   MI->eraseFromParent();
20704   return sinkMBB;
20705 }
20706
20707 MachineBasicBlock *
20708 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
20709                                      MachineBasicBlock *MBB) const {
20710   DebugLoc DL = MI->getDebugLoc();
20711   MachineFunction *MF = MBB->getParent();
20712   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20713   MachineRegisterInfo &MRI = MF->getRegInfo();
20714
20715   // Memory Reference
20716   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
20717   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
20718
20719   MVT PVT = getPointerTy(MF->getDataLayout());
20720   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
20721          "Invalid Pointer Size!");
20722
20723   const TargetRegisterClass *RC =
20724     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
20725   unsigned Tmp = MRI.createVirtualRegister(RC);
20726   // Since FP is only updated here but NOT referenced, it's treated as GPR.
20727   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
20728   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
20729   unsigned SP = RegInfo->getStackRegister();
20730
20731   MachineInstrBuilder MIB;
20732
20733   const int64_t LabelOffset = 1 * PVT.getStoreSize();
20734   const int64_t SPOffset = 2 * PVT.getStoreSize();
20735
20736   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
20737   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
20738
20739   // Reload FP
20740   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
20741   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
20742     MIB.addOperand(MI->getOperand(i));
20743   MIB.setMemRefs(MMOBegin, MMOEnd);
20744   // Reload IP
20745   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
20746   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
20747     if (i == X86::AddrDisp)
20748       MIB.addDisp(MI->getOperand(i), LabelOffset);
20749     else
20750       MIB.addOperand(MI->getOperand(i));
20751   }
20752   MIB.setMemRefs(MMOBegin, MMOEnd);
20753   // Reload SP
20754   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
20755   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
20756     if (i == X86::AddrDisp)
20757       MIB.addDisp(MI->getOperand(i), SPOffset);
20758     else
20759       MIB.addOperand(MI->getOperand(i));
20760   }
20761   MIB.setMemRefs(MMOBegin, MMOEnd);
20762   // Jump
20763   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
20764
20765   MI->eraseFromParent();
20766   return MBB;
20767 }
20768
20769 // Replace 213-type (isel default) FMA3 instructions with 231-type for
20770 // accumulator loops. Writing back to the accumulator allows the coalescer
20771 // to remove extra copies in the loop.
20772 // FIXME: Do this on AVX512.  We don't support 231 variants yet (PR23937).
20773 MachineBasicBlock *
20774 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
20775                                  MachineBasicBlock *MBB) const {
20776   MachineOperand &AddendOp = MI->getOperand(3);
20777
20778   // Bail out early if the addend isn't a register - we can't switch these.
20779   if (!AddendOp.isReg())
20780     return MBB;
20781
20782   MachineFunction &MF = *MBB->getParent();
20783   MachineRegisterInfo &MRI = MF.getRegInfo();
20784
20785   // Check whether the addend is defined by a PHI:
20786   assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
20787   MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
20788   if (!AddendDef.isPHI())
20789     return MBB;
20790
20791   // Look for the following pattern:
20792   // loop:
20793   //   %addend = phi [%entry, 0], [%loop, %result]
20794   //   ...
20795   //   %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
20796
20797   // Replace with:
20798   //   loop:
20799   //   %addend = phi [%entry, 0], [%loop, %result]
20800   //   ...
20801   //   %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
20802
20803   for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
20804     assert(AddendDef.getOperand(i).isReg());
20805     MachineOperand PHISrcOp = AddendDef.getOperand(i);
20806     MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
20807     if (&PHISrcInst == MI) {
20808       // Found a matching instruction.
20809       unsigned NewFMAOpc = 0;
20810       switch (MI->getOpcode()) {
20811         case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
20812         case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
20813         case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
20814         case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
20815         case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
20816         case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
20817         case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
20818         case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
20819         case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
20820         case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
20821         case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
20822         case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
20823         case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
20824         case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
20825         case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
20826         case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
20827         case X86::VFMADDSUBPDr213r: NewFMAOpc = X86::VFMADDSUBPDr231r; break;
20828         case X86::VFMADDSUBPSr213r: NewFMAOpc = X86::VFMADDSUBPSr231r; break;
20829         case X86::VFMSUBADDPDr213r: NewFMAOpc = X86::VFMSUBADDPDr231r; break;
20830         case X86::VFMSUBADDPSr213r: NewFMAOpc = X86::VFMSUBADDPSr231r; break;
20831
20832         case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
20833         case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
20834         case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
20835         case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
20836         case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
20837         case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
20838         case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
20839         case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
20840         case X86::VFMADDSUBPDr213rY: NewFMAOpc = X86::VFMADDSUBPDr231rY; break;
20841         case X86::VFMADDSUBPSr213rY: NewFMAOpc = X86::VFMADDSUBPSr231rY; break;
20842         case X86::VFMSUBADDPDr213rY: NewFMAOpc = X86::VFMSUBADDPDr231rY; break;
20843         case X86::VFMSUBADDPSr213rY: NewFMAOpc = X86::VFMSUBADDPSr231rY; break;
20844         default: llvm_unreachable("Unrecognized FMA variant.");
20845       }
20846
20847       const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
20848       MachineInstrBuilder MIB =
20849         BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
20850         .addOperand(MI->getOperand(0))
20851         .addOperand(MI->getOperand(3))
20852         .addOperand(MI->getOperand(2))
20853         .addOperand(MI->getOperand(1));
20854       MBB->insert(MachineBasicBlock::iterator(MI), MIB);
20855       MI->eraseFromParent();
20856     }
20857   }
20858
20859   return MBB;
20860 }
20861
20862 MachineBasicBlock *
20863 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
20864                                                MachineBasicBlock *BB) const {
20865   switch (MI->getOpcode()) {
20866   default: llvm_unreachable("Unexpected instr type to insert");
20867   case X86::TAILJMPd64:
20868   case X86::TAILJMPr64:
20869   case X86::TAILJMPm64:
20870   case X86::TAILJMPd64_REX:
20871   case X86::TAILJMPr64_REX:
20872   case X86::TAILJMPm64_REX:
20873     llvm_unreachable("TAILJMP64 would not be touched here.");
20874   case X86::TCRETURNdi64:
20875   case X86::TCRETURNri64:
20876   case X86::TCRETURNmi64:
20877     return BB;
20878   case X86::WIN_ALLOCA:
20879     return EmitLoweredWinAlloca(MI, BB);
20880   case X86::SEG_ALLOCA_32:
20881   case X86::SEG_ALLOCA_64:
20882     return EmitLoweredSegAlloca(MI, BB);
20883   case X86::TLSCall_32:
20884   case X86::TLSCall_64:
20885     return EmitLoweredTLSCall(MI, BB);
20886   case X86::CMOV_FR32:
20887   case X86::CMOV_FR64:
20888   case X86::CMOV_GR8:
20889   case X86::CMOV_GR16:
20890   case X86::CMOV_GR32:
20891   case X86::CMOV_RFP32:
20892   case X86::CMOV_RFP64:
20893   case X86::CMOV_RFP80:
20894   case X86::CMOV_V2F64:
20895   case X86::CMOV_V2I64:
20896   case X86::CMOV_V4F32:
20897   case X86::CMOV_V4F64:
20898   case X86::CMOV_V4I64:
20899   case X86::CMOV_V16F32:
20900   case X86::CMOV_V8F32:
20901   case X86::CMOV_V8F64:
20902   case X86::CMOV_V8I64:
20903   case X86::CMOV_V8I1:
20904   case X86::CMOV_V16I1:
20905   case X86::CMOV_V32I1:
20906   case X86::CMOV_V64I1:
20907     return EmitLoweredSelect(MI, BB);
20908
20909   case X86::RELEASE_FADD32mr:
20910   case X86::RELEASE_FADD64mr:
20911     return EmitLoweredAtomicFP(MI, BB);
20912
20913   case X86::FP32_TO_INT16_IN_MEM:
20914   case X86::FP32_TO_INT32_IN_MEM:
20915   case X86::FP32_TO_INT64_IN_MEM:
20916   case X86::FP64_TO_INT16_IN_MEM:
20917   case X86::FP64_TO_INT32_IN_MEM:
20918   case X86::FP64_TO_INT64_IN_MEM:
20919   case X86::FP80_TO_INT16_IN_MEM:
20920   case X86::FP80_TO_INT32_IN_MEM:
20921   case X86::FP80_TO_INT64_IN_MEM: {
20922     MachineFunction *F = BB->getParent();
20923     const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20924     DebugLoc DL = MI->getDebugLoc();
20925
20926     // Change the floating point control register to use "round towards zero"
20927     // mode when truncating to an integer value.
20928     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
20929     addFrameReference(BuildMI(*BB, MI, DL,
20930                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
20931
20932     // Load the old value of the high byte of the control word...
20933     unsigned OldCW =
20934       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
20935     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
20936                       CWFrameIdx);
20937
20938     // Set the high part to be round to zero...
20939     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
20940       .addImm(0xC7F);
20941
20942     // Reload the modified control word now...
20943     addFrameReference(BuildMI(*BB, MI, DL,
20944                               TII->get(X86::FLDCW16m)), CWFrameIdx);
20945
20946     // Restore the memory image of control word to original value
20947     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
20948       .addReg(OldCW);
20949
20950     // Get the X86 opcode to use.
20951     unsigned Opc;
20952     switch (MI->getOpcode()) {
20953     default: llvm_unreachable("illegal opcode!");
20954     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
20955     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
20956     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
20957     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
20958     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
20959     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
20960     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
20961     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
20962     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
20963     }
20964
20965     X86AddressMode AM;
20966     MachineOperand &Op = MI->getOperand(0);
20967     if (Op.isReg()) {
20968       AM.BaseType = X86AddressMode::RegBase;
20969       AM.Base.Reg = Op.getReg();
20970     } else {
20971       AM.BaseType = X86AddressMode::FrameIndexBase;
20972       AM.Base.FrameIndex = Op.getIndex();
20973     }
20974     Op = MI->getOperand(1);
20975     if (Op.isImm())
20976       AM.Scale = Op.getImm();
20977     Op = MI->getOperand(2);
20978     if (Op.isImm())
20979       AM.IndexReg = Op.getImm();
20980     Op = MI->getOperand(3);
20981     if (Op.isGlobal()) {
20982       AM.GV = Op.getGlobal();
20983     } else {
20984       AM.Disp = Op.getImm();
20985     }
20986     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
20987                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
20988
20989     // Reload the original control word now.
20990     addFrameReference(BuildMI(*BB, MI, DL,
20991                               TII->get(X86::FLDCW16m)), CWFrameIdx);
20992
20993     MI->eraseFromParent();   // The pseudo instruction is gone now.
20994     return BB;
20995   }
20996     // String/text processing lowering.
20997   case X86::PCMPISTRM128REG:
20998   case X86::VPCMPISTRM128REG:
20999   case X86::PCMPISTRM128MEM:
21000   case X86::VPCMPISTRM128MEM:
21001   case X86::PCMPESTRM128REG:
21002   case X86::VPCMPESTRM128REG:
21003   case X86::PCMPESTRM128MEM:
21004   case X86::VPCMPESTRM128MEM:
21005     assert(Subtarget->hasSSE42() &&
21006            "Target must have SSE4.2 or AVX features enabled");
21007     return EmitPCMPSTRM(MI, BB, Subtarget->getInstrInfo());
21008
21009   // String/text processing lowering.
21010   case X86::PCMPISTRIREG:
21011   case X86::VPCMPISTRIREG:
21012   case X86::PCMPISTRIMEM:
21013   case X86::VPCMPISTRIMEM:
21014   case X86::PCMPESTRIREG:
21015   case X86::VPCMPESTRIREG:
21016   case X86::PCMPESTRIMEM:
21017   case X86::VPCMPESTRIMEM:
21018     assert(Subtarget->hasSSE42() &&
21019            "Target must have SSE4.2 or AVX features enabled");
21020     return EmitPCMPSTRI(MI, BB, Subtarget->getInstrInfo());
21021
21022   // Thread synchronization.
21023   case X86::MONITOR:
21024     return EmitMonitor(MI, BB, Subtarget);
21025
21026   // xbegin
21027   case X86::XBEGIN:
21028     return EmitXBegin(MI, BB, Subtarget->getInstrInfo());
21029
21030   case X86::VASTART_SAVE_XMM_REGS:
21031     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
21032
21033   case X86::VAARG_64:
21034     return EmitVAARG64WithCustomInserter(MI, BB);
21035
21036   case X86::EH_SjLj_SetJmp32:
21037   case X86::EH_SjLj_SetJmp64:
21038     return emitEHSjLjSetJmp(MI, BB);
21039
21040   case X86::EH_SjLj_LongJmp32:
21041   case X86::EH_SjLj_LongJmp64:
21042     return emitEHSjLjLongJmp(MI, BB);
21043
21044   case TargetOpcode::STATEPOINT:
21045     // As an implementation detail, STATEPOINT shares the STACKMAP format at
21046     // this point in the process.  We diverge later.
21047     return emitPatchPoint(MI, BB);
21048
21049   case TargetOpcode::STACKMAP:
21050   case TargetOpcode::PATCHPOINT:
21051     return emitPatchPoint(MI, BB);
21052
21053   case X86::VFMADDPDr213r:
21054   case X86::VFMADDPSr213r:
21055   case X86::VFMADDSDr213r:
21056   case X86::VFMADDSSr213r:
21057   case X86::VFMSUBPDr213r:
21058   case X86::VFMSUBPSr213r:
21059   case X86::VFMSUBSDr213r:
21060   case X86::VFMSUBSSr213r:
21061   case X86::VFNMADDPDr213r:
21062   case X86::VFNMADDPSr213r:
21063   case X86::VFNMADDSDr213r:
21064   case X86::VFNMADDSSr213r:
21065   case X86::VFNMSUBPDr213r:
21066   case X86::VFNMSUBPSr213r:
21067   case X86::VFNMSUBSDr213r:
21068   case X86::VFNMSUBSSr213r:
21069   case X86::VFMADDSUBPDr213r:
21070   case X86::VFMADDSUBPSr213r:
21071   case X86::VFMSUBADDPDr213r:
21072   case X86::VFMSUBADDPSr213r:
21073   case X86::VFMADDPDr213rY:
21074   case X86::VFMADDPSr213rY:
21075   case X86::VFMSUBPDr213rY:
21076   case X86::VFMSUBPSr213rY:
21077   case X86::VFNMADDPDr213rY:
21078   case X86::VFNMADDPSr213rY:
21079   case X86::VFNMSUBPDr213rY:
21080   case X86::VFNMSUBPSr213rY:
21081   case X86::VFMADDSUBPDr213rY:
21082   case X86::VFMADDSUBPSr213rY:
21083   case X86::VFMSUBADDPDr213rY:
21084   case X86::VFMSUBADDPSr213rY:
21085     return emitFMA3Instr(MI, BB);
21086   }
21087 }
21088
21089 //===----------------------------------------------------------------------===//
21090 //                           X86 Optimization Hooks
21091 //===----------------------------------------------------------------------===//
21092
21093 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
21094                                                       APInt &KnownZero,
21095                                                       APInt &KnownOne,
21096                                                       const SelectionDAG &DAG,
21097                                                       unsigned Depth) const {
21098   unsigned BitWidth = KnownZero.getBitWidth();
21099   unsigned Opc = Op.getOpcode();
21100   assert((Opc >= ISD::BUILTIN_OP_END ||
21101           Opc == ISD::INTRINSIC_WO_CHAIN ||
21102           Opc == ISD::INTRINSIC_W_CHAIN ||
21103           Opc == ISD::INTRINSIC_VOID) &&
21104          "Should use MaskedValueIsZero if you don't know whether Op"
21105          " is a target node!");
21106
21107   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
21108   switch (Opc) {
21109   default: break;
21110   case X86ISD::ADD:
21111   case X86ISD::SUB:
21112   case X86ISD::ADC:
21113   case X86ISD::SBB:
21114   case X86ISD::SMUL:
21115   case X86ISD::UMUL:
21116   case X86ISD::INC:
21117   case X86ISD::DEC:
21118   case X86ISD::OR:
21119   case X86ISD::XOR:
21120   case X86ISD::AND:
21121     // These nodes' second result is a boolean.
21122     if (Op.getResNo() == 0)
21123       break;
21124     // Fallthrough
21125   case X86ISD::SETCC:
21126     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
21127     break;
21128   case ISD::INTRINSIC_WO_CHAIN: {
21129     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
21130     unsigned NumLoBits = 0;
21131     switch (IntId) {
21132     default: break;
21133     case Intrinsic::x86_sse_movmsk_ps:
21134     case Intrinsic::x86_avx_movmsk_ps_256:
21135     case Intrinsic::x86_sse2_movmsk_pd:
21136     case Intrinsic::x86_avx_movmsk_pd_256:
21137     case Intrinsic::x86_mmx_pmovmskb:
21138     case Intrinsic::x86_sse2_pmovmskb_128:
21139     case Intrinsic::x86_avx2_pmovmskb: {
21140       // High bits of movmskp{s|d}, pmovmskb are known zero.
21141       switch (IntId) {
21142         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
21143         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
21144         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
21145         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
21146         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
21147         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
21148         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
21149         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
21150       }
21151       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
21152       break;
21153     }
21154     }
21155     break;
21156   }
21157   }
21158 }
21159
21160 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
21161   SDValue Op,
21162   const SelectionDAG &,
21163   unsigned Depth) const {
21164   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
21165   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
21166     return Op.getValueType().getScalarType().getSizeInBits();
21167
21168   // Fallback case.
21169   return 1;
21170 }
21171
21172 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
21173 /// node is a GlobalAddress + offset.
21174 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
21175                                        const GlobalValue* &GA,
21176                                        int64_t &Offset) const {
21177   if (N->getOpcode() == X86ISD::Wrapper) {
21178     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
21179       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
21180       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
21181       return true;
21182     }
21183   }
21184   return TargetLowering::isGAPlusOffset(N, GA, Offset);
21185 }
21186
21187 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
21188 /// same as extracting the high 128-bit part of 256-bit vector and then
21189 /// inserting the result into the low part of a new 256-bit vector
21190 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
21191   EVT VT = SVOp->getValueType(0);
21192   unsigned NumElems = VT.getVectorNumElements();
21193
21194   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
21195   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
21196     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
21197         SVOp->getMaskElt(j) >= 0)
21198       return false;
21199
21200   return true;
21201 }
21202
21203 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
21204 /// same as extracting the low 128-bit part of 256-bit vector and then
21205 /// inserting the result into the high part of a new 256-bit vector
21206 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
21207   EVT VT = SVOp->getValueType(0);
21208   unsigned NumElems = VT.getVectorNumElements();
21209
21210   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
21211   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
21212     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
21213         SVOp->getMaskElt(j) >= 0)
21214       return false;
21215
21216   return true;
21217 }
21218
21219 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
21220 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
21221                                         TargetLowering::DAGCombinerInfo &DCI,
21222                                         const X86Subtarget* Subtarget) {
21223   SDLoc dl(N);
21224   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
21225   SDValue V1 = SVOp->getOperand(0);
21226   SDValue V2 = SVOp->getOperand(1);
21227   EVT VT = SVOp->getValueType(0);
21228   unsigned NumElems = VT.getVectorNumElements();
21229
21230   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
21231       V2.getOpcode() == ISD::CONCAT_VECTORS) {
21232     //
21233     //                   0,0,0,...
21234     //                      |
21235     //    V      UNDEF    BUILD_VECTOR    UNDEF
21236     //     \      /           \           /
21237     //  CONCAT_VECTOR         CONCAT_VECTOR
21238     //         \                  /
21239     //          \                /
21240     //          RESULT: V + zero extended
21241     //
21242     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
21243         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
21244         V1.getOperand(1).getOpcode() != ISD::UNDEF)
21245       return SDValue();
21246
21247     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
21248       return SDValue();
21249
21250     // To match the shuffle mask, the first half of the mask should
21251     // be exactly the first vector, and all the rest a splat with the
21252     // first element of the second one.
21253     for (unsigned i = 0; i != NumElems/2; ++i)
21254       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
21255           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
21256         return SDValue();
21257
21258     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
21259     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
21260       if (Ld->hasNUsesOfValue(1, 0)) {
21261         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
21262         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
21263         SDValue ResNode =
21264           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
21265                                   Ld->getMemoryVT(),
21266                                   Ld->getPointerInfo(),
21267                                   Ld->getAlignment(),
21268                                   false/*isVolatile*/, true/*ReadMem*/,
21269                                   false/*WriteMem*/);
21270
21271         // Make sure the newly-created LOAD is in the same position as Ld in
21272         // terms of dependency. We create a TokenFactor for Ld and ResNode,
21273         // and update uses of Ld's output chain to use the TokenFactor.
21274         if (Ld->hasAnyUseOfValue(1)) {
21275           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
21276                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
21277           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
21278           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
21279                                  SDValue(ResNode.getNode(), 1));
21280         }
21281
21282         return DAG.getBitcast(VT, ResNode);
21283       }
21284     }
21285
21286     // Emit a zeroed vector and insert the desired subvector on its
21287     // first half.
21288     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
21289     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
21290     return DCI.CombineTo(N, InsV);
21291   }
21292
21293   //===--------------------------------------------------------------------===//
21294   // Combine some shuffles into subvector extracts and inserts:
21295   //
21296
21297   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
21298   if (isShuffleHigh128VectorInsertLow(SVOp)) {
21299     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
21300     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
21301     return DCI.CombineTo(N, InsV);
21302   }
21303
21304   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
21305   if (isShuffleLow128VectorInsertHigh(SVOp)) {
21306     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
21307     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
21308     return DCI.CombineTo(N, InsV);
21309   }
21310
21311   return SDValue();
21312 }
21313
21314 /// \brief Combine an arbitrary chain of shuffles into a single instruction if
21315 /// possible.
21316 ///
21317 /// This is the leaf of the recursive combinine below. When we have found some
21318 /// chain of single-use x86 shuffle instructions and accumulated the combined
21319 /// shuffle mask represented by them, this will try to pattern match that mask
21320 /// into either a single instruction if there is a special purpose instruction
21321 /// for this operation, or into a PSHUFB instruction which is a fully general
21322 /// instruction but should only be used to replace chains over a certain depth.
21323 static bool combineX86ShuffleChain(SDValue Op, SDValue Root, ArrayRef<int> Mask,
21324                                    int Depth, bool HasPSHUFB, SelectionDAG &DAG,
21325                                    TargetLowering::DAGCombinerInfo &DCI,
21326                                    const X86Subtarget *Subtarget) {
21327   assert(!Mask.empty() && "Cannot combine an empty shuffle mask!");
21328
21329   // Find the operand that enters the chain. Note that multiple uses are OK
21330   // here, we're not going to remove the operand we find.
21331   SDValue Input = Op.getOperand(0);
21332   while (Input.getOpcode() == ISD::BITCAST)
21333     Input = Input.getOperand(0);
21334
21335   MVT VT = Input.getSimpleValueType();
21336   MVT RootVT = Root.getSimpleValueType();
21337   SDLoc DL(Root);
21338
21339   // Just remove no-op shuffle masks.
21340   if (Mask.size() == 1) {
21341     DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Input),
21342                   /*AddTo*/ true);
21343     return true;
21344   }
21345
21346   // Use the float domain if the operand type is a floating point type.
21347   bool FloatDomain = VT.isFloatingPoint();
21348
21349   // For floating point shuffles, we don't have free copies in the shuffle
21350   // instructions or the ability to load as part of the instruction, so
21351   // canonicalize their shuffles to UNPCK or MOV variants.
21352   //
21353   // Note that even with AVX we prefer the PSHUFD form of shuffle for integer
21354   // vectors because it can have a load folded into it that UNPCK cannot. This
21355   // doesn't preclude something switching to the shorter encoding post-RA.
21356   //
21357   // FIXME: Should teach these routines about AVX vector widths.
21358   if (FloatDomain && VT.getSizeInBits() == 128) {
21359     if (Mask.equals({0, 0}) || Mask.equals({1, 1})) {
21360       bool Lo = Mask.equals({0, 0});
21361       unsigned Shuffle;
21362       MVT ShuffleVT;
21363       // Check if we have SSE3 which will let us use MOVDDUP. That instruction
21364       // is no slower than UNPCKLPD but has the option to fold the input operand
21365       // into even an unaligned memory load.
21366       if (Lo && Subtarget->hasSSE3()) {
21367         Shuffle = X86ISD::MOVDDUP;
21368         ShuffleVT = MVT::v2f64;
21369       } else {
21370         // We have MOVLHPS and MOVHLPS throughout SSE and they encode smaller
21371         // than the UNPCK variants.
21372         Shuffle = Lo ? X86ISD::MOVLHPS : X86ISD::MOVHLPS;
21373         ShuffleVT = MVT::v4f32;
21374       }
21375       if (Depth == 1 && Root->getOpcode() == Shuffle)
21376         return false; // Nothing to do!
21377       Op = DAG.getBitcast(ShuffleVT, Input);
21378       DCI.AddToWorklist(Op.getNode());
21379       if (Shuffle == X86ISD::MOVDDUP)
21380         Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
21381       else
21382         Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
21383       DCI.AddToWorklist(Op.getNode());
21384       DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21385                     /*AddTo*/ true);
21386       return true;
21387     }
21388     if (Subtarget->hasSSE3() &&
21389         (Mask.equals({0, 0, 2, 2}) || Mask.equals({1, 1, 3, 3}))) {
21390       bool Lo = Mask.equals({0, 0, 2, 2});
21391       unsigned Shuffle = Lo ? X86ISD::MOVSLDUP : X86ISD::MOVSHDUP;
21392       MVT ShuffleVT = MVT::v4f32;
21393       if (Depth == 1 && Root->getOpcode() == Shuffle)
21394         return false; // Nothing to do!
21395       Op = DAG.getBitcast(ShuffleVT, Input);
21396       DCI.AddToWorklist(Op.getNode());
21397       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
21398       DCI.AddToWorklist(Op.getNode());
21399       DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21400                     /*AddTo*/ true);
21401       return true;
21402     }
21403     if (Mask.equals({0, 0, 1, 1}) || Mask.equals({2, 2, 3, 3})) {
21404       bool Lo = Mask.equals({0, 0, 1, 1});
21405       unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
21406       MVT ShuffleVT = MVT::v4f32;
21407       if (Depth == 1 && Root->getOpcode() == Shuffle)
21408         return false; // Nothing to do!
21409       Op = DAG.getBitcast(ShuffleVT, Input);
21410       DCI.AddToWorklist(Op.getNode());
21411       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
21412       DCI.AddToWorklist(Op.getNode());
21413       DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21414                     /*AddTo*/ true);
21415       return true;
21416     }
21417   }
21418
21419   // We always canonicalize the 8 x i16 and 16 x i8 shuffles into their UNPCK
21420   // variants as none of these have single-instruction variants that are
21421   // superior to the UNPCK formulation.
21422   if (!FloatDomain && VT.getSizeInBits() == 128 &&
21423       (Mask.equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
21424        Mask.equals({4, 4, 5, 5, 6, 6, 7, 7}) ||
21425        Mask.equals({0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7}) ||
21426        Mask.equals(
21427            {8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15, 15}))) {
21428     bool Lo = Mask[0] == 0;
21429     unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
21430     if (Depth == 1 && Root->getOpcode() == Shuffle)
21431       return false; // Nothing to do!
21432     MVT ShuffleVT;
21433     switch (Mask.size()) {
21434     case 8:
21435       ShuffleVT = MVT::v8i16;
21436       break;
21437     case 16:
21438       ShuffleVT = MVT::v16i8;
21439       break;
21440     default:
21441       llvm_unreachable("Impossible mask size!");
21442     };
21443     Op = DAG.getBitcast(ShuffleVT, Input);
21444     DCI.AddToWorklist(Op.getNode());
21445     Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
21446     DCI.AddToWorklist(Op.getNode());
21447     DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21448                   /*AddTo*/ true);
21449     return true;
21450   }
21451
21452   // Don't try to re-form single instruction chains under any circumstances now
21453   // that we've done encoding canonicalization for them.
21454   if (Depth < 2)
21455     return false;
21456
21457   // If we have 3 or more shuffle instructions or a chain involving PSHUFB, we
21458   // can replace them with a single PSHUFB instruction profitably. Intel's
21459   // manuals suggest only using PSHUFB if doing so replacing 5 instructions, but
21460   // in practice PSHUFB tends to be *very* fast so we're more aggressive.
21461   if ((Depth >= 3 || HasPSHUFB) && Subtarget->hasSSSE3()) {
21462     SmallVector<SDValue, 16> PSHUFBMask;
21463     int NumBytes = VT.getSizeInBits() / 8;
21464     int Ratio = NumBytes / Mask.size();
21465     for (int i = 0; i < NumBytes; ++i) {
21466       if (Mask[i / Ratio] == SM_SentinelUndef) {
21467         PSHUFBMask.push_back(DAG.getUNDEF(MVT::i8));
21468         continue;
21469       }
21470       int M = Mask[i / Ratio] != SM_SentinelZero
21471                   ? Ratio * Mask[i / Ratio] + i % Ratio
21472                   : 255;
21473       PSHUFBMask.push_back(DAG.getConstant(M, DL, MVT::i8));
21474     }
21475     MVT ByteVT = MVT::getVectorVT(MVT::i8, NumBytes);
21476     Op = DAG.getBitcast(ByteVT, Input);
21477     DCI.AddToWorklist(Op.getNode());
21478     SDValue PSHUFBMaskOp =
21479         DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVT, PSHUFBMask);
21480     DCI.AddToWorklist(PSHUFBMaskOp.getNode());
21481     Op = DAG.getNode(X86ISD::PSHUFB, DL, ByteVT, Op, PSHUFBMaskOp);
21482     DCI.AddToWorklist(Op.getNode());
21483     DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21484                   /*AddTo*/ true);
21485     return true;
21486   }
21487
21488   // Failed to find any combines.
21489   return false;
21490 }
21491
21492 /// \brief Fully generic combining of x86 shuffle instructions.
21493 ///
21494 /// This should be the last combine run over the x86 shuffle instructions. Once
21495 /// they have been fully optimized, this will recursively consider all chains
21496 /// of single-use shuffle instructions, build a generic model of the cumulative
21497 /// shuffle operation, and check for simpler instructions which implement this
21498 /// operation. We use this primarily for two purposes:
21499 ///
21500 /// 1) Collapse generic shuffles to specialized single instructions when
21501 ///    equivalent. In most cases, this is just an encoding size win, but
21502 ///    sometimes we will collapse multiple generic shuffles into a single
21503 ///    special-purpose shuffle.
21504 /// 2) Look for sequences of shuffle instructions with 3 or more total
21505 ///    instructions, and replace them with the slightly more expensive SSSE3
21506 ///    PSHUFB instruction if available. We do this as the last combining step
21507 ///    to ensure we avoid using PSHUFB if we can implement the shuffle with
21508 ///    a suitable short sequence of other instructions. The PHUFB will either
21509 ///    use a register or have to read from memory and so is slightly (but only
21510 ///    slightly) more expensive than the other shuffle instructions.
21511 ///
21512 /// Because this is inherently a quadratic operation (for each shuffle in
21513 /// a chain, we recurse up the chain), the depth is limited to 8 instructions.
21514 /// This should never be an issue in practice as the shuffle lowering doesn't
21515 /// produce sequences of more than 8 instructions.
21516 ///
21517 /// FIXME: We will currently miss some cases where the redundant shuffling
21518 /// would simplify under the threshold for PSHUFB formation because of
21519 /// combine-ordering. To fix this, we should do the redundant instruction
21520 /// combining in this recursive walk.
21521 static bool combineX86ShufflesRecursively(SDValue Op, SDValue Root,
21522                                           ArrayRef<int> RootMask,
21523                                           int Depth, bool HasPSHUFB,
21524                                           SelectionDAG &DAG,
21525                                           TargetLowering::DAGCombinerInfo &DCI,
21526                                           const X86Subtarget *Subtarget) {
21527   // Bound the depth of our recursive combine because this is ultimately
21528   // quadratic in nature.
21529   if (Depth > 8)
21530     return false;
21531
21532   // Directly rip through bitcasts to find the underlying operand.
21533   while (Op.getOpcode() == ISD::BITCAST && Op.getOperand(0).hasOneUse())
21534     Op = Op.getOperand(0);
21535
21536   MVT VT = Op.getSimpleValueType();
21537   if (!VT.isVector())
21538     return false; // Bail if we hit a non-vector.
21539
21540   assert(Root.getSimpleValueType().isVector() &&
21541          "Shuffles operate on vector types!");
21542   assert(VT.getSizeInBits() == Root.getSimpleValueType().getSizeInBits() &&
21543          "Can only combine shuffles of the same vector register size.");
21544
21545   if (!isTargetShuffle(Op.getOpcode()))
21546     return false;
21547   SmallVector<int, 16> OpMask;
21548   bool IsUnary;
21549   bool HaveMask = getTargetShuffleMask(Op.getNode(), VT, OpMask, IsUnary);
21550   // We only can combine unary shuffles which we can decode the mask for.
21551   if (!HaveMask || !IsUnary)
21552     return false;
21553
21554   assert(VT.getVectorNumElements() == OpMask.size() &&
21555          "Different mask size from vector size!");
21556   assert(((RootMask.size() > OpMask.size() &&
21557            RootMask.size() % OpMask.size() == 0) ||
21558           (OpMask.size() > RootMask.size() &&
21559            OpMask.size() % RootMask.size() == 0) ||
21560           OpMask.size() == RootMask.size()) &&
21561          "The smaller number of elements must divide the larger.");
21562   int RootRatio = std::max<int>(1, OpMask.size() / RootMask.size());
21563   int OpRatio = std::max<int>(1, RootMask.size() / OpMask.size());
21564   assert(((RootRatio == 1 && OpRatio == 1) ||
21565           (RootRatio == 1) != (OpRatio == 1)) &&
21566          "Must not have a ratio for both incoming and op masks!");
21567
21568   SmallVector<int, 16> Mask;
21569   Mask.reserve(std::max(OpMask.size(), RootMask.size()));
21570
21571   // Merge this shuffle operation's mask into our accumulated mask. Note that
21572   // this shuffle's mask will be the first applied to the input, followed by the
21573   // root mask to get us all the way to the root value arrangement. The reason
21574   // for this order is that we are recursing up the operation chain.
21575   for (int i = 0, e = std::max(OpMask.size(), RootMask.size()); i < e; ++i) {
21576     int RootIdx = i / RootRatio;
21577     if (RootMask[RootIdx] < 0) {
21578       // This is a zero or undef lane, we're done.
21579       Mask.push_back(RootMask[RootIdx]);
21580       continue;
21581     }
21582
21583     int RootMaskedIdx = RootMask[RootIdx] * RootRatio + i % RootRatio;
21584     int OpIdx = RootMaskedIdx / OpRatio;
21585     if (OpMask[OpIdx] < 0) {
21586       // The incoming lanes are zero or undef, it doesn't matter which ones we
21587       // are using.
21588       Mask.push_back(OpMask[OpIdx]);
21589       continue;
21590     }
21591
21592     // Ok, we have non-zero lanes, map them through.
21593     Mask.push_back(OpMask[OpIdx] * OpRatio +
21594                    RootMaskedIdx % OpRatio);
21595   }
21596
21597   // See if we can recurse into the operand to combine more things.
21598   switch (Op.getOpcode()) {
21599     case X86ISD::PSHUFB:
21600       HasPSHUFB = true;
21601     case X86ISD::PSHUFD:
21602     case X86ISD::PSHUFHW:
21603     case X86ISD::PSHUFLW:
21604       if (Op.getOperand(0).hasOneUse() &&
21605           combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
21606                                         HasPSHUFB, DAG, DCI, Subtarget))
21607         return true;
21608       break;
21609
21610     case X86ISD::UNPCKL:
21611     case X86ISD::UNPCKH:
21612       assert(Op.getOperand(0) == Op.getOperand(1) && "We only combine unary shuffles!");
21613       // We can't check for single use, we have to check that this shuffle is the only user.
21614       if (Op->isOnlyUserOf(Op.getOperand(0).getNode()) &&
21615           combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
21616                                         HasPSHUFB, DAG, DCI, Subtarget))
21617           return true;
21618       break;
21619   }
21620
21621   // Minor canonicalization of the accumulated shuffle mask to make it easier
21622   // to match below. All this does is detect masks with squential pairs of
21623   // elements, and shrink them to the half-width mask. It does this in a loop
21624   // so it will reduce the size of the mask to the minimal width mask which
21625   // performs an equivalent shuffle.
21626   SmallVector<int, 16> WidenedMask;
21627   while (Mask.size() > 1 && canWidenShuffleElements(Mask, WidenedMask)) {
21628     Mask = std::move(WidenedMask);
21629     WidenedMask.clear();
21630   }
21631
21632   return combineX86ShuffleChain(Op, Root, Mask, Depth, HasPSHUFB, DAG, DCI,
21633                                 Subtarget);
21634 }
21635
21636 /// \brief Get the PSHUF-style mask from PSHUF node.
21637 ///
21638 /// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
21639 /// PSHUF-style masks that can be reused with such instructions.
21640 static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
21641   MVT VT = N.getSimpleValueType();
21642   SmallVector<int, 4> Mask;
21643   bool IsUnary;
21644   bool HaveMask = getTargetShuffleMask(N.getNode(), VT, Mask, IsUnary);
21645   (void)HaveMask;
21646   assert(HaveMask);
21647
21648   // If we have more than 128-bits, only the low 128-bits of shuffle mask
21649   // matter. Check that the upper masks are repeats and remove them.
21650   if (VT.getSizeInBits() > 128) {
21651     int LaneElts = 128 / VT.getScalarSizeInBits();
21652 #ifndef NDEBUG
21653     for (int i = 1, NumLanes = VT.getSizeInBits() / 128; i < NumLanes; ++i)
21654       for (int j = 0; j < LaneElts; ++j)
21655         assert(Mask[j] == Mask[i * LaneElts + j] - (LaneElts * i) &&
21656                "Mask doesn't repeat in high 128-bit lanes!");
21657 #endif
21658     Mask.resize(LaneElts);
21659   }
21660
21661   switch (N.getOpcode()) {
21662   case X86ISD::PSHUFD:
21663     return Mask;
21664   case X86ISD::PSHUFLW:
21665     Mask.resize(4);
21666     return Mask;
21667   case X86ISD::PSHUFHW:
21668     Mask.erase(Mask.begin(), Mask.begin() + 4);
21669     for (int &M : Mask)
21670       M -= 4;
21671     return Mask;
21672   default:
21673     llvm_unreachable("No valid shuffle instruction found!");
21674   }
21675 }
21676
21677 /// \brief Search for a combinable shuffle across a chain ending in pshufd.
21678 ///
21679 /// We walk up the chain and look for a combinable shuffle, skipping over
21680 /// shuffles that we could hoist this shuffle's transformation past without
21681 /// altering anything.
21682 static SDValue
21683 combineRedundantDWordShuffle(SDValue N, MutableArrayRef<int> Mask,
21684                              SelectionDAG &DAG,
21685                              TargetLowering::DAGCombinerInfo &DCI) {
21686   assert(N.getOpcode() == X86ISD::PSHUFD &&
21687          "Called with something other than an x86 128-bit half shuffle!");
21688   SDLoc DL(N);
21689
21690   // Walk up a single-use chain looking for a combinable shuffle. Keep a stack
21691   // of the shuffles in the chain so that we can form a fresh chain to replace
21692   // this one.
21693   SmallVector<SDValue, 8> Chain;
21694   SDValue V = N.getOperand(0);
21695   for (; V.hasOneUse(); V = V.getOperand(0)) {
21696     switch (V.getOpcode()) {
21697     default:
21698       return SDValue(); // Nothing combined!
21699
21700     case ISD::BITCAST:
21701       // Skip bitcasts as we always know the type for the target specific
21702       // instructions.
21703       continue;
21704
21705     case X86ISD::PSHUFD:
21706       // Found another dword shuffle.
21707       break;
21708
21709     case X86ISD::PSHUFLW:
21710       // Check that the low words (being shuffled) are the identity in the
21711       // dword shuffle, and the high words are self-contained.
21712       if (Mask[0] != 0 || Mask[1] != 1 ||
21713           !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
21714         return SDValue();
21715
21716       Chain.push_back(V);
21717       continue;
21718
21719     case X86ISD::PSHUFHW:
21720       // Check that the high words (being shuffled) are the identity in the
21721       // dword shuffle, and the low words are self-contained.
21722       if (Mask[2] != 2 || Mask[3] != 3 ||
21723           !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
21724         return SDValue();
21725
21726       Chain.push_back(V);
21727       continue;
21728
21729     case X86ISD::UNPCKL:
21730     case X86ISD::UNPCKH:
21731       // For either i8 -> i16 or i16 -> i32 unpacks, we can combine a dword
21732       // shuffle into a preceding word shuffle.
21733       if (V.getSimpleValueType().getScalarType() != MVT::i8 &&
21734           V.getSimpleValueType().getScalarType() != MVT::i16)
21735         return SDValue();
21736
21737       // Search for a half-shuffle which we can combine with.
21738       unsigned CombineOp =
21739           V.getOpcode() == X86ISD::UNPCKL ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
21740       if (V.getOperand(0) != V.getOperand(1) ||
21741           !V->isOnlyUserOf(V.getOperand(0).getNode()))
21742         return SDValue();
21743       Chain.push_back(V);
21744       V = V.getOperand(0);
21745       do {
21746         switch (V.getOpcode()) {
21747         default:
21748           return SDValue(); // Nothing to combine.
21749
21750         case X86ISD::PSHUFLW:
21751         case X86ISD::PSHUFHW:
21752           if (V.getOpcode() == CombineOp)
21753             break;
21754
21755           Chain.push_back(V);
21756
21757           // Fallthrough!
21758         case ISD::BITCAST:
21759           V = V.getOperand(0);
21760           continue;
21761         }
21762         break;
21763       } while (V.hasOneUse());
21764       break;
21765     }
21766     // Break out of the loop if we break out of the switch.
21767     break;
21768   }
21769
21770   if (!V.hasOneUse())
21771     // We fell out of the loop without finding a viable combining instruction.
21772     return SDValue();
21773
21774   // Merge this node's mask and our incoming mask.
21775   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
21776   for (int &M : Mask)
21777     M = VMask[M];
21778   V = DAG.getNode(V.getOpcode(), DL, V.getValueType(), V.getOperand(0),
21779                   getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
21780
21781   // Rebuild the chain around this new shuffle.
21782   while (!Chain.empty()) {
21783     SDValue W = Chain.pop_back_val();
21784
21785     if (V.getValueType() != W.getOperand(0).getValueType())
21786       V = DAG.getBitcast(W.getOperand(0).getValueType(), V);
21787
21788     switch (W.getOpcode()) {
21789     default:
21790       llvm_unreachable("Only PSHUF and UNPCK instructions get here!");
21791
21792     case X86ISD::UNPCKL:
21793     case X86ISD::UNPCKH:
21794       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, V);
21795       break;
21796
21797     case X86ISD::PSHUFD:
21798     case X86ISD::PSHUFLW:
21799     case X86ISD::PSHUFHW:
21800       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, W.getOperand(1));
21801       break;
21802     }
21803   }
21804   if (V.getValueType() != N.getValueType())
21805     V = DAG.getBitcast(N.getValueType(), V);
21806
21807   // Return the new chain to replace N.
21808   return V;
21809 }
21810
21811 /// \brief Search for a combinable shuffle across a chain ending in pshuflw or pshufhw.
21812 ///
21813 /// We walk up the chain, skipping shuffles of the other half and looking
21814 /// through shuffles which switch halves trying to find a shuffle of the same
21815 /// pair of dwords.
21816 static bool combineRedundantHalfShuffle(SDValue N, MutableArrayRef<int> Mask,
21817                                         SelectionDAG &DAG,
21818                                         TargetLowering::DAGCombinerInfo &DCI) {
21819   assert(
21820       (N.getOpcode() == X86ISD::PSHUFLW || N.getOpcode() == X86ISD::PSHUFHW) &&
21821       "Called with something other than an x86 128-bit half shuffle!");
21822   SDLoc DL(N);
21823   unsigned CombineOpcode = N.getOpcode();
21824
21825   // Walk up a single-use chain looking for a combinable shuffle.
21826   SDValue V = N.getOperand(0);
21827   for (; V.hasOneUse(); V = V.getOperand(0)) {
21828     switch (V.getOpcode()) {
21829     default:
21830       return false; // Nothing combined!
21831
21832     case ISD::BITCAST:
21833       // Skip bitcasts as we always know the type for the target specific
21834       // instructions.
21835       continue;
21836
21837     case X86ISD::PSHUFLW:
21838     case X86ISD::PSHUFHW:
21839       if (V.getOpcode() == CombineOpcode)
21840         break;
21841
21842       // Other-half shuffles are no-ops.
21843       continue;
21844     }
21845     // Break out of the loop if we break out of the switch.
21846     break;
21847   }
21848
21849   if (!V.hasOneUse())
21850     // We fell out of the loop without finding a viable combining instruction.
21851     return false;
21852
21853   // Combine away the bottom node as its shuffle will be accumulated into
21854   // a preceding shuffle.
21855   DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
21856
21857   // Record the old value.
21858   SDValue Old = V;
21859
21860   // Merge this node's mask and our incoming mask (adjusted to account for all
21861   // the pshufd instructions encountered).
21862   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
21863   for (int &M : Mask)
21864     M = VMask[M];
21865   V = DAG.getNode(V.getOpcode(), DL, MVT::v8i16, V.getOperand(0),
21866                   getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
21867
21868   // Check that the shuffles didn't cancel each other out. If not, we need to
21869   // combine to the new one.
21870   if (Old != V)
21871     // Replace the combinable shuffle with the combined one, updating all users
21872     // so that we re-evaluate the chain here.
21873     DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
21874
21875   return true;
21876 }
21877
21878 /// \brief Try to combine x86 target specific shuffles.
21879 static SDValue PerformTargetShuffleCombine(SDValue N, SelectionDAG &DAG,
21880                                            TargetLowering::DAGCombinerInfo &DCI,
21881                                            const X86Subtarget *Subtarget) {
21882   SDLoc DL(N);
21883   MVT VT = N.getSimpleValueType();
21884   SmallVector<int, 4> Mask;
21885
21886   switch (N.getOpcode()) {
21887   case X86ISD::PSHUFD:
21888   case X86ISD::PSHUFLW:
21889   case X86ISD::PSHUFHW:
21890     Mask = getPSHUFShuffleMask(N);
21891     assert(Mask.size() == 4);
21892     break;
21893   default:
21894     return SDValue();
21895   }
21896
21897   // Nuke no-op shuffles that show up after combining.
21898   if (isNoopShuffleMask(Mask))
21899     return DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
21900
21901   // Look for simplifications involving one or two shuffle instructions.
21902   SDValue V = N.getOperand(0);
21903   switch (N.getOpcode()) {
21904   default:
21905     break;
21906   case X86ISD::PSHUFLW:
21907   case X86ISD::PSHUFHW:
21908     assert(VT.getScalarType() == MVT::i16 && "Bad word shuffle type!");
21909
21910     if (combineRedundantHalfShuffle(N, Mask, DAG, DCI))
21911       return SDValue(); // We combined away this shuffle, so we're done.
21912
21913     // See if this reduces to a PSHUFD which is no more expensive and can
21914     // combine with more operations. Note that it has to at least flip the
21915     // dwords as otherwise it would have been removed as a no-op.
21916     if (makeArrayRef(Mask).equals({2, 3, 0, 1})) {
21917       int DMask[] = {0, 1, 2, 3};
21918       int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
21919       DMask[DOffset + 0] = DOffset + 1;
21920       DMask[DOffset + 1] = DOffset + 0;
21921       MVT DVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
21922       V = DAG.getBitcast(DVT, V);
21923       DCI.AddToWorklist(V.getNode());
21924       V = DAG.getNode(X86ISD::PSHUFD, DL, DVT, V,
21925                       getV4X86ShuffleImm8ForMask(DMask, DL, DAG));
21926       DCI.AddToWorklist(V.getNode());
21927       return DAG.getBitcast(VT, V);
21928     }
21929
21930     // Look for shuffle patterns which can be implemented as a single unpack.
21931     // FIXME: This doesn't handle the location of the PSHUFD generically, and
21932     // only works when we have a PSHUFD followed by two half-shuffles.
21933     if (Mask[0] == Mask[1] && Mask[2] == Mask[3] &&
21934         (V.getOpcode() == X86ISD::PSHUFLW ||
21935          V.getOpcode() == X86ISD::PSHUFHW) &&
21936         V.getOpcode() != N.getOpcode() &&
21937         V.hasOneUse()) {
21938       SDValue D = V.getOperand(0);
21939       while (D.getOpcode() == ISD::BITCAST && D.hasOneUse())
21940         D = D.getOperand(0);
21941       if (D.getOpcode() == X86ISD::PSHUFD && D.hasOneUse()) {
21942         SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
21943         SmallVector<int, 4> DMask = getPSHUFShuffleMask(D);
21944         int NOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
21945         int VOffset = V.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
21946         int WordMask[8];
21947         for (int i = 0; i < 4; ++i) {
21948           WordMask[i + NOffset] = Mask[i] + NOffset;
21949           WordMask[i + VOffset] = VMask[i] + VOffset;
21950         }
21951         // Map the word mask through the DWord mask.
21952         int MappedMask[8];
21953         for (int i = 0; i < 8; ++i)
21954           MappedMask[i] = 2 * DMask[WordMask[i] / 2] + WordMask[i] % 2;
21955         if (makeArrayRef(MappedMask).equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
21956             makeArrayRef(MappedMask).equals({4, 4, 5, 5, 6, 6, 7, 7})) {
21957           // We can replace all three shuffles with an unpack.
21958           V = DAG.getBitcast(VT, D.getOperand(0));
21959           DCI.AddToWorklist(V.getNode());
21960           return DAG.getNode(MappedMask[0] == 0 ? X86ISD::UNPCKL
21961                                                 : X86ISD::UNPCKH,
21962                              DL, VT, V, V);
21963         }
21964       }
21965     }
21966
21967     break;
21968
21969   case X86ISD::PSHUFD:
21970     if (SDValue NewN = combineRedundantDWordShuffle(N, Mask, DAG, DCI))
21971       return NewN;
21972
21973     break;
21974   }
21975
21976   return SDValue();
21977 }
21978
21979 /// \brief Try to combine a shuffle into a target-specific add-sub node.
21980 ///
21981 /// We combine this directly on the abstract vector shuffle nodes so it is
21982 /// easier to generically match. We also insert dummy vector shuffle nodes for
21983 /// the operands which explicitly discard the lanes which are unused by this
21984 /// operation to try to flow through the rest of the combiner the fact that
21985 /// they're unused.
21986 static SDValue combineShuffleToAddSub(SDNode *N, SelectionDAG &DAG) {
21987   SDLoc DL(N);
21988   EVT VT = N->getValueType(0);
21989
21990   // We only handle target-independent shuffles.
21991   // FIXME: It would be easy and harmless to use the target shuffle mask
21992   // extraction tool to support more.
21993   if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
21994     return SDValue();
21995
21996   auto *SVN = cast<ShuffleVectorSDNode>(N);
21997   ArrayRef<int> Mask = SVN->getMask();
21998   SDValue V1 = N->getOperand(0);
21999   SDValue V2 = N->getOperand(1);
22000
22001   // We require the first shuffle operand to be the SUB node, and the second to
22002   // be the ADD node.
22003   // FIXME: We should support the commuted patterns.
22004   if (V1->getOpcode() != ISD::FSUB || V2->getOpcode() != ISD::FADD)
22005     return SDValue();
22006
22007   // If there are other uses of these operations we can't fold them.
22008   if (!V1->hasOneUse() || !V2->hasOneUse())
22009     return SDValue();
22010
22011   // Ensure that both operations have the same operands. Note that we can
22012   // commute the FADD operands.
22013   SDValue LHS = V1->getOperand(0), RHS = V1->getOperand(1);
22014   if ((V2->getOperand(0) != LHS || V2->getOperand(1) != RHS) &&
22015       (V2->getOperand(0) != RHS || V2->getOperand(1) != LHS))
22016     return SDValue();
22017
22018   // We're looking for blends between FADD and FSUB nodes. We insist on these
22019   // nodes being lined up in a specific expected pattern.
22020   if (!(isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
22021         isShuffleEquivalent(V1, V2, Mask, {0, 5, 2, 7}) ||
22022         isShuffleEquivalent(V1, V2, Mask, {0, 9, 2, 11, 4, 13, 6, 15})))
22023     return SDValue();
22024
22025   // Only specific types are legal at this point, assert so we notice if and
22026   // when these change.
22027   assert((VT == MVT::v4f32 || VT == MVT::v2f64 || VT == MVT::v8f32 ||
22028           VT == MVT::v4f64) &&
22029          "Unknown vector type encountered!");
22030
22031   return DAG.getNode(X86ISD::ADDSUB, DL, VT, LHS, RHS);
22032 }
22033
22034 /// PerformShuffleCombine - Performs several different shuffle combines.
22035 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
22036                                      TargetLowering::DAGCombinerInfo &DCI,
22037                                      const X86Subtarget *Subtarget) {
22038   SDLoc dl(N);
22039   SDValue N0 = N->getOperand(0);
22040   SDValue N1 = N->getOperand(1);
22041   EVT VT = N->getValueType(0);
22042
22043   // Don't create instructions with illegal types after legalize types has run.
22044   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22045   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
22046     return SDValue();
22047
22048   // If we have legalized the vector types, look for blends of FADD and FSUB
22049   // nodes that we can fuse into an ADDSUB node.
22050   if (TLI.isTypeLegal(VT) && Subtarget->hasSSE3())
22051     if (SDValue AddSub = combineShuffleToAddSub(N, DAG))
22052       return AddSub;
22053
22054   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
22055   if (Subtarget->hasFp256() && VT.is256BitVector() &&
22056       N->getOpcode() == ISD::VECTOR_SHUFFLE)
22057     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
22058
22059   // During Type Legalization, when promoting illegal vector types,
22060   // the backend might introduce new shuffle dag nodes and bitcasts.
22061   //
22062   // This code performs the following transformation:
22063   // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
22064   //       (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
22065   //
22066   // We do this only if both the bitcast and the BINOP dag nodes have
22067   // one use. Also, perform this transformation only if the new binary
22068   // operation is legal. This is to avoid introducing dag nodes that
22069   // potentially need to be further expanded (or custom lowered) into a
22070   // less optimal sequence of dag nodes.
22071   if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
22072       N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
22073       N0.getOpcode() == ISD::BITCAST) {
22074     SDValue BC0 = N0.getOperand(0);
22075     EVT SVT = BC0.getValueType();
22076     unsigned Opcode = BC0.getOpcode();
22077     unsigned NumElts = VT.getVectorNumElements();
22078
22079     if (BC0.hasOneUse() && SVT.isVector() &&
22080         SVT.getVectorNumElements() * 2 == NumElts &&
22081         TLI.isOperationLegal(Opcode, VT)) {
22082       bool CanFold = false;
22083       switch (Opcode) {
22084       default : break;
22085       case ISD::ADD :
22086       case ISD::FADD :
22087       case ISD::SUB :
22088       case ISD::FSUB :
22089       case ISD::MUL :
22090       case ISD::FMUL :
22091         CanFold = true;
22092       }
22093
22094       unsigned SVTNumElts = SVT.getVectorNumElements();
22095       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
22096       for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
22097         CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
22098       for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
22099         CanFold = SVOp->getMaskElt(i) < 0;
22100
22101       if (CanFold) {
22102         SDValue BC00 = DAG.getBitcast(VT, BC0.getOperand(0));
22103         SDValue BC01 = DAG.getBitcast(VT, BC0.getOperand(1));
22104         SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
22105         return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
22106       }
22107     }
22108   }
22109
22110   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
22111   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
22112   // consecutive, non-overlapping, and in the right order.
22113   SmallVector<SDValue, 16> Elts;
22114   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
22115     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
22116
22117   if (SDValue LD = EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true))
22118     return LD;
22119
22120   if (isTargetShuffle(N->getOpcode())) {
22121     SDValue Shuffle =
22122         PerformTargetShuffleCombine(SDValue(N, 0), DAG, DCI, Subtarget);
22123     if (Shuffle.getNode())
22124       return Shuffle;
22125
22126     // Try recursively combining arbitrary sequences of x86 shuffle
22127     // instructions into higher-order shuffles. We do this after combining
22128     // specific PSHUF instruction sequences into their minimal form so that we
22129     // can evaluate how many specialized shuffle instructions are involved in
22130     // a particular chain.
22131     SmallVector<int, 1> NonceMask; // Just a placeholder.
22132     NonceMask.push_back(0);
22133     if (combineX86ShufflesRecursively(SDValue(N, 0), SDValue(N, 0), NonceMask,
22134                                       /*Depth*/ 1, /*HasPSHUFB*/ false, DAG,
22135                                       DCI, Subtarget))
22136       return SDValue(); // This routine will use CombineTo to replace N.
22137   }
22138
22139   return SDValue();
22140 }
22141
22142 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
22143 /// specific shuffle of a load can be folded into a single element load.
22144 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
22145 /// shuffles have been custom lowered so we need to handle those here.
22146 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
22147                                          TargetLowering::DAGCombinerInfo &DCI) {
22148   if (DCI.isBeforeLegalizeOps())
22149     return SDValue();
22150
22151   SDValue InVec = N->getOperand(0);
22152   SDValue EltNo = N->getOperand(1);
22153
22154   if (!isa<ConstantSDNode>(EltNo))
22155     return SDValue();
22156
22157   EVT OriginalVT = InVec.getValueType();
22158
22159   if (InVec.getOpcode() == ISD::BITCAST) {
22160     // Don't duplicate a load with other uses.
22161     if (!InVec.hasOneUse())
22162       return SDValue();
22163     EVT BCVT = InVec.getOperand(0).getValueType();
22164     if (!BCVT.isVector() ||
22165         BCVT.getVectorNumElements() != OriginalVT.getVectorNumElements())
22166       return SDValue();
22167     InVec = InVec.getOperand(0);
22168   }
22169
22170   EVT CurrentVT = InVec.getValueType();
22171
22172   if (!isTargetShuffle(InVec.getOpcode()))
22173     return SDValue();
22174
22175   // Don't duplicate a load with other uses.
22176   if (!InVec.hasOneUse())
22177     return SDValue();
22178
22179   SmallVector<int, 16> ShuffleMask;
22180   bool UnaryShuffle;
22181   if (!getTargetShuffleMask(InVec.getNode(), CurrentVT.getSimpleVT(),
22182                             ShuffleMask, UnaryShuffle))
22183     return SDValue();
22184
22185   // Select the input vector, guarding against out of range extract vector.
22186   unsigned NumElems = CurrentVT.getVectorNumElements();
22187   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
22188   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
22189   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
22190                                          : InVec.getOperand(1);
22191
22192   // If inputs to shuffle are the same for both ops, then allow 2 uses
22193   unsigned AllowedUses = InVec.getNumOperands() > 1 &&
22194                          InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
22195
22196   if (LdNode.getOpcode() == ISD::BITCAST) {
22197     // Don't duplicate a load with other uses.
22198     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
22199       return SDValue();
22200
22201     AllowedUses = 1; // only allow 1 load use if we have a bitcast
22202     LdNode = LdNode.getOperand(0);
22203   }
22204
22205   if (!ISD::isNormalLoad(LdNode.getNode()))
22206     return SDValue();
22207
22208   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
22209
22210   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
22211     return SDValue();
22212
22213   EVT EltVT = N->getValueType(0);
22214   // If there's a bitcast before the shuffle, check if the load type and
22215   // alignment is valid.
22216   unsigned Align = LN0->getAlignment();
22217   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22218   unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
22219       EltVT.getTypeForEVT(*DAG.getContext()));
22220
22221   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, EltVT))
22222     return SDValue();
22223
22224   // All checks match so transform back to vector_shuffle so that DAG combiner
22225   // can finish the job
22226   SDLoc dl(N);
22227
22228   // Create shuffle node taking into account the case that its a unary shuffle
22229   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(CurrentVT)
22230                                    : InVec.getOperand(1);
22231   Shuffle = DAG.getVectorShuffle(CurrentVT, dl,
22232                                  InVec.getOperand(0), Shuffle,
22233                                  &ShuffleMask[0]);
22234   Shuffle = DAG.getBitcast(OriginalVT, Shuffle);
22235   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
22236                      EltNo);
22237 }
22238
22239 /// \brief Detect bitcasts between i32 to x86mmx low word. Since MMX types are
22240 /// special and don't usually play with other vector types, it's better to
22241 /// handle them early to be sure we emit efficient code by avoiding
22242 /// store-load conversions.
22243 static SDValue PerformBITCASTCombine(SDNode *N, SelectionDAG &DAG) {
22244   if (N->getValueType(0) != MVT::x86mmx ||
22245       N->getOperand(0)->getOpcode() != ISD::BUILD_VECTOR ||
22246       N->getOperand(0)->getValueType(0) != MVT::v2i32)
22247     return SDValue();
22248
22249   SDValue V = N->getOperand(0);
22250   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V.getOperand(1));
22251   if (C && C->getZExtValue() == 0 && V.getOperand(0).getValueType() == MVT::i32)
22252     return DAG.getNode(X86ISD::MMX_MOVW2D, SDLoc(V.getOperand(0)),
22253                        N->getValueType(0), V.getOperand(0));
22254
22255   return SDValue();
22256 }
22257
22258 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
22259 /// generation and convert it from being a bunch of shuffles and extracts
22260 /// into a somewhat faster sequence. For i686, the best sequence is apparently
22261 /// storing the value and loading scalars back, while for x64 we should
22262 /// use 64-bit extracts and shifts.
22263 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
22264                                          TargetLowering::DAGCombinerInfo &DCI) {
22265   if (SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI))
22266     return NewOp;
22267
22268   SDValue InputVector = N->getOperand(0);
22269   SDLoc dl(InputVector);
22270   // Detect mmx to i32 conversion through a v2i32 elt extract.
22271   if (InputVector.getOpcode() == ISD::BITCAST && InputVector.hasOneUse() &&
22272       N->getValueType(0) == MVT::i32 &&
22273       InputVector.getValueType() == MVT::v2i32) {
22274
22275     // The bitcast source is a direct mmx result.
22276     SDValue MMXSrc = InputVector.getNode()->getOperand(0);
22277     if (MMXSrc.getValueType() == MVT::x86mmx)
22278       return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
22279                          N->getValueType(0),
22280                          InputVector.getNode()->getOperand(0));
22281
22282     // The mmx is indirect: (i64 extract_elt (v1i64 bitcast (x86mmx ...))).
22283     SDValue MMXSrcOp = MMXSrc.getOperand(0);
22284     if (MMXSrc.getOpcode() == ISD::EXTRACT_VECTOR_ELT && MMXSrc.hasOneUse() &&
22285         MMXSrc.getValueType() == MVT::i64 && MMXSrcOp.hasOneUse() &&
22286         MMXSrcOp.getOpcode() == ISD::BITCAST &&
22287         MMXSrcOp.getValueType() == MVT::v1i64 &&
22288         MMXSrcOp.getOperand(0).getValueType() == MVT::x86mmx)
22289       return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
22290                          N->getValueType(0),
22291                          MMXSrcOp.getOperand(0));
22292   }
22293
22294   EVT VT = N->getValueType(0);
22295
22296   if (VT == MVT::i1 && dyn_cast<ConstantSDNode>(N->getOperand(1)) &&
22297       InputVector.getOpcode() == ISD::BITCAST &&
22298       dyn_cast<ConstantSDNode>(InputVector.getOperand(0))) {
22299     uint64_t ExtractedElt =
22300           cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
22301     uint64_t InputValue =
22302           cast<ConstantSDNode>(InputVector.getOperand(0))->getZExtValue();
22303     uint64_t Res = (InputValue >> ExtractedElt) & 1;
22304     return DAG.getConstant(Res, dl, MVT::i1);
22305   }
22306   // Only operate on vectors of 4 elements, where the alternative shuffling
22307   // gets to be more expensive.
22308   if (InputVector.getValueType() != MVT::v4i32)
22309     return SDValue();
22310
22311   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
22312   // single use which is a sign-extend or zero-extend, and all elements are
22313   // used.
22314   SmallVector<SDNode *, 4> Uses;
22315   unsigned ExtractedElements = 0;
22316   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
22317        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
22318     if (UI.getUse().getResNo() != InputVector.getResNo())
22319       return SDValue();
22320
22321     SDNode *Extract = *UI;
22322     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
22323       return SDValue();
22324
22325     if (Extract->getValueType(0) != MVT::i32)
22326       return SDValue();
22327     if (!Extract->hasOneUse())
22328       return SDValue();
22329     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
22330         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
22331       return SDValue();
22332     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
22333       return SDValue();
22334
22335     // Record which element was extracted.
22336     ExtractedElements |=
22337       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
22338
22339     Uses.push_back(Extract);
22340   }
22341
22342   // If not all the elements were used, this may not be worthwhile.
22343   if (ExtractedElements != 15)
22344     return SDValue();
22345
22346   // Ok, we've now decided to do the transformation.
22347   // If 64-bit shifts are legal, use the extract-shift sequence,
22348   // otherwise bounce the vector off the cache.
22349   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22350   SDValue Vals[4];
22351
22352   if (TLI.isOperationLegal(ISD::SRA, MVT::i64)) {
22353     SDValue Cst = DAG.getBitcast(MVT::v2i64, InputVector);
22354     auto &DL = DAG.getDataLayout();
22355     EVT VecIdxTy = DAG.getTargetLoweringInfo().getVectorIdxTy(DL);
22356     SDValue BottomHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
22357       DAG.getConstant(0, dl, VecIdxTy));
22358     SDValue TopHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
22359       DAG.getConstant(1, dl, VecIdxTy));
22360
22361     SDValue ShAmt = DAG.getConstant(
22362         32, dl, DAG.getTargetLoweringInfo().getShiftAmountTy(MVT::i64, DL));
22363     Vals[0] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BottomHalf);
22364     Vals[1] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
22365       DAG.getNode(ISD::SRA, dl, MVT::i64, BottomHalf, ShAmt));
22366     Vals[2] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, TopHalf);
22367     Vals[3] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
22368       DAG.getNode(ISD::SRA, dl, MVT::i64, TopHalf, ShAmt));
22369   } else {
22370     // Store the value to a temporary stack slot.
22371     SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
22372     SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
22373       MachinePointerInfo(), false, false, 0);
22374
22375     EVT ElementType = InputVector.getValueType().getVectorElementType();
22376     unsigned EltSize = ElementType.getSizeInBits() / 8;
22377
22378     // Replace each use (extract) with a load of the appropriate element.
22379     for (unsigned i = 0; i < 4; ++i) {
22380       uint64_t Offset = EltSize * i;
22381       auto PtrVT = TLI.getPointerTy(DAG.getDataLayout());
22382       SDValue OffsetVal = DAG.getConstant(Offset, dl, PtrVT);
22383
22384       SDValue ScalarAddr =
22385           DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, OffsetVal);
22386
22387       // Load the scalar.
22388       Vals[i] = DAG.getLoad(ElementType, dl, Ch,
22389                             ScalarAddr, MachinePointerInfo(),
22390                             false, false, false, 0);
22391
22392     }
22393   }
22394
22395   // Replace the extracts
22396   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
22397     UE = Uses.end(); UI != UE; ++UI) {
22398     SDNode *Extract = *UI;
22399
22400     SDValue Idx = Extract->getOperand(1);
22401     uint64_t IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
22402     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), Vals[IdxVal]);
22403   }
22404
22405   // The replacement was made in place; don't return anything.
22406   return SDValue();
22407 }
22408
22409 static SDValue
22410 transformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
22411                                       const X86Subtarget *Subtarget) {
22412   SDLoc dl(N);
22413   SDValue Cond = N->getOperand(0);
22414   SDValue LHS = N->getOperand(1);
22415   SDValue RHS = N->getOperand(2);
22416
22417   if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
22418     SDValue CondSrc = Cond->getOperand(0);
22419     if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
22420       Cond = CondSrc->getOperand(0);
22421   }
22422
22423   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
22424     return SDValue();
22425
22426   // A vselect where all conditions and data are constants can be optimized into
22427   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
22428   if (ISD::isBuildVectorOfConstantSDNodes(LHS.getNode()) &&
22429       ISD::isBuildVectorOfConstantSDNodes(RHS.getNode()))
22430     return SDValue();
22431
22432   unsigned MaskValue = 0;
22433   if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
22434     return SDValue();
22435
22436   MVT VT = N->getSimpleValueType(0);
22437   unsigned NumElems = VT.getVectorNumElements();
22438   SmallVector<int, 8> ShuffleMask(NumElems, -1);
22439   for (unsigned i = 0; i < NumElems; ++i) {
22440     // Be sure we emit undef where we can.
22441     if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
22442       ShuffleMask[i] = -1;
22443     else
22444       ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
22445   }
22446
22447   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22448   if (!TLI.isShuffleMaskLegal(ShuffleMask, VT))
22449     return SDValue();
22450   return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
22451 }
22452
22453 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
22454 /// nodes.
22455 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
22456                                     TargetLowering::DAGCombinerInfo &DCI,
22457                                     const X86Subtarget *Subtarget) {
22458   SDLoc DL(N);
22459   SDValue Cond = N->getOperand(0);
22460   // Get the LHS/RHS of the select.
22461   SDValue LHS = N->getOperand(1);
22462   SDValue RHS = N->getOperand(2);
22463   EVT VT = LHS.getValueType();
22464   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22465
22466   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
22467   // instructions match the semantics of the common C idiom x<y?x:y but not
22468   // x<=y?x:y, because of how they handle negative zero (which can be
22469   // ignored in unsafe-math mode).
22470   // We also try to create v2f32 min/max nodes, which we later widen to v4f32.
22471   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
22472       VT != MVT::f80 && (TLI.isTypeLegal(VT) || VT == MVT::v2f32) &&
22473       (Subtarget->hasSSE2() ||
22474        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
22475     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
22476
22477     unsigned Opcode = 0;
22478     // Check for x CC y ? x : y.
22479     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
22480         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
22481       switch (CC) {
22482       default: break;
22483       case ISD::SETULT:
22484         // Converting this to a min would handle NaNs incorrectly, and swapping
22485         // the operands would cause it to handle comparisons between positive
22486         // and negative zero incorrectly.
22487         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
22488           if (!DAG.getTarget().Options.UnsafeFPMath &&
22489               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
22490             break;
22491           std::swap(LHS, RHS);
22492         }
22493         Opcode = X86ISD::FMIN;
22494         break;
22495       case ISD::SETOLE:
22496         // Converting this to a min would handle comparisons between positive
22497         // and negative zero incorrectly.
22498         if (!DAG.getTarget().Options.UnsafeFPMath &&
22499             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
22500           break;
22501         Opcode = X86ISD::FMIN;
22502         break;
22503       case ISD::SETULE:
22504         // Converting this to a min would handle both negative zeros and NaNs
22505         // incorrectly, but we can swap the operands to fix both.
22506         std::swap(LHS, RHS);
22507       case ISD::SETOLT:
22508       case ISD::SETLT:
22509       case ISD::SETLE:
22510         Opcode = X86ISD::FMIN;
22511         break;
22512
22513       case ISD::SETOGE:
22514         // Converting this to a max would handle comparisons between positive
22515         // and negative zero incorrectly.
22516         if (!DAG.getTarget().Options.UnsafeFPMath &&
22517             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
22518           break;
22519         Opcode = X86ISD::FMAX;
22520         break;
22521       case ISD::SETUGT:
22522         // Converting this to a max would handle NaNs incorrectly, and swapping
22523         // the operands would cause it to handle comparisons between positive
22524         // and negative zero incorrectly.
22525         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
22526           if (!DAG.getTarget().Options.UnsafeFPMath &&
22527               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
22528             break;
22529           std::swap(LHS, RHS);
22530         }
22531         Opcode = X86ISD::FMAX;
22532         break;
22533       case ISD::SETUGE:
22534         // Converting this to a max would handle both negative zeros and NaNs
22535         // incorrectly, but we can swap the operands to fix both.
22536         std::swap(LHS, RHS);
22537       case ISD::SETOGT:
22538       case ISD::SETGT:
22539       case ISD::SETGE:
22540         Opcode = X86ISD::FMAX;
22541         break;
22542       }
22543     // Check for x CC y ? y : x -- a min/max with reversed arms.
22544     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
22545                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
22546       switch (CC) {
22547       default: break;
22548       case ISD::SETOGE:
22549         // Converting this to a min would handle comparisons between positive
22550         // and negative zero incorrectly, and swapping the operands would
22551         // cause it to handle NaNs incorrectly.
22552         if (!DAG.getTarget().Options.UnsafeFPMath &&
22553             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
22554           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
22555             break;
22556           std::swap(LHS, RHS);
22557         }
22558         Opcode = X86ISD::FMIN;
22559         break;
22560       case ISD::SETUGT:
22561         // Converting this to a min would handle NaNs incorrectly.
22562         if (!DAG.getTarget().Options.UnsafeFPMath &&
22563             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
22564           break;
22565         Opcode = X86ISD::FMIN;
22566         break;
22567       case ISD::SETUGE:
22568         // Converting this to a min would handle both negative zeros and NaNs
22569         // incorrectly, but we can swap the operands to fix both.
22570         std::swap(LHS, RHS);
22571       case ISD::SETOGT:
22572       case ISD::SETGT:
22573       case ISD::SETGE:
22574         Opcode = X86ISD::FMIN;
22575         break;
22576
22577       case ISD::SETULT:
22578         // Converting this to a max would handle NaNs incorrectly.
22579         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
22580           break;
22581         Opcode = X86ISD::FMAX;
22582         break;
22583       case ISD::SETOLE:
22584         // Converting this to a max would handle comparisons between positive
22585         // and negative zero incorrectly, and swapping the operands would
22586         // cause it to handle NaNs incorrectly.
22587         if (!DAG.getTarget().Options.UnsafeFPMath &&
22588             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
22589           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
22590             break;
22591           std::swap(LHS, RHS);
22592         }
22593         Opcode = X86ISD::FMAX;
22594         break;
22595       case ISD::SETULE:
22596         // Converting this to a max would handle both negative zeros and NaNs
22597         // incorrectly, but we can swap the operands to fix both.
22598         std::swap(LHS, RHS);
22599       case ISD::SETOLT:
22600       case ISD::SETLT:
22601       case ISD::SETLE:
22602         Opcode = X86ISD::FMAX;
22603         break;
22604       }
22605     }
22606
22607     if (Opcode)
22608       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
22609   }
22610
22611   EVT CondVT = Cond.getValueType();
22612   if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
22613       CondVT.getVectorElementType() == MVT::i1) {
22614     // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
22615     // lowering on KNL. In this case we convert it to
22616     // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
22617     // The same situation for all 128 and 256-bit vectors of i8 and i16.
22618     // Since SKX these selects have a proper lowering.
22619     EVT OpVT = LHS.getValueType();
22620     if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
22621         (OpVT.getVectorElementType() == MVT::i8 ||
22622          OpVT.getVectorElementType() == MVT::i16) &&
22623         !(Subtarget->hasBWI() && Subtarget->hasVLX())) {
22624       Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
22625       DCI.AddToWorklist(Cond.getNode());
22626       return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
22627     }
22628   }
22629   // If this is a select between two integer constants, try to do some
22630   // optimizations.
22631   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
22632     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
22633       // Don't do this for crazy integer types.
22634       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
22635         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
22636         // so that TrueC (the true value) is larger than FalseC.
22637         bool NeedsCondInvert = false;
22638
22639         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
22640             // Efficiently invertible.
22641             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
22642              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
22643               isa<ConstantSDNode>(Cond.getOperand(1))))) {
22644           NeedsCondInvert = true;
22645           std::swap(TrueC, FalseC);
22646         }
22647
22648         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
22649         if (FalseC->getAPIntValue() == 0 &&
22650             TrueC->getAPIntValue().isPowerOf2()) {
22651           if (NeedsCondInvert) // Invert the condition if needed.
22652             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
22653                                DAG.getConstant(1, DL, Cond.getValueType()));
22654
22655           // Zero extend the condition if needed.
22656           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
22657
22658           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
22659           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
22660                              DAG.getConstant(ShAmt, DL, MVT::i8));
22661         }
22662
22663         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
22664         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
22665           if (NeedsCondInvert) // Invert the condition if needed.
22666             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
22667                                DAG.getConstant(1, DL, Cond.getValueType()));
22668
22669           // Zero extend the condition if needed.
22670           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
22671                              FalseC->getValueType(0), Cond);
22672           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
22673                              SDValue(FalseC, 0));
22674         }
22675
22676         // Optimize cases that will turn into an LEA instruction.  This requires
22677         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
22678         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
22679           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
22680           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
22681
22682           bool isFastMultiplier = false;
22683           if (Diff < 10) {
22684             switch ((unsigned char)Diff) {
22685               default: break;
22686               case 1:  // result = add base, cond
22687               case 2:  // result = lea base(    , cond*2)
22688               case 3:  // result = lea base(cond, cond*2)
22689               case 4:  // result = lea base(    , cond*4)
22690               case 5:  // result = lea base(cond, cond*4)
22691               case 8:  // result = lea base(    , cond*8)
22692               case 9:  // result = lea base(cond, cond*8)
22693                 isFastMultiplier = true;
22694                 break;
22695             }
22696           }
22697
22698           if (isFastMultiplier) {
22699             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
22700             if (NeedsCondInvert) // Invert the condition if needed.
22701               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
22702                                  DAG.getConstant(1, DL, Cond.getValueType()));
22703
22704             // Zero extend the condition if needed.
22705             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
22706                                Cond);
22707             // Scale the condition by the difference.
22708             if (Diff != 1)
22709               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
22710                                  DAG.getConstant(Diff, DL,
22711                                                  Cond.getValueType()));
22712
22713             // Add the base if non-zero.
22714             if (FalseC->getAPIntValue() != 0)
22715               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
22716                                  SDValue(FalseC, 0));
22717             return Cond;
22718           }
22719         }
22720       }
22721   }
22722
22723   // Canonicalize max and min:
22724   // (x > y) ? x : y -> (x >= y) ? x : y
22725   // (x < y) ? x : y -> (x <= y) ? x : y
22726   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
22727   // the need for an extra compare
22728   // against zero. e.g.
22729   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
22730   // subl   %esi, %edi
22731   // testl  %edi, %edi
22732   // movl   $0, %eax
22733   // cmovgl %edi, %eax
22734   // =>
22735   // xorl   %eax, %eax
22736   // subl   %esi, $edi
22737   // cmovsl %eax, %edi
22738   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
22739       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
22740       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
22741     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
22742     switch (CC) {
22743     default: break;
22744     case ISD::SETLT:
22745     case ISD::SETGT: {
22746       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
22747       Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
22748                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
22749       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
22750     }
22751     }
22752   }
22753
22754   // Early exit check
22755   if (!TLI.isTypeLegal(VT))
22756     return SDValue();
22757
22758   // Match VSELECTs into subs with unsigned saturation.
22759   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
22760       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
22761       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
22762        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
22763     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
22764
22765     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
22766     // left side invert the predicate to simplify logic below.
22767     SDValue Other;
22768     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
22769       Other = RHS;
22770       CC = ISD::getSetCCInverse(CC, true);
22771     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
22772       Other = LHS;
22773     }
22774
22775     if (Other.getNode() && Other->getNumOperands() == 2 &&
22776         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
22777       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
22778       SDValue CondRHS = Cond->getOperand(1);
22779
22780       // Look for a general sub with unsigned saturation first.
22781       // x >= y ? x-y : 0 --> subus x, y
22782       // x >  y ? x-y : 0 --> subus x, y
22783       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
22784           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
22785         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
22786
22787       if (auto *OpRHSBV = dyn_cast<BuildVectorSDNode>(OpRHS))
22788         if (auto *OpRHSConst = OpRHSBV->getConstantSplatNode()) {
22789           if (auto *CondRHSBV = dyn_cast<BuildVectorSDNode>(CondRHS))
22790             if (auto *CondRHSConst = CondRHSBV->getConstantSplatNode())
22791               // If the RHS is a constant we have to reverse the const
22792               // canonicalization.
22793               // x > C-1 ? x+-C : 0 --> subus x, C
22794               if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
22795                   CondRHSConst->getAPIntValue() ==
22796                       (-OpRHSConst->getAPIntValue() - 1))
22797                 return DAG.getNode(
22798                     X86ISD::SUBUS, DL, VT, OpLHS,
22799                     DAG.getConstant(-OpRHSConst->getAPIntValue(), DL, VT));
22800
22801           // Another special case: If C was a sign bit, the sub has been
22802           // canonicalized into a xor.
22803           // FIXME: Would it be better to use computeKnownBits to determine
22804           //        whether it's safe to decanonicalize the xor?
22805           // x s< 0 ? x^C : 0 --> subus x, C
22806           if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
22807               ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
22808               OpRHSConst->getAPIntValue().isSignBit())
22809             // Note that we have to rebuild the RHS constant here to ensure we
22810             // don't rely on particular values of undef lanes.
22811             return DAG.getNode(
22812                 X86ISD::SUBUS, DL, VT, OpLHS,
22813                 DAG.getConstant(OpRHSConst->getAPIntValue(), DL, VT));
22814         }
22815     }
22816   }
22817
22818   // Simplify vector selection if condition value type matches vselect
22819   // operand type
22820   if (N->getOpcode() == ISD::VSELECT && CondVT == VT) {
22821     assert(Cond.getValueType().isVector() &&
22822            "vector select expects a vector selector!");
22823
22824     bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
22825     bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
22826
22827     // Try invert the condition if true value is not all 1s and false value
22828     // is not all 0s.
22829     if (!TValIsAllOnes && !FValIsAllZeros &&
22830         // Check if the selector will be produced by CMPP*/PCMP*
22831         Cond.getOpcode() == ISD::SETCC &&
22832         // Check if SETCC has already been promoted
22833         TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT) ==
22834             CondVT) {
22835       bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
22836       bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
22837
22838       if (TValIsAllZeros || FValIsAllOnes) {
22839         SDValue CC = Cond.getOperand(2);
22840         ISD::CondCode NewCC =
22841           ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
22842                                Cond.getOperand(0).getValueType().isInteger());
22843         Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
22844         std::swap(LHS, RHS);
22845         TValIsAllOnes = FValIsAllOnes;
22846         FValIsAllZeros = TValIsAllZeros;
22847       }
22848     }
22849
22850     if (TValIsAllOnes || FValIsAllZeros) {
22851       SDValue Ret;
22852
22853       if (TValIsAllOnes && FValIsAllZeros)
22854         Ret = Cond;
22855       else if (TValIsAllOnes)
22856         Ret =
22857             DAG.getNode(ISD::OR, DL, CondVT, Cond, DAG.getBitcast(CondVT, RHS));
22858       else if (FValIsAllZeros)
22859         Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
22860                           DAG.getBitcast(CondVT, LHS));
22861
22862       return DAG.getBitcast(VT, Ret);
22863     }
22864   }
22865
22866   // We should generate an X86ISD::BLENDI from a vselect if its argument
22867   // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
22868   // constants. This specific pattern gets generated when we split a
22869   // selector for a 512 bit vector in a machine without AVX512 (but with
22870   // 256-bit vectors), during legalization:
22871   //
22872   // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
22873   //
22874   // Iff we find this pattern and the build_vectors are built from
22875   // constants, we translate the vselect into a shuffle_vector that we
22876   // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
22877   if ((N->getOpcode() == ISD::VSELECT ||
22878        N->getOpcode() == X86ISD::SHRUNKBLEND) &&
22879       !DCI.isBeforeLegalize() && !VT.is512BitVector()) {
22880     SDValue Shuffle = transformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
22881     if (Shuffle.getNode())
22882       return Shuffle;
22883   }
22884
22885   // If this is a *dynamic* select (non-constant condition) and we can match
22886   // this node with one of the variable blend instructions, restructure the
22887   // condition so that the blends can use the high bit of each element and use
22888   // SimplifyDemandedBits to simplify the condition operand.
22889   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
22890       !DCI.isBeforeLegalize() &&
22891       !ISD::isBuildVectorOfConstantSDNodes(Cond.getNode())) {
22892     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
22893
22894     // Don't optimize vector selects that map to mask-registers.
22895     if (BitWidth == 1)
22896       return SDValue();
22897
22898     // We can only handle the cases where VSELECT is directly legal on the
22899     // subtarget. We custom lower VSELECT nodes with constant conditions and
22900     // this makes it hard to see whether a dynamic VSELECT will correctly
22901     // lower, so we both check the operation's status and explicitly handle the
22902     // cases where a *dynamic* blend will fail even though a constant-condition
22903     // blend could be custom lowered.
22904     // FIXME: We should find a better way to handle this class of problems.
22905     // Potentially, we should combine constant-condition vselect nodes
22906     // pre-legalization into shuffles and not mark as many types as custom
22907     // lowered.
22908     if (!TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
22909       return SDValue();
22910     // FIXME: We don't support i16-element blends currently. We could and
22911     // should support them by making *all* the bits in the condition be set
22912     // rather than just the high bit and using an i8-element blend.
22913     if (VT.getScalarType() == MVT::i16)
22914       return SDValue();
22915     // Dynamic blending was only available from SSE4.1 onward.
22916     if (VT.getSizeInBits() == 128 && !Subtarget->hasSSE41())
22917       return SDValue();
22918     // Byte blends are only available in AVX2
22919     if (VT.getSizeInBits() == 256 && VT.getScalarType() == MVT::i8 &&
22920         !Subtarget->hasAVX2())
22921       return SDValue();
22922
22923     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
22924     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
22925
22926     APInt KnownZero, KnownOne;
22927     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
22928                                           DCI.isBeforeLegalizeOps());
22929     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
22930         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne,
22931                                  TLO)) {
22932       // If we changed the computation somewhere in the DAG, this change
22933       // will affect all users of Cond.
22934       // Make sure it is fine and update all the nodes so that we do not
22935       // use the generic VSELECT anymore. Otherwise, we may perform
22936       // wrong optimizations as we messed up with the actual expectation
22937       // for the vector boolean values.
22938       if (Cond != TLO.Old) {
22939         // Check all uses of that condition operand to check whether it will be
22940         // consumed by non-BLEND instructions, which may depend on all bits are
22941         // set properly.
22942         for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
22943              I != E; ++I)
22944           if (I->getOpcode() != ISD::VSELECT)
22945             // TODO: Add other opcodes eventually lowered into BLEND.
22946             return SDValue();
22947
22948         // Update all the users of the condition, before committing the change,
22949         // so that the VSELECT optimizations that expect the correct vector
22950         // boolean value will not be triggered.
22951         for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
22952              I != E; ++I)
22953           DAG.ReplaceAllUsesOfValueWith(
22954               SDValue(*I, 0),
22955               DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(*I), I->getValueType(0),
22956                           Cond, I->getOperand(1), I->getOperand(2)));
22957         DCI.CommitTargetLoweringOpt(TLO);
22958         return SDValue();
22959       }
22960       // At this point, only Cond is changed. Change the condition
22961       // just for N to keep the opportunity to optimize all other
22962       // users their own way.
22963       DAG.ReplaceAllUsesOfValueWith(
22964           SDValue(N, 0),
22965           DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(N), N->getValueType(0),
22966                       TLO.New, N->getOperand(1), N->getOperand(2)));
22967       return SDValue();
22968     }
22969   }
22970
22971   return SDValue();
22972 }
22973
22974 // Check whether a boolean test is testing a boolean value generated by
22975 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
22976 // code.
22977 //
22978 // Simplify the following patterns:
22979 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
22980 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
22981 // to (Op EFLAGS Cond)
22982 //
22983 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
22984 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
22985 // to (Op EFLAGS !Cond)
22986 //
22987 // where Op could be BRCOND or CMOV.
22988 //
22989 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
22990   // Quit if not CMP and SUB with its value result used.
22991   if (Cmp.getOpcode() != X86ISD::CMP &&
22992       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
22993       return SDValue();
22994
22995   // Quit if not used as a boolean value.
22996   if (CC != X86::COND_E && CC != X86::COND_NE)
22997     return SDValue();
22998
22999   // Check CMP operands. One of them should be 0 or 1 and the other should be
23000   // an SetCC or extended from it.
23001   SDValue Op1 = Cmp.getOperand(0);
23002   SDValue Op2 = Cmp.getOperand(1);
23003
23004   SDValue SetCC;
23005   const ConstantSDNode* C = nullptr;
23006   bool needOppositeCond = (CC == X86::COND_E);
23007   bool checkAgainstTrue = false; // Is it a comparison against 1?
23008
23009   if ((C = dyn_cast<ConstantSDNode>(Op1)))
23010     SetCC = Op2;
23011   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
23012     SetCC = Op1;
23013   else // Quit if all operands are not constants.
23014     return SDValue();
23015
23016   if (C->getZExtValue() == 1) {
23017     needOppositeCond = !needOppositeCond;
23018     checkAgainstTrue = true;
23019   } else if (C->getZExtValue() != 0)
23020     // Quit if the constant is neither 0 or 1.
23021     return SDValue();
23022
23023   bool truncatedToBoolWithAnd = false;
23024   // Skip (zext $x), (trunc $x), or (and $x, 1) node.
23025   while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
23026          SetCC.getOpcode() == ISD::TRUNCATE ||
23027          SetCC.getOpcode() == ISD::AND) {
23028     if (SetCC.getOpcode() == ISD::AND) {
23029       int OpIdx = -1;
23030       ConstantSDNode *CS;
23031       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
23032           CS->getZExtValue() == 1)
23033         OpIdx = 1;
23034       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
23035           CS->getZExtValue() == 1)
23036         OpIdx = 0;
23037       if (OpIdx == -1)
23038         break;
23039       SetCC = SetCC.getOperand(OpIdx);
23040       truncatedToBoolWithAnd = true;
23041     } else
23042       SetCC = SetCC.getOperand(0);
23043   }
23044
23045   switch (SetCC.getOpcode()) {
23046   case X86ISD::SETCC_CARRY:
23047     // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
23048     // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
23049     // i.e. it's a comparison against true but the result of SETCC_CARRY is not
23050     // truncated to i1 using 'and'.
23051     if (checkAgainstTrue && !truncatedToBoolWithAnd)
23052       break;
23053     assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
23054            "Invalid use of SETCC_CARRY!");
23055     // FALL THROUGH
23056   case X86ISD::SETCC:
23057     // Set the condition code or opposite one if necessary.
23058     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
23059     if (needOppositeCond)
23060       CC = X86::GetOppositeBranchCondition(CC);
23061     return SetCC.getOperand(1);
23062   case X86ISD::CMOV: {
23063     // Check whether false/true value has canonical one, i.e. 0 or 1.
23064     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
23065     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
23066     // Quit if true value is not a constant.
23067     if (!TVal)
23068       return SDValue();
23069     // Quit if false value is not a constant.
23070     if (!FVal) {
23071       SDValue Op = SetCC.getOperand(0);
23072       // Skip 'zext' or 'trunc' node.
23073       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
23074           Op.getOpcode() == ISD::TRUNCATE)
23075         Op = Op.getOperand(0);
23076       // A special case for rdrand/rdseed, where 0 is set if false cond is
23077       // found.
23078       if ((Op.getOpcode() != X86ISD::RDRAND &&
23079            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
23080         return SDValue();
23081     }
23082     // Quit if false value is not the constant 0 or 1.
23083     bool FValIsFalse = true;
23084     if (FVal && FVal->getZExtValue() != 0) {
23085       if (FVal->getZExtValue() != 1)
23086         return SDValue();
23087       // If FVal is 1, opposite cond is needed.
23088       needOppositeCond = !needOppositeCond;
23089       FValIsFalse = false;
23090     }
23091     // Quit if TVal is not the constant opposite of FVal.
23092     if (FValIsFalse && TVal->getZExtValue() != 1)
23093       return SDValue();
23094     if (!FValIsFalse && TVal->getZExtValue() != 0)
23095       return SDValue();
23096     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
23097     if (needOppositeCond)
23098       CC = X86::GetOppositeBranchCondition(CC);
23099     return SetCC.getOperand(3);
23100   }
23101   }
23102
23103   return SDValue();
23104 }
23105
23106 /// Check whether Cond is an AND/OR of SETCCs off of the same EFLAGS.
23107 /// Match:
23108 ///   (X86or (X86setcc) (X86setcc))
23109 ///   (X86cmp (and (X86setcc) (X86setcc)), 0)
23110 static bool checkBoolTestAndOrSetCCCombine(SDValue Cond, X86::CondCode &CC0,
23111                                            X86::CondCode &CC1, SDValue &Flags,
23112                                            bool &isAnd) {
23113   if (Cond->getOpcode() == X86ISD::CMP) {
23114     ConstantSDNode *CondOp1C = dyn_cast<ConstantSDNode>(Cond->getOperand(1));
23115     if (!CondOp1C || !CondOp1C->isNullValue())
23116       return false;
23117
23118     Cond = Cond->getOperand(0);
23119   }
23120
23121   isAnd = false;
23122
23123   SDValue SetCC0, SetCC1;
23124   switch (Cond->getOpcode()) {
23125   default: return false;
23126   case ISD::AND:
23127   case X86ISD::AND:
23128     isAnd = true;
23129     // fallthru
23130   case ISD::OR:
23131   case X86ISD::OR:
23132     SetCC0 = Cond->getOperand(0);
23133     SetCC1 = Cond->getOperand(1);
23134     break;
23135   };
23136
23137   // Make sure we have SETCC nodes, using the same flags value.
23138   if (SetCC0.getOpcode() != X86ISD::SETCC ||
23139       SetCC1.getOpcode() != X86ISD::SETCC ||
23140       SetCC0->getOperand(1) != SetCC1->getOperand(1))
23141     return false;
23142
23143   CC0 = (X86::CondCode)SetCC0->getConstantOperandVal(0);
23144   CC1 = (X86::CondCode)SetCC1->getConstantOperandVal(0);
23145   Flags = SetCC0->getOperand(1);
23146   return true;
23147 }
23148
23149 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
23150 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
23151                                   TargetLowering::DAGCombinerInfo &DCI,
23152                                   const X86Subtarget *Subtarget) {
23153   SDLoc DL(N);
23154
23155   // If the flag operand isn't dead, don't touch this CMOV.
23156   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
23157     return SDValue();
23158
23159   SDValue FalseOp = N->getOperand(0);
23160   SDValue TrueOp = N->getOperand(1);
23161   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
23162   SDValue Cond = N->getOperand(3);
23163
23164   if (CC == X86::COND_E || CC == X86::COND_NE) {
23165     switch (Cond.getOpcode()) {
23166     default: break;
23167     case X86ISD::BSR:
23168     case X86ISD::BSF:
23169       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
23170       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
23171         return (CC == X86::COND_E) ? FalseOp : TrueOp;
23172     }
23173   }
23174
23175   SDValue Flags;
23176
23177   Flags = checkBoolTestSetCCCombine(Cond, CC);
23178   if (Flags.getNode() &&
23179       // Extra check as FCMOV only supports a subset of X86 cond.
23180       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
23181     SDValue Ops[] = { FalseOp, TrueOp,
23182                       DAG.getConstant(CC, DL, MVT::i8), Flags };
23183     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
23184   }
23185
23186   // If this is a select between two integer constants, try to do some
23187   // optimizations.  Note that the operands are ordered the opposite of SELECT
23188   // operands.
23189   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
23190     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
23191       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
23192       // larger than FalseC (the false value).
23193       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
23194         CC = X86::GetOppositeBranchCondition(CC);
23195         std::swap(TrueC, FalseC);
23196         std::swap(TrueOp, FalseOp);
23197       }
23198
23199       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
23200       // This is efficient for any integer data type (including i8/i16) and
23201       // shift amount.
23202       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
23203         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
23204                            DAG.getConstant(CC, DL, MVT::i8), Cond);
23205
23206         // Zero extend the condition if needed.
23207         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
23208
23209         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
23210         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
23211                            DAG.getConstant(ShAmt, DL, MVT::i8));
23212         if (N->getNumValues() == 2)  // Dead flag value?
23213           return DCI.CombineTo(N, Cond, SDValue());
23214         return Cond;
23215       }
23216
23217       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
23218       // for any integer data type, including i8/i16.
23219       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
23220         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
23221                            DAG.getConstant(CC, DL, MVT::i8), Cond);
23222
23223         // Zero extend the condition if needed.
23224         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
23225                            FalseC->getValueType(0), Cond);
23226         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
23227                            SDValue(FalseC, 0));
23228
23229         if (N->getNumValues() == 2)  // Dead flag value?
23230           return DCI.CombineTo(N, Cond, SDValue());
23231         return Cond;
23232       }
23233
23234       // Optimize cases that will turn into an LEA instruction.  This requires
23235       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
23236       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
23237         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
23238         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
23239
23240         bool isFastMultiplier = false;
23241         if (Diff < 10) {
23242           switch ((unsigned char)Diff) {
23243           default: break;
23244           case 1:  // result = add base, cond
23245           case 2:  // result = lea base(    , cond*2)
23246           case 3:  // result = lea base(cond, cond*2)
23247           case 4:  // result = lea base(    , cond*4)
23248           case 5:  // result = lea base(cond, cond*4)
23249           case 8:  // result = lea base(    , cond*8)
23250           case 9:  // result = lea base(cond, cond*8)
23251             isFastMultiplier = true;
23252             break;
23253           }
23254         }
23255
23256         if (isFastMultiplier) {
23257           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
23258           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
23259                              DAG.getConstant(CC, DL, MVT::i8), Cond);
23260           // Zero extend the condition if needed.
23261           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
23262                              Cond);
23263           // Scale the condition by the difference.
23264           if (Diff != 1)
23265             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
23266                                DAG.getConstant(Diff, DL, Cond.getValueType()));
23267
23268           // Add the base if non-zero.
23269           if (FalseC->getAPIntValue() != 0)
23270             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
23271                                SDValue(FalseC, 0));
23272           if (N->getNumValues() == 2)  // Dead flag value?
23273             return DCI.CombineTo(N, Cond, SDValue());
23274           return Cond;
23275         }
23276       }
23277     }
23278   }
23279
23280   // Handle these cases:
23281   //   (select (x != c), e, c) -> select (x != c), e, x),
23282   //   (select (x == c), c, e) -> select (x == c), x, e)
23283   // where the c is an integer constant, and the "select" is the combination
23284   // of CMOV and CMP.
23285   //
23286   // The rationale for this change is that the conditional-move from a constant
23287   // needs two instructions, however, conditional-move from a register needs
23288   // only one instruction.
23289   //
23290   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
23291   //  some instruction-combining opportunities. This opt needs to be
23292   //  postponed as late as possible.
23293   //
23294   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
23295     // the DCI.xxxx conditions are provided to postpone the optimization as
23296     // late as possible.
23297
23298     ConstantSDNode *CmpAgainst = nullptr;
23299     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
23300         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
23301         !isa<ConstantSDNode>(Cond.getOperand(0))) {
23302
23303       if (CC == X86::COND_NE &&
23304           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
23305         CC = X86::GetOppositeBranchCondition(CC);
23306         std::swap(TrueOp, FalseOp);
23307       }
23308
23309       if (CC == X86::COND_E &&
23310           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
23311         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
23312                           DAG.getConstant(CC, DL, MVT::i8), Cond };
23313         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
23314       }
23315     }
23316   }
23317
23318   // Fold and/or of setcc's to double CMOV:
23319   //   (CMOV F, T, ((cc1 | cc2) != 0)) -> (CMOV (CMOV F, T, cc1), T, cc2)
23320   //   (CMOV F, T, ((cc1 & cc2) != 0)) -> (CMOV (CMOV T, F, !cc1), F, !cc2)
23321   //
23322   // This combine lets us generate:
23323   //   cmovcc1 (jcc1 if we don't have CMOV)
23324   //   cmovcc2 (same)
23325   // instead of:
23326   //   setcc1
23327   //   setcc2
23328   //   and/or
23329   //   cmovne (jne if we don't have CMOV)
23330   // When we can't use the CMOV instruction, it might increase branch
23331   // mispredicts.
23332   // When we can use CMOV, or when there is no mispredict, this improves
23333   // throughput and reduces register pressure.
23334   //
23335   if (CC == X86::COND_NE) {
23336     SDValue Flags;
23337     X86::CondCode CC0, CC1;
23338     bool isAndSetCC;
23339     if (checkBoolTestAndOrSetCCCombine(Cond, CC0, CC1, Flags, isAndSetCC)) {
23340       if (isAndSetCC) {
23341         std::swap(FalseOp, TrueOp);
23342         CC0 = X86::GetOppositeBranchCondition(CC0);
23343         CC1 = X86::GetOppositeBranchCondition(CC1);
23344       }
23345
23346       SDValue LOps[] = {FalseOp, TrueOp, DAG.getConstant(CC0, DL, MVT::i8),
23347         Flags};
23348       SDValue LCMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), LOps);
23349       SDValue Ops[] = {LCMOV, TrueOp, DAG.getConstant(CC1, DL, MVT::i8), Flags};
23350       SDValue CMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
23351       DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SDValue(CMOV.getNode(), 1));
23352       return CMOV;
23353     }
23354   }
23355
23356   return SDValue();
23357 }
23358
23359 /// PerformMulCombine - Optimize a single multiply with constant into two
23360 /// in order to implement it with two cheaper instructions, e.g.
23361 /// LEA + SHL, LEA + LEA.
23362 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
23363                                  TargetLowering::DAGCombinerInfo &DCI) {
23364   // An imul is usually smaller than the alternative sequence.
23365   if (DAG.getMachineFunction().getFunction()->optForMinSize())
23366     return SDValue();
23367
23368   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
23369     return SDValue();
23370
23371   EVT VT = N->getValueType(0);
23372   if (VT != MVT::i64 && VT != MVT::i32)
23373     return SDValue();
23374
23375   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
23376   if (!C)
23377     return SDValue();
23378   uint64_t MulAmt = C->getZExtValue();
23379   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
23380     return SDValue();
23381
23382   uint64_t MulAmt1 = 0;
23383   uint64_t MulAmt2 = 0;
23384   if ((MulAmt % 9) == 0) {
23385     MulAmt1 = 9;
23386     MulAmt2 = MulAmt / 9;
23387   } else if ((MulAmt % 5) == 0) {
23388     MulAmt1 = 5;
23389     MulAmt2 = MulAmt / 5;
23390   } else if ((MulAmt % 3) == 0) {
23391     MulAmt1 = 3;
23392     MulAmt2 = MulAmt / 3;
23393   }
23394   if (MulAmt2 &&
23395       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
23396     SDLoc DL(N);
23397
23398     if (isPowerOf2_64(MulAmt2) &&
23399         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
23400       // If second multiplifer is pow2, issue it first. We want the multiply by
23401       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
23402       // is an add.
23403       std::swap(MulAmt1, MulAmt2);
23404
23405     SDValue NewMul;
23406     if (isPowerOf2_64(MulAmt1))
23407       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
23408                            DAG.getConstant(Log2_64(MulAmt1), DL, MVT::i8));
23409     else
23410       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
23411                            DAG.getConstant(MulAmt1, DL, VT));
23412
23413     if (isPowerOf2_64(MulAmt2))
23414       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
23415                            DAG.getConstant(Log2_64(MulAmt2), DL, MVT::i8));
23416     else
23417       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
23418                            DAG.getConstant(MulAmt2, DL, VT));
23419
23420     // Do not add new nodes to DAG combiner worklist.
23421     DCI.CombineTo(N, NewMul, false);
23422   }
23423   return SDValue();
23424 }
23425
23426 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
23427   SDValue N0 = N->getOperand(0);
23428   SDValue N1 = N->getOperand(1);
23429   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
23430   EVT VT = N0.getValueType();
23431
23432   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
23433   // since the result of setcc_c is all zero's or all ones.
23434   if (VT.isInteger() && !VT.isVector() &&
23435       N1C && N0.getOpcode() == ISD::AND &&
23436       N0.getOperand(1).getOpcode() == ISD::Constant) {
23437     SDValue N00 = N0.getOperand(0);
23438     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
23439         ((N00.getOpcode() == ISD::ANY_EXTEND ||
23440           N00.getOpcode() == ISD::ZERO_EXTEND) &&
23441          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
23442       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
23443       APInt ShAmt = N1C->getAPIntValue();
23444       Mask = Mask.shl(ShAmt);
23445       if (Mask != 0) {
23446         SDLoc DL(N);
23447         return DAG.getNode(ISD::AND, DL, VT,
23448                            N00, DAG.getConstant(Mask, DL, VT));
23449       }
23450     }
23451   }
23452
23453   // Hardware support for vector shifts is sparse which makes us scalarize the
23454   // vector operations in many cases. Also, on sandybridge ADD is faster than
23455   // shl.
23456   // (shl V, 1) -> add V,V
23457   if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
23458     if (auto *N1SplatC = N1BV->getConstantSplatNode()) {
23459       assert(N0.getValueType().isVector() && "Invalid vector shift type");
23460       // We shift all of the values by one. In many cases we do not have
23461       // hardware support for this operation. This is better expressed as an ADD
23462       // of two values.
23463       if (N1SplatC->getAPIntValue() == 1)
23464         return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
23465     }
23466
23467   return SDValue();
23468 }
23469
23470 /// \brief Returns a vector of 0s if the node in input is a vector logical
23471 /// shift by a constant amount which is known to be bigger than or equal
23472 /// to the vector element size in bits.
23473 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
23474                                       const X86Subtarget *Subtarget) {
23475   EVT VT = N->getValueType(0);
23476
23477   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
23478       (!Subtarget->hasInt256() ||
23479        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
23480     return SDValue();
23481
23482   SDValue Amt = N->getOperand(1);
23483   SDLoc DL(N);
23484   if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Amt))
23485     if (auto *AmtSplat = AmtBV->getConstantSplatNode()) {
23486       APInt ShiftAmt = AmtSplat->getAPIntValue();
23487       unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
23488
23489       // SSE2/AVX2 logical shifts always return a vector of 0s
23490       // if the shift amount is bigger than or equal to
23491       // the element size. The constant shift amount will be
23492       // encoded as a 8-bit immediate.
23493       if (ShiftAmt.trunc(8).uge(MaxAmount))
23494         return getZeroVector(VT, Subtarget, DAG, DL);
23495     }
23496
23497   return SDValue();
23498 }
23499
23500 /// PerformShiftCombine - Combine shifts.
23501 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
23502                                    TargetLowering::DAGCombinerInfo &DCI,
23503                                    const X86Subtarget *Subtarget) {
23504   if (N->getOpcode() == ISD::SHL)
23505     if (SDValue V = PerformSHLCombine(N, DAG))
23506       return V;
23507
23508   // Try to fold this logical shift into a zero vector.
23509   if (N->getOpcode() != ISD::SRA)
23510     if (SDValue V = performShiftToAllZeros(N, DAG, Subtarget))
23511       return V;
23512
23513   return SDValue();
23514 }
23515
23516 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
23517 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
23518 // and friends.  Likewise for OR -> CMPNEQSS.
23519 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
23520                             TargetLowering::DAGCombinerInfo &DCI,
23521                             const X86Subtarget *Subtarget) {
23522   unsigned opcode;
23523
23524   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
23525   // we're requiring SSE2 for both.
23526   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
23527     SDValue N0 = N->getOperand(0);
23528     SDValue N1 = N->getOperand(1);
23529     SDValue CMP0 = N0->getOperand(1);
23530     SDValue CMP1 = N1->getOperand(1);
23531     SDLoc DL(N);
23532
23533     // The SETCCs should both refer to the same CMP.
23534     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
23535       return SDValue();
23536
23537     SDValue CMP00 = CMP0->getOperand(0);
23538     SDValue CMP01 = CMP0->getOperand(1);
23539     EVT     VT    = CMP00.getValueType();
23540
23541     if (VT == MVT::f32 || VT == MVT::f64) {
23542       bool ExpectingFlags = false;
23543       // Check for any users that want flags:
23544       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
23545            !ExpectingFlags && UI != UE; ++UI)
23546         switch (UI->getOpcode()) {
23547         default:
23548         case ISD::BR_CC:
23549         case ISD::BRCOND:
23550         case ISD::SELECT:
23551           ExpectingFlags = true;
23552           break;
23553         case ISD::CopyToReg:
23554         case ISD::SIGN_EXTEND:
23555         case ISD::ZERO_EXTEND:
23556         case ISD::ANY_EXTEND:
23557           break;
23558         }
23559
23560       if (!ExpectingFlags) {
23561         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
23562         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
23563
23564         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
23565           X86::CondCode tmp = cc0;
23566           cc0 = cc1;
23567           cc1 = tmp;
23568         }
23569
23570         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
23571             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
23572           // FIXME: need symbolic constants for these magic numbers.
23573           // See X86ATTInstPrinter.cpp:printSSECC().
23574           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
23575           if (Subtarget->hasAVX512()) {
23576             SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
23577                                          CMP01,
23578                                          DAG.getConstant(x86cc, DL, MVT::i8));
23579             if (N->getValueType(0) != MVT::i1)
23580               return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
23581                                  FSetCC);
23582             return FSetCC;
23583           }
23584           SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
23585                                               CMP00.getValueType(), CMP00, CMP01,
23586                                               DAG.getConstant(x86cc, DL,
23587                                                               MVT::i8));
23588
23589           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
23590           MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
23591
23592           if (is64BitFP && !Subtarget->is64Bit()) {
23593             // On a 32-bit target, we cannot bitcast the 64-bit float to a
23594             // 64-bit integer, since that's not a legal type. Since
23595             // OnesOrZeroesF is all ones of all zeroes, we don't need all the
23596             // bits, but can do this little dance to extract the lowest 32 bits
23597             // and work with those going forward.
23598             SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
23599                                            OnesOrZeroesF);
23600             SDValue Vector32 = DAG.getBitcast(MVT::v4f32, Vector64);
23601             OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
23602                                         Vector32, DAG.getIntPtrConstant(0, DL));
23603             IntVT = MVT::i32;
23604           }
23605
23606           SDValue OnesOrZeroesI = DAG.getBitcast(IntVT, OnesOrZeroesF);
23607           SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
23608                                       DAG.getConstant(1, DL, IntVT));
23609           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8,
23610                                               ANDed);
23611           return OneBitOfTruth;
23612         }
23613       }
23614     }
23615   }
23616   return SDValue();
23617 }
23618
23619 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
23620 /// so it can be folded inside ANDNP.
23621 static bool CanFoldXORWithAllOnes(const SDNode *N) {
23622   EVT VT = N->getValueType(0);
23623
23624   // Match direct AllOnes for 128 and 256-bit vectors
23625   if (ISD::isBuildVectorAllOnes(N))
23626     return true;
23627
23628   // Look through a bit convert.
23629   if (N->getOpcode() == ISD::BITCAST)
23630     N = N->getOperand(0).getNode();
23631
23632   // Sometimes the operand may come from a insert_subvector building a 256-bit
23633   // allones vector
23634   if (VT.is256BitVector() &&
23635       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
23636     SDValue V1 = N->getOperand(0);
23637     SDValue V2 = N->getOperand(1);
23638
23639     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
23640         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
23641         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
23642         ISD::isBuildVectorAllOnes(V2.getNode()))
23643       return true;
23644   }
23645
23646   return false;
23647 }
23648
23649 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
23650 // register. In most cases we actually compare or select YMM-sized registers
23651 // and mixing the two types creates horrible code. This method optimizes
23652 // some of the transition sequences.
23653 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
23654                                  TargetLowering::DAGCombinerInfo &DCI,
23655                                  const X86Subtarget *Subtarget) {
23656   EVT VT = N->getValueType(0);
23657   if (!VT.is256BitVector())
23658     return SDValue();
23659
23660   assert((N->getOpcode() == ISD::ANY_EXTEND ||
23661           N->getOpcode() == ISD::ZERO_EXTEND ||
23662           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
23663
23664   SDValue Narrow = N->getOperand(0);
23665   EVT NarrowVT = Narrow->getValueType(0);
23666   if (!NarrowVT.is128BitVector())
23667     return SDValue();
23668
23669   if (Narrow->getOpcode() != ISD::XOR &&
23670       Narrow->getOpcode() != ISD::AND &&
23671       Narrow->getOpcode() != ISD::OR)
23672     return SDValue();
23673
23674   SDValue N0  = Narrow->getOperand(0);
23675   SDValue N1  = Narrow->getOperand(1);
23676   SDLoc DL(Narrow);
23677
23678   // The Left side has to be a trunc.
23679   if (N0.getOpcode() != ISD::TRUNCATE)
23680     return SDValue();
23681
23682   // The type of the truncated inputs.
23683   EVT WideVT = N0->getOperand(0)->getValueType(0);
23684   if (WideVT != VT)
23685     return SDValue();
23686
23687   // The right side has to be a 'trunc' or a constant vector.
23688   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
23689   ConstantSDNode *RHSConstSplat = nullptr;
23690   if (auto *RHSBV = dyn_cast<BuildVectorSDNode>(N1))
23691     RHSConstSplat = RHSBV->getConstantSplatNode();
23692   if (!RHSTrunc && !RHSConstSplat)
23693     return SDValue();
23694
23695   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23696
23697   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
23698     return SDValue();
23699
23700   // Set N0 and N1 to hold the inputs to the new wide operation.
23701   N0 = N0->getOperand(0);
23702   if (RHSConstSplat) {
23703     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
23704                      SDValue(RHSConstSplat, 0));
23705     SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
23706     N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
23707   } else if (RHSTrunc) {
23708     N1 = N1->getOperand(0);
23709   }
23710
23711   // Generate the wide operation.
23712   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
23713   unsigned Opcode = N->getOpcode();
23714   switch (Opcode) {
23715   case ISD::ANY_EXTEND:
23716     return Op;
23717   case ISD::ZERO_EXTEND: {
23718     unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
23719     APInt Mask = APInt::getAllOnesValue(InBits);
23720     Mask = Mask.zext(VT.getScalarType().getSizeInBits());
23721     return DAG.getNode(ISD::AND, DL, VT,
23722                        Op, DAG.getConstant(Mask, DL, VT));
23723   }
23724   case ISD::SIGN_EXTEND:
23725     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
23726                        Op, DAG.getValueType(NarrowVT));
23727   default:
23728     llvm_unreachable("Unexpected opcode");
23729   }
23730 }
23731
23732 static SDValue VectorZextCombine(SDNode *N, SelectionDAG &DAG,
23733                                  TargetLowering::DAGCombinerInfo &DCI,
23734                                  const X86Subtarget *Subtarget) {
23735   SDValue N0 = N->getOperand(0);
23736   SDValue N1 = N->getOperand(1);
23737   SDLoc DL(N);
23738
23739   // A vector zext_in_reg may be represented as a shuffle,
23740   // feeding into a bitcast (this represents anyext) feeding into
23741   // an and with a mask.
23742   // We'd like to try to combine that into a shuffle with zero
23743   // plus a bitcast, removing the and.
23744   if (N0.getOpcode() != ISD::BITCAST ||
23745       N0.getOperand(0).getOpcode() != ISD::VECTOR_SHUFFLE)
23746     return SDValue();
23747
23748   // The other side of the AND should be a splat of 2^C, where C
23749   // is the number of bits in the source type.
23750   if (N1.getOpcode() == ISD::BITCAST)
23751     N1 = N1.getOperand(0);
23752   if (N1.getOpcode() != ISD::BUILD_VECTOR)
23753     return SDValue();
23754   BuildVectorSDNode *Vector = cast<BuildVectorSDNode>(N1);
23755
23756   ShuffleVectorSDNode *Shuffle = cast<ShuffleVectorSDNode>(N0.getOperand(0));
23757   EVT SrcType = Shuffle->getValueType(0);
23758
23759   // We expect a single-source shuffle
23760   if (Shuffle->getOperand(1)->getOpcode() != ISD::UNDEF)
23761     return SDValue();
23762
23763   unsigned SrcSize = SrcType.getScalarSizeInBits();
23764
23765   APInt SplatValue, SplatUndef;
23766   unsigned SplatBitSize;
23767   bool HasAnyUndefs;
23768   if (!Vector->isConstantSplat(SplatValue, SplatUndef,
23769                                 SplatBitSize, HasAnyUndefs))
23770     return SDValue();
23771
23772   unsigned ResSize = N1.getValueType().getScalarSizeInBits();
23773   // Make sure the splat matches the mask we expect
23774   if (SplatBitSize > ResSize ||
23775       (SplatValue + 1).exactLogBase2() != (int)SrcSize)
23776     return SDValue();
23777
23778   // Make sure the input and output size make sense
23779   if (SrcSize >= ResSize || ResSize % SrcSize)
23780     return SDValue();
23781
23782   // We expect a shuffle of the form <0, u, u, u, 1, u, u, u...>
23783   // The number of u's between each two values depends on the ratio between
23784   // the source and dest type.
23785   unsigned ZextRatio = ResSize / SrcSize;
23786   bool IsZext = true;
23787   for (unsigned i = 0; i < SrcType.getVectorNumElements(); ++i) {
23788     if (i % ZextRatio) {
23789       if (Shuffle->getMaskElt(i) > 0) {
23790         // Expected undef
23791         IsZext = false;
23792         break;
23793       }
23794     } else {
23795       if (Shuffle->getMaskElt(i) != (int)(i / ZextRatio)) {
23796         // Expected element number
23797         IsZext = false;
23798         break;
23799       }
23800     }
23801   }
23802
23803   if (!IsZext)
23804     return SDValue();
23805
23806   // Ok, perform the transformation - replace the shuffle with
23807   // a shuffle of the form <0, k, k, k, 1, k, k, k> with zero
23808   // (instead of undef) where the k elements come from the zero vector.
23809   SmallVector<int, 8> Mask;
23810   unsigned NumElems = SrcType.getVectorNumElements();
23811   for (unsigned i = 0; i < NumElems; ++i)
23812     if (i % ZextRatio)
23813       Mask.push_back(NumElems);
23814     else
23815       Mask.push_back(i / ZextRatio);
23816
23817   SDValue NewShuffle = DAG.getVectorShuffle(Shuffle->getValueType(0), DL,
23818     Shuffle->getOperand(0), DAG.getConstant(0, DL, SrcType), Mask);
23819   return DAG.getBitcast(N0.getValueType(), NewShuffle);
23820 }
23821
23822 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
23823                                  TargetLowering::DAGCombinerInfo &DCI,
23824                                  const X86Subtarget *Subtarget) {
23825   if (DCI.isBeforeLegalizeOps())
23826     return SDValue();
23827
23828   if (SDValue Zext = VectorZextCombine(N, DAG, DCI, Subtarget))
23829     return Zext;
23830
23831   if (SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget))
23832     return R;
23833
23834   EVT VT = N->getValueType(0);
23835   SDValue N0 = N->getOperand(0);
23836   SDValue N1 = N->getOperand(1);
23837   SDLoc DL(N);
23838
23839   // Create BEXTR instructions
23840   // BEXTR is ((X >> imm) & (2**size-1))
23841   if (VT == MVT::i32 || VT == MVT::i64) {
23842     // Check for BEXTR.
23843     if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
23844         (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
23845       ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
23846       ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
23847       if (MaskNode && ShiftNode) {
23848         uint64_t Mask = MaskNode->getZExtValue();
23849         uint64_t Shift = ShiftNode->getZExtValue();
23850         if (isMask_64(Mask)) {
23851           uint64_t MaskSize = countPopulation(Mask);
23852           if (Shift + MaskSize <= VT.getSizeInBits())
23853             return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
23854                                DAG.getConstant(Shift | (MaskSize << 8), DL,
23855                                                VT));
23856         }
23857       }
23858     } // BEXTR
23859
23860     return SDValue();
23861   }
23862
23863   // Want to form ANDNP nodes:
23864   // 1) In the hopes of then easily combining them with OR and AND nodes
23865   //    to form PBLEND/PSIGN.
23866   // 2) To match ANDN packed intrinsics
23867   if (VT != MVT::v2i64 && VT != MVT::v4i64)
23868     return SDValue();
23869
23870   // Check LHS for vnot
23871   if (N0.getOpcode() == ISD::XOR &&
23872       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
23873       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
23874     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
23875
23876   // Check RHS for vnot
23877   if (N1.getOpcode() == ISD::XOR &&
23878       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
23879       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
23880     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
23881
23882   return SDValue();
23883 }
23884
23885 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
23886                                 TargetLowering::DAGCombinerInfo &DCI,
23887                                 const X86Subtarget *Subtarget) {
23888   if (DCI.isBeforeLegalizeOps())
23889     return SDValue();
23890
23891   if (SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget))
23892     return R;
23893
23894   SDValue N0 = N->getOperand(0);
23895   SDValue N1 = N->getOperand(1);
23896   EVT VT = N->getValueType(0);
23897
23898   // look for psign/blend
23899   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
23900     if (!Subtarget->hasSSSE3() ||
23901         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
23902       return SDValue();
23903
23904     // Canonicalize pandn to RHS
23905     if (N0.getOpcode() == X86ISD::ANDNP)
23906       std::swap(N0, N1);
23907     // or (and (m, y), (pandn m, x))
23908     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
23909       SDValue Mask = N1.getOperand(0);
23910       SDValue X    = N1.getOperand(1);
23911       SDValue Y;
23912       if (N0.getOperand(0) == Mask)
23913         Y = N0.getOperand(1);
23914       if (N0.getOperand(1) == Mask)
23915         Y = N0.getOperand(0);
23916
23917       // Check to see if the mask appeared in both the AND and ANDNP and
23918       if (!Y.getNode())
23919         return SDValue();
23920
23921       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
23922       // Look through mask bitcast.
23923       if (Mask.getOpcode() == ISD::BITCAST)
23924         Mask = Mask.getOperand(0);
23925       if (X.getOpcode() == ISD::BITCAST)
23926         X = X.getOperand(0);
23927       if (Y.getOpcode() == ISD::BITCAST)
23928         Y = Y.getOperand(0);
23929
23930       EVT MaskVT = Mask.getValueType();
23931
23932       // Validate that the Mask operand is a vector sra node.
23933       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
23934       // there is no psrai.b
23935       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
23936       unsigned SraAmt = ~0;
23937       if (Mask.getOpcode() == ISD::SRA) {
23938         if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Mask.getOperand(1)))
23939           if (auto *AmtConst = AmtBV->getConstantSplatNode())
23940             SraAmt = AmtConst->getZExtValue();
23941       } else if (Mask.getOpcode() == X86ISD::VSRAI) {
23942         SDValue SraC = Mask.getOperand(1);
23943         SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
23944       }
23945       if ((SraAmt + 1) != EltBits)
23946         return SDValue();
23947
23948       SDLoc DL(N);
23949
23950       // Now we know we at least have a plendvb with the mask val.  See if
23951       // we can form a psignb/w/d.
23952       // psign = x.type == y.type == mask.type && y = sub(0, x);
23953       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
23954           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
23955           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
23956         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
23957                "Unsupported VT for PSIGN");
23958         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
23959         return DAG.getBitcast(VT, Mask);
23960       }
23961       // PBLENDVB only available on SSE 4.1
23962       if (!Subtarget->hasSSE41())
23963         return SDValue();
23964
23965       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
23966
23967       X = DAG.getBitcast(BlendVT, X);
23968       Y = DAG.getBitcast(BlendVT, Y);
23969       Mask = DAG.getBitcast(BlendVT, Mask);
23970       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
23971       return DAG.getBitcast(VT, Mask);
23972     }
23973   }
23974
23975   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
23976     return SDValue();
23977
23978   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
23979   bool OptForSize = DAG.getMachineFunction().getFunction()->optForSize();
23980
23981   // SHLD/SHRD instructions have lower register pressure, but on some
23982   // platforms they have higher latency than the equivalent
23983   // series of shifts/or that would otherwise be generated.
23984   // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
23985   // have higher latencies and we are not optimizing for size.
23986   if (!OptForSize && Subtarget->isSHLDSlow())
23987     return SDValue();
23988
23989   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
23990     std::swap(N0, N1);
23991   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
23992     return SDValue();
23993   if (!N0.hasOneUse() || !N1.hasOneUse())
23994     return SDValue();
23995
23996   SDValue ShAmt0 = N0.getOperand(1);
23997   if (ShAmt0.getValueType() != MVT::i8)
23998     return SDValue();
23999   SDValue ShAmt1 = N1.getOperand(1);
24000   if (ShAmt1.getValueType() != MVT::i8)
24001     return SDValue();
24002   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
24003     ShAmt0 = ShAmt0.getOperand(0);
24004   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
24005     ShAmt1 = ShAmt1.getOperand(0);
24006
24007   SDLoc DL(N);
24008   unsigned Opc = X86ISD::SHLD;
24009   SDValue Op0 = N0.getOperand(0);
24010   SDValue Op1 = N1.getOperand(0);
24011   if (ShAmt0.getOpcode() == ISD::SUB) {
24012     Opc = X86ISD::SHRD;
24013     std::swap(Op0, Op1);
24014     std::swap(ShAmt0, ShAmt1);
24015   }
24016
24017   unsigned Bits = VT.getSizeInBits();
24018   if (ShAmt1.getOpcode() == ISD::SUB) {
24019     SDValue Sum = ShAmt1.getOperand(0);
24020     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
24021       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
24022       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
24023         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
24024       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
24025         return DAG.getNode(Opc, DL, VT,
24026                            Op0, Op1,
24027                            DAG.getNode(ISD::TRUNCATE, DL,
24028                                        MVT::i8, ShAmt0));
24029     }
24030   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
24031     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
24032     if (ShAmt0C &&
24033         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
24034       return DAG.getNode(Opc, DL, VT,
24035                          N0.getOperand(0), N1.getOperand(0),
24036                          DAG.getNode(ISD::TRUNCATE, DL,
24037                                        MVT::i8, ShAmt0));
24038   }
24039
24040   return SDValue();
24041 }
24042
24043 // Generate NEG and CMOV for integer abs.
24044 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
24045   EVT VT = N->getValueType(0);
24046
24047   // Since X86 does not have CMOV for 8-bit integer, we don't convert
24048   // 8-bit integer abs to NEG and CMOV.
24049   if (VT.isInteger() && VT.getSizeInBits() == 8)
24050     return SDValue();
24051
24052   SDValue N0 = N->getOperand(0);
24053   SDValue N1 = N->getOperand(1);
24054   SDLoc DL(N);
24055
24056   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
24057   // and change it to SUB and CMOV.
24058   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
24059       N0.getOpcode() == ISD::ADD &&
24060       N0.getOperand(1) == N1 &&
24061       N1.getOpcode() == ISD::SRA &&
24062       N1.getOperand(0) == N0.getOperand(0))
24063     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
24064       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
24065         // Generate SUB & CMOV.
24066         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
24067                                   DAG.getConstant(0, DL, VT), N0.getOperand(0));
24068
24069         SDValue Ops[] = { N0.getOperand(0), Neg,
24070                           DAG.getConstant(X86::COND_GE, DL, MVT::i8),
24071                           SDValue(Neg.getNode(), 1) };
24072         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
24073       }
24074   return SDValue();
24075 }
24076
24077 // Try to turn tests against the signbit in the form of:
24078 //   XOR(TRUNCATE(SRL(X, size(X)-1)), 1)
24079 // into:
24080 //   SETGT(X, -1)
24081 static SDValue foldXorTruncShiftIntoCmp(SDNode *N, SelectionDAG &DAG) {
24082   // This is only worth doing if the output type is i8.
24083   if (N->getValueType(0) != MVT::i8)
24084     return SDValue();
24085
24086   SDValue N0 = N->getOperand(0);
24087   SDValue N1 = N->getOperand(1);
24088
24089   // We should be performing an xor against a truncated shift.
24090   if (N0.getOpcode() != ISD::TRUNCATE || !N0.hasOneUse())
24091     return SDValue();
24092
24093   // Make sure we are performing an xor against one.
24094   if (!isa<ConstantSDNode>(N1) || !cast<ConstantSDNode>(N1)->isOne())
24095     return SDValue();
24096
24097   // SetCC on x86 zero extends so only act on this if it's a logical shift.
24098   SDValue Shift = N0.getOperand(0);
24099   if (Shift.getOpcode() != ISD::SRL || !Shift.hasOneUse())
24100     return SDValue();
24101
24102   // Make sure we are truncating from one of i16, i32 or i64.
24103   EVT ShiftTy = Shift.getValueType();
24104   if (ShiftTy != MVT::i16 && ShiftTy != MVT::i32 && ShiftTy != MVT::i64)
24105     return SDValue();
24106
24107   // Make sure the shift amount extracts the sign bit.
24108   if (!isa<ConstantSDNode>(Shift.getOperand(1)) ||
24109       Shift.getConstantOperandVal(1) != ShiftTy.getSizeInBits() - 1)
24110     return SDValue();
24111
24112   // Create a greater-than comparison against -1.
24113   // N.B. Using SETGE against 0 works but we want a canonical looking
24114   // comparison, using SETGT matches up with what TranslateX86CC.
24115   SDLoc DL(N);
24116   SDValue ShiftOp = Shift.getOperand(0);
24117   EVT ShiftOpTy = ShiftOp.getValueType();
24118   SDValue Cond = DAG.getSetCC(DL, MVT::i8, ShiftOp,
24119                               DAG.getConstant(-1, DL, ShiftOpTy), ISD::SETGT);
24120   return Cond;
24121 }
24122
24123 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
24124                                  TargetLowering::DAGCombinerInfo &DCI,
24125                                  const X86Subtarget *Subtarget) {
24126   if (DCI.isBeforeLegalizeOps())
24127     return SDValue();
24128
24129   if (SDValue RV = foldXorTruncShiftIntoCmp(N, DAG))
24130     return RV;
24131
24132   if (Subtarget->hasCMov())
24133     if (SDValue RV = performIntegerAbsCombine(N, DAG))
24134       return RV;
24135
24136   return SDValue();
24137 }
24138
24139 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
24140 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
24141                                   TargetLowering::DAGCombinerInfo &DCI,
24142                                   const X86Subtarget *Subtarget) {
24143   LoadSDNode *Ld = cast<LoadSDNode>(N);
24144   EVT RegVT = Ld->getValueType(0);
24145   EVT MemVT = Ld->getMemoryVT();
24146   SDLoc dl(Ld);
24147   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24148
24149   // For chips with slow 32-byte unaligned loads, break the 32-byte operation
24150   // into two 16-byte operations.
24151   ISD::LoadExtType Ext = Ld->getExtensionType();
24152   bool Fast;
24153   unsigned AddressSpace = Ld->getAddressSpace();
24154   unsigned Alignment = Ld->getAlignment();
24155   if (RegVT.is256BitVector() && !DCI.isBeforeLegalizeOps() &&
24156       Ext == ISD::NON_EXTLOAD &&
24157       TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), RegVT,
24158                              AddressSpace, Alignment, &Fast) && !Fast) {
24159     unsigned NumElems = RegVT.getVectorNumElements();
24160     if (NumElems < 2)
24161       return SDValue();
24162
24163     SDValue Ptr = Ld->getBasePtr();
24164     SDValue Increment =
24165         DAG.getConstant(16, dl, TLI.getPointerTy(DAG.getDataLayout()));
24166
24167     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
24168                                   NumElems/2);
24169     SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
24170                                 Ld->getPointerInfo(), Ld->isVolatile(),
24171                                 Ld->isNonTemporal(), Ld->isInvariant(),
24172                                 Alignment);
24173     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
24174     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
24175                                 Ld->getPointerInfo(), Ld->isVolatile(),
24176                                 Ld->isNonTemporal(), Ld->isInvariant(),
24177                                 std::min(16U, Alignment));
24178     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
24179                              Load1.getValue(1),
24180                              Load2.getValue(1));
24181
24182     SDValue NewVec = DAG.getUNDEF(RegVT);
24183     NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
24184     NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
24185     return DCI.CombineTo(N, NewVec, TF, true);
24186   }
24187
24188   return SDValue();
24189 }
24190
24191 /// PerformMLOADCombine - Resolve extending loads
24192 static SDValue PerformMLOADCombine(SDNode *N, SelectionDAG &DAG,
24193                                    TargetLowering::DAGCombinerInfo &DCI,
24194                                    const X86Subtarget *Subtarget) {
24195   MaskedLoadSDNode *Mld = cast<MaskedLoadSDNode>(N);
24196   if (Mld->getExtensionType() != ISD::SEXTLOAD)
24197     return SDValue();
24198
24199   EVT VT = Mld->getValueType(0);
24200   unsigned NumElems = VT.getVectorNumElements();
24201   EVT LdVT = Mld->getMemoryVT();
24202   SDLoc dl(Mld);
24203
24204   assert(LdVT != VT && "Cannot extend to the same type");
24205   unsigned ToSz = VT.getVectorElementType().getSizeInBits();
24206   unsigned FromSz = LdVT.getVectorElementType().getSizeInBits();
24207   // From, To sizes and ElemCount must be pow of two
24208   assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
24209     "Unexpected size for extending masked load");
24210
24211   unsigned SizeRatio  = ToSz / FromSz;
24212   assert(SizeRatio * NumElems * FromSz == VT.getSizeInBits());
24213
24214   // Create a type on which we perform the shuffle
24215   EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
24216           LdVT.getScalarType(), NumElems*SizeRatio);
24217   assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
24218
24219   // Convert Src0 value
24220   SDValue WideSrc0 = DAG.getBitcast(WideVecVT, Mld->getSrc0());
24221   if (Mld->getSrc0().getOpcode() != ISD::UNDEF) {
24222     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
24223     for (unsigned i = 0; i != NumElems; ++i)
24224       ShuffleVec[i] = i * SizeRatio;
24225
24226     // Can't shuffle using an illegal type.
24227     assert (DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT)
24228             && "WideVecVT should be legal");
24229     WideSrc0 = DAG.getVectorShuffle(WideVecVT, dl, WideSrc0,
24230                                     DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
24231   }
24232   // Prepare the new mask
24233   SDValue NewMask;
24234   SDValue Mask = Mld->getMask();
24235   if (Mask.getValueType() == VT) {
24236     // Mask and original value have the same type
24237     NewMask = DAG.getBitcast(WideVecVT, Mask);
24238     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
24239     for (unsigned i = 0; i != NumElems; ++i)
24240       ShuffleVec[i] = i * SizeRatio;
24241     for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
24242       ShuffleVec[i] = NumElems*SizeRatio;
24243     NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
24244                                    DAG.getConstant(0, dl, WideVecVT),
24245                                    &ShuffleVec[0]);
24246   }
24247   else {
24248     assert(Mask.getValueType().getVectorElementType() == MVT::i1);
24249     unsigned WidenNumElts = NumElems*SizeRatio;
24250     unsigned MaskNumElts = VT.getVectorNumElements();
24251     EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(),  MVT::i1,
24252                                      WidenNumElts);
24253
24254     unsigned NumConcat = WidenNumElts / MaskNumElts;
24255     SmallVector<SDValue, 16> Ops(NumConcat);
24256     SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
24257     Ops[0] = Mask;
24258     for (unsigned i = 1; i != NumConcat; ++i)
24259       Ops[i] = ZeroVal;
24260
24261     NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
24262   }
24263
24264   SDValue WideLd = DAG.getMaskedLoad(WideVecVT, dl, Mld->getChain(),
24265                                      Mld->getBasePtr(), NewMask, WideSrc0,
24266                                      Mld->getMemoryVT(), Mld->getMemOperand(),
24267                                      ISD::NON_EXTLOAD);
24268   SDValue NewVec = DAG.getNode(X86ISD::VSEXT, dl, VT, WideLd);
24269   return DCI.CombineTo(N, NewVec, WideLd.getValue(1), true);
24270
24271 }
24272 /// PerformMSTORECombine - Resolve truncating stores
24273 static SDValue PerformMSTORECombine(SDNode *N, SelectionDAG &DAG,
24274                                     const X86Subtarget *Subtarget) {
24275   MaskedStoreSDNode *Mst = cast<MaskedStoreSDNode>(N);
24276   if (!Mst->isTruncatingStore())
24277     return SDValue();
24278
24279   EVT VT = Mst->getValue().getValueType();
24280   unsigned NumElems = VT.getVectorNumElements();
24281   EVT StVT = Mst->getMemoryVT();
24282   SDLoc dl(Mst);
24283
24284   assert(StVT != VT && "Cannot truncate to the same type");
24285   unsigned FromSz = VT.getVectorElementType().getSizeInBits();
24286   unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
24287
24288   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24289
24290   // The truncating store is legal in some cases. For example
24291   // vpmovqb, vpmovqw, vpmovqd, vpmovdb, vpmovdw
24292   // are designated for truncate store.
24293   // In this case we don't need any further transformations.
24294   if (TLI.isTruncStoreLegal(VT, StVT))
24295     return SDValue();
24296
24297   // From, To sizes and ElemCount must be pow of two
24298   assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
24299     "Unexpected size for truncating masked store");
24300   // We are going to use the original vector elt for storing.
24301   // Accumulated smaller vector elements must be a multiple of the store size.
24302   assert (((NumElems * FromSz) % ToSz) == 0 &&
24303           "Unexpected ratio for truncating masked store");
24304
24305   unsigned SizeRatio  = FromSz / ToSz;
24306   assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
24307
24308   // Create a type on which we perform the shuffle
24309   EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
24310           StVT.getScalarType(), NumElems*SizeRatio);
24311
24312   assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
24313
24314   SDValue WideVec = DAG.getBitcast(WideVecVT, Mst->getValue());
24315   SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
24316   for (unsigned i = 0; i != NumElems; ++i)
24317     ShuffleVec[i] = i * SizeRatio;
24318
24319   // Can't shuffle using an illegal type.
24320   assert (DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT)
24321           && "WideVecVT should be legal");
24322
24323   SDValue TruncatedVal = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
24324                                         DAG.getUNDEF(WideVecVT),
24325                                         &ShuffleVec[0]);
24326
24327   SDValue NewMask;
24328   SDValue Mask = Mst->getMask();
24329   if (Mask.getValueType() == VT) {
24330     // Mask and original value have the same type
24331     NewMask = DAG.getBitcast(WideVecVT, Mask);
24332     for (unsigned i = 0; i != NumElems; ++i)
24333       ShuffleVec[i] = i * SizeRatio;
24334     for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
24335       ShuffleVec[i] = NumElems*SizeRatio;
24336     NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
24337                                    DAG.getConstant(0, dl, WideVecVT),
24338                                    &ShuffleVec[0]);
24339   }
24340   else {
24341     assert(Mask.getValueType().getVectorElementType() == MVT::i1);
24342     unsigned WidenNumElts = NumElems*SizeRatio;
24343     unsigned MaskNumElts = VT.getVectorNumElements();
24344     EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(),  MVT::i1,
24345                                      WidenNumElts);
24346
24347     unsigned NumConcat = WidenNumElts / MaskNumElts;
24348     SmallVector<SDValue, 16> Ops(NumConcat);
24349     SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
24350     Ops[0] = Mask;
24351     for (unsigned i = 1; i != NumConcat; ++i)
24352       Ops[i] = ZeroVal;
24353
24354     NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
24355   }
24356
24357   return DAG.getMaskedStore(Mst->getChain(), dl, TruncatedVal, Mst->getBasePtr(),
24358                             NewMask, StVT, Mst->getMemOperand(), false);
24359 }
24360 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
24361 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
24362                                    const X86Subtarget *Subtarget) {
24363   StoreSDNode *St = cast<StoreSDNode>(N);
24364   EVT VT = St->getValue().getValueType();
24365   EVT StVT = St->getMemoryVT();
24366   SDLoc dl(St);
24367   SDValue StoredVal = St->getOperand(1);
24368   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24369
24370   // If we are saving a concatenation of two XMM registers and 32-byte stores
24371   // are slow, such as on Sandy Bridge, perform two 16-byte stores.
24372   bool Fast;
24373   unsigned AddressSpace = St->getAddressSpace();
24374   unsigned Alignment = St->getAlignment();
24375   if (VT.is256BitVector() && StVT == VT &&
24376       TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT,
24377                              AddressSpace, Alignment, &Fast) && !Fast) {
24378     unsigned NumElems = VT.getVectorNumElements();
24379     if (NumElems < 2)
24380       return SDValue();
24381
24382     SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
24383     SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
24384
24385     SDValue Stride =
24386         DAG.getConstant(16, dl, TLI.getPointerTy(DAG.getDataLayout()));
24387     SDValue Ptr0 = St->getBasePtr();
24388     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
24389
24390     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
24391                                 St->getPointerInfo(), St->isVolatile(),
24392                                 St->isNonTemporal(), Alignment);
24393     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
24394                                 St->getPointerInfo(), St->isVolatile(),
24395                                 St->isNonTemporal(),
24396                                 std::min(16U, Alignment));
24397     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
24398   }
24399
24400   // Optimize trunc store (of multiple scalars) to shuffle and store.
24401   // First, pack all of the elements in one place. Next, store to memory
24402   // in fewer chunks.
24403   if (St->isTruncatingStore() && VT.isVector()) {
24404     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24405     unsigned NumElems = VT.getVectorNumElements();
24406     assert(StVT != VT && "Cannot truncate to the same type");
24407     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
24408     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
24409
24410     // The truncating store is legal in some cases. For example
24411     // vpmovqb, vpmovqw, vpmovqd, vpmovdb, vpmovdw
24412     // are designated for truncate store.
24413     // In this case we don't need any further transformations.
24414     if (TLI.isTruncStoreLegal(VT, StVT))
24415       return SDValue();
24416
24417     // From, To sizes and ElemCount must be pow of two
24418     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
24419     // We are going to use the original vector elt for storing.
24420     // Accumulated smaller vector elements must be a multiple of the store size.
24421     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
24422
24423     unsigned SizeRatio  = FromSz / ToSz;
24424
24425     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
24426
24427     // Create a type on which we perform the shuffle
24428     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
24429             StVT.getScalarType(), NumElems*SizeRatio);
24430
24431     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
24432
24433     SDValue WideVec = DAG.getBitcast(WideVecVT, St->getValue());
24434     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
24435     for (unsigned i = 0; i != NumElems; ++i)
24436       ShuffleVec[i] = i * SizeRatio;
24437
24438     // Can't shuffle using an illegal type.
24439     if (!TLI.isTypeLegal(WideVecVT))
24440       return SDValue();
24441
24442     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
24443                                          DAG.getUNDEF(WideVecVT),
24444                                          &ShuffleVec[0]);
24445     // At this point all of the data is stored at the bottom of the
24446     // register. We now need to save it to mem.
24447
24448     // Find the largest store unit
24449     MVT StoreType = MVT::i8;
24450     for (MVT Tp : MVT::integer_valuetypes()) {
24451       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
24452         StoreType = Tp;
24453     }
24454
24455     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
24456     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
24457         (64 <= NumElems * ToSz))
24458       StoreType = MVT::f64;
24459
24460     // Bitcast the original vector into a vector of store-size units
24461     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
24462             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
24463     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
24464     SDValue ShuffWide = DAG.getBitcast(StoreVecVT, Shuff);
24465     SmallVector<SDValue, 8> Chains;
24466     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, dl,
24467                                         TLI.getPointerTy(DAG.getDataLayout()));
24468     SDValue Ptr = St->getBasePtr();
24469
24470     // Perform one or more big stores into memory.
24471     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
24472       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
24473                                    StoreType, ShuffWide,
24474                                    DAG.getIntPtrConstant(i, dl));
24475       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
24476                                 St->getPointerInfo(), St->isVolatile(),
24477                                 St->isNonTemporal(), St->getAlignment());
24478       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
24479       Chains.push_back(Ch);
24480     }
24481
24482     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
24483   }
24484
24485   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
24486   // the FP state in cases where an emms may be missing.
24487   // A preferable solution to the general problem is to figure out the right
24488   // places to insert EMMS.  This qualifies as a quick hack.
24489
24490   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
24491   if (VT.getSizeInBits() != 64)
24492     return SDValue();
24493
24494   const Function *F = DAG.getMachineFunction().getFunction();
24495   bool NoImplicitFloatOps = F->hasFnAttribute(Attribute::NoImplicitFloat);
24496   bool F64IsLegal =
24497       !Subtarget->useSoftFloat() && !NoImplicitFloatOps && Subtarget->hasSSE2();
24498   if ((VT.isVector() ||
24499        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
24500       isa<LoadSDNode>(St->getValue()) &&
24501       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
24502       St->getChain().hasOneUse() && !St->isVolatile()) {
24503     SDNode* LdVal = St->getValue().getNode();
24504     LoadSDNode *Ld = nullptr;
24505     int TokenFactorIndex = -1;
24506     SmallVector<SDValue, 8> Ops;
24507     SDNode* ChainVal = St->getChain().getNode();
24508     // Must be a store of a load.  We currently handle two cases:  the load
24509     // is a direct child, and it's under an intervening TokenFactor.  It is
24510     // possible to dig deeper under nested TokenFactors.
24511     if (ChainVal == LdVal)
24512       Ld = cast<LoadSDNode>(St->getChain());
24513     else if (St->getValue().hasOneUse() &&
24514              ChainVal->getOpcode() == ISD::TokenFactor) {
24515       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
24516         if (ChainVal->getOperand(i).getNode() == LdVal) {
24517           TokenFactorIndex = i;
24518           Ld = cast<LoadSDNode>(St->getValue());
24519         } else
24520           Ops.push_back(ChainVal->getOperand(i));
24521       }
24522     }
24523
24524     if (!Ld || !ISD::isNormalLoad(Ld))
24525       return SDValue();
24526
24527     // If this is not the MMX case, i.e. we are just turning i64 load/store
24528     // into f64 load/store, avoid the transformation if there are multiple
24529     // uses of the loaded value.
24530     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
24531       return SDValue();
24532
24533     SDLoc LdDL(Ld);
24534     SDLoc StDL(N);
24535     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
24536     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
24537     // pair instead.
24538     if (Subtarget->is64Bit() || F64IsLegal) {
24539       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
24540       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
24541                                   Ld->getPointerInfo(), Ld->isVolatile(),
24542                                   Ld->isNonTemporal(), Ld->isInvariant(),
24543                                   Ld->getAlignment());
24544       SDValue NewChain = NewLd.getValue(1);
24545       if (TokenFactorIndex != -1) {
24546         Ops.push_back(NewChain);
24547         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
24548       }
24549       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
24550                           St->getPointerInfo(),
24551                           St->isVolatile(), St->isNonTemporal(),
24552                           St->getAlignment());
24553     }
24554
24555     // Otherwise, lower to two pairs of 32-bit loads / stores.
24556     SDValue LoAddr = Ld->getBasePtr();
24557     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
24558                                  DAG.getConstant(4, LdDL, MVT::i32));
24559
24560     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
24561                                Ld->getPointerInfo(),
24562                                Ld->isVolatile(), Ld->isNonTemporal(),
24563                                Ld->isInvariant(), Ld->getAlignment());
24564     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
24565                                Ld->getPointerInfo().getWithOffset(4),
24566                                Ld->isVolatile(), Ld->isNonTemporal(),
24567                                Ld->isInvariant(),
24568                                MinAlign(Ld->getAlignment(), 4));
24569
24570     SDValue NewChain = LoLd.getValue(1);
24571     if (TokenFactorIndex != -1) {
24572       Ops.push_back(LoLd);
24573       Ops.push_back(HiLd);
24574       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
24575     }
24576
24577     LoAddr = St->getBasePtr();
24578     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
24579                          DAG.getConstant(4, StDL, MVT::i32));
24580
24581     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
24582                                 St->getPointerInfo(),
24583                                 St->isVolatile(), St->isNonTemporal(),
24584                                 St->getAlignment());
24585     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
24586                                 St->getPointerInfo().getWithOffset(4),
24587                                 St->isVolatile(),
24588                                 St->isNonTemporal(),
24589                                 MinAlign(St->getAlignment(), 4));
24590     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
24591   }
24592
24593   // This is similar to the above case, but here we handle a scalar 64-bit
24594   // integer store that is extracted from a vector on a 32-bit target.
24595   // If we have SSE2, then we can treat it like a floating-point double
24596   // to get past legalization. The execution dependencies fixup pass will
24597   // choose the optimal machine instruction for the store if this really is
24598   // an integer or v2f32 rather than an f64.
24599   if (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit() &&
24600       St->getOperand(1).getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
24601     SDValue OldExtract = St->getOperand(1);
24602     SDValue ExtOp0 = OldExtract.getOperand(0);
24603     unsigned VecSize = ExtOp0.getValueSizeInBits();
24604     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, VecSize / 64);
24605     SDValue BitCast = DAG.getBitcast(VecVT, ExtOp0);
24606     SDValue NewExtract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
24607                                      BitCast, OldExtract.getOperand(1));
24608     return DAG.getStore(St->getChain(), dl, NewExtract, St->getBasePtr(),
24609                         St->getPointerInfo(), St->isVolatile(),
24610                         St->isNonTemporal(), St->getAlignment());
24611   }
24612
24613   return SDValue();
24614 }
24615
24616 /// Return 'true' if this vector operation is "horizontal"
24617 /// and return the operands for the horizontal operation in LHS and RHS.  A
24618 /// horizontal operation performs the binary operation on successive elements
24619 /// of its first operand, then on successive elements of its second operand,
24620 /// returning the resulting values in a vector.  For example, if
24621 ///   A = < float a0, float a1, float a2, float a3 >
24622 /// and
24623 ///   B = < float b0, float b1, float b2, float b3 >
24624 /// then the result of doing a horizontal operation on A and B is
24625 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
24626 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
24627 /// A horizontal-op B, for some already available A and B, and if so then LHS is
24628 /// set to A, RHS to B, and the routine returns 'true'.
24629 /// Note that the binary operation should have the property that if one of the
24630 /// operands is UNDEF then the result is UNDEF.
24631 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
24632   // Look for the following pattern: if
24633   //   A = < float a0, float a1, float a2, float a3 >
24634   //   B = < float b0, float b1, float b2, float b3 >
24635   // and
24636   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
24637   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
24638   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
24639   // which is A horizontal-op B.
24640
24641   // At least one of the operands should be a vector shuffle.
24642   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
24643       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
24644     return false;
24645
24646   MVT VT = LHS.getSimpleValueType();
24647
24648   assert((VT.is128BitVector() || VT.is256BitVector()) &&
24649          "Unsupported vector type for horizontal add/sub");
24650
24651   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
24652   // operate independently on 128-bit lanes.
24653   unsigned NumElts = VT.getVectorNumElements();
24654   unsigned NumLanes = VT.getSizeInBits()/128;
24655   unsigned NumLaneElts = NumElts / NumLanes;
24656   assert((NumLaneElts % 2 == 0) &&
24657          "Vector type should have an even number of elements in each lane");
24658   unsigned HalfLaneElts = NumLaneElts/2;
24659
24660   // View LHS in the form
24661   //   LHS = VECTOR_SHUFFLE A, B, LMask
24662   // If LHS is not a shuffle then pretend it is the shuffle
24663   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
24664   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
24665   // type VT.
24666   SDValue A, B;
24667   SmallVector<int, 16> LMask(NumElts);
24668   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
24669     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
24670       A = LHS.getOperand(0);
24671     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
24672       B = LHS.getOperand(1);
24673     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
24674     std::copy(Mask.begin(), Mask.end(), LMask.begin());
24675   } else {
24676     if (LHS.getOpcode() != ISD::UNDEF)
24677       A = LHS;
24678     for (unsigned i = 0; i != NumElts; ++i)
24679       LMask[i] = i;
24680   }
24681
24682   // Likewise, view RHS in the form
24683   //   RHS = VECTOR_SHUFFLE C, D, RMask
24684   SDValue C, D;
24685   SmallVector<int, 16> RMask(NumElts);
24686   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
24687     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
24688       C = RHS.getOperand(0);
24689     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
24690       D = RHS.getOperand(1);
24691     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
24692     std::copy(Mask.begin(), Mask.end(), RMask.begin());
24693   } else {
24694     if (RHS.getOpcode() != ISD::UNDEF)
24695       C = RHS;
24696     for (unsigned i = 0; i != NumElts; ++i)
24697       RMask[i] = i;
24698   }
24699
24700   // Check that the shuffles are both shuffling the same vectors.
24701   if (!(A == C && B == D) && !(A == D && B == C))
24702     return false;
24703
24704   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
24705   if (!A.getNode() && !B.getNode())
24706     return false;
24707
24708   // If A and B occur in reverse order in RHS, then "swap" them (which means
24709   // rewriting the mask).
24710   if (A != C)
24711     ShuffleVectorSDNode::commuteMask(RMask);
24712
24713   // At this point LHS and RHS are equivalent to
24714   //   LHS = VECTOR_SHUFFLE A, B, LMask
24715   //   RHS = VECTOR_SHUFFLE A, B, RMask
24716   // Check that the masks correspond to performing a horizontal operation.
24717   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
24718     for (unsigned i = 0; i != NumLaneElts; ++i) {
24719       int LIdx = LMask[i+l], RIdx = RMask[i+l];
24720
24721       // Ignore any UNDEF components.
24722       if (LIdx < 0 || RIdx < 0 ||
24723           (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
24724           (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
24725         continue;
24726
24727       // Check that successive elements are being operated on.  If not, this is
24728       // not a horizontal operation.
24729       unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
24730       int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
24731       if (!(LIdx == Index && RIdx == Index + 1) &&
24732           !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
24733         return false;
24734     }
24735   }
24736
24737   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
24738   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
24739   return true;
24740 }
24741
24742 /// Do target-specific dag combines on floating point adds.
24743 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
24744                                   const X86Subtarget *Subtarget) {
24745   EVT VT = N->getValueType(0);
24746   SDValue LHS = N->getOperand(0);
24747   SDValue RHS = N->getOperand(1);
24748
24749   // Try to synthesize horizontal adds from adds of shuffles.
24750   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
24751        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
24752       isHorizontalBinOp(LHS, RHS, true))
24753     return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
24754   return SDValue();
24755 }
24756
24757 /// Do target-specific dag combines on floating point subs.
24758 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
24759                                   const X86Subtarget *Subtarget) {
24760   EVT VT = N->getValueType(0);
24761   SDValue LHS = N->getOperand(0);
24762   SDValue RHS = N->getOperand(1);
24763
24764   // Try to synthesize horizontal subs from subs of shuffles.
24765   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
24766        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
24767       isHorizontalBinOp(LHS, RHS, false))
24768     return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
24769   return SDValue();
24770 }
24771
24772 /// Do target-specific dag combines on X86ISD::FOR and X86ISD::FXOR nodes.
24773 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
24774   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
24775
24776   // F[X]OR(0.0, x) -> x
24777   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
24778     if (C->getValueAPF().isPosZero())
24779       return N->getOperand(1);
24780
24781   // F[X]OR(x, 0.0) -> x
24782   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
24783     if (C->getValueAPF().isPosZero())
24784       return N->getOperand(0);
24785   return SDValue();
24786 }
24787
24788 /// Do target-specific dag combines on X86ISD::FMIN and X86ISD::FMAX nodes.
24789 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
24790   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
24791
24792   // Only perform optimizations if UnsafeMath is used.
24793   if (!DAG.getTarget().Options.UnsafeFPMath)
24794     return SDValue();
24795
24796   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
24797   // into FMINC and FMAXC, which are Commutative operations.
24798   unsigned NewOp = 0;
24799   switch (N->getOpcode()) {
24800     default: llvm_unreachable("unknown opcode");
24801     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
24802     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
24803   }
24804
24805   return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
24806                      N->getOperand(0), N->getOperand(1));
24807 }
24808
24809 /// Do target-specific dag combines on X86ISD::FAND nodes.
24810 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
24811   // FAND(0.0, x) -> 0.0
24812   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
24813     if (C->getValueAPF().isPosZero())
24814       return N->getOperand(0);
24815
24816   // FAND(x, 0.0) -> 0.0
24817   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
24818     if (C->getValueAPF().isPosZero())
24819       return N->getOperand(1);
24820
24821   return SDValue();
24822 }
24823
24824 /// Do target-specific dag combines on X86ISD::FANDN nodes
24825 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
24826   // FANDN(0.0, x) -> x
24827   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
24828     if (C->getValueAPF().isPosZero())
24829       return N->getOperand(1);
24830
24831   // FANDN(x, 0.0) -> 0.0
24832   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
24833     if (C->getValueAPF().isPosZero())
24834       return N->getOperand(1);
24835
24836   return SDValue();
24837 }
24838
24839 static SDValue PerformBTCombine(SDNode *N,
24840                                 SelectionDAG &DAG,
24841                                 TargetLowering::DAGCombinerInfo &DCI) {
24842   // BT ignores high bits in the bit index operand.
24843   SDValue Op1 = N->getOperand(1);
24844   if (Op1.hasOneUse()) {
24845     unsigned BitWidth = Op1.getValueSizeInBits();
24846     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
24847     APInt KnownZero, KnownOne;
24848     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
24849                                           !DCI.isBeforeLegalizeOps());
24850     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24851     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
24852         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
24853       DCI.CommitTargetLoweringOpt(TLO);
24854   }
24855   return SDValue();
24856 }
24857
24858 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
24859   SDValue Op = N->getOperand(0);
24860   if (Op.getOpcode() == ISD::BITCAST)
24861     Op = Op.getOperand(0);
24862   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
24863   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
24864       VT.getVectorElementType().getSizeInBits() ==
24865       OpVT.getVectorElementType().getSizeInBits()) {
24866     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
24867   }
24868   return SDValue();
24869 }
24870
24871 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
24872                                                const X86Subtarget *Subtarget) {
24873   EVT VT = N->getValueType(0);
24874   if (!VT.isVector())
24875     return SDValue();
24876
24877   SDValue N0 = N->getOperand(0);
24878   SDValue N1 = N->getOperand(1);
24879   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
24880   SDLoc dl(N);
24881
24882   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
24883   // both SSE and AVX2 since there is no sign-extended shift right
24884   // operation on a vector with 64-bit elements.
24885   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
24886   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
24887   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
24888       N0.getOpcode() == ISD::SIGN_EXTEND)) {
24889     SDValue N00 = N0.getOperand(0);
24890
24891     // EXTLOAD has a better solution on AVX2,
24892     // it may be replaced with X86ISD::VSEXT node.
24893     if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
24894       if (!ISD::isNormalLoad(N00.getNode()))
24895         return SDValue();
24896
24897     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
24898         SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
24899                                   N00, N1);
24900       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
24901     }
24902   }
24903   return SDValue();
24904 }
24905
24906 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
24907                                   TargetLowering::DAGCombinerInfo &DCI,
24908                                   const X86Subtarget *Subtarget) {
24909   SDValue N0 = N->getOperand(0);
24910   EVT VT = N->getValueType(0);
24911   EVT SVT = VT.getScalarType();
24912   EVT InVT = N0.getValueType();
24913   EVT InSVT = InVT.getScalarType();
24914   SDLoc DL(N);
24915
24916   // (i8,i32 sext (sdivrem (i8 x, i8 y)) ->
24917   // (i8,i32 (sdivrem_sext_hreg (i8 x, i8 y)
24918   // This exposes the sext to the sdivrem lowering, so that it directly extends
24919   // from AH (which we otherwise need to do contortions to access).
24920   if (N0.getOpcode() == ISD::SDIVREM && N0.getResNo() == 1 &&
24921       InVT == MVT::i8 && VT == MVT::i32) {
24922     SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
24923     SDValue R = DAG.getNode(X86ISD::SDIVREM8_SEXT_HREG, DL, NodeTys,
24924                             N0.getOperand(0), N0.getOperand(1));
24925     DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
24926     return R.getValue(1);
24927   }
24928
24929   if (!DCI.isBeforeLegalizeOps()) {
24930     if (InVT == MVT::i1) {
24931       SDValue Zero = DAG.getConstant(0, DL, VT);
24932       SDValue AllOnes =
24933         DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), DL, VT);
24934       return DAG.getNode(ISD::SELECT, DL, VT, N0, AllOnes, Zero);
24935     }
24936     return SDValue();
24937   }
24938
24939   if (VT.isVector() && Subtarget->hasSSE2()) {
24940     auto ExtendVecSize = [&DAG](SDLoc DL, SDValue N, unsigned Size) {
24941       EVT InVT = N.getValueType();
24942       EVT OutVT = EVT::getVectorVT(*DAG.getContext(), InVT.getScalarType(),
24943                                    Size / InVT.getScalarSizeInBits());
24944       SmallVector<SDValue, 8> Opnds(Size / InVT.getSizeInBits(),
24945                                     DAG.getUNDEF(InVT));
24946       Opnds[0] = N;
24947       return DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, Opnds);
24948     };
24949
24950     // If target-size is less than 128-bits, extend to a type that would extend
24951     // to 128 bits, extend that and extract the original target vector.
24952     if (VT.getSizeInBits() < 128 && !(128 % VT.getSizeInBits()) &&
24953         (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
24954         (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
24955       unsigned Scale = 128 / VT.getSizeInBits();
24956       EVT ExVT =
24957           EVT::getVectorVT(*DAG.getContext(), SVT, 128 / SVT.getSizeInBits());
24958       SDValue Ex = ExtendVecSize(DL, N0, Scale * InVT.getSizeInBits());
24959       SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND, DL, ExVT, Ex);
24960       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, SExt,
24961                          DAG.getIntPtrConstant(0, DL));
24962     }
24963
24964     // If target-size is 128-bits, then convert to ISD::SIGN_EXTEND_VECTOR_INREG
24965     // which ensures lowering to X86ISD::VSEXT (pmovsx*).
24966     if (VT.getSizeInBits() == 128 &&
24967         (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
24968         (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
24969       SDValue ExOp = ExtendVecSize(DL, N0, 128);
24970       return DAG.getSignExtendVectorInReg(ExOp, DL, VT);
24971     }
24972
24973     // On pre-AVX2 targets, split into 128-bit nodes of
24974     // ISD::SIGN_EXTEND_VECTOR_INREG.
24975     if (!Subtarget->hasInt256() && !(VT.getSizeInBits() % 128) &&
24976         (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
24977         (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
24978       unsigned NumVecs = VT.getSizeInBits() / 128;
24979       unsigned NumSubElts = 128 / SVT.getSizeInBits();
24980       EVT SubVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumSubElts);
24981       EVT InSubVT = EVT::getVectorVT(*DAG.getContext(), InSVT, NumSubElts);
24982
24983       SmallVector<SDValue, 8> Opnds;
24984       for (unsigned i = 0, Offset = 0; i != NumVecs;
24985            ++i, Offset += NumSubElts) {
24986         SDValue SrcVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InSubVT, N0,
24987                                      DAG.getIntPtrConstant(Offset, DL));
24988         SrcVec = ExtendVecSize(DL, SrcVec, 128);
24989         SrcVec = DAG.getSignExtendVectorInReg(SrcVec, DL, SubVT);
24990         Opnds.push_back(SrcVec);
24991       }
24992       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Opnds);
24993     }
24994   }
24995
24996   if (!Subtarget->hasFp256())
24997     return SDValue();
24998
24999   if (VT.isVector() && VT.getSizeInBits() == 256)
25000     if (SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget))
25001       return R;
25002
25003   return SDValue();
25004 }
25005
25006 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
25007                                  const X86Subtarget* Subtarget) {
25008   SDLoc dl(N);
25009   EVT VT = N->getValueType(0);
25010
25011   // Let legalize expand this if it isn't a legal type yet.
25012   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
25013     return SDValue();
25014
25015   EVT ScalarVT = VT.getScalarType();
25016   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
25017       (!Subtarget->hasFMA() && !Subtarget->hasFMA4() &&
25018        !Subtarget->hasAVX512()))
25019     return SDValue();
25020
25021   SDValue A = N->getOperand(0);
25022   SDValue B = N->getOperand(1);
25023   SDValue C = N->getOperand(2);
25024
25025   bool NegA = (A.getOpcode() == ISD::FNEG);
25026   bool NegB = (B.getOpcode() == ISD::FNEG);
25027   bool NegC = (C.getOpcode() == ISD::FNEG);
25028
25029   // Negative multiplication when NegA xor NegB
25030   bool NegMul = (NegA != NegB);
25031   if (NegA)
25032     A = A.getOperand(0);
25033   if (NegB)
25034     B = B.getOperand(0);
25035   if (NegC)
25036     C = C.getOperand(0);
25037
25038   unsigned Opcode;
25039   if (!NegMul)
25040     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
25041   else
25042     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
25043
25044   return DAG.getNode(Opcode, dl, VT, A, B, C);
25045 }
25046
25047 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
25048                                   TargetLowering::DAGCombinerInfo &DCI,
25049                                   const X86Subtarget *Subtarget) {
25050   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
25051   //           (and (i32 x86isd::setcc_carry), 1)
25052   // This eliminates the zext. This transformation is necessary because
25053   // ISD::SETCC is always legalized to i8.
25054   SDLoc dl(N);
25055   SDValue N0 = N->getOperand(0);
25056   EVT VT = N->getValueType(0);
25057
25058   if (N0.getOpcode() == ISD::AND &&
25059       N0.hasOneUse() &&
25060       N0.getOperand(0).hasOneUse()) {
25061     SDValue N00 = N0.getOperand(0);
25062     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
25063       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
25064       if (!C || C->getZExtValue() != 1)
25065         return SDValue();
25066       return DAG.getNode(ISD::AND, dl, VT,
25067                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
25068                                      N00.getOperand(0), N00.getOperand(1)),
25069                          DAG.getConstant(1, dl, VT));
25070     }
25071   }
25072
25073   if (N0.getOpcode() == ISD::TRUNCATE &&
25074       N0.hasOneUse() &&
25075       N0.getOperand(0).hasOneUse()) {
25076     SDValue N00 = N0.getOperand(0);
25077     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
25078       return DAG.getNode(ISD::AND, dl, VT,
25079                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
25080                                      N00.getOperand(0), N00.getOperand(1)),
25081                          DAG.getConstant(1, dl, VT));
25082     }
25083   }
25084
25085   if (VT.is256BitVector())
25086     if (SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget))
25087       return R;
25088
25089   // (i8,i32 zext (udivrem (i8 x, i8 y)) ->
25090   // (i8,i32 (udivrem_zext_hreg (i8 x, i8 y)
25091   // This exposes the zext to the udivrem lowering, so that it directly extends
25092   // from AH (which we otherwise need to do contortions to access).
25093   if (N0.getOpcode() == ISD::UDIVREM &&
25094       N0.getResNo() == 1 && N0.getValueType() == MVT::i8 &&
25095       (VT == MVT::i32 || VT == MVT::i64)) {
25096     SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
25097     SDValue R = DAG.getNode(X86ISD::UDIVREM8_ZEXT_HREG, dl, NodeTys,
25098                             N0.getOperand(0), N0.getOperand(1));
25099     DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
25100     return R.getValue(1);
25101   }
25102
25103   return SDValue();
25104 }
25105
25106 // Optimize x == -y --> x+y == 0
25107 //          x != -y --> x+y != 0
25108 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
25109                                       const X86Subtarget* Subtarget) {
25110   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
25111   SDValue LHS = N->getOperand(0);
25112   SDValue RHS = N->getOperand(1);
25113   EVT VT = N->getValueType(0);
25114   SDLoc DL(N);
25115
25116   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
25117     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
25118       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
25119         SDValue addV = DAG.getNode(ISD::ADD, DL, LHS.getValueType(), RHS,
25120                                    LHS.getOperand(1));
25121         return DAG.getSetCC(DL, N->getValueType(0), addV,
25122                             DAG.getConstant(0, DL, addV.getValueType()), CC);
25123       }
25124   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
25125     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
25126       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
25127         SDValue addV = DAG.getNode(ISD::ADD, DL, RHS.getValueType(), LHS,
25128                                    RHS.getOperand(1));
25129         return DAG.getSetCC(DL, N->getValueType(0), addV,
25130                             DAG.getConstant(0, DL, addV.getValueType()), CC);
25131       }
25132
25133   if (VT.getScalarType() == MVT::i1 &&
25134       (CC == ISD::SETNE || CC == ISD::SETEQ || ISD::isSignedIntSetCC(CC))) {
25135     bool IsSEXT0 =
25136         (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
25137         (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
25138     bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
25139
25140     if (!IsSEXT0 || !IsVZero1) {
25141       // Swap the operands and update the condition code.
25142       std::swap(LHS, RHS);
25143       CC = ISD::getSetCCSwappedOperands(CC);
25144
25145       IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
25146                 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
25147       IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
25148     }
25149
25150     if (IsSEXT0 && IsVZero1) {
25151       assert(VT == LHS.getOperand(0).getValueType() &&
25152              "Uexpected operand type");
25153       if (CC == ISD::SETGT)
25154         return DAG.getConstant(0, DL, VT);
25155       if (CC == ISD::SETLE)
25156         return DAG.getConstant(1, DL, VT);
25157       if (CC == ISD::SETEQ || CC == ISD::SETGE)
25158         return DAG.getNOT(DL, LHS.getOperand(0), VT);
25159
25160       assert((CC == ISD::SETNE || CC == ISD::SETLT) &&
25161              "Unexpected condition code!");
25162       return LHS.getOperand(0);
25163     }
25164   }
25165
25166   return SDValue();
25167 }
25168
25169 static SDValue NarrowVectorLoadToElement(LoadSDNode *Load, unsigned Index,
25170                                          SelectionDAG &DAG) {
25171   SDLoc dl(Load);
25172   MVT VT = Load->getSimpleValueType(0);
25173   MVT EVT = VT.getVectorElementType();
25174   SDValue Addr = Load->getOperand(1);
25175   SDValue NewAddr = DAG.getNode(
25176       ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
25177       DAG.getConstant(Index * EVT.getStoreSize(), dl,
25178                       Addr.getSimpleValueType()));
25179
25180   SDValue NewLoad =
25181       DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
25182                   DAG.getMachineFunction().getMachineMemOperand(
25183                       Load->getMemOperand(), 0, EVT.getStoreSize()));
25184   return NewLoad;
25185 }
25186
25187 static SDValue PerformINSERTPSCombine(SDNode *N, SelectionDAG &DAG,
25188                                       const X86Subtarget *Subtarget) {
25189   SDLoc dl(N);
25190   MVT VT = N->getOperand(1)->getSimpleValueType(0);
25191   assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
25192          "X86insertps is only defined for v4x32");
25193
25194   SDValue Ld = N->getOperand(1);
25195   if (MayFoldLoad(Ld)) {
25196     // Extract the countS bits from the immediate so we can get the proper
25197     // address when narrowing the vector load to a specific element.
25198     // When the second source op is a memory address, insertps doesn't use
25199     // countS and just gets an f32 from that address.
25200     unsigned DestIndex =
25201         cast<ConstantSDNode>(N->getOperand(2))->getZExtValue() >> 6;
25202
25203     Ld = NarrowVectorLoadToElement(cast<LoadSDNode>(Ld), DestIndex, DAG);
25204
25205     // Create this as a scalar to vector to match the instruction pattern.
25206     SDValue LoadScalarToVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Ld);
25207     // countS bits are ignored when loading from memory on insertps, which
25208     // means we don't need to explicitly set them to 0.
25209     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N->getOperand(0),
25210                        LoadScalarToVector, N->getOperand(2));
25211   }
25212   return SDValue();
25213 }
25214
25215 static SDValue PerformBLENDICombine(SDNode *N, SelectionDAG &DAG) {
25216   SDValue V0 = N->getOperand(0);
25217   SDValue V1 = N->getOperand(1);
25218   SDLoc DL(N);
25219   EVT VT = N->getValueType(0);
25220
25221   // Canonicalize a v2f64 blend with a mask of 2 by swapping the vector
25222   // operands and changing the mask to 1. This saves us a bunch of
25223   // pattern-matching possibilities related to scalar math ops in SSE/AVX.
25224   // x86InstrInfo knows how to commute this back after instruction selection
25225   // if it would help register allocation.
25226
25227   // TODO: If optimizing for size or a processor that doesn't suffer from
25228   // partial register update stalls, this should be transformed into a MOVSD
25229   // instruction because a MOVSD is 1-2 bytes smaller than a BLENDPD.
25230
25231   if (VT == MVT::v2f64)
25232     if (auto *Mask = dyn_cast<ConstantSDNode>(N->getOperand(2)))
25233       if (Mask->getZExtValue() == 2 && !isShuffleFoldableLoad(V0)) {
25234         SDValue NewMask = DAG.getConstant(1, DL, MVT::i8);
25235         return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V0, NewMask);
25236       }
25237
25238   return SDValue();
25239 }
25240
25241 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
25242 // as "sbb reg,reg", since it can be extended without zext and produces
25243 // an all-ones bit which is more useful than 0/1 in some cases.
25244 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
25245                                MVT VT) {
25246   if (VT == MVT::i8)
25247     return DAG.getNode(ISD::AND, DL, VT,
25248                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
25249                                    DAG.getConstant(X86::COND_B, DL, MVT::i8),
25250                                    EFLAGS),
25251                        DAG.getConstant(1, DL, VT));
25252   assert (VT == MVT::i1 && "Unexpected type for SECCC node");
25253   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
25254                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
25255                                  DAG.getConstant(X86::COND_B, DL, MVT::i8),
25256                                  EFLAGS));
25257 }
25258
25259 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
25260 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
25261                                    TargetLowering::DAGCombinerInfo &DCI,
25262                                    const X86Subtarget *Subtarget) {
25263   SDLoc DL(N);
25264   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
25265   SDValue EFLAGS = N->getOperand(1);
25266
25267   if (CC == X86::COND_A) {
25268     // Try to convert COND_A into COND_B in an attempt to facilitate
25269     // materializing "setb reg".
25270     //
25271     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
25272     // cannot take an immediate as its first operand.
25273     //
25274     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
25275         EFLAGS.getValueType().isInteger() &&
25276         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
25277       SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
25278                                    EFLAGS.getNode()->getVTList(),
25279                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
25280       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
25281       return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
25282     }
25283   }
25284
25285   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
25286   // a zext and produces an all-ones bit which is more useful than 0/1 in some
25287   // cases.
25288   if (CC == X86::COND_B)
25289     return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
25290
25291   if (SDValue Flags = checkBoolTestSetCCCombine(EFLAGS, CC)) {
25292     SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
25293     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
25294   }
25295
25296   return SDValue();
25297 }
25298
25299 // Optimize branch condition evaluation.
25300 //
25301 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
25302                                     TargetLowering::DAGCombinerInfo &DCI,
25303                                     const X86Subtarget *Subtarget) {
25304   SDLoc DL(N);
25305   SDValue Chain = N->getOperand(0);
25306   SDValue Dest = N->getOperand(1);
25307   SDValue EFLAGS = N->getOperand(3);
25308   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
25309
25310   if (SDValue Flags = checkBoolTestSetCCCombine(EFLAGS, CC)) {
25311     SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
25312     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
25313                        Flags);
25314   }
25315
25316   return SDValue();
25317 }
25318
25319 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
25320                                                          SelectionDAG &DAG) {
25321   // Take advantage of vector comparisons producing 0 or -1 in each lane to
25322   // optimize away operation when it's from a constant.
25323   //
25324   // The general transformation is:
25325   //    UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
25326   //       AND(VECTOR_CMP(x,y), constant2)
25327   //    constant2 = UNARYOP(constant)
25328
25329   // Early exit if this isn't a vector operation, the operand of the
25330   // unary operation isn't a bitwise AND, or if the sizes of the operations
25331   // aren't the same.
25332   EVT VT = N->getValueType(0);
25333   if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
25334       N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
25335       VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
25336     return SDValue();
25337
25338   // Now check that the other operand of the AND is a constant. We could
25339   // make the transformation for non-constant splats as well, but it's unclear
25340   // that would be a benefit as it would not eliminate any operations, just
25341   // perform one more step in scalar code before moving to the vector unit.
25342   if (BuildVectorSDNode *BV =
25343           dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
25344     // Bail out if the vector isn't a constant.
25345     if (!BV->isConstant())
25346       return SDValue();
25347
25348     // Everything checks out. Build up the new and improved node.
25349     SDLoc DL(N);
25350     EVT IntVT = BV->getValueType(0);
25351     // Create a new constant of the appropriate type for the transformed
25352     // DAG.
25353     SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
25354     // The AND node needs bitcasts to/from an integer vector type around it.
25355     SDValue MaskConst = DAG.getBitcast(IntVT, SourceConst);
25356     SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
25357                                  N->getOperand(0)->getOperand(0), MaskConst);
25358     SDValue Res = DAG.getBitcast(VT, NewAnd);
25359     return Res;
25360   }
25361
25362   return SDValue();
25363 }
25364
25365 static SDValue PerformUINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
25366                                         const X86Subtarget *Subtarget) {
25367   SDValue Op0 = N->getOperand(0);
25368   EVT VT = N->getValueType(0);
25369   EVT InVT = Op0.getValueType();
25370   EVT InSVT = InVT.getScalarType();
25371   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
25372
25373   // UINT_TO_FP(vXi8) -> SINT_TO_FP(ZEXT(vXi8 to vXi32))
25374   // UINT_TO_FP(vXi16) -> SINT_TO_FP(ZEXT(vXi16 to vXi32))
25375   if (InVT.isVector() && (InSVT == MVT::i8 || InSVT == MVT::i16)) {
25376     SDLoc dl(N);
25377     EVT DstVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
25378                                  InVT.getVectorNumElements());
25379     SDValue P = DAG.getNode(ISD::ZERO_EXTEND, dl, DstVT, Op0);
25380
25381     if (TLI.isOperationLegal(ISD::UINT_TO_FP, DstVT))
25382       return DAG.getNode(ISD::UINT_TO_FP, dl, VT, P);
25383
25384     return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
25385   }
25386
25387   return SDValue();
25388 }
25389
25390 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
25391                                         const X86Subtarget *Subtarget) {
25392   // First try to optimize away the conversion entirely when it's
25393   // conditionally from a constant. Vectors only.
25394   if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG))
25395     return Res;
25396
25397   // Now move on to more general possibilities.
25398   SDValue Op0 = N->getOperand(0);
25399   EVT VT = N->getValueType(0);
25400   EVT InVT = Op0.getValueType();
25401   EVT InSVT = InVT.getScalarType();
25402
25403   // SINT_TO_FP(vXi8) -> SINT_TO_FP(SEXT(vXi8 to vXi32))
25404   // SINT_TO_FP(vXi16) -> SINT_TO_FP(SEXT(vXi16 to vXi32))
25405   if (InVT.isVector() && (InSVT == MVT::i8 || InSVT == MVT::i16)) {
25406     SDLoc dl(N);
25407     EVT DstVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
25408                                  InVT.getVectorNumElements());
25409     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
25410     return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
25411   }
25412
25413   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
25414   // a 32-bit target where SSE doesn't support i64->FP operations.
25415   if (Op0.getOpcode() == ISD::LOAD) {
25416     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
25417     EVT LdVT = Ld->getValueType(0);
25418
25419     // This transformation is not supported if the result type is f16
25420     if (VT == MVT::f16)
25421       return SDValue();
25422
25423     if (!Ld->isVolatile() && !VT.isVector() &&
25424         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
25425         !Subtarget->is64Bit() && LdVT == MVT::i64) {
25426       SDValue FILDChain = Subtarget->getTargetLowering()->BuildFILD(
25427           SDValue(N, 0), LdVT, Ld->getChain(), Op0, DAG);
25428       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
25429       return FILDChain;
25430     }
25431   }
25432   return SDValue();
25433 }
25434
25435 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
25436 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
25437                                  X86TargetLowering::DAGCombinerInfo &DCI) {
25438   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
25439   // the result is either zero or one (depending on the input carry bit).
25440   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
25441   if (X86::isZeroNode(N->getOperand(0)) &&
25442       X86::isZeroNode(N->getOperand(1)) &&
25443       // We don't have a good way to replace an EFLAGS use, so only do this when
25444       // dead right now.
25445       SDValue(N, 1).use_empty()) {
25446     SDLoc DL(N);
25447     EVT VT = N->getValueType(0);
25448     SDValue CarryOut = DAG.getConstant(0, DL, N->getValueType(1));
25449     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
25450                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
25451                                            DAG.getConstant(X86::COND_B, DL,
25452                                                            MVT::i8),
25453                                            N->getOperand(2)),
25454                                DAG.getConstant(1, DL, VT));
25455     return DCI.CombineTo(N, Res1, CarryOut);
25456   }
25457
25458   return SDValue();
25459 }
25460
25461 // fold (add Y, (sete  X, 0)) -> adc  0, Y
25462 //      (add Y, (setne X, 0)) -> sbb -1, Y
25463 //      (sub (sete  X, 0), Y) -> sbb  0, Y
25464 //      (sub (setne X, 0), Y) -> adc -1, Y
25465 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
25466   SDLoc DL(N);
25467
25468   // Look through ZExts.
25469   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
25470   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
25471     return SDValue();
25472
25473   SDValue SetCC = Ext.getOperand(0);
25474   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
25475     return SDValue();
25476
25477   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
25478   if (CC != X86::COND_E && CC != X86::COND_NE)
25479     return SDValue();
25480
25481   SDValue Cmp = SetCC.getOperand(1);
25482   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
25483       !X86::isZeroNode(Cmp.getOperand(1)) ||
25484       !Cmp.getOperand(0).getValueType().isInteger())
25485     return SDValue();
25486
25487   SDValue CmpOp0 = Cmp.getOperand(0);
25488   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
25489                                DAG.getConstant(1, DL, CmpOp0.getValueType()));
25490
25491   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
25492   if (CC == X86::COND_NE)
25493     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
25494                        DL, OtherVal.getValueType(), OtherVal,
25495                        DAG.getConstant(-1ULL, DL, OtherVal.getValueType()),
25496                        NewCmp);
25497   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
25498                      DL, OtherVal.getValueType(), OtherVal,
25499                      DAG.getConstant(0, DL, OtherVal.getValueType()), NewCmp);
25500 }
25501
25502 /// PerformADDCombine - Do target-specific dag combines on integer adds.
25503 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
25504                                  const X86Subtarget *Subtarget) {
25505   EVT VT = N->getValueType(0);
25506   SDValue Op0 = N->getOperand(0);
25507   SDValue Op1 = N->getOperand(1);
25508
25509   // Try to synthesize horizontal adds from adds of shuffles.
25510   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
25511        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
25512       isHorizontalBinOp(Op0, Op1, true))
25513     return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
25514
25515   return OptimizeConditionalInDecrement(N, DAG);
25516 }
25517
25518 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
25519                                  const X86Subtarget *Subtarget) {
25520   SDValue Op0 = N->getOperand(0);
25521   SDValue Op1 = N->getOperand(1);
25522
25523   // X86 can't encode an immediate LHS of a sub. See if we can push the
25524   // negation into a preceding instruction.
25525   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
25526     // If the RHS of the sub is a XOR with one use and a constant, invert the
25527     // immediate. Then add one to the LHS of the sub so we can turn
25528     // X-Y -> X+~Y+1, saving one register.
25529     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
25530         isa<ConstantSDNode>(Op1.getOperand(1))) {
25531       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
25532       EVT VT = Op0.getValueType();
25533       SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
25534                                    Op1.getOperand(0),
25535                                    DAG.getConstant(~XorC, SDLoc(Op1), VT));
25536       return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
25537                          DAG.getConstant(C->getAPIntValue() + 1, SDLoc(N), VT));
25538     }
25539   }
25540
25541   // Try to synthesize horizontal adds from adds of shuffles.
25542   EVT VT = N->getValueType(0);
25543   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
25544        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
25545       isHorizontalBinOp(Op0, Op1, true))
25546     return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
25547
25548   return OptimizeConditionalInDecrement(N, DAG);
25549 }
25550
25551 /// performVZEXTCombine - Performs build vector combines
25552 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
25553                                    TargetLowering::DAGCombinerInfo &DCI,
25554                                    const X86Subtarget *Subtarget) {
25555   SDLoc DL(N);
25556   MVT VT = N->getSimpleValueType(0);
25557   SDValue Op = N->getOperand(0);
25558   MVT OpVT = Op.getSimpleValueType();
25559   MVT OpEltVT = OpVT.getVectorElementType();
25560   unsigned InputBits = OpEltVT.getSizeInBits() * VT.getVectorNumElements();
25561
25562   // (vzext (bitcast (vzext (x)) -> (vzext x)
25563   SDValue V = Op;
25564   while (V.getOpcode() == ISD::BITCAST)
25565     V = V.getOperand(0);
25566
25567   if (V != Op && V.getOpcode() == X86ISD::VZEXT) {
25568     MVT InnerVT = V.getSimpleValueType();
25569     MVT InnerEltVT = InnerVT.getVectorElementType();
25570
25571     // If the element sizes match exactly, we can just do one larger vzext. This
25572     // is always an exact type match as vzext operates on integer types.
25573     if (OpEltVT == InnerEltVT) {
25574       assert(OpVT == InnerVT && "Types must match for vzext!");
25575       return DAG.getNode(X86ISD::VZEXT, DL, VT, V.getOperand(0));
25576     }
25577
25578     // The only other way we can combine them is if only a single element of the
25579     // inner vzext is used in the input to the outer vzext.
25580     if (InnerEltVT.getSizeInBits() < InputBits)
25581       return SDValue();
25582
25583     // In this case, the inner vzext is completely dead because we're going to
25584     // only look at bits inside of the low element. Just do the outer vzext on
25585     // a bitcast of the input to the inner.
25586     return DAG.getNode(X86ISD::VZEXT, DL, VT, DAG.getBitcast(OpVT, V));
25587   }
25588
25589   // Check if we can bypass extracting and re-inserting an element of an input
25590   // vector. Essentially:
25591   // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
25592   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR &&
25593       V.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
25594       V.getOperand(0).getSimpleValueType().getSizeInBits() == InputBits) {
25595     SDValue ExtractedV = V.getOperand(0);
25596     SDValue OrigV = ExtractedV.getOperand(0);
25597     if (auto *ExtractIdx = dyn_cast<ConstantSDNode>(ExtractedV.getOperand(1)))
25598       if (ExtractIdx->getZExtValue() == 0) {
25599         MVT OrigVT = OrigV.getSimpleValueType();
25600         // Extract a subvector if necessary...
25601         if (OrigVT.getSizeInBits() > OpVT.getSizeInBits()) {
25602           int Ratio = OrigVT.getSizeInBits() / OpVT.getSizeInBits();
25603           OrigVT = MVT::getVectorVT(OrigVT.getVectorElementType(),
25604                                     OrigVT.getVectorNumElements() / Ratio);
25605           OrigV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigVT, OrigV,
25606                               DAG.getIntPtrConstant(0, DL));
25607         }
25608         Op = DAG.getBitcast(OpVT, OrigV);
25609         return DAG.getNode(X86ISD::VZEXT, DL, VT, Op);
25610       }
25611   }
25612
25613   return SDValue();
25614 }
25615
25616 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
25617                                              DAGCombinerInfo &DCI) const {
25618   SelectionDAG &DAG = DCI.DAG;
25619   switch (N->getOpcode()) {
25620   default: break;
25621   case ISD::EXTRACT_VECTOR_ELT:
25622     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
25623   case ISD::VSELECT:
25624   case ISD::SELECT:
25625   case X86ISD::SHRUNKBLEND:
25626     return PerformSELECTCombine(N, DAG, DCI, Subtarget);
25627   case ISD::BITCAST:        return PerformBITCASTCombine(N, DAG);
25628   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
25629   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
25630   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
25631   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
25632   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
25633   case ISD::SHL:
25634   case ISD::SRA:
25635   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
25636   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
25637   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
25638   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
25639   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
25640   case ISD::MLOAD:          return PerformMLOADCombine(N, DAG, DCI, Subtarget);
25641   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
25642   case ISD::MSTORE:         return PerformMSTORECombine(N, DAG, Subtarget);
25643   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, Subtarget);
25644   case ISD::UINT_TO_FP:     return PerformUINT_TO_FPCombine(N, DAG, Subtarget);
25645   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
25646   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
25647   case X86ISD::FXOR:
25648   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
25649   case X86ISD::FMIN:
25650   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
25651   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
25652   case X86ISD::FANDN:       return PerformFANDNCombine(N, DAG);
25653   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
25654   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
25655   case ISD::ANY_EXTEND:
25656   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
25657   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
25658   case ISD::SIGN_EXTEND_INREG:
25659     return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
25660   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG, Subtarget);
25661   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
25662   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
25663   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
25664   case X86ISD::SHUFP:       // Handle all target specific shuffles
25665   case X86ISD::PALIGNR:
25666   case X86ISD::UNPCKH:
25667   case X86ISD::UNPCKL:
25668   case X86ISD::MOVHLPS:
25669   case X86ISD::MOVLHPS:
25670   case X86ISD::PSHUFB:
25671   case X86ISD::PSHUFD:
25672   case X86ISD::PSHUFHW:
25673   case X86ISD::PSHUFLW:
25674   case X86ISD::MOVSS:
25675   case X86ISD::MOVSD:
25676   case X86ISD::VPERMILPI:
25677   case X86ISD::VPERM2X128:
25678   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
25679   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
25680   case X86ISD::INSERTPS: {
25681     if (getTargetMachine().getOptLevel() > CodeGenOpt::None)
25682       return PerformINSERTPSCombine(N, DAG, Subtarget);
25683     break;
25684   }
25685   case X86ISD::BLENDI:    return PerformBLENDICombine(N, DAG);
25686   }
25687
25688   return SDValue();
25689 }
25690
25691 /// isTypeDesirableForOp - Return true if the target has native support for
25692 /// the specified value type and it is 'desirable' to use the type for the
25693 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
25694 /// instruction encodings are longer and some i16 instructions are slow.
25695 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
25696   if (!isTypeLegal(VT))
25697     return false;
25698   if (VT != MVT::i16)
25699     return true;
25700
25701   switch (Opc) {
25702   default:
25703     return true;
25704   case ISD::LOAD:
25705   case ISD::SIGN_EXTEND:
25706   case ISD::ZERO_EXTEND:
25707   case ISD::ANY_EXTEND:
25708   case ISD::SHL:
25709   case ISD::SRL:
25710   case ISD::SUB:
25711   case ISD::ADD:
25712   case ISD::MUL:
25713   case ISD::AND:
25714   case ISD::OR:
25715   case ISD::XOR:
25716     return false;
25717   }
25718 }
25719
25720 /// IsDesirableToPromoteOp - This method query the target whether it is
25721 /// beneficial for dag combiner to promote the specified node. If true, it
25722 /// should return the desired promotion type by reference.
25723 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
25724   EVT VT = Op.getValueType();
25725   if (VT != MVT::i16)
25726     return false;
25727
25728   bool Promote = false;
25729   bool Commute = false;
25730   switch (Op.getOpcode()) {
25731   default: break;
25732   case ISD::LOAD: {
25733     LoadSDNode *LD = cast<LoadSDNode>(Op);
25734     // If the non-extending load has a single use and it's not live out, then it
25735     // might be folded.
25736     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
25737                                                      Op.hasOneUse()*/) {
25738       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
25739              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
25740         // The only case where we'd want to promote LOAD (rather then it being
25741         // promoted as an operand is when it's only use is liveout.
25742         if (UI->getOpcode() != ISD::CopyToReg)
25743           return false;
25744       }
25745     }
25746     Promote = true;
25747     break;
25748   }
25749   case ISD::SIGN_EXTEND:
25750   case ISD::ZERO_EXTEND:
25751   case ISD::ANY_EXTEND:
25752     Promote = true;
25753     break;
25754   case ISD::SHL:
25755   case ISD::SRL: {
25756     SDValue N0 = Op.getOperand(0);
25757     // Look out for (store (shl (load), x)).
25758     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
25759       return false;
25760     Promote = true;
25761     break;
25762   }
25763   case ISD::ADD:
25764   case ISD::MUL:
25765   case ISD::AND:
25766   case ISD::OR:
25767   case ISD::XOR:
25768     Commute = true;
25769     // fallthrough
25770   case ISD::SUB: {
25771     SDValue N0 = Op.getOperand(0);
25772     SDValue N1 = Op.getOperand(1);
25773     if (!Commute && MayFoldLoad(N1))
25774       return false;
25775     // Avoid disabling potential load folding opportunities.
25776     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
25777       return false;
25778     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
25779       return false;
25780     Promote = true;
25781   }
25782   }
25783
25784   PVT = MVT::i32;
25785   return Promote;
25786 }
25787
25788 //===----------------------------------------------------------------------===//
25789 //                           X86 Inline Assembly Support
25790 //===----------------------------------------------------------------------===//
25791
25792 // Helper to match a string separated by whitespace.
25793 static bool matchAsm(StringRef S, ArrayRef<const char *> Pieces) {
25794   S = S.substr(S.find_first_not_of(" \t")); // Skip leading whitespace.
25795
25796   for (StringRef Piece : Pieces) {
25797     if (!S.startswith(Piece)) // Check if the piece matches.
25798       return false;
25799
25800     S = S.substr(Piece.size());
25801     StringRef::size_type Pos = S.find_first_not_of(" \t");
25802     if (Pos == 0) // We matched a prefix.
25803       return false;
25804
25805     S = S.substr(Pos);
25806   }
25807
25808   return S.empty();
25809 }
25810
25811 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
25812
25813   if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
25814     if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
25815         std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
25816         std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
25817
25818       if (AsmPieces.size() == 3)
25819         return true;
25820       else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
25821         return true;
25822     }
25823   }
25824   return false;
25825 }
25826
25827 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
25828   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
25829
25830   std::string AsmStr = IA->getAsmString();
25831
25832   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
25833   if (!Ty || Ty->getBitWidth() % 16 != 0)
25834     return false;
25835
25836   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
25837   SmallVector<StringRef, 4> AsmPieces;
25838   SplitString(AsmStr, AsmPieces, ";\n");
25839
25840   switch (AsmPieces.size()) {
25841   default: return false;
25842   case 1:
25843     // FIXME: this should verify that we are targeting a 486 or better.  If not,
25844     // we will turn this bswap into something that will be lowered to logical
25845     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
25846     // lower so don't worry about this.
25847     // bswap $0
25848     if (matchAsm(AsmPieces[0], {"bswap", "$0"}) ||
25849         matchAsm(AsmPieces[0], {"bswapl", "$0"}) ||
25850         matchAsm(AsmPieces[0], {"bswapq", "$0"}) ||
25851         matchAsm(AsmPieces[0], {"bswap", "${0:q}"}) ||
25852         matchAsm(AsmPieces[0], {"bswapl", "${0:q}"}) ||
25853         matchAsm(AsmPieces[0], {"bswapq", "${0:q}"})) {
25854       // No need to check constraints, nothing other than the equivalent of
25855       // "=r,0" would be valid here.
25856       return IntrinsicLowering::LowerToByteSwap(CI);
25857     }
25858
25859     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
25860     if (CI->getType()->isIntegerTy(16) &&
25861         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
25862         (matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) ||
25863          matchAsm(AsmPieces[0], {"rolw", "$$8,", "${0:w}"}))) {
25864       AsmPieces.clear();
25865       StringRef ConstraintsStr = IA->getConstraintString();
25866       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
25867       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
25868       if (clobbersFlagRegisters(AsmPieces))
25869         return IntrinsicLowering::LowerToByteSwap(CI);
25870     }
25871     break;
25872   case 3:
25873     if (CI->getType()->isIntegerTy(32) &&
25874         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
25875         matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) &&
25876         matchAsm(AsmPieces[1], {"rorl", "$$16,", "$0"}) &&
25877         matchAsm(AsmPieces[2], {"rorw", "$$8,", "${0:w}"})) {
25878       AsmPieces.clear();
25879       StringRef ConstraintsStr = IA->getConstraintString();
25880       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
25881       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
25882       if (clobbersFlagRegisters(AsmPieces))
25883         return IntrinsicLowering::LowerToByteSwap(CI);
25884     }
25885
25886     if (CI->getType()->isIntegerTy(64)) {
25887       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
25888       if (Constraints.size() >= 2 &&
25889           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
25890           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
25891         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
25892         if (matchAsm(AsmPieces[0], {"bswap", "%eax"}) &&
25893             matchAsm(AsmPieces[1], {"bswap", "%edx"}) &&
25894             matchAsm(AsmPieces[2], {"xchgl", "%eax,", "%edx"}))
25895           return IntrinsicLowering::LowerToByteSwap(CI);
25896       }
25897     }
25898     break;
25899   }
25900   return false;
25901 }
25902
25903 /// getConstraintType - Given a constraint letter, return the type of
25904 /// constraint it is for this target.
25905 X86TargetLowering::ConstraintType
25906 X86TargetLowering::getConstraintType(StringRef Constraint) const {
25907   if (Constraint.size() == 1) {
25908     switch (Constraint[0]) {
25909     case 'R':
25910     case 'q':
25911     case 'Q':
25912     case 'f':
25913     case 't':
25914     case 'u':
25915     case 'y':
25916     case 'x':
25917     case 'Y':
25918     case 'l':
25919       return C_RegisterClass;
25920     case 'a':
25921     case 'b':
25922     case 'c':
25923     case 'd':
25924     case 'S':
25925     case 'D':
25926     case 'A':
25927       return C_Register;
25928     case 'I':
25929     case 'J':
25930     case 'K':
25931     case 'L':
25932     case 'M':
25933     case 'N':
25934     case 'G':
25935     case 'C':
25936     case 'e':
25937     case 'Z':
25938       return C_Other;
25939     default:
25940       break;
25941     }
25942   }
25943   return TargetLowering::getConstraintType(Constraint);
25944 }
25945
25946 /// Examine constraint type and operand type and determine a weight value.
25947 /// This object must already have been set up with the operand type
25948 /// and the current alternative constraint selected.
25949 TargetLowering::ConstraintWeight
25950   X86TargetLowering::getSingleConstraintMatchWeight(
25951     AsmOperandInfo &info, const char *constraint) const {
25952   ConstraintWeight weight = CW_Invalid;
25953   Value *CallOperandVal = info.CallOperandVal;
25954     // If we don't have a value, we can't do a match,
25955     // but allow it at the lowest weight.
25956   if (!CallOperandVal)
25957     return CW_Default;
25958   Type *type = CallOperandVal->getType();
25959   // Look at the constraint type.
25960   switch (*constraint) {
25961   default:
25962     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
25963   case 'R':
25964   case 'q':
25965   case 'Q':
25966   case 'a':
25967   case 'b':
25968   case 'c':
25969   case 'd':
25970   case 'S':
25971   case 'D':
25972   case 'A':
25973     if (CallOperandVal->getType()->isIntegerTy())
25974       weight = CW_SpecificReg;
25975     break;
25976   case 'f':
25977   case 't':
25978   case 'u':
25979     if (type->isFloatingPointTy())
25980       weight = CW_SpecificReg;
25981     break;
25982   case 'y':
25983     if (type->isX86_MMXTy() && Subtarget->hasMMX())
25984       weight = CW_SpecificReg;
25985     break;
25986   case 'x':
25987   case 'Y':
25988     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
25989         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
25990       weight = CW_Register;
25991     break;
25992   case 'I':
25993     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
25994       if (C->getZExtValue() <= 31)
25995         weight = CW_Constant;
25996     }
25997     break;
25998   case 'J':
25999     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26000       if (C->getZExtValue() <= 63)
26001         weight = CW_Constant;
26002     }
26003     break;
26004   case 'K':
26005     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26006       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
26007         weight = CW_Constant;
26008     }
26009     break;
26010   case 'L':
26011     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26012       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
26013         weight = CW_Constant;
26014     }
26015     break;
26016   case 'M':
26017     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26018       if (C->getZExtValue() <= 3)
26019         weight = CW_Constant;
26020     }
26021     break;
26022   case 'N':
26023     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26024       if (C->getZExtValue() <= 0xff)
26025         weight = CW_Constant;
26026     }
26027     break;
26028   case 'G':
26029   case 'C':
26030     if (isa<ConstantFP>(CallOperandVal)) {
26031       weight = CW_Constant;
26032     }
26033     break;
26034   case 'e':
26035     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26036       if ((C->getSExtValue() >= -0x80000000LL) &&
26037           (C->getSExtValue() <= 0x7fffffffLL))
26038         weight = CW_Constant;
26039     }
26040     break;
26041   case 'Z':
26042     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26043       if (C->getZExtValue() <= 0xffffffff)
26044         weight = CW_Constant;
26045     }
26046     break;
26047   }
26048   return weight;
26049 }
26050
26051 /// LowerXConstraint - try to replace an X constraint, which matches anything,
26052 /// with another that has more specific requirements based on the type of the
26053 /// corresponding operand.
26054 const char *X86TargetLowering::
26055 LowerXConstraint(EVT ConstraintVT) const {
26056   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
26057   // 'f' like normal targets.
26058   if (ConstraintVT.isFloatingPoint()) {
26059     if (Subtarget->hasSSE2())
26060       return "Y";
26061     if (Subtarget->hasSSE1())
26062       return "x";
26063   }
26064
26065   return TargetLowering::LowerXConstraint(ConstraintVT);
26066 }
26067
26068 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
26069 /// vector.  If it is invalid, don't add anything to Ops.
26070 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
26071                                                      std::string &Constraint,
26072                                                      std::vector<SDValue>&Ops,
26073                                                      SelectionDAG &DAG) const {
26074   SDValue Result;
26075
26076   // Only support length 1 constraints for now.
26077   if (Constraint.length() > 1) return;
26078
26079   char ConstraintLetter = Constraint[0];
26080   switch (ConstraintLetter) {
26081   default: break;
26082   case 'I':
26083     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26084       if (C->getZExtValue() <= 31) {
26085         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26086                                        Op.getValueType());
26087         break;
26088       }
26089     }
26090     return;
26091   case 'J':
26092     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26093       if (C->getZExtValue() <= 63) {
26094         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26095                                        Op.getValueType());
26096         break;
26097       }
26098     }
26099     return;
26100   case 'K':
26101     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26102       if (isInt<8>(C->getSExtValue())) {
26103         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26104                                        Op.getValueType());
26105         break;
26106       }
26107     }
26108     return;
26109   case 'L':
26110     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26111       if (C->getZExtValue() == 0xff || C->getZExtValue() == 0xffff ||
26112           (Subtarget->is64Bit() && C->getZExtValue() == 0xffffffff)) {
26113         Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op),
26114                                        Op.getValueType());
26115         break;
26116       }
26117     }
26118     return;
26119   case 'M':
26120     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26121       if (C->getZExtValue() <= 3) {
26122         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26123                                        Op.getValueType());
26124         break;
26125       }
26126     }
26127     return;
26128   case 'N':
26129     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26130       if (C->getZExtValue() <= 255) {
26131         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26132                                        Op.getValueType());
26133         break;
26134       }
26135     }
26136     return;
26137   case 'O':
26138     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26139       if (C->getZExtValue() <= 127) {
26140         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26141                                        Op.getValueType());
26142         break;
26143       }
26144     }
26145     return;
26146   case 'e': {
26147     // 32-bit signed value
26148     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26149       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
26150                                            C->getSExtValue())) {
26151         // Widen to 64 bits here to get it sign extended.
26152         Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op), MVT::i64);
26153         break;
26154       }
26155     // FIXME gcc accepts some relocatable values here too, but only in certain
26156     // memory models; it's complicated.
26157     }
26158     return;
26159   }
26160   case 'Z': {
26161     // 32-bit unsigned value
26162     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26163       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
26164                                            C->getZExtValue())) {
26165         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26166                                        Op.getValueType());
26167         break;
26168       }
26169     }
26170     // FIXME gcc accepts some relocatable values here too, but only in certain
26171     // memory models; it's complicated.
26172     return;
26173   }
26174   case 'i': {
26175     // Literal immediates are always ok.
26176     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
26177       // Widen to 64 bits here to get it sign extended.
26178       Result = DAG.getTargetConstant(CST->getSExtValue(), SDLoc(Op), MVT::i64);
26179       break;
26180     }
26181
26182     // In any sort of PIC mode addresses need to be computed at runtime by
26183     // adding in a register or some sort of table lookup.  These can't
26184     // be used as immediates.
26185     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
26186       return;
26187
26188     // If we are in non-pic codegen mode, we allow the address of a global (with
26189     // an optional displacement) to be used with 'i'.
26190     GlobalAddressSDNode *GA = nullptr;
26191     int64_t Offset = 0;
26192
26193     // Match either (GA), (GA+C), (GA+C1+C2), etc.
26194     while (1) {
26195       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
26196         Offset += GA->getOffset();
26197         break;
26198       } else if (Op.getOpcode() == ISD::ADD) {
26199         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
26200           Offset += C->getZExtValue();
26201           Op = Op.getOperand(0);
26202           continue;
26203         }
26204       } else if (Op.getOpcode() == ISD::SUB) {
26205         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
26206           Offset += -C->getZExtValue();
26207           Op = Op.getOperand(0);
26208           continue;
26209         }
26210       }
26211
26212       // Otherwise, this isn't something we can handle, reject it.
26213       return;
26214     }
26215
26216     const GlobalValue *GV = GA->getGlobal();
26217     // If we require an extra load to get this address, as in PIC mode, we
26218     // can't accept it.
26219     if (isGlobalStubReference(
26220             Subtarget->ClassifyGlobalReference(GV, DAG.getTarget())))
26221       return;
26222
26223     Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
26224                                         GA->getValueType(0), Offset);
26225     break;
26226   }
26227   }
26228
26229   if (Result.getNode()) {
26230     Ops.push_back(Result);
26231     return;
26232   }
26233   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
26234 }
26235
26236 std::pair<unsigned, const TargetRegisterClass *>
26237 X86TargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
26238                                                 StringRef Constraint,
26239                                                 MVT VT) const {
26240   // First, see if this is a constraint that directly corresponds to an LLVM
26241   // register class.
26242   if (Constraint.size() == 1) {
26243     // GCC Constraint Letters
26244     switch (Constraint[0]) {
26245     default: break;
26246       // TODO: Slight differences here in allocation order and leaving
26247       // RIP in the class. Do they matter any more here than they do
26248       // in the normal allocation?
26249     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
26250       if (Subtarget->is64Bit()) {
26251         if (VT == MVT::i32 || VT == MVT::f32)
26252           return std::make_pair(0U, &X86::GR32RegClass);
26253         if (VT == MVT::i16)
26254           return std::make_pair(0U, &X86::GR16RegClass);
26255         if (VT == MVT::i8 || VT == MVT::i1)
26256           return std::make_pair(0U, &X86::GR8RegClass);
26257         if (VT == MVT::i64 || VT == MVT::f64)
26258           return std::make_pair(0U, &X86::GR64RegClass);
26259         break;
26260       }
26261       // 32-bit fallthrough
26262     case 'Q':   // Q_REGS
26263       if (VT == MVT::i32 || VT == MVT::f32)
26264         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
26265       if (VT == MVT::i16)
26266         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
26267       if (VT == MVT::i8 || VT == MVT::i1)
26268         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
26269       if (VT == MVT::i64)
26270         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
26271       break;
26272     case 'r':   // GENERAL_REGS
26273     case 'l':   // INDEX_REGS
26274       if (VT == MVT::i8 || VT == MVT::i1)
26275         return std::make_pair(0U, &X86::GR8RegClass);
26276       if (VT == MVT::i16)
26277         return std::make_pair(0U, &X86::GR16RegClass);
26278       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
26279         return std::make_pair(0U, &X86::GR32RegClass);
26280       return std::make_pair(0U, &X86::GR64RegClass);
26281     case 'R':   // LEGACY_REGS
26282       if (VT == MVT::i8 || VT == MVT::i1)
26283         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
26284       if (VT == MVT::i16)
26285         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
26286       if (VT == MVT::i32 || !Subtarget->is64Bit())
26287         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
26288       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
26289     case 'f':  // FP Stack registers.
26290       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
26291       // value to the correct fpstack register class.
26292       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
26293         return std::make_pair(0U, &X86::RFP32RegClass);
26294       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
26295         return std::make_pair(0U, &X86::RFP64RegClass);
26296       return std::make_pair(0U, &X86::RFP80RegClass);
26297     case 'y':   // MMX_REGS if MMX allowed.
26298       if (!Subtarget->hasMMX()) break;
26299       return std::make_pair(0U, &X86::VR64RegClass);
26300     case 'Y':   // SSE_REGS if SSE2 allowed
26301       if (!Subtarget->hasSSE2()) break;
26302       // FALL THROUGH.
26303     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
26304       if (!Subtarget->hasSSE1()) break;
26305
26306       switch (VT.SimpleTy) {
26307       default: break;
26308       // Scalar SSE types.
26309       case MVT::f32:
26310       case MVT::i32:
26311         return std::make_pair(0U, &X86::FR32RegClass);
26312       case MVT::f64:
26313       case MVT::i64:
26314         return std::make_pair(0U, &X86::FR64RegClass);
26315       // Vector types.
26316       case MVT::v16i8:
26317       case MVT::v8i16:
26318       case MVT::v4i32:
26319       case MVT::v2i64:
26320       case MVT::v4f32:
26321       case MVT::v2f64:
26322         return std::make_pair(0U, &X86::VR128RegClass);
26323       // AVX types.
26324       case MVT::v32i8:
26325       case MVT::v16i16:
26326       case MVT::v8i32:
26327       case MVT::v4i64:
26328       case MVT::v8f32:
26329       case MVT::v4f64:
26330         return std::make_pair(0U, &X86::VR256RegClass);
26331       case MVT::v8f64:
26332       case MVT::v16f32:
26333       case MVT::v16i32:
26334       case MVT::v8i64:
26335         return std::make_pair(0U, &X86::VR512RegClass);
26336       }
26337       break;
26338     }
26339   }
26340
26341   // Use the default implementation in TargetLowering to convert the register
26342   // constraint into a member of a register class.
26343   std::pair<unsigned, const TargetRegisterClass*> Res;
26344   Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
26345
26346   // Not found as a standard register?
26347   if (!Res.second) {
26348     // Map st(0) -> st(7) -> ST0
26349     if (Constraint.size() == 7 && Constraint[0] == '{' &&
26350         tolower(Constraint[1]) == 's' &&
26351         tolower(Constraint[2]) == 't' &&
26352         Constraint[3] == '(' &&
26353         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
26354         Constraint[5] == ')' &&
26355         Constraint[6] == '}') {
26356
26357       Res.first = X86::FP0+Constraint[4]-'0';
26358       Res.second = &X86::RFP80RegClass;
26359       return Res;
26360     }
26361
26362     // GCC allows "st(0)" to be called just plain "st".
26363     if (StringRef("{st}").equals_lower(Constraint)) {
26364       Res.first = X86::FP0;
26365       Res.second = &X86::RFP80RegClass;
26366       return Res;
26367     }
26368
26369     // flags -> EFLAGS
26370     if (StringRef("{flags}").equals_lower(Constraint)) {
26371       Res.first = X86::EFLAGS;
26372       Res.second = &X86::CCRRegClass;
26373       return Res;
26374     }
26375
26376     // 'A' means EAX + EDX.
26377     if (Constraint == "A") {
26378       Res.first = X86::EAX;
26379       Res.second = &X86::GR32_ADRegClass;
26380       return Res;
26381     }
26382     return Res;
26383   }
26384
26385   // Otherwise, check to see if this is a register class of the wrong value
26386   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
26387   // turn into {ax},{dx}.
26388   // MVT::Other is used to specify clobber names.
26389   if (Res.second->hasType(VT) || VT == MVT::Other)
26390     return Res;   // Correct type already, nothing to do.
26391
26392   // Get a matching integer of the correct size. i.e. "ax" with MVT::32 should
26393   // return "eax". This should even work for things like getting 64bit integer
26394   // registers when given an f64 type.
26395   const TargetRegisterClass *Class = Res.second;
26396   if (Class == &X86::GR8RegClass || Class == &X86::GR16RegClass ||
26397       Class == &X86::GR32RegClass || Class == &X86::GR64RegClass) {
26398     unsigned Size = VT.getSizeInBits();
26399     MVT::SimpleValueType SimpleTy = Size == 1 || Size == 8 ? MVT::i8
26400                                   : Size == 16 ? MVT::i16
26401                                   : Size == 32 ? MVT::i32
26402                                   : Size == 64 ? MVT::i64
26403                                   : MVT::Other;
26404     unsigned DestReg = getX86SubSuperRegisterOrZero(Res.first, SimpleTy);
26405     if (DestReg > 0) {
26406       Res.first = DestReg;
26407       Res.second = SimpleTy == MVT::i8 ? &X86::GR8RegClass
26408                  : SimpleTy == MVT::i16 ? &X86::GR16RegClass
26409                  : SimpleTy == MVT::i32 ? &X86::GR32RegClass
26410                  : &X86::GR64RegClass;
26411       assert(Res.second->contains(Res.first) && "Register in register class");
26412     } else {
26413       // No register found/type mismatch.
26414       Res.first = 0;
26415       Res.second = nullptr;
26416     }
26417   } else if (Class == &X86::FR32RegClass || Class == &X86::FR64RegClass ||
26418              Class == &X86::VR128RegClass || Class == &X86::VR256RegClass ||
26419              Class == &X86::FR32XRegClass || Class == &X86::FR64XRegClass ||
26420              Class == &X86::VR128XRegClass || Class == &X86::VR256XRegClass ||
26421              Class == &X86::VR512RegClass) {
26422     // Handle references to XMM physical registers that got mapped into the
26423     // wrong class.  This can happen with constraints like {xmm0} where the
26424     // target independent register mapper will just pick the first match it can
26425     // find, ignoring the required type.
26426
26427     if (VT == MVT::f32 || VT == MVT::i32)
26428       Res.second = &X86::FR32RegClass;
26429     else if (VT == MVT::f64 || VT == MVT::i64)
26430       Res.second = &X86::FR64RegClass;
26431     else if (X86::VR128RegClass.hasType(VT))
26432       Res.second = &X86::VR128RegClass;
26433     else if (X86::VR256RegClass.hasType(VT))
26434       Res.second = &X86::VR256RegClass;
26435     else if (X86::VR512RegClass.hasType(VT))
26436       Res.second = &X86::VR512RegClass;
26437     else {
26438       // Type mismatch and not a clobber: Return an error;
26439       Res.first = 0;
26440       Res.second = nullptr;
26441     }
26442   }
26443
26444   return Res;
26445 }
26446
26447 int X86TargetLowering::getScalingFactorCost(const DataLayout &DL,
26448                                             const AddrMode &AM, Type *Ty,
26449                                             unsigned AS) const {
26450   // Scaling factors are not free at all.
26451   // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
26452   // will take 2 allocations in the out of order engine instead of 1
26453   // for plain addressing mode, i.e. inst (reg1).
26454   // E.g.,
26455   // vaddps (%rsi,%drx), %ymm0, %ymm1
26456   // Requires two allocations (one for the load, one for the computation)
26457   // whereas:
26458   // vaddps (%rsi), %ymm0, %ymm1
26459   // Requires just 1 allocation, i.e., freeing allocations for other operations
26460   // and having less micro operations to execute.
26461   //
26462   // For some X86 architectures, this is even worse because for instance for
26463   // stores, the complex addressing mode forces the instruction to use the
26464   // "load" ports instead of the dedicated "store" port.
26465   // E.g., on Haswell:
26466   // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
26467   // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.
26468   if (isLegalAddressingMode(DL, AM, Ty, AS))
26469     // Scale represents reg2 * scale, thus account for 1
26470     // as soon as we use a second register.
26471     return AM.Scale != 0;
26472   return -1;
26473 }
26474
26475 bool X86TargetLowering::isTargetFTOL() const {
26476   return Subtarget->isTargetKnownWindowsMSVC() && !Subtarget->is64Bit();
26477 }
26478
26479 bool X86TargetLowering::isIntDivCheap(EVT VT, bool OptSize) const {
26480   // Integer division on x86 is expensive. However, when aggressively optimizing
26481   // for code size, we prefer to use a div instruction, as it is usually smaller
26482   // than the alternative sequence.
26483   // The exception to this is vector division. Since x86 doesn't have vector
26484   // integer division, leaving the division as-is is a loss even in terms of
26485   // size, because it will have to be scalarized, while the alternative code
26486   // sequence can be performed in vector form.
26487   return OptSize && !VT.isVector();
26488 }