make reciprocal estimate code generation more flexible by adding command-line options
[oota-llvm.git] / lib / Target / X86 / X86ISelLowering.cpp
1 //===-- X86ISelLowering.cpp - X86 DAG Lowering Implementation -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the interfaces that X86 uses to lower LLVM code into a
11 // selection DAG.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "X86ISelLowering.h"
16 #include "Utils/X86ShuffleDecode.h"
17 #include "X86CallingConv.h"
18 #include "X86FrameLowering.h"
19 #include "X86InstrBuilder.h"
20 #include "X86MachineFunctionInfo.h"
21 #include "X86TargetMachine.h"
22 #include "X86TargetObjectFile.h"
23 #include "llvm/ADT/SmallBitVector.h"
24 #include "llvm/ADT/SmallSet.h"
25 #include "llvm/ADT/Statistic.h"
26 #include "llvm/ADT/StringExtras.h"
27 #include "llvm/ADT/StringSwitch.h"
28 #include "llvm/CodeGen/IntrinsicLowering.h"
29 #include "llvm/CodeGen/MachineFrameInfo.h"
30 #include "llvm/CodeGen/MachineFunction.h"
31 #include "llvm/CodeGen/MachineInstrBuilder.h"
32 #include "llvm/CodeGen/MachineJumpTableInfo.h"
33 #include "llvm/CodeGen/MachineModuleInfo.h"
34 #include "llvm/CodeGen/MachineRegisterInfo.h"
35 #include "llvm/CodeGen/WinEHFuncInfo.h"
36 #include "llvm/IR/CallSite.h"
37 #include "llvm/IR/CallingConv.h"
38 #include "llvm/IR/Constants.h"
39 #include "llvm/IR/DerivedTypes.h"
40 #include "llvm/IR/Function.h"
41 #include "llvm/IR/GlobalAlias.h"
42 #include "llvm/IR/GlobalVariable.h"
43 #include "llvm/IR/Instructions.h"
44 #include "llvm/IR/Intrinsics.h"
45 #include "llvm/MC/MCAsmInfo.h"
46 #include "llvm/MC/MCContext.h"
47 #include "llvm/MC/MCExpr.h"
48 #include "llvm/MC/MCSymbol.h"
49 #include "llvm/Support/CommandLine.h"
50 #include "llvm/Support/Debug.h"
51 #include "llvm/Support/ErrorHandling.h"
52 #include "llvm/Support/MathExtras.h"
53 #include "llvm/Target/TargetOptions.h"
54 #include "X86IntrinsicsInfo.h"
55 #include <bitset>
56 #include <numeric>
57 #include <cctype>
58 using namespace llvm;
59
60 #define DEBUG_TYPE "x86-isel"
61
62 STATISTIC(NumTailCalls, "Number of tail calls");
63
64 static cl::opt<bool> ExperimentalVectorWideningLegalization(
65     "x86-experimental-vector-widening-legalization", cl::init(false),
66     cl::desc("Enable an experimental vector type legalization through widening "
67              "rather than promotion."),
68     cl::Hidden);
69
70 // Forward declarations.
71 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
72                        SDValue V2);
73
74 X86TargetLowering::X86TargetLowering(const X86TargetMachine &TM,
75                                      const X86Subtarget &STI)
76     : TargetLowering(TM), Subtarget(&STI) {
77   X86ScalarSSEf64 = Subtarget->hasSSE2();
78   X86ScalarSSEf32 = Subtarget->hasSSE1();
79   TD = getDataLayout();
80
81   // Set up the TargetLowering object.
82   static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
83
84   // X86 is weird. It always uses i8 for shift amounts and setcc results.
85   setBooleanContents(ZeroOrOneBooleanContent);
86   // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
87   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
88
89   // For 64-bit, since we have so many registers, use the ILP scheduler.
90   // For 32-bit, use the register pressure specific scheduling.
91   // For Atom, always use ILP scheduling.
92   if (Subtarget->isAtom())
93     setSchedulingPreference(Sched::ILP);
94   else if (Subtarget->is64Bit())
95     setSchedulingPreference(Sched::ILP);
96   else
97     setSchedulingPreference(Sched::RegPressure);
98   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
99   setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
100
101   // Bypass expensive divides on Atom when compiling with O2.
102   if (TM.getOptLevel() >= CodeGenOpt::Default) {
103     if (Subtarget->hasSlowDivide32())
104       addBypassSlowDiv(32, 8);
105     if (Subtarget->hasSlowDivide64() && Subtarget->is64Bit())
106       addBypassSlowDiv(64, 16);
107   }
108
109   if (Subtarget->isTargetKnownWindowsMSVC()) {
110     // Setup Windows compiler runtime calls.
111     setLibcallName(RTLIB::SDIV_I64, "_alldiv");
112     setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
113     setLibcallName(RTLIB::SREM_I64, "_allrem");
114     setLibcallName(RTLIB::UREM_I64, "_aullrem");
115     setLibcallName(RTLIB::MUL_I64, "_allmul");
116     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
117     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
118     setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
119     setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
120     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
121
122     // The _ftol2 runtime function has an unusual calling conv, which
123     // is modeled by a special pseudo-instruction.
124     setLibcallName(RTLIB::FPTOUINT_F64_I64, nullptr);
125     setLibcallName(RTLIB::FPTOUINT_F32_I64, nullptr);
126     setLibcallName(RTLIB::FPTOUINT_F64_I32, nullptr);
127     setLibcallName(RTLIB::FPTOUINT_F32_I32, nullptr);
128   }
129
130   if (Subtarget->isTargetDarwin()) {
131     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
132     setUseUnderscoreSetJmp(false);
133     setUseUnderscoreLongJmp(false);
134   } else if (Subtarget->isTargetWindowsGNU()) {
135     // MS runtime is weird: it exports _setjmp, but longjmp!
136     setUseUnderscoreSetJmp(true);
137     setUseUnderscoreLongJmp(false);
138   } else {
139     setUseUnderscoreSetJmp(true);
140     setUseUnderscoreLongJmp(true);
141   }
142
143   // Set up the register classes.
144   addRegisterClass(MVT::i8, &X86::GR8RegClass);
145   addRegisterClass(MVT::i16, &X86::GR16RegClass);
146   addRegisterClass(MVT::i32, &X86::GR32RegClass);
147   if (Subtarget->is64Bit())
148     addRegisterClass(MVT::i64, &X86::GR64RegClass);
149
150   for (MVT VT : MVT::integer_valuetypes())
151     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
152
153   // We don't accept any truncstore of integer registers.
154   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
155   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
156   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
157   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
158   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
159   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
160
161   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
162
163   // SETOEQ and SETUNE require checking two conditions.
164   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
165   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
166   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
167   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
168   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
169   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
170
171   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
172   // operation.
173   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
174   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
175   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
176
177   if (Subtarget->is64Bit()) {
178     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
179     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
180   } else if (!Subtarget->useSoftFloat()) {
181     // We have an algorithm for SSE2->double, and we turn this into a
182     // 64-bit FILD followed by conditional FADD for other targets.
183     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
184     // We have an algorithm for SSE2, and we turn this into a 64-bit
185     // FILD for other targets.
186     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
187   }
188
189   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
190   // this operation.
191   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
192   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
193
194   if (!Subtarget->useSoftFloat()) {
195     // SSE has no i16 to fp conversion, only i32
196     if (X86ScalarSSEf32) {
197       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
198       // f32 and f64 cases are Legal, f80 case is not
199       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
200     } else {
201       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
202       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
203     }
204   } else {
205     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
206     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
207   }
208
209   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
210   // are Legal, f80 is custom lowered.
211   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
212   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
213
214   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
215   // this operation.
216   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
217   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
218
219   if (X86ScalarSSEf32) {
220     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
221     // f32 and f64 cases are Legal, f80 case is not
222     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
223   } else {
224     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
225     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
226   }
227
228   // Handle FP_TO_UINT by promoting the destination to a larger signed
229   // conversion.
230   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
231   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
232   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
233
234   if (Subtarget->is64Bit()) {
235     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
236     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
237   } else if (!Subtarget->useSoftFloat()) {
238     // Since AVX is a superset of SSE3, only check for SSE here.
239     if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
240       // Expand FP_TO_UINT into a select.
241       // FIXME: We would like to use a Custom expander here eventually to do
242       // the optimal thing for SSE vs. the default expansion in the legalizer.
243       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
244     else
245       // With SSE3 we can use fisttpll to convert to a signed i64; without
246       // SSE, we're stuck with a fistpll.
247       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
248   }
249
250   if (isTargetFTOL()) {
251     // Use the _ftol2 runtime function, which has a pseudo-instruction
252     // to handle its weird calling convention.
253     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Custom);
254   }
255
256   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
257   if (!X86ScalarSSEf64) {
258     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
259     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
260     if (Subtarget->is64Bit()) {
261       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
262       // Without SSE, i64->f64 goes through memory.
263       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
264     }
265   }
266
267   // Scalar integer divide and remainder are lowered to use operations that
268   // produce two results, to match the available instructions. This exposes
269   // the two-result form to trivial CSE, which is able to combine x/y and x%y
270   // into a single instruction.
271   //
272   // Scalar integer multiply-high is also lowered to use two-result
273   // operations, to match the available instructions. However, plain multiply
274   // (low) operations are left as Legal, as there are single-result
275   // instructions for this in x86. Using the two-result multiply instructions
276   // when both high and low results are needed must be arranged by dagcombine.
277   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
278     MVT VT = IntVTs[i];
279     setOperationAction(ISD::MULHS, VT, Expand);
280     setOperationAction(ISD::MULHU, VT, Expand);
281     setOperationAction(ISD::SDIV, VT, Expand);
282     setOperationAction(ISD::UDIV, VT, Expand);
283     setOperationAction(ISD::SREM, VT, Expand);
284     setOperationAction(ISD::UREM, VT, Expand);
285
286     // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
287     setOperationAction(ISD::ADDC, VT, Custom);
288     setOperationAction(ISD::ADDE, VT, Custom);
289     setOperationAction(ISD::SUBC, VT, Custom);
290     setOperationAction(ISD::SUBE, VT, Custom);
291   }
292
293   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
294   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
295   setOperationAction(ISD::BR_CC            , MVT::f32,   Expand);
296   setOperationAction(ISD::BR_CC            , MVT::f64,   Expand);
297   setOperationAction(ISD::BR_CC            , MVT::f80,   Expand);
298   setOperationAction(ISD::BR_CC            , MVT::i8,    Expand);
299   setOperationAction(ISD::BR_CC            , MVT::i16,   Expand);
300   setOperationAction(ISD::BR_CC            , MVT::i32,   Expand);
301   setOperationAction(ISD::BR_CC            , MVT::i64,   Expand);
302   setOperationAction(ISD::SELECT_CC        , MVT::f32,   Expand);
303   setOperationAction(ISD::SELECT_CC        , MVT::f64,   Expand);
304   setOperationAction(ISD::SELECT_CC        , MVT::f80,   Expand);
305   setOperationAction(ISD::SELECT_CC        , MVT::i8,    Expand);
306   setOperationAction(ISD::SELECT_CC        , MVT::i16,   Expand);
307   setOperationAction(ISD::SELECT_CC        , MVT::i32,   Expand);
308   setOperationAction(ISD::SELECT_CC        , MVT::i64,   Expand);
309   if (Subtarget->is64Bit())
310     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
311   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
312   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
313   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
314   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
315   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
316   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
317   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
318   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
319
320   // Promote the i8 variants and force them on up to i32 which has a shorter
321   // encoding.
322   setOperationAction(ISD::CTTZ             , MVT::i8   , Promote);
323   AddPromotedToType (ISD::CTTZ             , MVT::i8   , MVT::i32);
324   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , Promote);
325   AddPromotedToType (ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , MVT::i32);
326   if (Subtarget->hasBMI()) {
327     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16  , Expand);
328     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32  , Expand);
329     if (Subtarget->is64Bit())
330       setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
331   } else {
332     setOperationAction(ISD::CTTZ           , MVT::i16  , Custom);
333     setOperationAction(ISD::CTTZ           , MVT::i32  , Custom);
334     if (Subtarget->is64Bit())
335       setOperationAction(ISD::CTTZ         , MVT::i64  , Custom);
336   }
337
338   if (Subtarget->hasLZCNT()) {
339     // When promoting the i8 variants, force them to i32 for a shorter
340     // encoding.
341     setOperationAction(ISD::CTLZ           , MVT::i8   , Promote);
342     AddPromotedToType (ISD::CTLZ           , MVT::i8   , MVT::i32);
343     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Promote);
344     AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8   , MVT::i32);
345     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Expand);
346     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Expand);
347     if (Subtarget->is64Bit())
348       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
349   } else {
350     setOperationAction(ISD::CTLZ           , MVT::i8   , Custom);
351     setOperationAction(ISD::CTLZ           , MVT::i16  , Custom);
352     setOperationAction(ISD::CTLZ           , MVT::i32  , Custom);
353     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Custom);
354     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Custom);
355     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Custom);
356     if (Subtarget->is64Bit()) {
357       setOperationAction(ISD::CTLZ         , MVT::i64  , Custom);
358       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
359     }
360   }
361
362   // Special handling for half-precision floating point conversions.
363   // If we don't have F16C support, then lower half float conversions
364   // into library calls.
365   if (Subtarget->useSoftFloat() || !Subtarget->hasF16C()) {
366     setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
367     setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
368   }
369
370   // There's never any support for operations beyond MVT::f32.
371   setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
372   setOperationAction(ISD::FP16_TO_FP, MVT::f80, Expand);
373   setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
374   setOperationAction(ISD::FP_TO_FP16, MVT::f80, Expand);
375
376   setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
377   setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
378   setLoadExtAction(ISD::EXTLOAD, MVT::f80, MVT::f16, Expand);
379   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
380   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
381   setTruncStoreAction(MVT::f80, MVT::f16, Expand);
382
383   if (Subtarget->hasPOPCNT()) {
384     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
385   } else {
386     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
387     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
388     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
389     if (Subtarget->is64Bit())
390       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
391   }
392
393   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
394
395   if (!Subtarget->hasMOVBE())
396     setOperationAction(ISD::BSWAP          , MVT::i16  , Expand);
397
398   // These should be promoted to a larger select which is supported.
399   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
400   // X86 wants to expand cmov itself.
401   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
402   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
403   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
404   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
405   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
406   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
407   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
408   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
409   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
410   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
411   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
412   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
413   if (Subtarget->is64Bit()) {
414     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
415     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
416   }
417   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
418   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
419   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
420   // support continuation, user-level threading, and etc.. As a result, no
421   // other SjLj exception interfaces are implemented and please don't build
422   // your own exception handling based on them.
423   // LLVM/Clang supports zero-cost DWARF exception handling.
424   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
425   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
426
427   // Darwin ABI issue.
428   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
429   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
430   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
431   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
432   if (Subtarget->is64Bit())
433     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
434   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
435   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
436   if (Subtarget->is64Bit()) {
437     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
438     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
439     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
440     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
441     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
442   }
443   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
444   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
445   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
446   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
447   if (Subtarget->is64Bit()) {
448     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
449     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
450     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
451   }
452
453   if (Subtarget->hasSSE1())
454     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
455
456   setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
457
458   // Expand certain atomics
459   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
460     MVT VT = IntVTs[i];
461     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, VT, Custom);
462     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
463     setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
464   }
465
466   if (Subtarget->hasCmpxchg16b()) {
467     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i128, Custom);
468   }
469
470   // FIXME - use subtarget debug flags
471   if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetELF() &&
472       !Subtarget->isTargetCygMing() && !Subtarget->isTargetWin64()) {
473     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
474   }
475
476   if (Subtarget->is64Bit()) {
477     setExceptionPointerRegister(X86::RAX);
478     setExceptionSelectorRegister(X86::RDX);
479   } else {
480     setExceptionPointerRegister(X86::EAX);
481     setExceptionSelectorRegister(X86::EDX);
482   }
483   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
484   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
485
486   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
487   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
488
489   setOperationAction(ISD::TRAP, MVT::Other, Legal);
490   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
491
492   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
493   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
494   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
495   if (Subtarget->is64Bit() && !Subtarget->isTargetWin64()) {
496     // TargetInfo::X86_64ABIBuiltinVaList
497     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
498     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
499   } else {
500     // TargetInfo::CharPtrBuiltinVaList
501     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
502     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
503   }
504
505   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
506   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
507
508   setOperationAction(ISD::DYNAMIC_STACKALLOC, getPointerTy(), Custom);
509
510   // GC_TRANSITION_START and GC_TRANSITION_END need custom lowering.
511   setOperationAction(ISD::GC_TRANSITION_START, MVT::Other, Custom);
512   setOperationAction(ISD::GC_TRANSITION_END, MVT::Other, Custom);
513
514   if (!Subtarget->useSoftFloat() && X86ScalarSSEf64) {
515     // f32 and f64 use SSE.
516     // Set up the FP register classes.
517     addRegisterClass(MVT::f32, &X86::FR32RegClass);
518     addRegisterClass(MVT::f64, &X86::FR64RegClass);
519
520     // Use ANDPD to simulate FABS.
521     setOperationAction(ISD::FABS , MVT::f64, Custom);
522     setOperationAction(ISD::FABS , MVT::f32, Custom);
523
524     // Use XORP to simulate FNEG.
525     setOperationAction(ISD::FNEG , MVT::f64, Custom);
526     setOperationAction(ISD::FNEG , MVT::f32, Custom);
527
528     // Use ANDPD and ORPD to simulate FCOPYSIGN.
529     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
530     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
531
532     // Lower this to FGETSIGNx86 plus an AND.
533     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
534     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
535
536     // We don't support sin/cos/fmod
537     setOperationAction(ISD::FSIN   , MVT::f64, Expand);
538     setOperationAction(ISD::FCOS   , MVT::f64, Expand);
539     setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
540     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
541     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
542     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
543
544     // Expand FP immediates into loads from the stack, except for the special
545     // cases we handle.
546     addLegalFPImmediate(APFloat(+0.0)); // xorpd
547     addLegalFPImmediate(APFloat(+0.0f)); // xorps
548   } else if (!Subtarget->useSoftFloat() && X86ScalarSSEf32) {
549     // Use SSE for f32, x87 for f64.
550     // Set up the FP register classes.
551     addRegisterClass(MVT::f32, &X86::FR32RegClass);
552     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
553
554     // Use ANDPS to simulate FABS.
555     setOperationAction(ISD::FABS , MVT::f32, Custom);
556
557     // Use XORP to simulate FNEG.
558     setOperationAction(ISD::FNEG , MVT::f32, Custom);
559
560     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
561
562     // Use ANDPS and ORPS to simulate FCOPYSIGN.
563     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
564     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
565
566     // We don't support sin/cos/fmod
567     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
568     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
569     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
570
571     // Special cases we handle for FP constants.
572     addLegalFPImmediate(APFloat(+0.0f)); // xorps
573     addLegalFPImmediate(APFloat(+0.0)); // FLD0
574     addLegalFPImmediate(APFloat(+1.0)); // FLD1
575     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
576     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
577
578     if (!TM.Options.UnsafeFPMath) {
579       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
580       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
581       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
582     }
583   } else if (!Subtarget->useSoftFloat()) {
584     // f32 and f64 in x87.
585     // Set up the FP register classes.
586     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
587     addRegisterClass(MVT::f32, &X86::RFP32RegClass);
588
589     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
590     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
591     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
592     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
593
594     if (!TM.Options.UnsafeFPMath) {
595       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
596       setOperationAction(ISD::FSIN   , MVT::f32, Expand);
597       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
598       setOperationAction(ISD::FCOS   , MVT::f32, Expand);
599       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
600       setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
601     }
602     addLegalFPImmediate(APFloat(+0.0)); // FLD0
603     addLegalFPImmediate(APFloat(+1.0)); // FLD1
604     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
605     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
606     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
607     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
608     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
609     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
610   }
611
612   // We don't support FMA.
613   setOperationAction(ISD::FMA, MVT::f64, Expand);
614   setOperationAction(ISD::FMA, MVT::f32, Expand);
615
616   // Long double always uses X87.
617   if (!Subtarget->useSoftFloat()) {
618     addRegisterClass(MVT::f80, &X86::RFP80RegClass);
619     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
620     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
621     {
622       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
623       addLegalFPImmediate(TmpFlt);  // FLD0
624       TmpFlt.changeSign();
625       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
626
627       bool ignored;
628       APFloat TmpFlt2(+1.0);
629       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
630                       &ignored);
631       addLegalFPImmediate(TmpFlt2);  // FLD1
632       TmpFlt2.changeSign();
633       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
634     }
635
636     if (!TM.Options.UnsafeFPMath) {
637       setOperationAction(ISD::FSIN   , MVT::f80, Expand);
638       setOperationAction(ISD::FCOS   , MVT::f80, Expand);
639       setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
640     }
641
642     setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
643     setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
644     setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
645     setOperationAction(ISD::FRINT,  MVT::f80, Expand);
646     setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
647     setOperationAction(ISD::FMA, MVT::f80, Expand);
648   }
649
650   // Always use a library call for pow.
651   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
652   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
653   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
654
655   setOperationAction(ISD::FLOG, MVT::f80, Expand);
656   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
657   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
658   setOperationAction(ISD::FEXP, MVT::f80, Expand);
659   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
660   setOperationAction(ISD::FMINNUM, MVT::f80, Expand);
661   setOperationAction(ISD::FMAXNUM, MVT::f80, Expand);
662
663   // First set operation action for all vector types to either promote
664   // (for widening) or expand (for scalarization). Then we will selectively
665   // turn on ones that can be effectively codegen'd.
666   for (MVT VT : MVT::vector_valuetypes()) {
667     setOperationAction(ISD::ADD , VT, Expand);
668     setOperationAction(ISD::SUB , VT, Expand);
669     setOperationAction(ISD::FADD, VT, Expand);
670     setOperationAction(ISD::FNEG, VT, Expand);
671     setOperationAction(ISD::FSUB, VT, Expand);
672     setOperationAction(ISD::MUL , VT, Expand);
673     setOperationAction(ISD::FMUL, VT, Expand);
674     setOperationAction(ISD::SDIV, VT, Expand);
675     setOperationAction(ISD::UDIV, VT, Expand);
676     setOperationAction(ISD::FDIV, VT, Expand);
677     setOperationAction(ISD::SREM, VT, Expand);
678     setOperationAction(ISD::UREM, VT, Expand);
679     setOperationAction(ISD::LOAD, VT, Expand);
680     setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
681     setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
682     setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
683     setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
684     setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
685     setOperationAction(ISD::FABS, VT, Expand);
686     setOperationAction(ISD::FSIN, VT, Expand);
687     setOperationAction(ISD::FSINCOS, VT, Expand);
688     setOperationAction(ISD::FCOS, VT, Expand);
689     setOperationAction(ISD::FSINCOS, VT, Expand);
690     setOperationAction(ISD::FREM, VT, Expand);
691     setOperationAction(ISD::FMA,  VT, Expand);
692     setOperationAction(ISD::FPOWI, VT, Expand);
693     setOperationAction(ISD::FSQRT, VT, Expand);
694     setOperationAction(ISD::FCOPYSIGN, VT, Expand);
695     setOperationAction(ISD::FFLOOR, VT, Expand);
696     setOperationAction(ISD::FCEIL, VT, Expand);
697     setOperationAction(ISD::FTRUNC, VT, Expand);
698     setOperationAction(ISD::FRINT, VT, Expand);
699     setOperationAction(ISD::FNEARBYINT, VT, Expand);
700     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
701     setOperationAction(ISD::MULHS, VT, Expand);
702     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
703     setOperationAction(ISD::MULHU, VT, Expand);
704     setOperationAction(ISD::SDIVREM, VT, Expand);
705     setOperationAction(ISD::UDIVREM, VT, Expand);
706     setOperationAction(ISD::FPOW, VT, Expand);
707     setOperationAction(ISD::CTPOP, VT, Expand);
708     setOperationAction(ISD::CTTZ, VT, Expand);
709     setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
710     setOperationAction(ISD::CTLZ, VT, Expand);
711     setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
712     setOperationAction(ISD::SHL, VT, Expand);
713     setOperationAction(ISD::SRA, VT, Expand);
714     setOperationAction(ISD::SRL, VT, Expand);
715     setOperationAction(ISD::ROTL, VT, Expand);
716     setOperationAction(ISD::ROTR, VT, Expand);
717     setOperationAction(ISD::BSWAP, VT, Expand);
718     setOperationAction(ISD::SETCC, VT, Expand);
719     setOperationAction(ISD::FLOG, VT, Expand);
720     setOperationAction(ISD::FLOG2, VT, Expand);
721     setOperationAction(ISD::FLOG10, VT, Expand);
722     setOperationAction(ISD::FEXP, VT, Expand);
723     setOperationAction(ISD::FEXP2, VT, Expand);
724     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
725     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
726     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
727     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
728     setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
729     setOperationAction(ISD::TRUNCATE, VT, Expand);
730     setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
731     setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
732     setOperationAction(ISD::ANY_EXTEND, VT, Expand);
733     setOperationAction(ISD::VSELECT, VT, Expand);
734     setOperationAction(ISD::SELECT_CC, VT, Expand);
735     for (MVT InnerVT : MVT::vector_valuetypes()) {
736       setTruncStoreAction(InnerVT, VT, Expand);
737
738       setLoadExtAction(ISD::SEXTLOAD, InnerVT, VT, Expand);
739       setLoadExtAction(ISD::ZEXTLOAD, InnerVT, VT, Expand);
740
741       // N.b. ISD::EXTLOAD legality is basically ignored except for i1-like
742       // types, we have to deal with them whether we ask for Expansion or not.
743       // Setting Expand causes its own optimisation problems though, so leave
744       // them legal.
745       if (VT.getVectorElementType() == MVT::i1)
746         setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
747
748       // EXTLOAD for MVT::f16 vectors is not legal because f16 vectors are
749       // split/scalarized right now.
750       if (VT.getVectorElementType() == MVT::f16)
751         setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
752     }
753   }
754
755   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
756   // with -msoft-float, disable use of MMX as well.
757   if (!Subtarget->useSoftFloat() && Subtarget->hasMMX()) {
758     addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
759     // No operations on x86mmx supported, everything uses intrinsics.
760   }
761
762   // MMX-sized vectors (other than x86mmx) are expected to be expanded
763   // into smaller operations.
764   for (MVT MMXTy : {MVT::v8i8, MVT::v4i16, MVT::v2i32, MVT::v1i64}) {
765     setOperationAction(ISD::MULHS,              MMXTy,      Expand);
766     setOperationAction(ISD::AND,                MMXTy,      Expand);
767     setOperationAction(ISD::OR,                 MMXTy,      Expand);
768     setOperationAction(ISD::XOR,                MMXTy,      Expand);
769     setOperationAction(ISD::SCALAR_TO_VECTOR,   MMXTy,      Expand);
770     setOperationAction(ISD::SELECT,             MMXTy,      Expand);
771     setOperationAction(ISD::BITCAST,            MMXTy,      Expand);
772   }
773   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
774
775   if (!Subtarget->useSoftFloat() && Subtarget->hasSSE1()) {
776     addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
777
778     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
779     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
780     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
781     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
782     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
783     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
784     setOperationAction(ISD::FABS,               MVT::v4f32, Custom);
785     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
786     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
787     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
788     setOperationAction(ISD::VSELECT,            MVT::v4f32, Custom);
789     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
790     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
791     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Custom);
792   }
793
794   if (!Subtarget->useSoftFloat() && Subtarget->hasSSE2()) {
795     addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
796
797     // FIXME: Unfortunately, -soft-float and -no-implicit-float mean XMM
798     // registers cannot be used even for integer operations.
799     addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
800     addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
801     addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
802     addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
803
804     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
805     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
806     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
807     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
808     setOperationAction(ISD::MUL,                MVT::v16i8, Custom);
809     setOperationAction(ISD::MUL,                MVT::v4i32, Custom);
810     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
811     setOperationAction(ISD::UMUL_LOHI,          MVT::v4i32, Custom);
812     setOperationAction(ISD::SMUL_LOHI,          MVT::v4i32, Custom);
813     setOperationAction(ISD::MULHU,              MVT::v8i16, Legal);
814     setOperationAction(ISD::MULHS,              MVT::v8i16, Legal);
815     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
816     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
817     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
818     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
819     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
820     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
821     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
822     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
823     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
824     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
825     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
826     setOperationAction(ISD::FABS,               MVT::v2f64, Custom);
827
828     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
829     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
830     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
831     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
832
833     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
834     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
835     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
836     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
837     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
838
839     // Only provide customized ctpop vector bit twiddling for vector types we
840     // know to perform better than using the popcnt instructions on each vector
841     // element. If popcnt isn't supported, always provide the custom version.
842     if (!Subtarget->hasPOPCNT()) {
843       setOperationAction(ISD::CTPOP,            MVT::v4i32, Custom);
844       setOperationAction(ISD::CTPOP,            MVT::v2i64, Custom);
845     }
846
847     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
848     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
849       MVT VT = (MVT::SimpleValueType)i;
850       // Do not attempt to custom lower non-power-of-2 vectors
851       if (!isPowerOf2_32(VT.getVectorNumElements()))
852         continue;
853       // Do not attempt to custom lower non-128-bit vectors
854       if (!VT.is128BitVector())
855         continue;
856       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
857       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
858       setOperationAction(ISD::VSELECT,            VT, Custom);
859       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
860     }
861
862     // We support custom legalizing of sext and anyext loads for specific
863     // memory vector types which we can load as a scalar (or sequence of
864     // scalars) and extend in-register to a legal 128-bit vector type. For sext
865     // loads these must work with a single scalar load.
866     for (MVT VT : MVT::integer_vector_valuetypes()) {
867       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i8, Custom);
868       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i16, Custom);
869       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v8i8, Custom);
870       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i8, Custom);
871       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i16, Custom);
872       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i32, Custom);
873       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i8, Custom);
874       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i16, Custom);
875       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8i8, Custom);
876     }
877
878     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
879     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
880     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
881     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
882     setOperationAction(ISD::VSELECT,            MVT::v2f64, Custom);
883     setOperationAction(ISD::VSELECT,            MVT::v2i64, Custom);
884     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
885     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
886
887     if (Subtarget->is64Bit()) {
888       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
889       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
890     }
891
892     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
893     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
894       MVT VT = (MVT::SimpleValueType)i;
895
896       // Do not attempt to promote non-128-bit vectors
897       if (!VT.is128BitVector())
898         continue;
899
900       setOperationAction(ISD::AND,    VT, Promote);
901       AddPromotedToType (ISD::AND,    VT, MVT::v2i64);
902       setOperationAction(ISD::OR,     VT, Promote);
903       AddPromotedToType (ISD::OR,     VT, MVT::v2i64);
904       setOperationAction(ISD::XOR,    VT, Promote);
905       AddPromotedToType (ISD::XOR,    VT, MVT::v2i64);
906       setOperationAction(ISD::LOAD,   VT, Promote);
907       AddPromotedToType (ISD::LOAD,   VT, MVT::v2i64);
908       setOperationAction(ISD::SELECT, VT, Promote);
909       AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
910     }
911
912     // Custom lower v2i64 and v2f64 selects.
913     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
914     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
915     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
916     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
917
918     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
919     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
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     // FIXME: Do we need to handle scalar-to-vector here?
949     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
950
951     // We directly match byte blends in the backend as they match the VSELECT
952     // condition form.
953     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
954
955     // SSE41 brings specific instructions for doing vector sign extend even in
956     // cases where we don't have SRA.
957     for (MVT VT : MVT::integer_vector_valuetypes()) {
958       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i8, Custom);
959       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i16, Custom);
960       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i32, Custom);
961     }
962
963     // SSE41 also has vector sign/zero extending loads, PMOV[SZ]X
964     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i16, MVT::v8i8,  Legal);
965     setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i8,  Legal);
966     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i8,  Legal);
967     setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
968     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
969     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
970
971     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i16, MVT::v8i8,  Legal);
972     setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i8,  Legal);
973     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i8,  Legal);
974     setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
975     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
976     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
977
978     // i8 and i16 vectors are custom because the source register and source
979     // source memory operand types are not the same width.  f32 vectors are
980     // custom since the immediate controlling the insert encodes additional
981     // information.
982     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
983     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
984     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
985     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
986
987     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
988     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
989     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
990     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
991
992     // FIXME: these should be Legal, but that's only for the case where
993     // the index is constant.  For now custom expand to deal with that.
994     if (Subtarget->is64Bit()) {
995       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
996       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
997     }
998   }
999
1000   if (Subtarget->hasSSE2()) {
1001     setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v2i64, Custom);
1002     setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v4i32, Custom);
1003     setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v8i16, Custom);
1004
1005     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
1006     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
1007
1008     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
1009     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
1010
1011     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
1012     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
1013
1014     // In the customized shift lowering, the legal cases in AVX2 will be
1015     // recognized.
1016     setOperationAction(ISD::SRL,               MVT::v2i64, Custom);
1017     setOperationAction(ISD::SRL,               MVT::v4i32, Custom);
1018
1019     setOperationAction(ISD::SHL,               MVT::v2i64, Custom);
1020     setOperationAction(ISD::SHL,               MVT::v4i32, Custom);
1021
1022     setOperationAction(ISD::SRA,               MVT::v4i32, Custom);
1023   }
1024
1025   if (!Subtarget->useSoftFloat() && Subtarget->hasFp256()) {
1026     addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1027     addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1028     addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1029     addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1030     addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1031     addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1032
1033     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1034     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1035     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1036
1037     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1038     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1039     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1040     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1041     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1042     setOperationAction(ISD::FFLOOR,             MVT::v8f32, Legal);
1043     setOperationAction(ISD::FCEIL,              MVT::v8f32, Legal);
1044     setOperationAction(ISD::FTRUNC,             MVT::v8f32, Legal);
1045     setOperationAction(ISD::FRINT,              MVT::v8f32, Legal);
1046     setOperationAction(ISD::FNEARBYINT,         MVT::v8f32, Legal);
1047     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1048     setOperationAction(ISD::FABS,               MVT::v8f32, Custom);
1049
1050     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1051     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1052     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1053     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1054     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1055     setOperationAction(ISD::FFLOOR,             MVT::v4f64, Legal);
1056     setOperationAction(ISD::FCEIL,              MVT::v4f64, Legal);
1057     setOperationAction(ISD::FTRUNC,             MVT::v4f64, Legal);
1058     setOperationAction(ISD::FRINT,              MVT::v4f64, Legal);
1059     setOperationAction(ISD::FNEARBYINT,         MVT::v4f64, Legal);
1060     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1061     setOperationAction(ISD::FABS,               MVT::v4f64, Custom);
1062
1063     // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1064     // even though v8i16 is a legal type.
1065     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i16, Promote);
1066     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i16, Promote);
1067     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1068
1069     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i16, Promote);
1070     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1071     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1072
1073     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i8,  Custom);
1074     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i16, Custom);
1075
1076     for (MVT VT : MVT::fp_vector_valuetypes())
1077       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4f32, Legal);
1078
1079     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1080     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1081
1082     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1083     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1084
1085     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1086     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1087
1088     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1089     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1090     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1091     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1092
1093     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1094     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1095     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1096
1097     setOperationAction(ISD::SIGN_EXTEND,       MVT::v4i64, Custom);
1098     setOperationAction(ISD::SIGN_EXTEND,       MVT::v8i32, Custom);
1099     setOperationAction(ISD::SIGN_EXTEND,       MVT::v16i16, Custom);
1100     setOperationAction(ISD::ZERO_EXTEND,       MVT::v4i64, Custom);
1101     setOperationAction(ISD::ZERO_EXTEND,       MVT::v8i32, Custom);
1102     setOperationAction(ISD::ZERO_EXTEND,       MVT::v16i16, Custom);
1103     setOperationAction(ISD::ANY_EXTEND,        MVT::v4i64, Custom);
1104     setOperationAction(ISD::ANY_EXTEND,        MVT::v8i32, Custom);
1105     setOperationAction(ISD::ANY_EXTEND,        MVT::v16i16, Custom);
1106     setOperationAction(ISD::TRUNCATE,          MVT::v16i8, Custom);
1107     setOperationAction(ISD::TRUNCATE,          MVT::v8i16, Custom);
1108     setOperationAction(ISD::TRUNCATE,          MVT::v4i32, Custom);
1109
1110     if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1111       setOperationAction(ISD::FMA,             MVT::v8f32, Legal);
1112       setOperationAction(ISD::FMA,             MVT::v4f64, Legal);
1113       setOperationAction(ISD::FMA,             MVT::v4f32, Legal);
1114       setOperationAction(ISD::FMA,             MVT::v2f64, Legal);
1115       setOperationAction(ISD::FMA,             MVT::f32, Legal);
1116       setOperationAction(ISD::FMA,             MVT::f64, Legal);
1117     }
1118
1119     if (Subtarget->hasInt256()) {
1120       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1121       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1122       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1123       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1124
1125       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1126       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1127       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1128       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1129
1130       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1131       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1132       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1133       setOperationAction(ISD::MUL,             MVT::v32i8, Custom);
1134
1135       setOperationAction(ISD::UMUL_LOHI,       MVT::v8i32, Custom);
1136       setOperationAction(ISD::SMUL_LOHI,       MVT::v8i32, Custom);
1137       setOperationAction(ISD::MULHU,           MVT::v16i16, Legal);
1138       setOperationAction(ISD::MULHS,           MVT::v16i16, Legal);
1139
1140       // The custom lowering for UINT_TO_FP for v8i32 becomes interesting
1141       // when we have a 256bit-wide blend with immediate.
1142       setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Custom);
1143
1144       // Only provide customized ctpop vector bit twiddling for vector types we
1145       // know to perform better than using the popcnt instructions on each
1146       // vector element. If popcnt isn't supported, always provide the custom
1147       // version.
1148       if (!Subtarget->hasPOPCNT())
1149         setOperationAction(ISD::CTPOP,           MVT::v4i64, Custom);
1150
1151       // Custom CTPOP always performs better on natively supported v8i32
1152       setOperationAction(ISD::CTPOP,             MVT::v8i32, Custom);
1153
1154       // AVX2 also has wider vector sign/zero extending loads, VPMOV[SZ]X
1155       setLoadExtAction(ISD::SEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1156       setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32,  MVT::v8i8,  Legal);
1157       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i8,  Legal);
1158       setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32,  MVT::v8i16, Legal);
1159       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i16, Legal);
1160       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i32, Legal);
1161
1162       setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1163       setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32,  MVT::v8i8,  Legal);
1164       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i8,  Legal);
1165       setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32,  MVT::v8i16, Legal);
1166       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i16, Legal);
1167       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i32, Legal);
1168     } else {
1169       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1170       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1171       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1172       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1173
1174       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1175       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1176       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1177       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1178
1179       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1180       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1181       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1182       setOperationAction(ISD::MUL,             MVT::v32i8, Custom);
1183     }
1184
1185     // In the customized shift lowering, the legal cases in AVX2 will be
1186     // recognized.
1187     setOperationAction(ISD::SRL,               MVT::v4i64, Custom);
1188     setOperationAction(ISD::SRL,               MVT::v8i32, Custom);
1189
1190     setOperationAction(ISD::SHL,               MVT::v4i64, Custom);
1191     setOperationAction(ISD::SHL,               MVT::v8i32, Custom);
1192
1193     setOperationAction(ISD::SRA,               MVT::v8i32, Custom);
1194
1195     // Custom lower several nodes for 256-bit types.
1196     for (MVT VT : MVT::vector_valuetypes()) {
1197       if (VT.getScalarSizeInBits() >= 32) {
1198         setOperationAction(ISD::MLOAD,  VT, Legal);
1199         setOperationAction(ISD::MSTORE, VT, Legal);
1200       }
1201       // Extract subvector is special because the value type
1202       // (result) is 128-bit but the source is 256-bit wide.
1203       if (VT.is128BitVector()) {
1204         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1205       }
1206       // Do not attempt to custom lower other non-256-bit vectors
1207       if (!VT.is256BitVector())
1208         continue;
1209
1210       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1211       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1212       setOperationAction(ISD::VSELECT,            VT, Custom);
1213       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1214       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1215       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1216       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1217       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1218     }
1219
1220     if (Subtarget->hasInt256())
1221       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1222
1223
1224     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1225     for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1226       MVT VT = (MVT::SimpleValueType)i;
1227
1228       // Do not attempt to promote non-256-bit vectors
1229       if (!VT.is256BitVector())
1230         continue;
1231
1232       setOperationAction(ISD::AND,    VT, Promote);
1233       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1234       setOperationAction(ISD::OR,     VT, Promote);
1235       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1236       setOperationAction(ISD::XOR,    VT, Promote);
1237       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1238       setOperationAction(ISD::LOAD,   VT, Promote);
1239       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1240       setOperationAction(ISD::SELECT, VT, Promote);
1241       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1242     }
1243   }
1244
1245   if (!Subtarget->useSoftFloat() && Subtarget->hasAVX512()) {
1246     addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1247     addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1248     addRegisterClass(MVT::v8i64,  &X86::VR512RegClass);
1249     addRegisterClass(MVT::v8f64,  &X86::VR512RegClass);
1250
1251     addRegisterClass(MVT::i1,     &X86::VK1RegClass);
1252     addRegisterClass(MVT::v8i1,   &X86::VK8RegClass);
1253     addRegisterClass(MVT::v16i1,  &X86::VK16RegClass);
1254
1255     for (MVT VT : MVT::fp_vector_valuetypes())
1256       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8f32, Legal);
1257
1258     setOperationAction(ISD::BR_CC,              MVT::i1,    Expand);
1259     setOperationAction(ISD::SETCC,              MVT::i1,    Custom);
1260     setOperationAction(ISD::XOR,                MVT::i1,    Legal);
1261     setOperationAction(ISD::OR,                 MVT::i1,    Legal);
1262     setOperationAction(ISD::AND,                MVT::i1,    Legal);
1263     setOperationAction(ISD::LOAD,               MVT::v16f32, Legal);
1264     setOperationAction(ISD::LOAD,               MVT::v8f64, Legal);
1265     setOperationAction(ISD::LOAD,               MVT::v8i64, Legal);
1266     setOperationAction(ISD::LOAD,               MVT::v16i32, Legal);
1267     setOperationAction(ISD::LOAD,               MVT::v16i1, Legal);
1268
1269     setOperationAction(ISD::FADD,               MVT::v16f32, Legal);
1270     setOperationAction(ISD::FSUB,               MVT::v16f32, Legal);
1271     setOperationAction(ISD::FMUL,               MVT::v16f32, Legal);
1272     setOperationAction(ISD::FDIV,               MVT::v16f32, Legal);
1273     setOperationAction(ISD::FSQRT,              MVT::v16f32, Legal);
1274     setOperationAction(ISD::FNEG,               MVT::v16f32, Custom);
1275
1276     setOperationAction(ISD::FADD,               MVT::v8f64, Legal);
1277     setOperationAction(ISD::FSUB,               MVT::v8f64, Legal);
1278     setOperationAction(ISD::FMUL,               MVT::v8f64, Legal);
1279     setOperationAction(ISD::FDIV,               MVT::v8f64, Legal);
1280     setOperationAction(ISD::FSQRT,              MVT::v8f64, Legal);
1281     setOperationAction(ISD::FNEG,               MVT::v8f64, Custom);
1282     setOperationAction(ISD::FMA,                MVT::v8f64, Legal);
1283     setOperationAction(ISD::FMA,                MVT::v16f32, Legal);
1284
1285     setOperationAction(ISD::FP_TO_SINT,         MVT::i32, Legal);
1286     setOperationAction(ISD::FP_TO_UINT,         MVT::i32, Legal);
1287     setOperationAction(ISD::SINT_TO_FP,         MVT::i32, Legal);
1288     setOperationAction(ISD::UINT_TO_FP,         MVT::i32, Legal);
1289     if (Subtarget->is64Bit()) {
1290       setOperationAction(ISD::FP_TO_UINT,       MVT::i64, Legal);
1291       setOperationAction(ISD::FP_TO_SINT,       MVT::i64, Legal);
1292       setOperationAction(ISD::SINT_TO_FP,       MVT::i64, Legal);
1293       setOperationAction(ISD::UINT_TO_FP,       MVT::i64, Legal);
1294     }
1295     setOperationAction(ISD::FP_TO_SINT,         MVT::v16i32, Legal);
1296     setOperationAction(ISD::FP_TO_UINT,         MVT::v16i32, Legal);
1297     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i32, Legal);
1298     setOperationAction(ISD::FP_TO_UINT,         MVT::v4i32, Legal);
1299     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i32, Legal);
1300     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i1,   Custom);
1301     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i1,  Custom);
1302     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i8,  Promote);
1303     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i16, Promote);
1304     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i32, Legal);
1305     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i32, Legal);
1306     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Legal);
1307     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i8, Custom);
1308     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i16, Custom);
1309     setOperationAction(ISD::FP_ROUND,           MVT::v8f32, Legal);
1310     setOperationAction(ISD::FP_EXTEND,          MVT::v8f32, Legal);
1311
1312     setOperationAction(ISD::TRUNCATE,           MVT::i1, Custom);
1313     setOperationAction(ISD::TRUNCATE,           MVT::v16i8, Custom);
1314     setOperationAction(ISD::TRUNCATE,           MVT::v8i32, Custom);
1315     if (Subtarget->hasDQI()) {
1316       setOperationAction(ISD::TRUNCATE,           MVT::v2i1, Custom);
1317       setOperationAction(ISD::TRUNCATE,           MVT::v4i1, Custom);
1318     }
1319     setOperationAction(ISD::TRUNCATE,           MVT::v8i1, Custom);
1320     setOperationAction(ISD::TRUNCATE,           MVT::v16i1, Custom);
1321     setOperationAction(ISD::TRUNCATE,           MVT::v16i16, Custom);
1322     setOperationAction(ISD::ZERO_EXTEND,        MVT::v16i32, Custom);
1323     setOperationAction(ISD::ZERO_EXTEND,        MVT::v8i64, Custom);
1324     setOperationAction(ISD::ANY_EXTEND,         MVT::v16i32, Custom);
1325     setOperationAction(ISD::ANY_EXTEND,         MVT::v8i64, Custom);
1326     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i32, Custom);
1327     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i64, Custom);
1328     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i8, Custom);
1329     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i16, Custom);
1330     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i16, Custom);
1331     if (Subtarget->hasDQI()) {
1332       setOperationAction(ISD::SIGN_EXTEND,        MVT::v4i32, Custom);
1333       setOperationAction(ISD::SIGN_EXTEND,        MVT::v2i64, Custom);
1334     }
1335     setOperationAction(ISD::FFLOOR,             MVT::v16f32, Legal);
1336     setOperationAction(ISD::FFLOOR,             MVT::v8f64, Legal);
1337     setOperationAction(ISD::FCEIL,              MVT::v16f32, Legal);
1338     setOperationAction(ISD::FCEIL,              MVT::v8f64, Legal);
1339     setOperationAction(ISD::FTRUNC,             MVT::v16f32, Legal);
1340     setOperationAction(ISD::FTRUNC,             MVT::v8f64, Legal);
1341     setOperationAction(ISD::FRINT,              MVT::v16f32, Legal);
1342     setOperationAction(ISD::FRINT,              MVT::v8f64, Legal);
1343     setOperationAction(ISD::FNEARBYINT,         MVT::v16f32, Legal);
1344     setOperationAction(ISD::FNEARBYINT,         MVT::v8f64, Legal);
1345
1346     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8f64,  Custom);
1347     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i64,  Custom);
1348     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16f32,  Custom);
1349     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i32,  Custom);
1350     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i1, Legal);
1351
1352     setOperationAction(ISD::SETCC,              MVT::v16i1, Custom);
1353     setOperationAction(ISD::SETCC,              MVT::v8i1, Custom);
1354
1355     setOperationAction(ISD::MUL,              MVT::v8i64, Custom);
1356
1357     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1,  Custom);
1358     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1359     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i1, Custom);
1360     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i1, Custom);
1361     setOperationAction(ISD::BUILD_VECTOR,       MVT::v8i1, Custom);
1362     setOperationAction(ISD::BUILD_VECTOR,       MVT::v16i1, Custom);
1363     setOperationAction(ISD::SELECT,             MVT::v8f64, Custom);
1364     setOperationAction(ISD::SELECT,             MVT::v8i64, Custom);
1365     setOperationAction(ISD::SELECT,             MVT::v16f32, Custom);
1366     setOperationAction(ISD::SELECT,             MVT::v16i1, Custom);
1367     setOperationAction(ISD::SELECT,             MVT::v8i1,  Custom);
1368
1369     setOperationAction(ISD::ADD,                MVT::v8i64, Legal);
1370     setOperationAction(ISD::ADD,                MVT::v16i32, Legal);
1371
1372     setOperationAction(ISD::SUB,                MVT::v8i64, Legal);
1373     setOperationAction(ISD::SUB,                MVT::v16i32, Legal);
1374
1375     setOperationAction(ISD::MUL,                MVT::v16i32, Legal);
1376
1377     setOperationAction(ISD::SRL,                MVT::v8i64, Custom);
1378     setOperationAction(ISD::SRL,                MVT::v16i32, Custom);
1379
1380     setOperationAction(ISD::SHL,                MVT::v8i64, Custom);
1381     setOperationAction(ISD::SHL,                MVT::v16i32, Custom);
1382
1383     setOperationAction(ISD::SRA,                MVT::v8i64, Custom);
1384     setOperationAction(ISD::SRA,                MVT::v16i32, Custom);
1385
1386     setOperationAction(ISD::AND,                MVT::v8i64, Legal);
1387     setOperationAction(ISD::OR,                 MVT::v8i64, Legal);
1388     setOperationAction(ISD::XOR,                MVT::v8i64, Legal);
1389     setOperationAction(ISD::AND,                MVT::v16i32, Legal);
1390     setOperationAction(ISD::OR,                 MVT::v16i32, Legal);
1391     setOperationAction(ISD::XOR,                MVT::v16i32, Legal);
1392
1393     if (Subtarget->hasCDI()) {
1394       setOperationAction(ISD::CTLZ,             MVT::v8i64, Legal);
1395       setOperationAction(ISD::CTLZ,             MVT::v16i32, Legal);
1396     }
1397     if (Subtarget->hasDQI()) {
1398       setOperationAction(ISD::MUL,             MVT::v2i64, Legal);
1399       setOperationAction(ISD::MUL,             MVT::v4i64, Legal);
1400       setOperationAction(ISD::MUL,             MVT::v8i64, Legal);
1401     }
1402     // Custom lower several nodes.
1403     for (MVT VT : MVT::vector_valuetypes()) {
1404       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1405       if (EltSize == 1) {
1406         setOperationAction(ISD::AND, VT, Legal);
1407         setOperationAction(ISD::OR,  VT, Legal);
1408         setOperationAction(ISD::XOR,  VT, Legal);
1409       }
1410       if (EltSize >= 32 && VT.getSizeInBits() <= 512) {
1411         setOperationAction(ISD::MGATHER,  VT, Custom);
1412         setOperationAction(ISD::MSCATTER, VT, Custom);
1413       }
1414       // Extract subvector is special because the value type
1415       // (result) is 256/128-bit but the source is 512-bit wide.
1416       if (VT.is128BitVector() || VT.is256BitVector()) {
1417         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1418       }
1419       if (VT.getVectorElementType() == MVT::i1)
1420         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1421
1422       // Do not attempt to custom lower other non-512-bit vectors
1423       if (!VT.is512BitVector())
1424         continue;
1425
1426       if (EltSize >= 32) {
1427         setOperationAction(ISD::VECTOR_SHUFFLE,      VT, Custom);
1428         setOperationAction(ISD::INSERT_VECTOR_ELT,   VT, Custom);
1429         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1430         setOperationAction(ISD::VSELECT,             VT, Legal);
1431         setOperationAction(ISD::EXTRACT_VECTOR_ELT,  VT, Custom);
1432         setOperationAction(ISD::SCALAR_TO_VECTOR,    VT, Custom);
1433         setOperationAction(ISD::INSERT_SUBVECTOR,    VT, Custom);
1434         setOperationAction(ISD::MLOAD,               VT, Legal);
1435         setOperationAction(ISD::MSTORE,              VT, Legal);
1436       }
1437     }
1438     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1439       MVT VT = (MVT::SimpleValueType)i;
1440
1441       // Do not attempt to promote non-512-bit vectors.
1442       if (!VT.is512BitVector())
1443         continue;
1444
1445       setOperationAction(ISD::SELECT, VT, Promote);
1446       AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1447     }
1448   }// has  AVX-512
1449
1450   if (!Subtarget->useSoftFloat() && Subtarget->hasBWI()) {
1451     addRegisterClass(MVT::v32i16, &X86::VR512RegClass);
1452     addRegisterClass(MVT::v64i8,  &X86::VR512RegClass);
1453
1454     addRegisterClass(MVT::v32i1,  &X86::VK32RegClass);
1455     addRegisterClass(MVT::v64i1,  &X86::VK64RegClass);
1456
1457     setOperationAction(ISD::LOAD,               MVT::v32i16, Legal);
1458     setOperationAction(ISD::LOAD,               MVT::v64i8, Legal);
1459     setOperationAction(ISD::SETCC,              MVT::v32i1, Custom);
1460     setOperationAction(ISD::SETCC,              MVT::v64i1, Custom);
1461     setOperationAction(ISD::ADD,                MVT::v32i16, Legal);
1462     setOperationAction(ISD::ADD,                MVT::v64i8, Legal);
1463     setOperationAction(ISD::SUB,                MVT::v32i16, Legal);
1464     setOperationAction(ISD::SUB,                MVT::v64i8, Legal);
1465     setOperationAction(ISD::MUL,                MVT::v32i16, Legal);
1466     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v32i1, Custom);
1467     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v64i1, Custom);
1468     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v32i1, Custom);
1469     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v64i1, Custom);
1470     setOperationAction(ISD::SELECT,             MVT::v32i1, Custom);
1471     setOperationAction(ISD::SELECT,             MVT::v64i1, Custom);
1472     setOperationAction(ISD::SIGN_EXTEND,        MVT::v32i8, Custom);
1473     setOperationAction(ISD::SIGN_EXTEND,        MVT::v64i8, Custom);
1474     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v32i1, Custom);
1475     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v64i1, Custom);
1476
1477     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1478       const MVT VT = (MVT::SimpleValueType)i;
1479
1480       const unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1481
1482       // Do not attempt to promote non-512-bit vectors.
1483       if (!VT.is512BitVector())
1484         continue;
1485
1486       if (EltSize < 32) {
1487         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1488         setOperationAction(ISD::VSELECT,             VT, Legal);
1489       }
1490     }
1491   }
1492
1493   if (!Subtarget->useSoftFloat() && Subtarget->hasVLX()) {
1494     addRegisterClass(MVT::v4i1,   &X86::VK4RegClass);
1495     addRegisterClass(MVT::v2i1,   &X86::VK2RegClass);
1496
1497     setOperationAction(ISD::SETCC,              MVT::v4i1, Custom);
1498     setOperationAction(ISD::SETCC,              MVT::v2i1, Custom);
1499     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4i1, Custom);
1500     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i1, Custom);
1501     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v8i1, Custom);
1502     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v4i1, Custom);
1503     setOperationAction(ISD::SELECT,             MVT::v4i1, Custom);
1504     setOperationAction(ISD::SELECT,             MVT::v2i1, Custom);
1505     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4i1, Custom);
1506     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i1, Custom);
1507
1508     setOperationAction(ISD::AND,                MVT::v8i32, Legal);
1509     setOperationAction(ISD::OR,                 MVT::v8i32, Legal);
1510     setOperationAction(ISD::XOR,                MVT::v8i32, Legal);
1511     setOperationAction(ISD::AND,                MVT::v4i32, Legal);
1512     setOperationAction(ISD::OR,                 MVT::v4i32, Legal);
1513     setOperationAction(ISD::XOR,                MVT::v4i32, Legal);
1514     setOperationAction(ISD::SRA,                MVT::v2i64, Custom);
1515     setOperationAction(ISD::SRA,                MVT::v4i64, Custom);
1516   }
1517
1518   // We want to custom lower some of our intrinsics.
1519   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1520   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1521   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1522   if (!Subtarget->is64Bit())
1523     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1524
1525   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1526   // handle type legalization for these operations here.
1527   //
1528   // FIXME: We really should do custom legalization for addition and
1529   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1530   // than generic legalization for 64-bit multiplication-with-overflow, though.
1531   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1532     // Add/Sub/Mul with overflow operations are custom lowered.
1533     MVT VT = IntVTs[i];
1534     setOperationAction(ISD::SADDO, VT, Custom);
1535     setOperationAction(ISD::UADDO, VT, Custom);
1536     setOperationAction(ISD::SSUBO, VT, Custom);
1537     setOperationAction(ISD::USUBO, VT, Custom);
1538     setOperationAction(ISD::SMULO, VT, Custom);
1539     setOperationAction(ISD::UMULO, VT, Custom);
1540   }
1541
1542
1543   if (!Subtarget->is64Bit()) {
1544     // These libcalls are not available in 32-bit.
1545     setLibcallName(RTLIB::SHL_I128, nullptr);
1546     setLibcallName(RTLIB::SRL_I128, nullptr);
1547     setLibcallName(RTLIB::SRA_I128, nullptr);
1548   }
1549
1550   // Combine sin / cos into one node or libcall if possible.
1551   if (Subtarget->hasSinCos()) {
1552     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1553     setLibcallName(RTLIB::SINCOS_F64, "sincos");
1554     if (Subtarget->isTargetDarwin()) {
1555       // For MacOSX, we don't want the normal expansion of a libcall to sincos.
1556       // We want to issue a libcall to __sincos_stret to avoid memory traffic.
1557       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1558       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1559     }
1560   }
1561
1562   if (Subtarget->isTargetWin64()) {
1563     setOperationAction(ISD::SDIV, MVT::i128, Custom);
1564     setOperationAction(ISD::UDIV, MVT::i128, Custom);
1565     setOperationAction(ISD::SREM, MVT::i128, Custom);
1566     setOperationAction(ISD::UREM, MVT::i128, Custom);
1567     setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1568     setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1569   }
1570
1571   // We have target-specific dag combine patterns for the following nodes:
1572   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1573   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1574   setTargetDAGCombine(ISD::BITCAST);
1575   setTargetDAGCombine(ISD::VSELECT);
1576   setTargetDAGCombine(ISD::SELECT);
1577   setTargetDAGCombine(ISD::SHL);
1578   setTargetDAGCombine(ISD::SRA);
1579   setTargetDAGCombine(ISD::SRL);
1580   setTargetDAGCombine(ISD::OR);
1581   setTargetDAGCombine(ISD::AND);
1582   setTargetDAGCombine(ISD::ADD);
1583   setTargetDAGCombine(ISD::FADD);
1584   setTargetDAGCombine(ISD::FSUB);
1585   setTargetDAGCombine(ISD::FMA);
1586   setTargetDAGCombine(ISD::SUB);
1587   setTargetDAGCombine(ISD::LOAD);
1588   setTargetDAGCombine(ISD::MLOAD);
1589   setTargetDAGCombine(ISD::STORE);
1590   setTargetDAGCombine(ISD::MSTORE);
1591   setTargetDAGCombine(ISD::ZERO_EXTEND);
1592   setTargetDAGCombine(ISD::ANY_EXTEND);
1593   setTargetDAGCombine(ISD::SIGN_EXTEND);
1594   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1595   setTargetDAGCombine(ISD::SINT_TO_FP);
1596   setTargetDAGCombine(ISD::SETCC);
1597   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1598   setTargetDAGCombine(ISD::BUILD_VECTOR);
1599   setTargetDAGCombine(ISD::MUL);
1600   setTargetDAGCombine(ISD::XOR);
1601
1602   computeRegisterProperties(Subtarget->getRegisterInfo());
1603
1604   // On Darwin, -Os means optimize for size without hurting performance,
1605   // do not reduce the limit.
1606   MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1607   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1608   MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1609   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1610   MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1611   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1612   setPrefLoopAlignment(4); // 2^4 bytes.
1613
1614   // Predictable cmov don't hurt on atom because it's in-order.
1615   PredictableSelectIsExpensive = !Subtarget->isAtom();
1616   EnableExtLdPromotion = true;
1617   setPrefFunctionAlignment(4); // 2^4 bytes.
1618
1619   verifyIntrinsicTables();
1620 }
1621
1622 // This has so far only been implemented for 64-bit MachO.
1623 bool X86TargetLowering::useLoadStackGuardNode() const {
1624   return Subtarget->isTargetMachO() && Subtarget->is64Bit();
1625 }
1626
1627 TargetLoweringBase::LegalizeTypeAction
1628 X86TargetLowering::getPreferredVectorAction(EVT VT) const {
1629   if (ExperimentalVectorWideningLegalization &&
1630       VT.getVectorNumElements() != 1 &&
1631       VT.getVectorElementType().getSimpleVT() != MVT::i1)
1632     return TypeWidenVector;
1633
1634   return TargetLoweringBase::getPreferredVectorAction(VT);
1635 }
1636
1637 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1638   if (!VT.isVector())
1639     return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1640
1641   const unsigned NumElts = VT.getVectorNumElements();
1642   const EVT EltVT = VT.getVectorElementType();
1643   if (VT.is512BitVector()) {
1644     if (Subtarget->hasAVX512())
1645       if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1646           EltVT == MVT::f32 || EltVT == MVT::f64)
1647         switch(NumElts) {
1648         case  8: return MVT::v8i1;
1649         case 16: return MVT::v16i1;
1650       }
1651     if (Subtarget->hasBWI())
1652       if (EltVT == MVT::i8 || EltVT == MVT::i16)
1653         switch(NumElts) {
1654         case 32: return MVT::v32i1;
1655         case 64: return MVT::v64i1;
1656       }
1657   }
1658
1659   if (VT.is256BitVector() || VT.is128BitVector()) {
1660     if (Subtarget->hasVLX())
1661       if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1662           EltVT == MVT::f32 || EltVT == MVT::f64)
1663         switch(NumElts) {
1664         case 2: return MVT::v2i1;
1665         case 4: return MVT::v4i1;
1666         case 8: return MVT::v8i1;
1667       }
1668     if (Subtarget->hasBWI() && Subtarget->hasVLX())
1669       if (EltVT == MVT::i8 || EltVT == MVT::i16)
1670         switch(NumElts) {
1671         case  8: return MVT::v8i1;
1672         case 16: return MVT::v16i1;
1673         case 32: return MVT::v32i1;
1674       }
1675   }
1676
1677   return VT.changeVectorElementTypeToInteger();
1678 }
1679
1680 /// Helper for getByValTypeAlignment to determine
1681 /// the desired ByVal argument alignment.
1682 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1683   if (MaxAlign == 16)
1684     return;
1685   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1686     if (VTy->getBitWidth() == 128)
1687       MaxAlign = 16;
1688   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1689     unsigned EltAlign = 0;
1690     getMaxByValAlign(ATy->getElementType(), EltAlign);
1691     if (EltAlign > MaxAlign)
1692       MaxAlign = EltAlign;
1693   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1694     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1695       unsigned EltAlign = 0;
1696       getMaxByValAlign(STy->getElementType(i), EltAlign);
1697       if (EltAlign > MaxAlign)
1698         MaxAlign = EltAlign;
1699       if (MaxAlign == 16)
1700         break;
1701     }
1702   }
1703 }
1704
1705 /// Return the desired alignment for ByVal aggregate
1706 /// function arguments in the caller parameter area. For X86, aggregates
1707 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1708 /// are at 4-byte boundaries.
1709 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1710   if (Subtarget->is64Bit()) {
1711     // Max of 8 and alignment of type.
1712     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1713     if (TyAlign > 8)
1714       return TyAlign;
1715     return 8;
1716   }
1717
1718   unsigned Align = 4;
1719   if (Subtarget->hasSSE1())
1720     getMaxByValAlign(Ty, Align);
1721   return Align;
1722 }
1723
1724 /// Returns the target specific optimal type for load
1725 /// and store operations as a result of memset, memcpy, and memmove
1726 /// lowering. If DstAlign is zero that means it's safe to destination
1727 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1728 /// means there isn't a need to check it against alignment requirement,
1729 /// probably because the source does not need to be loaded. If 'IsMemset' is
1730 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1731 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1732 /// source is constant so it does not need to be loaded.
1733 /// It returns EVT::Other if the type should be determined using generic
1734 /// target-independent logic.
1735 EVT
1736 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1737                                        unsigned DstAlign, unsigned SrcAlign,
1738                                        bool IsMemset, bool ZeroMemset,
1739                                        bool MemcpyStrSrc,
1740                                        MachineFunction &MF) const {
1741   const Function *F = MF.getFunction();
1742   if ((!IsMemset || ZeroMemset) &&
1743       !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
1744     if (Size >= 16 &&
1745         (Subtarget->isUnalignedMemAccessFast() ||
1746          ((DstAlign == 0 || DstAlign >= 16) &&
1747           (SrcAlign == 0 || SrcAlign >= 16)))) {
1748       if (Size >= 32) {
1749         if (Subtarget->hasInt256())
1750           return MVT::v8i32;
1751         if (Subtarget->hasFp256())
1752           return MVT::v8f32;
1753       }
1754       if (Subtarget->hasSSE2())
1755         return MVT::v4i32;
1756       if (Subtarget->hasSSE1())
1757         return MVT::v4f32;
1758     } else if (!MemcpyStrSrc && Size >= 8 &&
1759                !Subtarget->is64Bit() &&
1760                Subtarget->hasSSE2()) {
1761       // Do not use f64 to lower memcpy if source is string constant. It's
1762       // better to use i32 to avoid the loads.
1763       return MVT::f64;
1764     }
1765   }
1766   if (Subtarget->is64Bit() && Size >= 8)
1767     return MVT::i64;
1768   return MVT::i32;
1769 }
1770
1771 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1772   if (VT == MVT::f32)
1773     return X86ScalarSSEf32;
1774   else if (VT == MVT::f64)
1775     return X86ScalarSSEf64;
1776   return true;
1777 }
1778
1779 bool
1780 X86TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
1781                                                   unsigned,
1782                                                   unsigned,
1783                                                   bool *Fast) const {
1784   if (Fast)
1785     *Fast = Subtarget->isUnalignedMemAccessFast();
1786   return true;
1787 }
1788
1789 /// Return the entry encoding for a jump table in the
1790 /// current function.  The returned value is a member of the
1791 /// MachineJumpTableInfo::JTEntryKind enum.
1792 unsigned X86TargetLowering::getJumpTableEncoding() const {
1793   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1794   // symbol.
1795   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1796       Subtarget->isPICStyleGOT())
1797     return MachineJumpTableInfo::EK_Custom32;
1798
1799   // Otherwise, use the normal jump table encoding heuristics.
1800   return TargetLowering::getJumpTableEncoding();
1801 }
1802
1803 bool X86TargetLowering::useSoftFloat() const {
1804   return Subtarget->useSoftFloat();
1805 }
1806
1807 const MCExpr *
1808 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1809                                              const MachineBasicBlock *MBB,
1810                                              unsigned uid,MCContext &Ctx) const{
1811   assert(MBB->getParent()->getTarget().getRelocationModel() == Reloc::PIC_ &&
1812          Subtarget->isPICStyleGOT());
1813   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1814   // entries.
1815   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1816                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1817 }
1818
1819 /// Returns relocation base for the given PIC jumptable.
1820 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1821                                                     SelectionDAG &DAG) const {
1822   if (!Subtarget->is64Bit())
1823     // This doesn't have SDLoc associated with it, but is not really the
1824     // same as a Register.
1825     return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy());
1826   return Table;
1827 }
1828
1829 /// This returns the relocation base for the given PIC jumptable,
1830 /// the same as getPICJumpTableRelocBase, but as an MCExpr.
1831 const MCExpr *X86TargetLowering::
1832 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1833                              MCContext &Ctx) const {
1834   // X86-64 uses RIP relative addressing based on the jump table label.
1835   if (Subtarget->isPICStyleRIPRel())
1836     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1837
1838   // Otherwise, the reference is relative to the PIC base.
1839   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1840 }
1841
1842 std::pair<const TargetRegisterClass *, uint8_t>
1843 X86TargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
1844                                            MVT VT) const {
1845   const TargetRegisterClass *RRC = nullptr;
1846   uint8_t Cost = 1;
1847   switch (VT.SimpleTy) {
1848   default:
1849     return TargetLowering::findRepresentativeClass(TRI, VT);
1850   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1851     RRC = Subtarget->is64Bit() ? &X86::GR64RegClass : &X86::GR32RegClass;
1852     break;
1853   case MVT::x86mmx:
1854     RRC = &X86::VR64RegClass;
1855     break;
1856   case MVT::f32: case MVT::f64:
1857   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1858   case MVT::v4f32: case MVT::v2f64:
1859   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1860   case MVT::v4f64:
1861     RRC = &X86::VR128RegClass;
1862     break;
1863   }
1864   return std::make_pair(RRC, Cost);
1865 }
1866
1867 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1868                                                unsigned &Offset) const {
1869   if (!Subtarget->isTargetLinux())
1870     return false;
1871
1872   if (Subtarget->is64Bit()) {
1873     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1874     Offset = 0x28;
1875     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1876       AddressSpace = 256;
1877     else
1878       AddressSpace = 257;
1879   } else {
1880     // %gs:0x14 on i386
1881     Offset = 0x14;
1882     AddressSpace = 256;
1883   }
1884   return true;
1885 }
1886
1887 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1888                                             unsigned DestAS) const {
1889   assert(SrcAS != DestAS && "Expected different address spaces!");
1890
1891   return SrcAS < 256 && DestAS < 256;
1892 }
1893
1894 //===----------------------------------------------------------------------===//
1895 //               Return Value Calling Convention Implementation
1896 //===----------------------------------------------------------------------===//
1897
1898 #include "X86GenCallingConv.inc"
1899
1900 bool
1901 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1902                                   MachineFunction &MF, bool isVarArg,
1903                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1904                         LLVMContext &Context) const {
1905   SmallVector<CCValAssign, 16> RVLocs;
1906   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
1907   return CCInfo.CheckReturn(Outs, RetCC_X86);
1908 }
1909
1910 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
1911   static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
1912   return ScratchRegs;
1913 }
1914
1915 SDValue
1916 X86TargetLowering::LowerReturn(SDValue Chain,
1917                                CallingConv::ID CallConv, bool isVarArg,
1918                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1919                                const SmallVectorImpl<SDValue> &OutVals,
1920                                SDLoc dl, SelectionDAG &DAG) const {
1921   MachineFunction &MF = DAG.getMachineFunction();
1922   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1923
1924   SmallVector<CCValAssign, 16> RVLocs;
1925   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, *DAG.getContext());
1926   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1927
1928   SDValue Flag;
1929   SmallVector<SDValue, 6> RetOps;
1930   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1931   // Operand #1 = Bytes To Pop
1932   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(), dl,
1933                    MVT::i16));
1934
1935   // Copy the result values into the output registers.
1936   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1937     CCValAssign &VA = RVLocs[i];
1938     assert(VA.isRegLoc() && "Can only return in registers!");
1939     SDValue ValToCopy = OutVals[i];
1940     EVT ValVT = ValToCopy.getValueType();
1941
1942     // Promote values to the appropriate types.
1943     if (VA.getLocInfo() == CCValAssign::SExt)
1944       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1945     else if (VA.getLocInfo() == CCValAssign::ZExt)
1946       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1947     else if (VA.getLocInfo() == CCValAssign::AExt) {
1948       if (ValVT.isVector() && ValVT.getScalarType() == MVT::i1)
1949         ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1950       else
1951         ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1952     }
1953     else if (VA.getLocInfo() == CCValAssign::BCvt)
1954       ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1955
1956     assert(VA.getLocInfo() != CCValAssign::FPExt &&
1957            "Unexpected FP-extend for return value.");
1958
1959     // If this is x86-64, and we disabled SSE, we can't return FP values,
1960     // or SSE or MMX vectors.
1961     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1962          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1963           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1964       report_fatal_error("SSE register return with SSE disabled");
1965     }
1966     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1967     // llvm-gcc has never done it right and no one has noticed, so this
1968     // should be OK for now.
1969     if (ValVT == MVT::f64 &&
1970         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1971       report_fatal_error("SSE2 register return with SSE2 disabled");
1972
1973     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1974     // the RET instruction and handled by the FP Stackifier.
1975     if (VA.getLocReg() == X86::FP0 ||
1976         VA.getLocReg() == X86::FP1) {
1977       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1978       // change the value to the FP stack register class.
1979       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1980         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1981       RetOps.push_back(ValToCopy);
1982       // Don't emit a copytoreg.
1983       continue;
1984     }
1985
1986     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1987     // which is returned in RAX / RDX.
1988     if (Subtarget->is64Bit()) {
1989       if (ValVT == MVT::x86mmx) {
1990         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1991           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1992           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1993                                   ValToCopy);
1994           // If we don't have SSE2 available, convert to v4f32 so the generated
1995           // register is legal.
1996           if (!Subtarget->hasSSE2())
1997             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1998         }
1999       }
2000     }
2001
2002     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
2003     Flag = Chain.getValue(1);
2004     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2005   }
2006
2007   // All x86 ABIs require that for returning structs by value we copy
2008   // the sret argument into %rax/%eax (depending on ABI) for the return.
2009   // We saved the argument into a virtual register in the entry block,
2010   // so now we copy the value out and into %rax/%eax.
2011   //
2012   // Checking Function.hasStructRetAttr() here is insufficient because the IR
2013   // may not have an explicit sret argument. If FuncInfo.CanLowerReturn is
2014   // false, then an sret argument may be implicitly inserted in the SelDAG. In
2015   // either case FuncInfo->setSRetReturnReg() will have been called.
2016   if (unsigned SRetReg = FuncInfo->getSRetReturnReg()) {
2017     SDValue Val = DAG.getCopyFromReg(Chain, dl, SRetReg, getPointerTy());
2018
2019     unsigned RetValReg
2020         = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
2021           X86::RAX : X86::EAX;
2022     Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
2023     Flag = Chain.getValue(1);
2024
2025     // RAX/EAX now acts like a return value.
2026     RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
2027   }
2028
2029   RetOps[0] = Chain;  // Update chain.
2030
2031   // Add the flag if we have it.
2032   if (Flag.getNode())
2033     RetOps.push_back(Flag);
2034
2035   return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
2036 }
2037
2038 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2039   if (N->getNumValues() != 1)
2040     return false;
2041   if (!N->hasNUsesOfValue(1, 0))
2042     return false;
2043
2044   SDValue TCChain = Chain;
2045   SDNode *Copy = *N->use_begin();
2046   if (Copy->getOpcode() == ISD::CopyToReg) {
2047     // If the copy has a glue operand, we conservatively assume it isn't safe to
2048     // perform a tail call.
2049     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2050       return false;
2051     TCChain = Copy->getOperand(0);
2052   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
2053     return false;
2054
2055   bool HasRet = false;
2056   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2057        UI != UE; ++UI) {
2058     if (UI->getOpcode() != X86ISD::RET_FLAG)
2059       return false;
2060     // If we are returning more than one value, we can definitely
2061     // not make a tail call see PR19530
2062     if (UI->getNumOperands() > 4)
2063       return false;
2064     if (UI->getNumOperands() == 4 &&
2065         UI->getOperand(UI->getNumOperands()-1).getValueType() != MVT::Glue)
2066       return false;
2067     HasRet = true;
2068   }
2069
2070   if (!HasRet)
2071     return false;
2072
2073   Chain = TCChain;
2074   return true;
2075 }
2076
2077 EVT
2078 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
2079                                             ISD::NodeType ExtendKind) const {
2080   MVT ReturnMVT;
2081   // TODO: Is this also valid on 32-bit?
2082   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
2083     ReturnMVT = MVT::i8;
2084   else
2085     ReturnMVT = MVT::i32;
2086
2087   EVT MinVT = getRegisterType(Context, ReturnMVT);
2088   return VT.bitsLT(MinVT) ? MinVT : VT;
2089 }
2090
2091 /// Lower the result values of a call into the
2092 /// appropriate copies out of appropriate physical registers.
2093 ///
2094 SDValue
2095 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2096                                    CallingConv::ID CallConv, bool isVarArg,
2097                                    const SmallVectorImpl<ISD::InputArg> &Ins,
2098                                    SDLoc dl, SelectionDAG &DAG,
2099                                    SmallVectorImpl<SDValue> &InVals) const {
2100
2101   // Assign locations to each value returned by this call.
2102   SmallVector<CCValAssign, 16> RVLocs;
2103   bool Is64Bit = Subtarget->is64Bit();
2104   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2105                  *DAG.getContext());
2106   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2107
2108   // Copy all of the result registers out of their specified physreg.
2109   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2110     CCValAssign &VA = RVLocs[i];
2111     EVT CopyVT = VA.getLocVT();
2112
2113     // If this is x86-64, and we disabled SSE, we can't return FP values
2114     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2115         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2116       report_fatal_error("SSE register return with SSE disabled");
2117     }
2118
2119     // If we prefer to use the value in xmm registers, copy it out as f80 and
2120     // use a truncate to move it from fp stack reg to xmm reg.
2121     bool RoundAfterCopy = false;
2122     if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
2123         isScalarFPTypeInSSEReg(VA.getValVT())) {
2124       CopyVT = MVT::f80;
2125       RoundAfterCopy = (CopyVT != VA.getLocVT());
2126     }
2127
2128     Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2129                                CopyVT, InFlag).getValue(1);
2130     SDValue Val = Chain.getValue(0);
2131
2132     if (RoundAfterCopy)
2133       Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2134                         // This truncation won't change the value.
2135                         DAG.getIntPtrConstant(1, dl));
2136
2137     if (VA.isExtInLoc() && VA.getValVT().getScalarType() == MVT::i1)
2138       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
2139
2140     InFlag = Chain.getValue(2);
2141     InVals.push_back(Val);
2142   }
2143
2144   return Chain;
2145 }
2146
2147 //===----------------------------------------------------------------------===//
2148 //                C & StdCall & Fast Calling Convention implementation
2149 //===----------------------------------------------------------------------===//
2150 //  StdCall calling convention seems to be standard for many Windows' API
2151 //  routines and around. It differs from C calling convention just a little:
2152 //  callee should clean up the stack, not caller. Symbols should be also
2153 //  decorated in some fancy way :) It doesn't support any vector arguments.
2154 //  For info on fast calling convention see Fast Calling Convention (tail call)
2155 //  implementation LowerX86_32FastCCCallTo.
2156
2157 /// CallIsStructReturn - Determines whether a call uses struct return
2158 /// semantics.
2159 enum StructReturnType {
2160   NotStructReturn,
2161   RegStructReturn,
2162   StackStructReturn
2163 };
2164 static StructReturnType
2165 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2166   if (Outs.empty())
2167     return NotStructReturn;
2168
2169   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2170   if (!Flags.isSRet())
2171     return NotStructReturn;
2172   if (Flags.isInReg())
2173     return RegStructReturn;
2174   return StackStructReturn;
2175 }
2176
2177 /// Determines whether a function uses struct return semantics.
2178 static StructReturnType
2179 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2180   if (Ins.empty())
2181     return NotStructReturn;
2182
2183   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2184   if (!Flags.isSRet())
2185     return NotStructReturn;
2186   if (Flags.isInReg())
2187     return RegStructReturn;
2188   return StackStructReturn;
2189 }
2190
2191 /// Make a copy of an aggregate at address specified by "Src" to address
2192 /// "Dst" with size and alignment information specified by the specific
2193 /// parameter attribute. The copy will be passed as a byval function parameter.
2194 static SDValue
2195 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2196                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2197                           SDLoc dl) {
2198   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
2199
2200   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2201                        /*isVolatile*/false, /*AlwaysInline=*/true,
2202                        /*isTailCall*/false,
2203                        MachinePointerInfo(), MachinePointerInfo());
2204 }
2205
2206 /// Return true if the calling convention is one that
2207 /// supports tail call optimization.
2208 static bool IsTailCallConvention(CallingConv::ID CC) {
2209   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2210           CC == CallingConv::HiPE);
2211 }
2212
2213 /// \brief Return true if the calling convention is a C calling convention.
2214 static bool IsCCallConvention(CallingConv::ID CC) {
2215   return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2216           CC == CallingConv::X86_64_SysV);
2217 }
2218
2219 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2220   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2221     return false;
2222
2223   CallSite CS(CI);
2224   CallingConv::ID CalleeCC = CS.getCallingConv();
2225   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2226     return false;
2227
2228   return true;
2229 }
2230
2231 /// Return true if the function is being made into
2232 /// a tailcall target by changing its ABI.
2233 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2234                                    bool GuaranteedTailCallOpt) {
2235   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2236 }
2237
2238 SDValue
2239 X86TargetLowering::LowerMemArgument(SDValue Chain,
2240                                     CallingConv::ID CallConv,
2241                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2242                                     SDLoc dl, SelectionDAG &DAG,
2243                                     const CCValAssign &VA,
2244                                     MachineFrameInfo *MFI,
2245                                     unsigned i) const {
2246   // Create the nodes corresponding to a load from this parameter slot.
2247   ISD::ArgFlagsTy Flags = Ins[i].Flags;
2248   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(
2249       CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2250   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2251   EVT ValVT;
2252
2253   // If value is passed by pointer we have address passed instead of the value
2254   // itself.
2255   bool ExtendedInMem = VA.isExtInLoc() &&
2256     VA.getValVT().getScalarType() == MVT::i1;
2257
2258   if (VA.getLocInfo() == CCValAssign::Indirect || ExtendedInMem)
2259     ValVT = VA.getLocVT();
2260   else
2261     ValVT = VA.getValVT();
2262
2263   // FIXME: For now, all byval parameter objects are marked mutable. This can be
2264   // changed with more analysis.
2265   // In case of tail call optimization mark all arguments mutable. Since they
2266   // could be overwritten by lowering of arguments in case of a tail call.
2267   if (Flags.isByVal()) {
2268     unsigned Bytes = Flags.getByValSize();
2269     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2270     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2271     return DAG.getFrameIndex(FI, getPointerTy());
2272   } else {
2273     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2274                                     VA.getLocMemOffset(), isImmutable);
2275     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2276     SDValue Val =  DAG.getLoad(ValVT, dl, Chain, FIN,
2277                                MachinePointerInfo::getFixedStack(FI),
2278                                false, false, false, 0);
2279     return ExtendedInMem ?
2280       DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val) : Val;
2281   }
2282 }
2283
2284 // FIXME: Get this from tablegen.
2285 static ArrayRef<MCPhysReg> get64BitArgumentGPRs(CallingConv::ID CallConv,
2286                                                 const X86Subtarget *Subtarget) {
2287   assert(Subtarget->is64Bit());
2288
2289   if (Subtarget->isCallingConvWin64(CallConv)) {
2290     static const MCPhysReg GPR64ArgRegsWin64[] = {
2291       X86::RCX, X86::RDX, X86::R8,  X86::R9
2292     };
2293     return makeArrayRef(std::begin(GPR64ArgRegsWin64), std::end(GPR64ArgRegsWin64));
2294   }
2295
2296   static const MCPhysReg GPR64ArgRegs64Bit[] = {
2297     X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2298   };
2299   return makeArrayRef(std::begin(GPR64ArgRegs64Bit), std::end(GPR64ArgRegs64Bit));
2300 }
2301
2302 // FIXME: Get this from tablegen.
2303 static ArrayRef<MCPhysReg> get64BitArgumentXMMs(MachineFunction &MF,
2304                                                 CallingConv::ID CallConv,
2305                                                 const X86Subtarget *Subtarget) {
2306   assert(Subtarget->is64Bit());
2307   if (Subtarget->isCallingConvWin64(CallConv)) {
2308     // The XMM registers which might contain var arg parameters are shadowed
2309     // in their paired GPR.  So we only need to save the GPR to their home
2310     // slots.
2311     // TODO: __vectorcall will change this.
2312     return None;
2313   }
2314
2315   const Function *Fn = MF.getFunction();
2316   bool NoImplicitFloatOps = Fn->hasFnAttribute(Attribute::NoImplicitFloat);
2317   bool isSoftFloat = Subtarget->useSoftFloat();
2318   assert(!(isSoftFloat && NoImplicitFloatOps) &&
2319          "SSE register cannot be used when SSE is disabled!");
2320   if (isSoftFloat || NoImplicitFloatOps || !Subtarget->hasSSE1())
2321     // Kernel mode asks for SSE to be disabled, so there are no XMM argument
2322     // registers.
2323     return None;
2324
2325   static const MCPhysReg XMMArgRegs64Bit[] = {
2326     X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2327     X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2328   };
2329   return makeArrayRef(std::begin(XMMArgRegs64Bit), std::end(XMMArgRegs64Bit));
2330 }
2331
2332 SDValue
2333 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2334                                         CallingConv::ID CallConv,
2335                                         bool isVarArg,
2336                                       const SmallVectorImpl<ISD::InputArg> &Ins,
2337                                         SDLoc dl,
2338                                         SelectionDAG &DAG,
2339                                         SmallVectorImpl<SDValue> &InVals)
2340                                           const {
2341   MachineFunction &MF = DAG.getMachineFunction();
2342   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2343   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
2344
2345   const Function* Fn = MF.getFunction();
2346   if (Fn->hasExternalLinkage() &&
2347       Subtarget->isTargetCygMing() &&
2348       Fn->getName() == "main")
2349     FuncInfo->setForceFramePointer(true);
2350
2351   MachineFrameInfo *MFI = MF.getFrameInfo();
2352   bool Is64Bit = Subtarget->is64Bit();
2353   bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2354
2355   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2356          "Var args not supported with calling convention fastcc, ghc or hipe");
2357
2358   // Assign locations to all of the incoming arguments.
2359   SmallVector<CCValAssign, 16> ArgLocs;
2360   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2361
2362   // Allocate shadow area for Win64
2363   if (IsWin64)
2364     CCInfo.AllocateStack(32, 8);
2365
2366   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2367
2368   unsigned LastVal = ~0U;
2369   SDValue ArgValue;
2370   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2371     CCValAssign &VA = ArgLocs[i];
2372     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2373     // places.
2374     assert(VA.getValNo() != LastVal &&
2375            "Don't support value assigned to multiple locs yet");
2376     (void)LastVal;
2377     LastVal = VA.getValNo();
2378
2379     if (VA.isRegLoc()) {
2380       EVT RegVT = VA.getLocVT();
2381       const TargetRegisterClass *RC;
2382       if (RegVT == MVT::i32)
2383         RC = &X86::GR32RegClass;
2384       else if (Is64Bit && RegVT == MVT::i64)
2385         RC = &X86::GR64RegClass;
2386       else if (RegVT == MVT::f32)
2387         RC = &X86::FR32RegClass;
2388       else if (RegVT == MVT::f64)
2389         RC = &X86::FR64RegClass;
2390       else if (RegVT.is512BitVector())
2391         RC = &X86::VR512RegClass;
2392       else if (RegVT.is256BitVector())
2393         RC = &X86::VR256RegClass;
2394       else if (RegVT.is128BitVector())
2395         RC = &X86::VR128RegClass;
2396       else if (RegVT == MVT::x86mmx)
2397         RC = &X86::VR64RegClass;
2398       else if (RegVT == MVT::i1)
2399         RC = &X86::VK1RegClass;
2400       else if (RegVT == MVT::v8i1)
2401         RC = &X86::VK8RegClass;
2402       else if (RegVT == MVT::v16i1)
2403         RC = &X86::VK16RegClass;
2404       else if (RegVT == MVT::v32i1)
2405         RC = &X86::VK32RegClass;
2406       else if (RegVT == MVT::v64i1)
2407         RC = &X86::VK64RegClass;
2408       else
2409         llvm_unreachable("Unknown argument type!");
2410
2411       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2412       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2413
2414       // If this is an 8 or 16-bit value, it is really passed promoted to 32
2415       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
2416       // right size.
2417       if (VA.getLocInfo() == CCValAssign::SExt)
2418         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2419                                DAG.getValueType(VA.getValVT()));
2420       else if (VA.getLocInfo() == CCValAssign::ZExt)
2421         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2422                                DAG.getValueType(VA.getValVT()));
2423       else if (VA.getLocInfo() == CCValAssign::BCvt)
2424         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2425
2426       if (VA.isExtInLoc()) {
2427         // Handle MMX values passed in XMM regs.
2428         if (RegVT.isVector() && VA.getValVT().getScalarType() != MVT::i1)
2429           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2430         else
2431           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2432       }
2433     } else {
2434       assert(VA.isMemLoc());
2435       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2436     }
2437
2438     // If value is passed via pointer - do a load.
2439     if (VA.getLocInfo() == CCValAssign::Indirect)
2440       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2441                              MachinePointerInfo(), false, false, false, 0);
2442
2443     InVals.push_back(ArgValue);
2444   }
2445
2446   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2447     // All x86 ABIs require that for returning structs by value we copy the
2448     // sret argument into %rax/%eax (depending on ABI) for the return. Save
2449     // the argument into a virtual register so that we can access it from the
2450     // return points.
2451     if (Ins[i].Flags.isSRet()) {
2452       unsigned Reg = FuncInfo->getSRetReturnReg();
2453       if (!Reg) {
2454         MVT PtrTy = getPointerTy();
2455         Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2456         FuncInfo->setSRetReturnReg(Reg);
2457       }
2458       SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2459       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2460       break;
2461     }
2462   }
2463
2464   unsigned StackSize = CCInfo.getNextStackOffset();
2465   // Align stack specially for tail calls.
2466   if (FuncIsMadeTailCallSafe(CallConv,
2467                              MF.getTarget().Options.GuaranteedTailCallOpt))
2468     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2469
2470   // If the function takes variable number of arguments, make a frame index for
2471   // the start of the first vararg value... for expansion of llvm.va_start. We
2472   // can skip this if there are no va_start calls.
2473   if (MFI->hasVAStart() &&
2474       (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2475                    CallConv != CallingConv::X86_ThisCall))) {
2476     FuncInfo->setVarArgsFrameIndex(
2477         MFI->CreateFixedObject(1, StackSize, true));
2478   }
2479
2480   MachineModuleInfo &MMI = MF.getMMI();
2481   const Function *WinEHParent = nullptr;
2482   if (IsWin64 && MMI.hasWinEHFuncInfo(Fn))
2483     WinEHParent = MMI.getWinEHParent(Fn);
2484   bool IsWinEHOutlined = WinEHParent && WinEHParent != Fn;
2485   bool IsWinEHParent = WinEHParent && WinEHParent == Fn;
2486
2487   // Figure out if XMM registers are in use.
2488   assert(!(Subtarget->useSoftFloat() &&
2489            Fn->hasFnAttribute(Attribute::NoImplicitFloat)) &&
2490          "SSE register cannot be used when SSE is disabled!");
2491
2492   // 64-bit calling conventions support varargs and register parameters, so we
2493   // have to do extra work to spill them in the prologue.
2494   if (Is64Bit && isVarArg && MFI->hasVAStart()) {
2495     // Find the first unallocated argument registers.
2496     ArrayRef<MCPhysReg> ArgGPRs = get64BitArgumentGPRs(CallConv, Subtarget);
2497     ArrayRef<MCPhysReg> ArgXMMs = get64BitArgumentXMMs(MF, CallConv, Subtarget);
2498     unsigned NumIntRegs = CCInfo.getFirstUnallocated(ArgGPRs);
2499     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(ArgXMMs);
2500     assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2501            "SSE register cannot be used when SSE is disabled!");
2502
2503     // Gather all the live in physical registers.
2504     SmallVector<SDValue, 6> LiveGPRs;
2505     SmallVector<SDValue, 8> LiveXMMRegs;
2506     SDValue ALVal;
2507     for (MCPhysReg Reg : ArgGPRs.slice(NumIntRegs)) {
2508       unsigned GPR = MF.addLiveIn(Reg, &X86::GR64RegClass);
2509       LiveGPRs.push_back(
2510           DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64));
2511     }
2512     if (!ArgXMMs.empty()) {
2513       unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2514       ALVal = DAG.getCopyFromReg(Chain, dl, AL, MVT::i8);
2515       for (MCPhysReg Reg : ArgXMMs.slice(NumXMMRegs)) {
2516         unsigned XMMReg = MF.addLiveIn(Reg, &X86::VR128RegClass);
2517         LiveXMMRegs.push_back(
2518             DAG.getCopyFromReg(Chain, dl, XMMReg, MVT::v4f32));
2519       }
2520     }
2521
2522     if (IsWin64) {
2523       // Get to the caller-allocated home save location.  Add 8 to account
2524       // for the return address.
2525       int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2526       FuncInfo->setRegSaveFrameIndex(
2527           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2528       // Fixup to set vararg frame on shadow area (4 x i64).
2529       if (NumIntRegs < 4)
2530         FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2531     } else {
2532       // For X86-64, if there are vararg parameters that are passed via
2533       // registers, then we must store them to their spots on the stack so
2534       // they may be loaded by deferencing the result of va_next.
2535       FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2536       FuncInfo->setVarArgsFPOffset(ArgGPRs.size() * 8 + NumXMMRegs * 16);
2537       FuncInfo->setRegSaveFrameIndex(MFI->CreateStackObject(
2538           ArgGPRs.size() * 8 + ArgXMMs.size() * 16, 16, false));
2539     }
2540
2541     // Store the integer parameter registers.
2542     SmallVector<SDValue, 8> MemOps;
2543     SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2544                                       getPointerTy());
2545     unsigned Offset = FuncInfo->getVarArgsGPOffset();
2546     for (SDValue Val : LiveGPRs) {
2547       SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2548                                 DAG.getIntPtrConstant(Offset, dl));
2549       SDValue Store =
2550         DAG.getStore(Val.getValue(1), dl, Val, FIN,
2551                      MachinePointerInfo::getFixedStack(
2552                        FuncInfo->getRegSaveFrameIndex(), Offset),
2553                      false, false, 0);
2554       MemOps.push_back(Store);
2555       Offset += 8;
2556     }
2557
2558     if (!ArgXMMs.empty() && NumXMMRegs != ArgXMMs.size()) {
2559       // Now store the XMM (fp + vector) parameter registers.
2560       SmallVector<SDValue, 12> SaveXMMOps;
2561       SaveXMMOps.push_back(Chain);
2562       SaveXMMOps.push_back(ALVal);
2563       SaveXMMOps.push_back(DAG.getIntPtrConstant(
2564                              FuncInfo->getRegSaveFrameIndex(), dl));
2565       SaveXMMOps.push_back(DAG.getIntPtrConstant(
2566                              FuncInfo->getVarArgsFPOffset(), dl));
2567       SaveXMMOps.insert(SaveXMMOps.end(), LiveXMMRegs.begin(),
2568                         LiveXMMRegs.end());
2569       MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2570                                    MVT::Other, SaveXMMOps));
2571     }
2572
2573     if (!MemOps.empty())
2574       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2575   } else if (IsWinEHOutlined) {
2576     // Get to the caller-allocated home save location.  Add 8 to account
2577     // for the return address.
2578     int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2579     FuncInfo->setRegSaveFrameIndex(MFI->CreateFixedObject(
2580         /*Size=*/1, /*SPOffset=*/HomeOffset + 8, /*Immutable=*/false));
2581
2582     MMI.getWinEHFuncInfo(Fn)
2583         .CatchHandlerParentFrameObjIdx[const_cast<Function *>(Fn)] =
2584         FuncInfo->getRegSaveFrameIndex();
2585
2586     // Store the second integer parameter (rdx) into rsp+16 relative to the
2587     // stack pointer at the entry of the function.
2588     SDValue RSFIN =
2589         DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(), getPointerTy());
2590     unsigned GPR = MF.addLiveIn(X86::RDX, &X86::GR64RegClass);
2591     SDValue Val = DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64);
2592     Chain = DAG.getStore(
2593         Val.getValue(1), dl, Val, RSFIN,
2594         MachinePointerInfo::getFixedStack(FuncInfo->getRegSaveFrameIndex()),
2595         /*isVolatile=*/true, /*isNonTemporal=*/false, /*Alignment=*/0);
2596   }
2597
2598   if (isVarArg && MFI->hasMustTailInVarArgFunc()) {
2599     // Find the largest legal vector type.
2600     MVT VecVT = MVT::Other;
2601     // FIXME: Only some x86_32 calling conventions support AVX512.
2602     if (Subtarget->hasAVX512() &&
2603         (Is64Bit || (CallConv == CallingConv::X86_VectorCall ||
2604                      CallConv == CallingConv::Intel_OCL_BI)))
2605       VecVT = MVT::v16f32;
2606     else if (Subtarget->hasAVX())
2607       VecVT = MVT::v8f32;
2608     else if (Subtarget->hasSSE2())
2609       VecVT = MVT::v4f32;
2610
2611     // We forward some GPRs and some vector types.
2612     SmallVector<MVT, 2> RegParmTypes;
2613     MVT IntVT = Is64Bit ? MVT::i64 : MVT::i32;
2614     RegParmTypes.push_back(IntVT);
2615     if (VecVT != MVT::Other)
2616       RegParmTypes.push_back(VecVT);
2617
2618     // Compute the set of forwarded registers. The rest are scratch.
2619     SmallVectorImpl<ForwardedRegister> &Forwards =
2620         FuncInfo->getForwardedMustTailRegParms();
2621     CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes, CC_X86);
2622
2623     // Conservatively forward AL on x86_64, since it might be used for varargs.
2624     if (Is64Bit && !CCInfo.isAllocated(X86::AL)) {
2625       unsigned ALVReg = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2626       Forwards.push_back(ForwardedRegister(ALVReg, X86::AL, MVT::i8));
2627     }
2628
2629     // Copy all forwards from physical to virtual registers.
2630     for (ForwardedRegister &F : Forwards) {
2631       // FIXME: Can we use a less constrained schedule?
2632       SDValue RegVal = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
2633       F.VReg = MF.getRegInfo().createVirtualRegister(getRegClassFor(F.VT));
2634       Chain = DAG.getCopyToReg(Chain, dl, F.VReg, RegVal);
2635     }
2636   }
2637
2638   // Some CCs need callee pop.
2639   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2640                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2641     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2642   } else {
2643     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2644     // If this is an sret function, the return should pop the hidden pointer.
2645     if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2646         !Subtarget->getTargetTriple().isOSMSVCRT() &&
2647         argsAreStructReturn(Ins) == StackStructReturn)
2648       FuncInfo->setBytesToPopOnReturn(4);
2649   }
2650
2651   if (!Is64Bit) {
2652     // RegSaveFrameIndex is X86-64 only.
2653     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2654     if (CallConv == CallingConv::X86_FastCall ||
2655         CallConv == CallingConv::X86_ThisCall)
2656       // fastcc functions can't have varargs.
2657       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2658   }
2659
2660   FuncInfo->setArgumentStackSize(StackSize);
2661
2662   if (IsWinEHParent) {
2663     int UnwindHelpFI = MFI->CreateStackObject(8, 8, /*isSS=*/false);
2664     SDValue StackSlot = DAG.getFrameIndex(UnwindHelpFI, MVT::i64);
2665     MMI.getWinEHFuncInfo(MF.getFunction()).UnwindHelpFrameIdx = UnwindHelpFI;
2666     SDValue Neg2 = DAG.getConstant(-2, dl, MVT::i64);
2667     Chain = DAG.getStore(Chain, dl, Neg2, StackSlot,
2668                          MachinePointerInfo::getFixedStack(UnwindHelpFI),
2669                          /*isVolatile=*/true,
2670                          /*isNonTemporal=*/false, /*Alignment=*/0);
2671   }
2672
2673   return Chain;
2674 }
2675
2676 SDValue
2677 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2678                                     SDValue StackPtr, SDValue Arg,
2679                                     SDLoc dl, SelectionDAG &DAG,
2680                                     const CCValAssign &VA,
2681                                     ISD::ArgFlagsTy Flags) const {
2682   unsigned LocMemOffset = VA.getLocMemOffset();
2683   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
2684   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2685   if (Flags.isByVal())
2686     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2687
2688   return DAG.getStore(Chain, dl, Arg, PtrOff,
2689                       MachinePointerInfo::getStack(LocMemOffset),
2690                       false, false, 0);
2691 }
2692
2693 /// Emit a load of return address if tail call
2694 /// optimization is performed and it is required.
2695 SDValue
2696 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2697                                            SDValue &OutRetAddr, SDValue Chain,
2698                                            bool IsTailCall, bool Is64Bit,
2699                                            int FPDiff, SDLoc dl) const {
2700   // Adjust the Return address stack slot.
2701   EVT VT = getPointerTy();
2702   OutRetAddr = getReturnAddressFrameIndex(DAG);
2703
2704   // Load the "old" Return address.
2705   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2706                            false, false, false, 0);
2707   return SDValue(OutRetAddr.getNode(), 1);
2708 }
2709
2710 /// Emit a store of the return address if tail call
2711 /// optimization is performed and it is required (FPDiff!=0).
2712 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2713                                         SDValue Chain, SDValue RetAddrFrIdx,
2714                                         EVT PtrVT, unsigned SlotSize,
2715                                         int FPDiff, SDLoc dl) {
2716   // Store the return address to the appropriate stack slot.
2717   if (!FPDiff) return Chain;
2718   // Calculate the new stack slot for the return address.
2719   int NewReturnAddrFI =
2720     MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2721                                          false);
2722   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2723   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2724                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2725                        false, false, 0);
2726   return Chain;
2727 }
2728
2729 SDValue
2730 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2731                              SmallVectorImpl<SDValue> &InVals) const {
2732   SelectionDAG &DAG                     = CLI.DAG;
2733   SDLoc &dl                             = CLI.DL;
2734   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2735   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
2736   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
2737   SDValue Chain                         = CLI.Chain;
2738   SDValue Callee                        = CLI.Callee;
2739   CallingConv::ID CallConv              = CLI.CallConv;
2740   bool &isTailCall                      = CLI.IsTailCall;
2741   bool isVarArg                         = CLI.IsVarArg;
2742
2743   MachineFunction &MF = DAG.getMachineFunction();
2744   bool Is64Bit        = Subtarget->is64Bit();
2745   bool IsWin64        = Subtarget->isCallingConvWin64(CallConv);
2746   StructReturnType SR = callIsStructReturn(Outs);
2747   bool IsSibcall      = false;
2748   X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2749
2750   if (MF.getTarget().Options.DisableTailCalls)
2751     isTailCall = false;
2752
2753   bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
2754   if (IsMustTail) {
2755     // Force this to be a tail call.  The verifier rules are enough to ensure
2756     // that we can lower this successfully without moving the return address
2757     // around.
2758     isTailCall = true;
2759   } else if (isTailCall) {
2760     // Check if it's really possible to do a tail call.
2761     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2762                     isVarArg, SR != NotStructReturn,
2763                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2764                     Outs, OutVals, Ins, DAG);
2765
2766     // Sibcalls are automatically detected tailcalls which do not require
2767     // ABI changes.
2768     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2769       IsSibcall = true;
2770
2771     if (isTailCall)
2772       ++NumTailCalls;
2773   }
2774
2775   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2776          "Var args not supported with calling convention fastcc, ghc or hipe");
2777
2778   // Analyze operands of the call, assigning locations to each operand.
2779   SmallVector<CCValAssign, 16> ArgLocs;
2780   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2781
2782   // Allocate shadow area for Win64
2783   if (IsWin64)
2784     CCInfo.AllocateStack(32, 8);
2785
2786   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2787
2788   // Get a count of how many bytes are to be pushed on the stack.
2789   unsigned NumBytes = CCInfo.getNextStackOffset();
2790   if (IsSibcall)
2791     // This is a sibcall. The memory operands are available in caller's
2792     // own caller's stack.
2793     NumBytes = 0;
2794   else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
2795            IsTailCallConvention(CallConv))
2796     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2797
2798   int FPDiff = 0;
2799   if (isTailCall && !IsSibcall && !IsMustTail) {
2800     // Lower arguments at fp - stackoffset + fpdiff.
2801     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2802
2803     FPDiff = NumBytesCallerPushed - NumBytes;
2804
2805     // Set the delta of movement of the returnaddr stackslot.
2806     // But only set if delta is greater than previous delta.
2807     if (FPDiff < X86Info->getTCReturnAddrDelta())
2808       X86Info->setTCReturnAddrDelta(FPDiff);
2809   }
2810
2811   unsigned NumBytesToPush = NumBytes;
2812   unsigned NumBytesToPop = NumBytes;
2813
2814   // If we have an inalloca argument, all stack space has already been allocated
2815   // for us and be right at the top of the stack.  We don't support multiple
2816   // arguments passed in memory when using inalloca.
2817   if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
2818     NumBytesToPush = 0;
2819     if (!ArgLocs.back().isMemLoc())
2820       report_fatal_error("cannot use inalloca attribute on a register "
2821                          "parameter");
2822     if (ArgLocs.back().getLocMemOffset() != 0)
2823       report_fatal_error("any parameter with the inalloca attribute must be "
2824                          "the only memory argument");
2825   }
2826
2827   if (!IsSibcall)
2828     Chain = DAG.getCALLSEQ_START(
2829         Chain, DAG.getIntPtrConstant(NumBytesToPush, dl, true), dl);
2830
2831   SDValue RetAddrFrIdx;
2832   // Load return address for tail calls.
2833   if (isTailCall && FPDiff)
2834     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2835                                     Is64Bit, FPDiff, dl);
2836
2837   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2838   SmallVector<SDValue, 8> MemOpChains;
2839   SDValue StackPtr;
2840
2841   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2842   // of tail call optimization arguments are handle later.
2843   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
2844   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2845     // Skip inalloca arguments, they have already been written.
2846     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2847     if (Flags.isInAlloca())
2848       continue;
2849
2850     CCValAssign &VA = ArgLocs[i];
2851     EVT RegVT = VA.getLocVT();
2852     SDValue Arg = OutVals[i];
2853     bool isByVal = Flags.isByVal();
2854
2855     // Promote the value if needed.
2856     switch (VA.getLocInfo()) {
2857     default: llvm_unreachable("Unknown loc info!");
2858     case CCValAssign::Full: break;
2859     case CCValAssign::SExt:
2860       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2861       break;
2862     case CCValAssign::ZExt:
2863       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2864       break;
2865     case CCValAssign::AExt:
2866       if (Arg.getValueType().isVector() &&
2867           Arg.getValueType().getScalarType() == MVT::i1)
2868         Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2869       else if (RegVT.is128BitVector()) {
2870         // Special case: passing MMX values in XMM registers.
2871         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2872         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2873         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2874       } else
2875         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2876       break;
2877     case CCValAssign::BCvt:
2878       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2879       break;
2880     case CCValAssign::Indirect: {
2881       // Store the argument.
2882       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2883       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2884       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2885                            MachinePointerInfo::getFixedStack(FI),
2886                            false, false, 0);
2887       Arg = SpillSlot;
2888       break;
2889     }
2890     }
2891
2892     if (VA.isRegLoc()) {
2893       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2894       if (isVarArg && IsWin64) {
2895         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2896         // shadow reg if callee is a varargs function.
2897         unsigned ShadowReg = 0;
2898         switch (VA.getLocReg()) {
2899         case X86::XMM0: ShadowReg = X86::RCX; break;
2900         case X86::XMM1: ShadowReg = X86::RDX; break;
2901         case X86::XMM2: ShadowReg = X86::R8; break;
2902         case X86::XMM3: ShadowReg = X86::R9; break;
2903         }
2904         if (ShadowReg)
2905           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2906       }
2907     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2908       assert(VA.isMemLoc());
2909       if (!StackPtr.getNode())
2910         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2911                                       getPointerTy());
2912       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2913                                              dl, DAG, VA, Flags));
2914     }
2915   }
2916
2917   if (!MemOpChains.empty())
2918     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
2919
2920   if (Subtarget->isPICStyleGOT()) {
2921     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2922     // GOT pointer.
2923     if (!isTailCall) {
2924       RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2925                DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
2926     } else {
2927       // If we are tail calling and generating PIC/GOT style code load the
2928       // address of the callee into ECX. The value in ecx is used as target of
2929       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2930       // for tail calls on PIC/GOT architectures. Normally we would just put the
2931       // address of GOT into ebx and then call target@PLT. But for tail calls
2932       // ebx would be restored (since ebx is callee saved) before jumping to the
2933       // target@PLT.
2934
2935       // Note: The actual moving to ECX is done further down.
2936       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2937       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2938           !G->getGlobal()->hasProtectedVisibility())
2939         Callee = LowerGlobalAddress(Callee, DAG);
2940       else if (isa<ExternalSymbolSDNode>(Callee))
2941         Callee = LowerExternalSymbol(Callee, DAG);
2942     }
2943   }
2944
2945   if (Is64Bit && isVarArg && !IsWin64 && !IsMustTail) {
2946     // From AMD64 ABI document:
2947     // For calls that may call functions that use varargs or stdargs
2948     // (prototype-less calls or calls to functions containing ellipsis (...) in
2949     // the declaration) %al is used as hidden argument to specify the number
2950     // of SSE registers used. The contents of %al do not need to match exactly
2951     // the number of registers, but must be an ubound on the number of SSE
2952     // registers used and is in the range 0 - 8 inclusive.
2953
2954     // Count the number of XMM registers allocated.
2955     static const MCPhysReg XMMArgRegs[] = {
2956       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2957       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2958     };
2959     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs);
2960     assert((Subtarget->hasSSE1() || !NumXMMRegs)
2961            && "SSE registers cannot be used when SSE is disabled");
2962
2963     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2964                                         DAG.getConstant(NumXMMRegs, dl,
2965                                                         MVT::i8)));
2966   }
2967
2968   if (isVarArg && IsMustTail) {
2969     const auto &Forwards = X86Info->getForwardedMustTailRegParms();
2970     for (const auto &F : Forwards) {
2971       SDValue Val = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
2972       RegsToPass.push_back(std::make_pair(unsigned(F.PReg), Val));
2973     }
2974   }
2975
2976   // For tail calls lower the arguments to the 'real' stack slots.  Sibcalls
2977   // don't need this because the eligibility check rejects calls that require
2978   // shuffling arguments passed in memory.
2979   if (!IsSibcall && isTailCall) {
2980     // Force all the incoming stack arguments to be loaded from the stack
2981     // before any new outgoing arguments are stored to the stack, because the
2982     // outgoing stack slots may alias the incoming argument stack slots, and
2983     // the alias isn't otherwise explicit. This is slightly more conservative
2984     // than necessary, because it means that each store effectively depends
2985     // on every argument instead of just those arguments it would clobber.
2986     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2987
2988     SmallVector<SDValue, 8> MemOpChains2;
2989     SDValue FIN;
2990     int FI = 0;
2991     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2992       CCValAssign &VA = ArgLocs[i];
2993       if (VA.isRegLoc())
2994         continue;
2995       assert(VA.isMemLoc());
2996       SDValue Arg = OutVals[i];
2997       ISD::ArgFlagsTy Flags = Outs[i].Flags;
2998       // Skip inalloca arguments.  They don't require any work.
2999       if (Flags.isInAlloca())
3000         continue;
3001       // Create frame index.
3002       int32_t Offset = VA.getLocMemOffset()+FPDiff;
3003       uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
3004       FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3005       FIN = DAG.getFrameIndex(FI, getPointerTy());
3006
3007       if (Flags.isByVal()) {
3008         // Copy relative to framepointer.
3009         SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset(), dl);
3010         if (!StackPtr.getNode())
3011           StackPtr = DAG.getCopyFromReg(Chain, dl,
3012                                         RegInfo->getStackRegister(),
3013                                         getPointerTy());
3014         Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
3015
3016         MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
3017                                                          ArgChain,
3018                                                          Flags, DAG, dl));
3019       } else {
3020         // Store relative to framepointer.
3021         MemOpChains2.push_back(
3022           DAG.getStore(ArgChain, dl, Arg, FIN,
3023                        MachinePointerInfo::getFixedStack(FI),
3024                        false, false, 0));
3025       }
3026     }
3027
3028     if (!MemOpChains2.empty())
3029       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
3030
3031     // Store the return address to the appropriate stack slot.
3032     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
3033                                      getPointerTy(), RegInfo->getSlotSize(),
3034                                      FPDiff, dl);
3035   }
3036
3037   // Build a sequence of copy-to-reg nodes chained together with token chain
3038   // and flag operands which copy the outgoing args into registers.
3039   SDValue InFlag;
3040   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
3041     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
3042                              RegsToPass[i].second, InFlag);
3043     InFlag = Chain.getValue(1);
3044   }
3045
3046   if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
3047     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
3048     // In the 64-bit large code model, we have to make all calls
3049     // through a register, since the call instruction's 32-bit
3050     // pc-relative offset may not be large enough to hold the whole
3051     // address.
3052   } else if (Callee->getOpcode() == ISD::GlobalAddress) {
3053     // If the callee is a GlobalAddress node (quite common, every direct call
3054     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
3055     // it.
3056     GlobalAddressSDNode* G = cast<GlobalAddressSDNode>(Callee);
3057
3058     // We should use extra load for direct calls to dllimported functions in
3059     // non-JIT mode.
3060     const GlobalValue *GV = G->getGlobal();
3061     if (!GV->hasDLLImportStorageClass()) {
3062       unsigned char OpFlags = 0;
3063       bool ExtraLoad = false;
3064       unsigned WrapperKind = ISD::DELETED_NODE;
3065
3066       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
3067       // external symbols most go through the PLT in PIC mode.  If the symbol
3068       // has hidden or protected visibility, or if it is static or local, then
3069       // we don't need to use the PLT - we can directly call it.
3070       if (Subtarget->isTargetELF() &&
3071           DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
3072           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
3073         OpFlags = X86II::MO_PLT;
3074       } else if (Subtarget->isPICStyleStubAny() &&
3075                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
3076                  (!Subtarget->getTargetTriple().isMacOSX() ||
3077                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3078         // PC-relative references to external symbols should go through $stub,
3079         // unless we're building with the leopard linker or later, which
3080         // automatically synthesizes these stubs.
3081         OpFlags = X86II::MO_DARWIN_STUB;
3082       } else if (Subtarget->isPICStyleRIPRel() && isa<Function>(GV) &&
3083                  cast<Function>(GV)->hasFnAttribute(Attribute::NonLazyBind)) {
3084         // If the function is marked as non-lazy, generate an indirect call
3085         // which loads from the GOT directly. This avoids runtime overhead
3086         // at the cost of eager binding (and one extra byte of encoding).
3087         OpFlags = X86II::MO_GOTPCREL;
3088         WrapperKind = X86ISD::WrapperRIP;
3089         ExtraLoad = true;
3090       }
3091
3092       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
3093                                           G->getOffset(), OpFlags);
3094
3095       // Add a wrapper if needed.
3096       if (WrapperKind != ISD::DELETED_NODE)
3097         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
3098       // Add extra indirection if needed.
3099       if (ExtraLoad)
3100         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
3101                              MachinePointerInfo::getGOT(),
3102                              false, false, false, 0);
3103     }
3104   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3105     unsigned char OpFlags = 0;
3106
3107     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
3108     // external symbols should go through the PLT.
3109     if (Subtarget->isTargetELF() &&
3110         DAG.getTarget().getRelocationModel() == Reloc::PIC_) {
3111       OpFlags = X86II::MO_PLT;
3112     } else if (Subtarget->isPICStyleStubAny() &&
3113                (!Subtarget->getTargetTriple().isMacOSX() ||
3114                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3115       // PC-relative references to external symbols should go through $stub,
3116       // unless we're building with the leopard linker or later, which
3117       // automatically synthesizes these stubs.
3118       OpFlags = X86II::MO_DARWIN_STUB;
3119     }
3120
3121     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
3122                                          OpFlags);
3123   } else if (Subtarget->isTarget64BitILP32() &&
3124              Callee->getValueType(0) == MVT::i32) {
3125     // Zero-extend the 32-bit Callee address into a 64-bit according to x32 ABI
3126     Callee = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, Callee);
3127   }
3128
3129   // Returns a chain & a flag for retval copy to use.
3130   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3131   SmallVector<SDValue, 8> Ops;
3132
3133   if (!IsSibcall && isTailCall) {
3134     Chain = DAG.getCALLSEQ_END(Chain,
3135                                DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3136                                DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
3137     InFlag = Chain.getValue(1);
3138   }
3139
3140   Ops.push_back(Chain);
3141   Ops.push_back(Callee);
3142
3143   if (isTailCall)
3144     Ops.push_back(DAG.getConstant(FPDiff, dl, MVT::i32));
3145
3146   // Add argument registers to the end of the list so that they are known live
3147   // into the call.
3148   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3149     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3150                                   RegsToPass[i].second.getValueType()));
3151
3152   // Add a register mask operand representing the call-preserved registers.
3153   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
3154   const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
3155   assert(Mask && "Missing call preserved mask for calling convention");
3156   Ops.push_back(DAG.getRegisterMask(Mask));
3157
3158   if (InFlag.getNode())
3159     Ops.push_back(InFlag);
3160
3161   if (isTailCall) {
3162     // We used to do:
3163     //// If this is the first return lowered for this function, add the regs
3164     //// to the liveout set for the function.
3165     // This isn't right, although it's probably harmless on x86; liveouts
3166     // should be computed from returns not tail calls.  Consider a void
3167     // function making a tail call to a function returning int.
3168     MF.getFrameInfo()->setHasTailCall();
3169     return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
3170   }
3171
3172   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
3173   InFlag = Chain.getValue(1);
3174
3175   // Create the CALLSEQ_END node.
3176   unsigned NumBytesForCalleeToPop;
3177   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
3178                        DAG.getTarget().Options.GuaranteedTailCallOpt))
3179     NumBytesForCalleeToPop = NumBytes;    // Callee pops everything
3180   else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
3181            !Subtarget->getTargetTriple().isOSMSVCRT() &&
3182            SR == StackStructReturn)
3183     // If this is a call to a struct-return function, the callee
3184     // pops the hidden struct pointer, so we have to push it back.
3185     // This is common for Darwin/X86, Linux & Mingw32 targets.
3186     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
3187     NumBytesForCalleeToPop = 4;
3188   else
3189     NumBytesForCalleeToPop = 0;  // Callee pops nothing.
3190
3191   // Returns a flag for retval copy to use.
3192   if (!IsSibcall) {
3193     Chain = DAG.getCALLSEQ_END(Chain,
3194                                DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3195                                DAG.getIntPtrConstant(NumBytesForCalleeToPop, dl,
3196                                                      true),
3197                                InFlag, dl);
3198     InFlag = Chain.getValue(1);
3199   }
3200
3201   // Handle result values, copying them out of physregs into vregs that we
3202   // return.
3203   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3204                          Ins, dl, DAG, InVals);
3205 }
3206
3207 //===----------------------------------------------------------------------===//
3208 //                Fast Calling Convention (tail call) implementation
3209 //===----------------------------------------------------------------------===//
3210
3211 //  Like std call, callee cleans arguments, convention except that ECX is
3212 //  reserved for storing the tail called function address. Only 2 registers are
3213 //  free for argument passing (inreg). Tail call optimization is performed
3214 //  provided:
3215 //                * tailcallopt is enabled
3216 //                * caller/callee are fastcc
3217 //  On X86_64 architecture with GOT-style position independent code only local
3218 //  (within module) calls are supported at the moment.
3219 //  To keep the stack aligned according to platform abi the function
3220 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
3221 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3222 //  If a tail called function callee has more arguments than the caller the
3223 //  caller needs to make sure that there is room to move the RETADDR to. This is
3224 //  achieved by reserving an area the size of the argument delta right after the
3225 //  original RETADDR, but before the saved framepointer or the spilled registers
3226 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3227 //  stack layout:
3228 //    arg1
3229 //    arg2
3230 //    RETADDR
3231 //    [ new RETADDR
3232 //      move area ]
3233 //    (possible EBP)
3234 //    ESI
3235 //    EDI
3236 //    local1 ..
3237
3238 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
3239 /// for a 16 byte align requirement.
3240 unsigned
3241 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3242                                                SelectionDAG& DAG) const {
3243   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3244   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
3245   unsigned StackAlignment = TFI.getStackAlignment();
3246   uint64_t AlignMask = StackAlignment - 1;
3247   int64_t Offset = StackSize;
3248   unsigned SlotSize = RegInfo->getSlotSize();
3249   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3250     // Number smaller than 12 so just add the difference.
3251     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3252   } else {
3253     // Mask out lower bits, add stackalignment once plus the 12 bytes.
3254     Offset = ((~AlignMask) & Offset) + StackAlignment +
3255       (StackAlignment-SlotSize);
3256   }
3257   return Offset;
3258 }
3259
3260 /// MatchingStackOffset - Return true if the given stack call argument is
3261 /// already available in the same position (relatively) of the caller's
3262 /// incoming argument stack.
3263 static
3264 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3265                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3266                          const X86InstrInfo *TII) {
3267   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3268   int FI = INT_MAX;
3269   if (Arg.getOpcode() == ISD::CopyFromReg) {
3270     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3271     if (!TargetRegisterInfo::isVirtualRegister(VR))
3272       return false;
3273     MachineInstr *Def = MRI->getVRegDef(VR);
3274     if (!Def)
3275       return false;
3276     if (!Flags.isByVal()) {
3277       if (!TII->isLoadFromStackSlot(Def, FI))
3278         return false;
3279     } else {
3280       unsigned Opcode = Def->getOpcode();
3281       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r ||
3282            Opcode == X86::LEA64_32r) &&
3283           Def->getOperand(1).isFI()) {
3284         FI = Def->getOperand(1).getIndex();
3285         Bytes = Flags.getByValSize();
3286       } else
3287         return false;
3288     }
3289   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3290     if (Flags.isByVal())
3291       // ByVal argument is passed in as a pointer but it's now being
3292       // dereferenced. e.g.
3293       // define @foo(%struct.X* %A) {
3294       //   tail call @bar(%struct.X* byval %A)
3295       // }
3296       return false;
3297     SDValue Ptr = Ld->getBasePtr();
3298     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3299     if (!FINode)
3300       return false;
3301     FI = FINode->getIndex();
3302   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3303     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3304     FI = FINode->getIndex();
3305     Bytes = Flags.getByValSize();
3306   } else
3307     return false;
3308
3309   assert(FI != INT_MAX);
3310   if (!MFI->isFixedObjectIndex(FI))
3311     return false;
3312   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3313 }
3314
3315 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3316 /// for tail call optimization. Targets which want to do tail call
3317 /// optimization should implement this function.
3318 bool
3319 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3320                                                      CallingConv::ID CalleeCC,
3321                                                      bool isVarArg,
3322                                                      bool isCalleeStructRet,
3323                                                      bool isCallerStructRet,
3324                                                      Type *RetTy,
3325                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
3326                                     const SmallVectorImpl<SDValue> &OutVals,
3327                                     const SmallVectorImpl<ISD::InputArg> &Ins,
3328                                                      SelectionDAG &DAG) const {
3329   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3330     return false;
3331
3332   // If -tailcallopt is specified, make fastcc functions tail-callable.
3333   const MachineFunction &MF = DAG.getMachineFunction();
3334   const Function *CallerF = MF.getFunction();
3335
3336   // If the function return type is x86_fp80 and the callee return type is not,
3337   // then the FP_EXTEND of the call result is not a nop. It's not safe to
3338   // perform a tailcall optimization here.
3339   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3340     return false;
3341
3342   CallingConv::ID CallerCC = CallerF->getCallingConv();
3343   bool CCMatch = CallerCC == CalleeCC;
3344   bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3345   bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3346
3347   // Win64 functions have extra shadow space for argument homing. Don't do the
3348   // sibcall if the caller and callee have mismatched expectations for this
3349   // space.
3350   if (IsCalleeWin64 != IsCallerWin64)
3351     return false;
3352
3353   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3354     if (IsTailCallConvention(CalleeCC) && CCMatch)
3355       return true;
3356     return false;
3357   }
3358
3359   // Look for obvious safe cases to perform tail call optimization that do not
3360   // require ABI changes. This is what gcc calls sibcall.
3361
3362   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3363   // emit a special epilogue.
3364   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3365   if (RegInfo->needsStackRealignment(MF))
3366     return false;
3367
3368   // Also avoid sibcall optimization if either caller or callee uses struct
3369   // return semantics.
3370   if (isCalleeStructRet || isCallerStructRet)
3371     return false;
3372
3373   // An stdcall/thiscall caller is expected to clean up its arguments; the
3374   // callee isn't going to do that.
3375   // FIXME: this is more restrictive than needed. We could produce a tailcall
3376   // when the stack adjustment matches. For example, with a thiscall that takes
3377   // only one argument.
3378   if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3379                    CallerCC == CallingConv::X86_ThisCall))
3380     return false;
3381
3382   // Do not sibcall optimize vararg calls unless all arguments are passed via
3383   // registers.
3384   if (isVarArg && !Outs.empty()) {
3385
3386     // Optimizing for varargs on Win64 is unlikely to be safe without
3387     // additional testing.
3388     if (IsCalleeWin64 || IsCallerWin64)
3389       return false;
3390
3391     SmallVector<CCValAssign, 16> ArgLocs;
3392     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3393                    *DAG.getContext());
3394
3395     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3396     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3397       if (!ArgLocs[i].isRegLoc())
3398         return false;
3399   }
3400
3401   // If the call result is in ST0 / ST1, it needs to be popped off the x87
3402   // stack.  Therefore, if it's not used by the call it is not safe to optimize
3403   // this into a sibcall.
3404   bool Unused = false;
3405   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3406     if (!Ins[i].Used) {
3407       Unused = true;
3408       break;
3409     }
3410   }
3411   if (Unused) {
3412     SmallVector<CCValAssign, 16> RVLocs;
3413     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(), RVLocs,
3414                    *DAG.getContext());
3415     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3416     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3417       CCValAssign &VA = RVLocs[i];
3418       if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
3419         return false;
3420     }
3421   }
3422
3423   // If the calling conventions do not match, then we'd better make sure the
3424   // results are returned in the same way as what the caller expects.
3425   if (!CCMatch) {
3426     SmallVector<CCValAssign, 16> RVLocs1;
3427     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
3428                     *DAG.getContext());
3429     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3430
3431     SmallVector<CCValAssign, 16> RVLocs2;
3432     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
3433                     *DAG.getContext());
3434     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3435
3436     if (RVLocs1.size() != RVLocs2.size())
3437       return false;
3438     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3439       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3440         return false;
3441       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3442         return false;
3443       if (RVLocs1[i].isRegLoc()) {
3444         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3445           return false;
3446       } else {
3447         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3448           return false;
3449       }
3450     }
3451   }
3452
3453   // If the callee takes no arguments then go on to check the results of the
3454   // call.
3455   if (!Outs.empty()) {
3456     // Check if stack adjustment is needed. For now, do not do this if any
3457     // argument is passed on the stack.
3458     SmallVector<CCValAssign, 16> ArgLocs;
3459     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3460                    *DAG.getContext());
3461
3462     // Allocate shadow area for Win64
3463     if (IsCalleeWin64)
3464       CCInfo.AllocateStack(32, 8);
3465
3466     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3467     if (CCInfo.getNextStackOffset()) {
3468       MachineFunction &MF = DAG.getMachineFunction();
3469       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3470         return false;
3471
3472       // Check if the arguments are already laid out in the right way as
3473       // the caller's fixed stack objects.
3474       MachineFrameInfo *MFI = MF.getFrameInfo();
3475       const MachineRegisterInfo *MRI = &MF.getRegInfo();
3476       const X86InstrInfo *TII = Subtarget->getInstrInfo();
3477       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3478         CCValAssign &VA = ArgLocs[i];
3479         SDValue Arg = OutVals[i];
3480         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3481         if (VA.getLocInfo() == CCValAssign::Indirect)
3482           return false;
3483         if (!VA.isRegLoc()) {
3484           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3485                                    MFI, MRI, TII))
3486             return false;
3487         }
3488       }
3489     }
3490
3491     // If the tailcall address may be in a register, then make sure it's
3492     // possible to register allocate for it. In 32-bit, the call address can
3493     // only target EAX, EDX, or ECX since the tail call must be scheduled after
3494     // callee-saved registers are restored. These happen to be the same
3495     // registers used to pass 'inreg' arguments so watch out for those.
3496     if (!Subtarget->is64Bit() &&
3497         ((!isa<GlobalAddressSDNode>(Callee) &&
3498           !isa<ExternalSymbolSDNode>(Callee)) ||
3499          DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3500       unsigned NumInRegs = 0;
3501       // In PIC we need an extra register to formulate the address computation
3502       // for the callee.
3503       unsigned MaxInRegs =
3504         (DAG.getTarget().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3505
3506       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3507         CCValAssign &VA = ArgLocs[i];
3508         if (!VA.isRegLoc())
3509           continue;
3510         unsigned Reg = VA.getLocReg();
3511         switch (Reg) {
3512         default: break;
3513         case X86::EAX: case X86::EDX: case X86::ECX:
3514           if (++NumInRegs == MaxInRegs)
3515             return false;
3516           break;
3517         }
3518       }
3519     }
3520   }
3521
3522   return true;
3523 }
3524
3525 FastISel *
3526 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3527                                   const TargetLibraryInfo *libInfo) const {
3528   return X86::createFastISel(funcInfo, libInfo);
3529 }
3530
3531 //===----------------------------------------------------------------------===//
3532 //                           Other Lowering Hooks
3533 //===----------------------------------------------------------------------===//
3534
3535 static bool MayFoldLoad(SDValue Op) {
3536   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3537 }
3538
3539 static bool MayFoldIntoStore(SDValue Op) {
3540   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3541 }
3542
3543 static bool isTargetShuffle(unsigned Opcode) {
3544   switch(Opcode) {
3545   default: return false;
3546   case X86ISD::BLENDI:
3547   case X86ISD::PSHUFB:
3548   case X86ISD::PSHUFD:
3549   case X86ISD::PSHUFHW:
3550   case X86ISD::PSHUFLW:
3551   case X86ISD::SHUFP:
3552   case X86ISD::PALIGNR:
3553   case X86ISD::MOVLHPS:
3554   case X86ISD::MOVLHPD:
3555   case X86ISD::MOVHLPS:
3556   case X86ISD::MOVLPS:
3557   case X86ISD::MOVLPD:
3558   case X86ISD::MOVSHDUP:
3559   case X86ISD::MOVSLDUP:
3560   case X86ISD::MOVDDUP:
3561   case X86ISD::MOVSS:
3562   case X86ISD::MOVSD:
3563   case X86ISD::UNPCKL:
3564   case X86ISD::UNPCKH:
3565   case X86ISD::VPERMILPI:
3566   case X86ISD::VPERM2X128:
3567   case X86ISD::VPERMI:
3568     return true;
3569   }
3570 }
3571
3572 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3573                                     SDValue V1, unsigned TargetMask,
3574                                     SelectionDAG &DAG) {
3575   switch(Opc) {
3576   default: llvm_unreachable("Unknown x86 shuffle node");
3577   case X86ISD::PSHUFD:
3578   case X86ISD::PSHUFHW:
3579   case X86ISD::PSHUFLW:
3580   case X86ISD::VPERMILPI:
3581   case X86ISD::VPERMI:
3582     return DAG.getNode(Opc, dl, VT, V1,
3583                        DAG.getConstant(TargetMask, dl, MVT::i8));
3584   }
3585 }
3586
3587 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3588                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
3589   switch(Opc) {
3590   default: llvm_unreachable("Unknown x86 shuffle node");
3591   case X86ISD::MOVLHPS:
3592   case X86ISD::MOVLHPD:
3593   case X86ISD::MOVHLPS:
3594   case X86ISD::MOVLPS:
3595   case X86ISD::MOVLPD:
3596   case X86ISD::MOVSS:
3597   case X86ISD::MOVSD:
3598   case X86ISD::UNPCKL:
3599   case X86ISD::UNPCKH:
3600     return DAG.getNode(Opc, dl, VT, V1, V2);
3601   }
3602 }
3603
3604 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3605   MachineFunction &MF = DAG.getMachineFunction();
3606   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3607   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3608   int ReturnAddrIndex = FuncInfo->getRAIndex();
3609
3610   if (ReturnAddrIndex == 0) {
3611     // Set up a frame object for the return address.
3612     unsigned SlotSize = RegInfo->getSlotSize();
3613     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3614                                                            -(int64_t)SlotSize,
3615                                                            false);
3616     FuncInfo->setRAIndex(ReturnAddrIndex);
3617   }
3618
3619   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3620 }
3621
3622 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3623                                        bool hasSymbolicDisplacement) {
3624   // Offset should fit into 32 bit immediate field.
3625   if (!isInt<32>(Offset))
3626     return false;
3627
3628   // If we don't have a symbolic displacement - we don't have any extra
3629   // restrictions.
3630   if (!hasSymbolicDisplacement)
3631     return true;
3632
3633   // FIXME: Some tweaks might be needed for medium code model.
3634   if (M != CodeModel::Small && M != CodeModel::Kernel)
3635     return false;
3636
3637   // For small code model we assume that latest object is 16MB before end of 31
3638   // bits boundary. We may also accept pretty large negative constants knowing
3639   // that all objects are in the positive half of address space.
3640   if (M == CodeModel::Small && Offset < 16*1024*1024)
3641     return true;
3642
3643   // For kernel code model we know that all object resist in the negative half
3644   // of 32bits address space. We may not accept negative offsets, since they may
3645   // be just off and we may accept pretty large positive ones.
3646   if (M == CodeModel::Kernel && Offset >= 0)
3647     return true;
3648
3649   return false;
3650 }
3651
3652 /// isCalleePop - Determines whether the callee is required to pop its
3653 /// own arguments. Callee pop is necessary to support tail calls.
3654 bool X86::isCalleePop(CallingConv::ID CallingConv,
3655                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3656   switch (CallingConv) {
3657   default:
3658     return false;
3659   case CallingConv::X86_StdCall:
3660   case CallingConv::X86_FastCall:
3661   case CallingConv::X86_ThisCall:
3662     return !is64Bit;
3663   case CallingConv::Fast:
3664   case CallingConv::GHC:
3665   case CallingConv::HiPE:
3666     if (IsVarArg)
3667       return false;
3668     return TailCallOpt;
3669   }
3670 }
3671
3672 /// \brief Return true if the condition is an unsigned comparison operation.
3673 static bool isX86CCUnsigned(unsigned X86CC) {
3674   switch (X86CC) {
3675   default: llvm_unreachable("Invalid integer condition!");
3676   case X86::COND_E:     return true;
3677   case X86::COND_G:     return false;
3678   case X86::COND_GE:    return false;
3679   case X86::COND_L:     return false;
3680   case X86::COND_LE:    return false;
3681   case X86::COND_NE:    return true;
3682   case X86::COND_B:     return true;
3683   case X86::COND_A:     return true;
3684   case X86::COND_BE:    return true;
3685   case X86::COND_AE:    return true;
3686   }
3687   llvm_unreachable("covered switch fell through?!");
3688 }
3689
3690 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3691 /// specific condition code, returning the condition code and the LHS/RHS of the
3692 /// comparison to make.
3693 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, SDLoc DL, bool isFP,
3694                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3695   if (!isFP) {
3696     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3697       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3698         // X > -1   -> X == 0, jump !sign.
3699         RHS = DAG.getConstant(0, DL, RHS.getValueType());
3700         return X86::COND_NS;
3701       }
3702       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3703         // X < 0   -> X == 0, jump on sign.
3704         return X86::COND_S;
3705       }
3706       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3707         // X < 1   -> X <= 0
3708         RHS = DAG.getConstant(0, DL, RHS.getValueType());
3709         return X86::COND_LE;
3710       }
3711     }
3712
3713     switch (SetCCOpcode) {
3714     default: llvm_unreachable("Invalid integer condition!");
3715     case ISD::SETEQ:  return X86::COND_E;
3716     case ISD::SETGT:  return X86::COND_G;
3717     case ISD::SETGE:  return X86::COND_GE;
3718     case ISD::SETLT:  return X86::COND_L;
3719     case ISD::SETLE:  return X86::COND_LE;
3720     case ISD::SETNE:  return X86::COND_NE;
3721     case ISD::SETULT: return X86::COND_B;
3722     case ISD::SETUGT: return X86::COND_A;
3723     case ISD::SETULE: return X86::COND_BE;
3724     case ISD::SETUGE: return X86::COND_AE;
3725     }
3726   }
3727
3728   // First determine if it is required or is profitable to flip the operands.
3729
3730   // If LHS is a foldable load, but RHS is not, flip the condition.
3731   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3732       !ISD::isNON_EXTLoad(RHS.getNode())) {
3733     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3734     std::swap(LHS, RHS);
3735   }
3736
3737   switch (SetCCOpcode) {
3738   default: break;
3739   case ISD::SETOLT:
3740   case ISD::SETOLE:
3741   case ISD::SETUGT:
3742   case ISD::SETUGE:
3743     std::swap(LHS, RHS);
3744     break;
3745   }
3746
3747   // On a floating point condition, the flags are set as follows:
3748   // ZF  PF  CF   op
3749   //  0 | 0 | 0 | X > Y
3750   //  0 | 0 | 1 | X < Y
3751   //  1 | 0 | 0 | X == Y
3752   //  1 | 1 | 1 | unordered
3753   switch (SetCCOpcode) {
3754   default: llvm_unreachable("Condcode should be pre-legalized away");
3755   case ISD::SETUEQ:
3756   case ISD::SETEQ:   return X86::COND_E;
3757   case ISD::SETOLT:              // flipped
3758   case ISD::SETOGT:
3759   case ISD::SETGT:   return X86::COND_A;
3760   case ISD::SETOLE:              // flipped
3761   case ISD::SETOGE:
3762   case ISD::SETGE:   return X86::COND_AE;
3763   case ISD::SETUGT:              // flipped
3764   case ISD::SETULT:
3765   case ISD::SETLT:   return X86::COND_B;
3766   case ISD::SETUGE:              // flipped
3767   case ISD::SETULE:
3768   case ISD::SETLE:   return X86::COND_BE;
3769   case ISD::SETONE:
3770   case ISD::SETNE:   return X86::COND_NE;
3771   case ISD::SETUO:   return X86::COND_P;
3772   case ISD::SETO:    return X86::COND_NP;
3773   case ISD::SETOEQ:
3774   case ISD::SETUNE:  return X86::COND_INVALID;
3775   }
3776 }
3777
3778 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3779 /// code. Current x86 isa includes the following FP cmov instructions:
3780 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3781 static bool hasFPCMov(unsigned X86CC) {
3782   switch (X86CC) {
3783   default:
3784     return false;
3785   case X86::COND_B:
3786   case X86::COND_BE:
3787   case X86::COND_E:
3788   case X86::COND_P:
3789   case X86::COND_A:
3790   case X86::COND_AE:
3791   case X86::COND_NE:
3792   case X86::COND_NP:
3793     return true;
3794   }
3795 }
3796
3797 /// isFPImmLegal - Returns true if the target can instruction select the
3798 /// specified FP immediate natively. If false, the legalizer will
3799 /// materialize the FP immediate as a load from a constant pool.
3800 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3801   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3802     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3803       return true;
3804   }
3805   return false;
3806 }
3807
3808 bool X86TargetLowering::shouldReduceLoadWidth(SDNode *Load,
3809                                               ISD::LoadExtType ExtTy,
3810                                               EVT NewVT) const {
3811   // "ELF Handling for Thread-Local Storage" specifies that R_X86_64_GOTTPOFF
3812   // relocation target a movq or addq instruction: don't let the load shrink.
3813   SDValue BasePtr = cast<LoadSDNode>(Load)->getBasePtr();
3814   if (BasePtr.getOpcode() == X86ISD::WrapperRIP)
3815     if (const auto *GA = dyn_cast<GlobalAddressSDNode>(BasePtr.getOperand(0)))
3816       return GA->getTargetFlags() != X86II::MO_GOTTPOFF;
3817   return true;
3818 }
3819
3820 /// \brief Returns true if it is beneficial to convert a load of a constant
3821 /// to just the constant itself.
3822 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
3823                                                           Type *Ty) const {
3824   assert(Ty->isIntegerTy());
3825
3826   unsigned BitSize = Ty->getPrimitiveSizeInBits();
3827   if (BitSize == 0 || BitSize > 64)
3828     return false;
3829   return true;
3830 }
3831
3832 bool X86TargetLowering::isExtractSubvectorCheap(EVT ResVT,
3833                                                 unsigned Index) const {
3834   if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
3835     return false;
3836
3837   return (Index == 0 || Index == ResVT.getVectorNumElements());
3838 }
3839
3840 bool X86TargetLowering::isCheapToSpeculateCttz() const {
3841   // Speculate cttz only if we can directly use TZCNT.
3842   return Subtarget->hasBMI();
3843 }
3844
3845 bool X86TargetLowering::isCheapToSpeculateCtlz() const {
3846   // Speculate ctlz only if we can directly use LZCNT.
3847   return Subtarget->hasLZCNT();
3848 }
3849
3850 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3851 /// the specified range (L, H].
3852 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3853   return (Val < 0) || (Val >= Low && Val < Hi);
3854 }
3855
3856 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3857 /// specified value.
3858 static bool isUndefOrEqual(int Val, int CmpVal) {
3859   return (Val < 0 || Val == CmpVal);
3860 }
3861
3862 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3863 /// from position Pos and ending in Pos+Size, falls within the specified
3864 /// sequential range (Low, Low+Size]. or is undef.
3865 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3866                                        unsigned Pos, unsigned Size, int Low) {
3867   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3868     if (!isUndefOrEqual(Mask[i], Low))
3869       return false;
3870   return true;
3871 }
3872
3873 /// isVEXTRACTIndex - Return true if the specified
3874 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
3875 /// suitable for instruction that extract 128 or 256 bit vectors
3876 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
3877   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
3878   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3879     return false;
3880
3881   // The index should be aligned on a vecWidth-bit boundary.
3882   uint64_t Index =
3883     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3884
3885   MVT VT = N->getSimpleValueType(0);
3886   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
3887   bool Result = (Index * ElSize) % vecWidth == 0;
3888
3889   return Result;
3890 }
3891
3892 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
3893 /// operand specifies a subvector insert that is suitable for input to
3894 /// insertion of 128 or 256-bit subvectors
3895 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
3896   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
3897   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3898     return false;
3899   // The index should be aligned on a vecWidth-bit boundary.
3900   uint64_t Index =
3901     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3902
3903   MVT VT = N->getSimpleValueType(0);
3904   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
3905   bool Result = (Index * ElSize) % vecWidth == 0;
3906
3907   return Result;
3908 }
3909
3910 bool X86::isVINSERT128Index(SDNode *N) {
3911   return isVINSERTIndex(N, 128);
3912 }
3913
3914 bool X86::isVINSERT256Index(SDNode *N) {
3915   return isVINSERTIndex(N, 256);
3916 }
3917
3918 bool X86::isVEXTRACT128Index(SDNode *N) {
3919   return isVEXTRACTIndex(N, 128);
3920 }
3921
3922 bool X86::isVEXTRACT256Index(SDNode *N) {
3923   return isVEXTRACTIndex(N, 256);
3924 }
3925
3926 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
3927   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
3928   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3929     llvm_unreachable("Illegal extract subvector for VEXTRACT");
3930
3931   uint64_t Index =
3932     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3933
3934   MVT VecVT = N->getOperand(0).getSimpleValueType();
3935   MVT ElVT = VecVT.getVectorElementType();
3936
3937   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
3938   return Index / NumElemsPerChunk;
3939 }
3940
3941 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
3942   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
3943   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3944     llvm_unreachable("Illegal insert subvector for VINSERT");
3945
3946   uint64_t Index =
3947     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3948
3949   MVT VecVT = N->getSimpleValueType(0);
3950   MVT ElVT = VecVT.getVectorElementType();
3951
3952   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
3953   return Index / NumElemsPerChunk;
3954 }
3955
3956 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
3957 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
3958 /// and VINSERTI128 instructions.
3959 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
3960   return getExtractVEXTRACTImmediate(N, 128);
3961 }
3962
3963 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
3964 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
3965 /// and VINSERTI64x4 instructions.
3966 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
3967   return getExtractVEXTRACTImmediate(N, 256);
3968 }
3969
3970 /// getInsertVINSERT128Immediate - Return the appropriate immediate
3971 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
3972 /// and VINSERTI128 instructions.
3973 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
3974   return getInsertVINSERTImmediate(N, 128);
3975 }
3976
3977 /// getInsertVINSERT256Immediate - Return the appropriate immediate
3978 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
3979 /// and VINSERTI64x4 instructions.
3980 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
3981   return getInsertVINSERTImmediate(N, 256);
3982 }
3983
3984 /// isZero - Returns true if Elt is a constant integer zero
3985 static bool isZero(SDValue V) {
3986   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
3987   return C && C->isNullValue();
3988 }
3989
3990 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
3991 /// constant +0.0.
3992 bool X86::isZeroNode(SDValue Elt) {
3993   if (isZero(Elt))
3994     return true;
3995   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
3996     return CFP->getValueAPF().isPosZero();
3997   return false;
3998 }
3999
4000 /// getZeroVector - Returns a vector of specified type with all zero elements.
4001 ///
4002 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4003                              SelectionDAG &DAG, SDLoc dl) {
4004   assert(VT.isVector() && "Expected a vector type");
4005
4006   // Always build SSE zero vectors as <4 x i32> bitcasted
4007   // to their dest type. This ensures they get CSE'd.
4008   SDValue Vec;
4009   if (VT.is128BitVector()) {  // SSE
4010     if (Subtarget->hasSSE2()) {  // SSE2
4011       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4012       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4013     } else { // SSE1
4014       SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4015       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4016     }
4017   } else if (VT.is256BitVector()) { // AVX
4018     if (Subtarget->hasInt256()) { // AVX2
4019       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4020       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4021       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4022     } else {
4023       // 256-bit logic and arithmetic instructions in AVX are all
4024       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4025       SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4026       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4027       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
4028     }
4029   } else if (VT.is512BitVector()) { // AVX-512
4030       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4031       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4032                         Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4033       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4034   } else if (VT.getScalarType() == MVT::i1) {
4035
4036     assert((Subtarget->hasBWI() || VT.getVectorNumElements() <= 16)
4037             && "Unexpected vector type");
4038     assert((Subtarget->hasVLX() || VT.getVectorNumElements() >= 8)
4039             && "Unexpected vector type");
4040     SDValue Cst = DAG.getConstant(0, dl, MVT::i1);
4041     SmallVector<SDValue, 64> Ops(VT.getVectorNumElements(), Cst);
4042     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
4043   } else
4044     llvm_unreachable("Unexpected vector type");
4045
4046   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4047 }
4048
4049 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
4050                                 SelectionDAG &DAG, SDLoc dl,
4051                                 unsigned vectorWidth) {
4052   assert((vectorWidth == 128 || vectorWidth == 256) &&
4053          "Unsupported vector width");
4054   EVT VT = Vec.getValueType();
4055   EVT ElVT = VT.getVectorElementType();
4056   unsigned Factor = VT.getSizeInBits()/vectorWidth;
4057   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
4058                                   VT.getVectorNumElements()/Factor);
4059
4060   // Extract from UNDEF is UNDEF.
4061   if (Vec.getOpcode() == ISD::UNDEF)
4062     return DAG.getUNDEF(ResultVT);
4063
4064   // Extract the relevant vectorWidth bits.  Generate an EXTRACT_SUBVECTOR
4065   unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
4066
4067   // This is the index of the first element of the vectorWidth-bit chunk
4068   // we want.
4069   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / vectorWidth)
4070                                * ElemsPerChunk);
4071
4072   // If the input is a buildvector just emit a smaller one.
4073   if (Vec.getOpcode() == ISD::BUILD_VECTOR)
4074     return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
4075                        makeArrayRef(Vec->op_begin() + NormalizedIdxVal,
4076                                     ElemsPerChunk));
4077
4078   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal, dl);
4079   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec, VecIdx);
4080 }
4081
4082 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
4083 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
4084 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
4085 /// instructions or a simple subregister reference. Idx is an index in the
4086 /// 128 bits we want.  It need not be aligned to a 128-bit boundary.  That makes
4087 /// lowering EXTRACT_VECTOR_ELT operations easier.
4088 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
4089                                    SelectionDAG &DAG, SDLoc dl) {
4090   assert((Vec.getValueType().is256BitVector() ||
4091           Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
4092   return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
4093 }
4094
4095 /// Generate a DAG to grab 256-bits from a 512-bit vector.
4096 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
4097                                    SelectionDAG &DAG, SDLoc dl) {
4098   assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
4099   return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
4100 }
4101
4102 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
4103                                unsigned IdxVal, SelectionDAG &DAG,
4104                                SDLoc dl, unsigned vectorWidth) {
4105   assert((vectorWidth == 128 || vectorWidth == 256) &&
4106          "Unsupported vector width");
4107   // Inserting UNDEF is Result
4108   if (Vec.getOpcode() == ISD::UNDEF)
4109     return Result;
4110   EVT VT = Vec.getValueType();
4111   EVT ElVT = VT.getVectorElementType();
4112   EVT ResultVT = Result.getValueType();
4113
4114   // Insert the relevant vectorWidth bits.
4115   unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
4116
4117   // This is the index of the first element of the vectorWidth-bit chunk
4118   // we want.
4119   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/vectorWidth)
4120                                * ElemsPerChunk);
4121
4122   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal, dl);
4123   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec, VecIdx);
4124 }
4125
4126 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
4127 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
4128 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
4129 /// simple superregister reference.  Idx is an index in the 128 bits
4130 /// we want.  It need not be aligned to a 128-bit boundary.  That makes
4131 /// lowering INSERT_VECTOR_ELT operations easier.
4132 static SDValue Insert128BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4133                                   SelectionDAG &DAG, SDLoc dl) {
4134   assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
4135
4136   // For insertion into the zero index (low half) of a 256-bit vector, it is
4137   // more efficient to generate a blend with immediate instead of an insert*128.
4138   // We are still creating an INSERT_SUBVECTOR below with an undef node to
4139   // extend the subvector to the size of the result vector. Make sure that
4140   // we are not recursing on that node by checking for undef here.
4141   if (IdxVal == 0 && Result.getValueType().is256BitVector() &&
4142       Result.getOpcode() != ISD::UNDEF) {
4143     EVT ResultVT = Result.getValueType();
4144     SDValue ZeroIndex = DAG.getIntPtrConstant(0, dl);
4145     SDValue Undef = DAG.getUNDEF(ResultVT);
4146     SDValue Vec256 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Undef,
4147                                  Vec, ZeroIndex);
4148
4149     // The blend instruction, and therefore its mask, depend on the data type.
4150     MVT ScalarType = ResultVT.getScalarType().getSimpleVT();
4151     if (ScalarType.isFloatingPoint()) {
4152       // Choose either vblendps (float) or vblendpd (double).
4153       unsigned ScalarSize = ScalarType.getSizeInBits();
4154       assert((ScalarSize == 64 || ScalarSize == 32) && "Unknown float type");
4155       unsigned MaskVal = (ScalarSize == 64) ? 0x03 : 0x0f;
4156       SDValue Mask = DAG.getConstant(MaskVal, dl, MVT::i8);
4157       return DAG.getNode(X86ISD::BLENDI, dl, ResultVT, Result, Vec256, Mask);
4158     }
4159
4160     const X86Subtarget &Subtarget =
4161     static_cast<const X86Subtarget &>(DAG.getSubtarget());
4162
4163     // AVX2 is needed for 256-bit integer blend support.
4164     // Integers must be cast to 32-bit because there is only vpblendd;
4165     // vpblendw can't be used for this because it has a handicapped mask.
4166
4167     // If we don't have AVX2, then cast to float. Using a wrong domain blend
4168     // is still more efficient than using the wrong domain vinsertf128 that
4169     // will be created by InsertSubVector().
4170     MVT CastVT = Subtarget.hasAVX2() ? MVT::v8i32 : MVT::v8f32;
4171
4172     SDValue Mask = DAG.getConstant(0x0f, dl, MVT::i8);
4173     Vec256 = DAG.getNode(ISD::BITCAST, dl, CastVT, Vec256);
4174     Vec256 = DAG.getNode(X86ISD::BLENDI, dl, CastVT, Result, Vec256, Mask);
4175     return DAG.getNode(ISD::BITCAST, dl, ResultVT, Vec256);
4176   }
4177
4178   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
4179 }
4180
4181 static SDValue Insert256BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4182                                   SelectionDAG &DAG, SDLoc dl) {
4183   assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
4184   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
4185 }
4186
4187 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
4188 /// instructions. This is used because creating CONCAT_VECTOR nodes of
4189 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
4190 /// large BUILD_VECTORS.
4191 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
4192                                    unsigned NumElems, SelectionDAG &DAG,
4193                                    SDLoc dl) {
4194   SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4195   return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
4196 }
4197
4198 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
4199                                    unsigned NumElems, SelectionDAG &DAG,
4200                                    SDLoc dl) {
4201   SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4202   return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
4203 }
4204
4205 /// getOnesVector - Returns a vector of specified type with all bits set.
4206 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4207 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4208 /// Then bitcast to their original type, ensuring they get CSE'd.
4209 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4210                              SDLoc dl) {
4211   assert(VT.isVector() && "Expected a vector type");
4212
4213   SDValue Cst = DAG.getConstant(~0U, dl, MVT::i32);
4214   SDValue Vec;
4215   if (VT.is256BitVector()) {
4216     if (HasInt256) { // AVX2
4217       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4218       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4219     } else { // AVX
4220       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4221       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4222     }
4223   } else if (VT.is128BitVector()) {
4224     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4225   } else
4226     llvm_unreachable("Unexpected vector type");
4227
4228   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4229 }
4230
4231 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4232 /// operation of specified width.
4233 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4234                        SDValue V2) {
4235   unsigned NumElems = VT.getVectorNumElements();
4236   SmallVector<int, 8> Mask;
4237   Mask.push_back(NumElems);
4238   for (unsigned i = 1; i != NumElems; ++i)
4239     Mask.push_back(i);
4240   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4241 }
4242
4243 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4244 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4245                           SDValue V2) {
4246   unsigned NumElems = VT.getVectorNumElements();
4247   SmallVector<int, 8> Mask;
4248   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4249     Mask.push_back(i);
4250     Mask.push_back(i + NumElems);
4251   }
4252   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4253 }
4254
4255 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4256 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4257                           SDValue V2) {
4258   unsigned NumElems = VT.getVectorNumElements();
4259   SmallVector<int, 8> Mask;
4260   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4261     Mask.push_back(i + Half);
4262     Mask.push_back(i + NumElems + Half);
4263   }
4264   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4265 }
4266
4267 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4268 /// vector of zero or undef vector.  This produces a shuffle where the low
4269 /// element of V2 is swizzled into the zero/undef vector, landing at element
4270 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
4271 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4272                                            bool IsZero,
4273                                            const X86Subtarget *Subtarget,
4274                                            SelectionDAG &DAG) {
4275   MVT VT = V2.getSimpleValueType();
4276   SDValue V1 = IsZero
4277     ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
4278   unsigned NumElems = VT.getVectorNumElements();
4279   SmallVector<int, 16> MaskVec;
4280   for (unsigned i = 0; i != NumElems; ++i)
4281     // If this is the insertion idx, put the low elt of V2 here.
4282     MaskVec.push_back(i == Idx ? NumElems : i);
4283   return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
4284 }
4285
4286 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
4287 /// target specific opcode. Returns true if the Mask could be calculated. Sets
4288 /// IsUnary to true if only uses one source. Note that this will set IsUnary for
4289 /// shuffles which use a single input multiple times, and in those cases it will
4290 /// adjust the mask to only have indices within that single input.
4291 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4292                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
4293   unsigned NumElems = VT.getVectorNumElements();
4294   SDValue ImmN;
4295
4296   IsUnary = false;
4297   bool IsFakeUnary = false;
4298   switch(N->getOpcode()) {
4299   case X86ISD::BLENDI:
4300     ImmN = N->getOperand(N->getNumOperands()-1);
4301     DecodeBLENDMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4302     break;
4303   case X86ISD::SHUFP:
4304     ImmN = N->getOperand(N->getNumOperands()-1);
4305     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4306     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4307     break;
4308   case X86ISD::UNPCKH:
4309     DecodeUNPCKHMask(VT, Mask);
4310     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4311     break;
4312   case X86ISD::UNPCKL:
4313     DecodeUNPCKLMask(VT, Mask);
4314     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4315     break;
4316   case X86ISD::MOVHLPS:
4317     DecodeMOVHLPSMask(NumElems, Mask);
4318     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4319     break;
4320   case X86ISD::MOVLHPS:
4321     DecodeMOVLHPSMask(NumElems, Mask);
4322     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4323     break;
4324   case X86ISD::PALIGNR:
4325     ImmN = N->getOperand(N->getNumOperands()-1);
4326     DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4327     break;
4328   case X86ISD::PSHUFD:
4329   case X86ISD::VPERMILPI:
4330     ImmN = N->getOperand(N->getNumOperands()-1);
4331     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4332     IsUnary = true;
4333     break;
4334   case X86ISD::PSHUFHW:
4335     ImmN = N->getOperand(N->getNumOperands()-1);
4336     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4337     IsUnary = true;
4338     break;
4339   case X86ISD::PSHUFLW:
4340     ImmN = N->getOperand(N->getNumOperands()-1);
4341     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4342     IsUnary = true;
4343     break;
4344   case X86ISD::PSHUFB: {
4345     IsUnary = true;
4346     SDValue MaskNode = N->getOperand(1);
4347     while (MaskNode->getOpcode() == ISD::BITCAST)
4348       MaskNode = MaskNode->getOperand(0);
4349
4350     if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
4351       // If we have a build-vector, then things are easy.
4352       EVT VT = MaskNode.getValueType();
4353       assert(VT.isVector() &&
4354              "Can't produce a non-vector with a build_vector!");
4355       if (!VT.isInteger())
4356         return false;
4357
4358       int NumBytesPerElement = VT.getVectorElementType().getSizeInBits() / 8;
4359
4360       SmallVector<uint64_t, 32> RawMask;
4361       for (int i = 0, e = MaskNode->getNumOperands(); i < e; ++i) {
4362         SDValue Op = MaskNode->getOperand(i);
4363         if (Op->getOpcode() == ISD::UNDEF) {
4364           RawMask.push_back((uint64_t)SM_SentinelUndef);
4365           continue;
4366         }
4367         auto *CN = dyn_cast<ConstantSDNode>(Op.getNode());
4368         if (!CN)
4369           return false;
4370         APInt MaskElement = CN->getAPIntValue();
4371
4372         // We now have to decode the element which could be any integer size and
4373         // extract each byte of it.
4374         for (int j = 0; j < NumBytesPerElement; ++j) {
4375           // Note that this is x86 and so always little endian: the low byte is
4376           // the first byte of the mask.
4377           RawMask.push_back(MaskElement.getLoBits(8).getZExtValue());
4378           MaskElement = MaskElement.lshr(8);
4379         }
4380       }
4381       DecodePSHUFBMask(RawMask, Mask);
4382       break;
4383     }
4384
4385     auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
4386     if (!MaskLoad)
4387       return false;
4388
4389     SDValue Ptr = MaskLoad->getBasePtr();
4390     if (Ptr->getOpcode() == X86ISD::Wrapper ||
4391         Ptr->getOpcode() == X86ISD::WrapperRIP)
4392       Ptr = Ptr->getOperand(0);
4393
4394     auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
4395     if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
4396       return false;
4397
4398     if (auto *C = dyn_cast<Constant>(MaskCP->getConstVal())) {
4399       DecodePSHUFBMask(C, Mask);
4400       if (Mask.empty())
4401         return false;
4402       break;
4403     }
4404
4405     return false;
4406   }
4407   case X86ISD::VPERMI:
4408     ImmN = N->getOperand(N->getNumOperands()-1);
4409     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4410     IsUnary = true;
4411     break;
4412   case X86ISD::MOVSS:
4413   case X86ISD::MOVSD:
4414     DecodeScalarMoveMask(VT, /* IsLoad */ false, Mask);
4415     break;
4416   case X86ISD::VPERM2X128:
4417     ImmN = N->getOperand(N->getNumOperands()-1);
4418     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4419     if (Mask.empty()) return false;
4420     break;
4421   case X86ISD::MOVSLDUP:
4422     DecodeMOVSLDUPMask(VT, Mask);
4423     IsUnary = true;
4424     break;
4425   case X86ISD::MOVSHDUP:
4426     DecodeMOVSHDUPMask(VT, Mask);
4427     IsUnary = true;
4428     break;
4429   case X86ISD::MOVDDUP:
4430     DecodeMOVDDUPMask(VT, Mask);
4431     IsUnary = true;
4432     break;
4433   case X86ISD::MOVLHPD:
4434   case X86ISD::MOVLPD:
4435   case X86ISD::MOVLPS:
4436     // Not yet implemented
4437     return false;
4438   default: llvm_unreachable("unknown target shuffle node");
4439   }
4440
4441   // If we have a fake unary shuffle, the shuffle mask is spread across two
4442   // inputs that are actually the same node. Re-map the mask to always point
4443   // into the first input.
4444   if (IsFakeUnary)
4445     for (int &M : Mask)
4446       if (M >= (int)Mask.size())
4447         M -= Mask.size();
4448
4449   return true;
4450 }
4451
4452 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4453 /// element of the result of the vector shuffle.
4454 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4455                                    unsigned Depth) {
4456   if (Depth == 6)
4457     return SDValue();  // Limit search depth.
4458
4459   SDValue V = SDValue(N, 0);
4460   EVT VT = V.getValueType();
4461   unsigned Opcode = V.getOpcode();
4462
4463   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4464   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4465     int Elt = SV->getMaskElt(Index);
4466
4467     if (Elt < 0)
4468       return DAG.getUNDEF(VT.getVectorElementType());
4469
4470     unsigned NumElems = VT.getVectorNumElements();
4471     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4472                                          : SV->getOperand(1);
4473     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4474   }
4475
4476   // Recurse into target specific vector shuffles to find scalars.
4477   if (isTargetShuffle(Opcode)) {
4478     MVT ShufVT = V.getSimpleValueType();
4479     unsigned NumElems = ShufVT.getVectorNumElements();
4480     SmallVector<int, 16> ShuffleMask;
4481     bool IsUnary;
4482
4483     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4484       return SDValue();
4485
4486     int Elt = ShuffleMask[Index];
4487     if (Elt < 0)
4488       return DAG.getUNDEF(ShufVT.getVectorElementType());
4489
4490     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4491                                          : N->getOperand(1);
4492     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4493                                Depth+1);
4494   }
4495
4496   // Actual nodes that may contain scalar elements
4497   if (Opcode == ISD::BITCAST) {
4498     V = V.getOperand(0);
4499     EVT SrcVT = V.getValueType();
4500     unsigned NumElems = VT.getVectorNumElements();
4501
4502     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4503       return SDValue();
4504   }
4505
4506   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4507     return (Index == 0) ? V.getOperand(0)
4508                         : DAG.getUNDEF(VT.getVectorElementType());
4509
4510   if (V.getOpcode() == ISD::BUILD_VECTOR)
4511     return V.getOperand(Index);
4512
4513   return SDValue();
4514 }
4515
4516 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4517 ///
4518 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4519                                        unsigned NumNonZero, unsigned NumZero,
4520                                        SelectionDAG &DAG,
4521                                        const X86Subtarget* Subtarget,
4522                                        const TargetLowering &TLI) {
4523   if (NumNonZero > 8)
4524     return SDValue();
4525
4526   SDLoc dl(Op);
4527   SDValue V;
4528   bool First = true;
4529
4530   // SSE4.1 - use PINSRB to insert each byte directly.
4531   if (Subtarget->hasSSE41()) {
4532     for (unsigned i = 0; i < 16; ++i) {
4533       bool isNonZero = (NonZeros & (1 << i)) != 0;
4534       if (isNonZero) {
4535         if (First) {
4536           if (NumZero)
4537             V = getZeroVector(MVT::v16i8, Subtarget, DAG, dl);
4538           else
4539             V = DAG.getUNDEF(MVT::v16i8);
4540           First = false;
4541         }
4542         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4543                         MVT::v16i8, V, Op.getOperand(i),
4544                         DAG.getIntPtrConstant(i, dl));
4545       }
4546     }
4547
4548     return V;
4549   }
4550
4551   // Pre-SSE4.1 - merge byte pairs and insert with PINSRW.
4552   for (unsigned i = 0; i < 16; ++i) {
4553     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4554     if (ThisIsNonZero && First) {
4555       if (NumZero)
4556         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4557       else
4558         V = DAG.getUNDEF(MVT::v8i16);
4559       First = false;
4560     }
4561
4562     if ((i & 1) != 0) {
4563       SDValue ThisElt, LastElt;
4564       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4565       if (LastIsNonZero) {
4566         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4567                               MVT::i16, Op.getOperand(i-1));
4568       }
4569       if (ThisIsNonZero) {
4570         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4571         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4572                               ThisElt, DAG.getConstant(8, dl, MVT::i8));
4573         if (LastIsNonZero)
4574           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4575       } else
4576         ThisElt = LastElt;
4577
4578       if (ThisElt.getNode())
4579         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4580                         DAG.getIntPtrConstant(i/2, dl));
4581     }
4582   }
4583
4584   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4585 }
4586
4587 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4588 ///
4589 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4590                                      unsigned NumNonZero, unsigned NumZero,
4591                                      SelectionDAG &DAG,
4592                                      const X86Subtarget* Subtarget,
4593                                      const TargetLowering &TLI) {
4594   if (NumNonZero > 4)
4595     return SDValue();
4596
4597   SDLoc dl(Op);
4598   SDValue V;
4599   bool First = true;
4600   for (unsigned i = 0; i < 8; ++i) {
4601     bool isNonZero = (NonZeros & (1 << i)) != 0;
4602     if (isNonZero) {
4603       if (First) {
4604         if (NumZero)
4605           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4606         else
4607           V = DAG.getUNDEF(MVT::v8i16);
4608         First = false;
4609       }
4610       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4611                       MVT::v8i16, V, Op.getOperand(i),
4612                       DAG.getIntPtrConstant(i, dl));
4613     }
4614   }
4615
4616   return V;
4617 }
4618
4619 /// LowerBuildVectorv4x32 - Custom lower build_vector of v4i32 or v4f32.
4620 static SDValue LowerBuildVectorv4x32(SDValue Op, SelectionDAG &DAG,
4621                                      const X86Subtarget *Subtarget,
4622                                      const TargetLowering &TLI) {
4623   // Find all zeroable elements.
4624   std::bitset<4> Zeroable;
4625   for (int i=0; i < 4; ++i) {
4626     SDValue Elt = Op->getOperand(i);
4627     Zeroable[i] = (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt));
4628   }
4629   assert(Zeroable.size() - Zeroable.count() > 1 &&
4630          "We expect at least two non-zero elements!");
4631
4632   // We only know how to deal with build_vector nodes where elements are either
4633   // zeroable or extract_vector_elt with constant index.
4634   SDValue FirstNonZero;
4635   unsigned FirstNonZeroIdx;
4636   for (unsigned i=0; i < 4; ++i) {
4637     if (Zeroable[i])
4638       continue;
4639     SDValue Elt = Op->getOperand(i);
4640     if (Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4641         !isa<ConstantSDNode>(Elt.getOperand(1)))
4642       return SDValue();
4643     // Make sure that this node is extracting from a 128-bit vector.
4644     MVT VT = Elt.getOperand(0).getSimpleValueType();
4645     if (!VT.is128BitVector())
4646       return SDValue();
4647     if (!FirstNonZero.getNode()) {
4648       FirstNonZero = Elt;
4649       FirstNonZeroIdx = i;
4650     }
4651   }
4652
4653   assert(FirstNonZero.getNode() && "Unexpected build vector of all zeros!");
4654   SDValue V1 = FirstNonZero.getOperand(0);
4655   MVT VT = V1.getSimpleValueType();
4656
4657   // See if this build_vector can be lowered as a blend with zero.
4658   SDValue Elt;
4659   unsigned EltMaskIdx, EltIdx;
4660   int Mask[4];
4661   for (EltIdx = 0; EltIdx < 4; ++EltIdx) {
4662     if (Zeroable[EltIdx]) {
4663       // The zero vector will be on the right hand side.
4664       Mask[EltIdx] = EltIdx+4;
4665       continue;
4666     }
4667
4668     Elt = Op->getOperand(EltIdx);
4669     // By construction, Elt is a EXTRACT_VECTOR_ELT with constant index.
4670     EltMaskIdx = cast<ConstantSDNode>(Elt.getOperand(1))->getZExtValue();
4671     if (Elt.getOperand(0) != V1 || EltMaskIdx != EltIdx)
4672       break;
4673     Mask[EltIdx] = EltIdx;
4674   }
4675
4676   if (EltIdx == 4) {
4677     // Let the shuffle legalizer deal with blend operations.
4678     SDValue VZero = getZeroVector(VT, Subtarget, DAG, SDLoc(Op));
4679     if (V1.getSimpleValueType() != VT)
4680       V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), VT, V1);
4681     return DAG.getVectorShuffle(VT, SDLoc(V1), V1, VZero, &Mask[0]);
4682   }
4683
4684   // See if we can lower this build_vector to a INSERTPS.
4685   if (!Subtarget->hasSSE41())
4686     return SDValue();
4687
4688   SDValue V2 = Elt.getOperand(0);
4689   if (Elt == FirstNonZero && EltIdx == FirstNonZeroIdx)
4690     V1 = SDValue();
4691
4692   bool CanFold = true;
4693   for (unsigned i = EltIdx + 1; i < 4 && CanFold; ++i) {
4694     if (Zeroable[i])
4695       continue;
4696
4697     SDValue Current = Op->getOperand(i);
4698     SDValue SrcVector = Current->getOperand(0);
4699     if (!V1.getNode())
4700       V1 = SrcVector;
4701     CanFold = SrcVector == V1 &&
4702       cast<ConstantSDNode>(Current.getOperand(1))->getZExtValue() == i;
4703   }
4704
4705   if (!CanFold)
4706     return SDValue();
4707
4708   assert(V1.getNode() && "Expected at least two non-zero elements!");
4709   if (V1.getSimpleValueType() != MVT::v4f32)
4710     V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), MVT::v4f32, V1);
4711   if (V2.getSimpleValueType() != MVT::v4f32)
4712     V2 = DAG.getNode(ISD::BITCAST, SDLoc(V2), MVT::v4f32, V2);
4713
4714   // Ok, we can emit an INSERTPS instruction.
4715   unsigned ZMask = Zeroable.to_ulong();
4716
4717   unsigned InsertPSMask = EltMaskIdx << 6 | EltIdx << 4 | ZMask;
4718   assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
4719   SDLoc DL(Op);
4720   SDValue Result = DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
4721                                DAG.getIntPtrConstant(InsertPSMask, DL));
4722   return DAG.getNode(ISD::BITCAST, DL, VT, Result);
4723 }
4724
4725 /// Return a vector logical shift node.
4726 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4727                          unsigned NumBits, SelectionDAG &DAG,
4728                          const TargetLowering &TLI, SDLoc dl) {
4729   assert(VT.is128BitVector() && "Unknown type for VShift");
4730   MVT ShVT = MVT::v2i64;
4731   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
4732   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4733   MVT ScalarShiftTy = TLI.getScalarShiftAmountTy(SrcOp.getValueType());
4734   assert(NumBits % 8 == 0 && "Only support byte sized shifts");
4735   SDValue ShiftVal = DAG.getConstant(NumBits/8, dl, ScalarShiftTy);
4736   return DAG.getNode(ISD::BITCAST, dl, VT,
4737                      DAG.getNode(Opc, dl, ShVT, SrcOp, ShiftVal));
4738 }
4739
4740 static SDValue
4741 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
4742
4743   // Check if the scalar load can be widened into a vector load. And if
4744   // the address is "base + cst" see if the cst can be "absorbed" into
4745   // the shuffle mask.
4746   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4747     SDValue Ptr = LD->getBasePtr();
4748     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4749       return SDValue();
4750     EVT PVT = LD->getValueType(0);
4751     if (PVT != MVT::i32 && PVT != MVT::f32)
4752       return SDValue();
4753
4754     int FI = -1;
4755     int64_t Offset = 0;
4756     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4757       FI = FINode->getIndex();
4758       Offset = 0;
4759     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4760                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4761       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4762       Offset = Ptr.getConstantOperandVal(1);
4763       Ptr = Ptr.getOperand(0);
4764     } else {
4765       return SDValue();
4766     }
4767
4768     // FIXME: 256-bit vector instructions don't require a strict alignment,
4769     // improve this code to support it better.
4770     unsigned RequiredAlign = VT.getSizeInBits()/8;
4771     SDValue Chain = LD->getChain();
4772     // Make sure the stack object alignment is at least 16 or 32.
4773     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4774     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
4775       if (MFI->isFixedObjectIndex(FI)) {
4776         // Can't change the alignment. FIXME: It's possible to compute
4777         // the exact stack offset and reference FI + adjust offset instead.
4778         // If someone *really* cares about this. That's the way to implement it.
4779         return SDValue();
4780       } else {
4781         MFI->setObjectAlignment(FI, RequiredAlign);
4782       }
4783     }
4784
4785     // (Offset % 16 or 32) must be multiple of 4. Then address is then
4786     // Ptr + (Offset & ~15).
4787     if (Offset < 0)
4788       return SDValue();
4789     if ((Offset % RequiredAlign) & 3)
4790       return SDValue();
4791     int64_t StartOffset = Offset & ~(RequiredAlign-1);
4792     if (StartOffset) {
4793       SDLoc DL(Ptr);
4794       Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
4795                         DAG.getConstant(StartOffset, DL, Ptr.getValueType()));
4796     }
4797
4798     int EltNo = (Offset - StartOffset) >> 2;
4799     unsigned NumElems = VT.getVectorNumElements();
4800
4801     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
4802     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
4803                              LD->getPointerInfo().getWithOffset(StartOffset),
4804                              false, false, false, 0);
4805
4806     SmallVector<int, 8> Mask(NumElems, EltNo);
4807
4808     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
4809   }
4810
4811   return SDValue();
4812 }
4813
4814 /// Given the initializing elements 'Elts' of a vector of type 'VT', see if the
4815 /// elements can be replaced by a single large load which has the same value as
4816 /// a build_vector or insert_subvector whose loaded operands are 'Elts'.
4817 ///
4818 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4819 ///
4820 /// FIXME: we'd also like to handle the case where the last elements are zero
4821 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4822 /// There's even a handy isZeroNode for that purpose.
4823 static SDValue EltsFromConsecutiveLoads(EVT VT, ArrayRef<SDValue> Elts,
4824                                         SDLoc &DL, SelectionDAG &DAG,
4825                                         bool isAfterLegalize) {
4826   unsigned NumElems = Elts.size();
4827
4828   LoadSDNode *LDBase = nullptr;
4829   unsigned LastLoadedElt = -1U;
4830
4831   // For each element in the initializer, see if we've found a load or an undef.
4832   // If we don't find an initial load element, or later load elements are
4833   // non-consecutive, bail out.
4834   for (unsigned i = 0; i < NumElems; ++i) {
4835     SDValue Elt = Elts[i];
4836     // Look through a bitcast.
4837     if (Elt.getNode() && Elt.getOpcode() == ISD::BITCAST)
4838       Elt = Elt.getOperand(0);
4839     if (!Elt.getNode() ||
4840         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
4841       return SDValue();
4842     if (!LDBase) {
4843       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
4844         return SDValue();
4845       LDBase = cast<LoadSDNode>(Elt.getNode());
4846       LastLoadedElt = i;
4847       continue;
4848     }
4849     if (Elt.getOpcode() == ISD::UNDEF)
4850       continue;
4851
4852     LoadSDNode *LD = cast<LoadSDNode>(Elt);
4853     EVT LdVT = Elt.getValueType();
4854     // Each loaded element must be the correct fractional portion of the
4855     // requested vector load.
4856     if (LdVT.getSizeInBits() != VT.getSizeInBits() / NumElems)
4857       return SDValue();
4858     if (!DAG.isConsecutiveLoad(LD, LDBase, LdVT.getSizeInBits() / 8, i))
4859       return SDValue();
4860     LastLoadedElt = i;
4861   }
4862
4863   // If we have found an entire vector of loads and undefs, then return a large
4864   // load of the entire vector width starting at the base pointer.  If we found
4865   // consecutive loads for the low half, generate a vzext_load node.
4866   if (LastLoadedElt == NumElems - 1) {
4867     assert(LDBase && "Did not find base load for merging consecutive loads");
4868     EVT EltVT = LDBase->getValueType(0);
4869     // Ensure that the input vector size for the merged loads matches the
4870     // cumulative size of the input elements.
4871     if (VT.getSizeInBits() != EltVT.getSizeInBits() * NumElems)
4872       return SDValue();
4873
4874     if (isAfterLegalize &&
4875         !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
4876       return SDValue();
4877
4878     SDValue NewLd = SDValue();
4879
4880     NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4881                         LDBase->getPointerInfo(), LDBase->isVolatile(),
4882                         LDBase->isNonTemporal(), LDBase->isInvariant(),
4883                         LDBase->getAlignment());
4884
4885     if (LDBase->hasAnyUseOfValue(1)) {
4886       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
4887                                      SDValue(LDBase, 1),
4888                                      SDValue(NewLd.getNode(), 1));
4889       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
4890       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
4891                              SDValue(NewLd.getNode(), 1));
4892     }
4893
4894     return NewLd;
4895   }
4896
4897   //TODO: The code below fires only for for loading the low v2i32 / v2f32
4898   //of a v4i32 / v4f32. It's probably worth generalizing.
4899   EVT EltVT = VT.getVectorElementType();
4900   if (NumElems == 4 && LastLoadedElt == 1 && (EltVT.getSizeInBits() == 32) &&
4901       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
4902     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
4903     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
4904     SDValue ResNode =
4905         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
4906                                 LDBase->getPointerInfo(),
4907                                 LDBase->getAlignment(),
4908                                 false/*isVolatile*/, true/*ReadMem*/,
4909                                 false/*WriteMem*/);
4910
4911     // Make sure the newly-created LOAD is in the same position as LDBase in
4912     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
4913     // update uses of LDBase's output chain to use the TokenFactor.
4914     if (LDBase->hasAnyUseOfValue(1)) {
4915       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
4916                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
4917       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
4918       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
4919                              SDValue(ResNode.getNode(), 1));
4920     }
4921
4922     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
4923   }
4924   return SDValue();
4925 }
4926
4927 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
4928 /// to generate a splat value for the following cases:
4929 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
4930 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
4931 /// a scalar load, or a constant.
4932 /// The VBROADCAST node is returned when a pattern is found,
4933 /// or SDValue() otherwise.
4934 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
4935                                     SelectionDAG &DAG) {
4936   // VBROADCAST requires AVX.
4937   // TODO: Splats could be generated for non-AVX CPUs using SSE
4938   // instructions, but there's less potential gain for only 128-bit vectors.
4939   if (!Subtarget->hasAVX())
4940     return SDValue();
4941
4942   MVT VT = Op.getSimpleValueType();
4943   SDLoc dl(Op);
4944
4945   assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
4946          "Unsupported vector type for broadcast.");
4947
4948   SDValue Ld;
4949   bool ConstSplatVal;
4950
4951   switch (Op.getOpcode()) {
4952     default:
4953       // Unknown pattern found.
4954       return SDValue();
4955
4956     case ISD::BUILD_VECTOR: {
4957       auto *BVOp = cast<BuildVectorSDNode>(Op.getNode());
4958       BitVector UndefElements;
4959       SDValue Splat = BVOp->getSplatValue(&UndefElements);
4960
4961       // We need a splat of a single value to use broadcast, and it doesn't
4962       // make any sense if the value is only in one element of the vector.
4963       if (!Splat || (VT.getVectorNumElements() - UndefElements.count()) <= 1)
4964         return SDValue();
4965
4966       Ld = Splat;
4967       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
4968                        Ld.getOpcode() == ISD::ConstantFP);
4969
4970       // Make sure that all of the users of a non-constant load are from the
4971       // BUILD_VECTOR node.
4972       if (!ConstSplatVal && !BVOp->isOnlyUserOf(Ld.getNode()))
4973         return SDValue();
4974       break;
4975     }
4976
4977     case ISD::VECTOR_SHUFFLE: {
4978       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
4979
4980       // Shuffles must have a splat mask where the first element is
4981       // broadcasted.
4982       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
4983         return SDValue();
4984
4985       SDValue Sc = Op.getOperand(0);
4986       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
4987           Sc.getOpcode() != ISD::BUILD_VECTOR) {
4988
4989         if (!Subtarget->hasInt256())
4990           return SDValue();
4991
4992         // Use the register form of the broadcast instruction available on AVX2.
4993         if (VT.getSizeInBits() >= 256)
4994           Sc = Extract128BitVector(Sc, 0, DAG, dl);
4995         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
4996       }
4997
4998       Ld = Sc.getOperand(0);
4999       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5000                        Ld.getOpcode() == ISD::ConstantFP);
5001
5002       // The scalar_to_vector node and the suspected
5003       // load node must have exactly one user.
5004       // Constants may have multiple users.
5005
5006       // AVX-512 has register version of the broadcast
5007       bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5008         Ld.getValueType().getSizeInBits() >= 32;
5009       if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5010           !hasRegVer))
5011         return SDValue();
5012       break;
5013     }
5014   }
5015
5016   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5017   bool IsGE256 = (VT.getSizeInBits() >= 256);
5018
5019   // When optimizing for size, generate up to 5 extra bytes for a broadcast
5020   // instruction to save 8 or more bytes of constant pool data.
5021   // TODO: If multiple splats are generated to load the same constant,
5022   // it may be detrimental to overall size. There needs to be a way to detect
5023   // that condition to know if this is truly a size win.
5024   const Function *F = DAG.getMachineFunction().getFunction();
5025   bool OptForSize = F->hasFnAttribute(Attribute::OptimizeForSize);
5026
5027   // Handle broadcasting a single constant scalar from the constant pool
5028   // into a vector.
5029   // On Sandybridge (no AVX2), it is still better to load a constant vector
5030   // from the constant pool and not to broadcast it from a scalar.
5031   // But override that restriction when optimizing for size.
5032   // TODO: Check if splatting is recommended for other AVX-capable CPUs.
5033   if (ConstSplatVal && (Subtarget->hasAVX2() || OptForSize)) {
5034     EVT CVT = Ld.getValueType();
5035     assert(!CVT.isVector() && "Must not broadcast a vector type");
5036
5037     // Splat f32, i32, v4f64, v4i64 in all cases with AVX2.
5038     // For size optimization, also splat v2f64 and v2i64, and for size opt
5039     // with AVX2, also splat i8 and i16.
5040     // With pattern matching, the VBROADCAST node may become a VMOVDDUP.
5041     if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5042         (OptForSize && (ScalarSize == 64 || Subtarget->hasAVX2()))) {
5043       const Constant *C = nullptr;
5044       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5045         C = CI->getConstantIntValue();
5046       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5047         C = CF->getConstantFPValue();
5048
5049       assert(C && "Invalid constant type");
5050
5051       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5052       SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
5053       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5054       Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5055                        MachinePointerInfo::getConstantPool(),
5056                        false, false, false, Alignment);
5057
5058       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5059     }
5060   }
5061
5062   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5063
5064   // Handle AVX2 in-register broadcasts.
5065   if (!IsLoad && Subtarget->hasInt256() &&
5066       (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5067     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5068
5069   // The scalar source must be a normal load.
5070   if (!IsLoad)
5071     return SDValue();
5072
5073   if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5074       (Subtarget->hasVLX() && ScalarSize == 64))
5075     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5076
5077   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5078   // double since there is no vbroadcastsd xmm
5079   if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5080     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5081       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5082   }
5083
5084   // Unsupported broadcast.
5085   return SDValue();
5086 }
5087
5088 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
5089 /// underlying vector and index.
5090 ///
5091 /// Modifies \p ExtractedFromVec to the real vector and returns the real
5092 /// index.
5093 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
5094                                          SDValue ExtIdx) {
5095   int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5096   if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
5097     return Idx;
5098
5099   // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
5100   // lowered this:
5101   //   (extract_vector_elt (v8f32 %vreg1), Constant<6>)
5102   // to:
5103   //   (extract_vector_elt (vector_shuffle<2,u,u,u>
5104   //                           (extract_subvector (v8f32 %vreg0), Constant<4>),
5105   //                           undef)
5106   //                       Constant<0>)
5107   // In this case the vector is the extract_subvector expression and the index
5108   // is 2, as specified by the shuffle.
5109   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
5110   SDValue ShuffleVec = SVOp->getOperand(0);
5111   MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
5112   assert(ShuffleVecVT.getVectorElementType() ==
5113          ExtractedFromVec.getSimpleValueType().getVectorElementType());
5114
5115   int ShuffleIdx = SVOp->getMaskElt(Idx);
5116   if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
5117     ExtractedFromVec = ShuffleVec;
5118     return ShuffleIdx;
5119   }
5120   return Idx;
5121 }
5122
5123 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5124   MVT VT = Op.getSimpleValueType();
5125
5126   // Skip if insert_vec_elt is not supported.
5127   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5128   if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5129     return SDValue();
5130
5131   SDLoc DL(Op);
5132   unsigned NumElems = Op.getNumOperands();
5133
5134   SDValue VecIn1;
5135   SDValue VecIn2;
5136   SmallVector<unsigned, 4> InsertIndices;
5137   SmallVector<int, 8> Mask(NumElems, -1);
5138
5139   for (unsigned i = 0; i != NumElems; ++i) {
5140     unsigned Opc = Op.getOperand(i).getOpcode();
5141
5142     if (Opc == ISD::UNDEF)
5143       continue;
5144
5145     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5146       // Quit if more than 1 elements need inserting.
5147       if (InsertIndices.size() > 1)
5148         return SDValue();
5149
5150       InsertIndices.push_back(i);
5151       continue;
5152     }
5153
5154     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5155     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5156     // Quit if non-constant index.
5157     if (!isa<ConstantSDNode>(ExtIdx))
5158       return SDValue();
5159     int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5160
5161     // Quit if extracted from vector of different type.
5162     if (ExtractedFromVec.getValueType() != VT)
5163       return SDValue();
5164
5165     if (!VecIn1.getNode())
5166       VecIn1 = ExtractedFromVec;
5167     else if (VecIn1 != ExtractedFromVec) {
5168       if (!VecIn2.getNode())
5169         VecIn2 = ExtractedFromVec;
5170       else if (VecIn2 != ExtractedFromVec)
5171         // Quit if more than 2 vectors to shuffle
5172         return SDValue();
5173     }
5174
5175     if (ExtractedFromVec == VecIn1)
5176       Mask[i] = Idx;
5177     else if (ExtractedFromVec == VecIn2)
5178       Mask[i] = Idx + NumElems;
5179   }
5180
5181   if (!VecIn1.getNode())
5182     return SDValue();
5183
5184   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5185   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5186   for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5187     unsigned Idx = InsertIndices[i];
5188     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5189                      DAG.getIntPtrConstant(Idx, DL));
5190   }
5191
5192   return NV;
5193 }
5194
5195 static SDValue ConvertI1VectorToInterger(SDValue Op, SelectionDAG &DAG) {
5196   assert(ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) &&
5197          Op.getScalarValueSizeInBits() == 1 &&
5198          "Can not convert non-constant vector");
5199   uint64_t Immediate = 0;
5200   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5201     SDValue In = Op.getOperand(idx);
5202     if (In.getOpcode() != ISD::UNDEF)
5203       Immediate |= cast<ConstantSDNode>(In)->getZExtValue() << idx;
5204   }
5205   SDLoc dl(Op);
5206   MVT VT =
5207    MVT::getIntegerVT(std::max((int)Op.getValueType().getSizeInBits(), 8));
5208   return DAG.getConstant(Immediate, dl, VT);
5209 }
5210 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5211 SDValue
5212 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5213
5214   MVT VT = Op.getSimpleValueType();
5215   assert((VT.getVectorElementType() == MVT::i1) &&
5216          "Unexpected type in LowerBUILD_VECTORvXi1!");
5217
5218   SDLoc dl(Op);
5219   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5220     SDValue Cst = DAG.getTargetConstant(0, dl, MVT::i1);
5221     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5222     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5223   }
5224
5225   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5226     SDValue Cst = DAG.getTargetConstant(1, dl, MVT::i1);
5227     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5228     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5229   }
5230
5231   if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) {
5232     SDValue Imm = ConvertI1VectorToInterger(Op, DAG);
5233     if (Imm.getValueSizeInBits() == VT.getSizeInBits())
5234       return DAG.getNode(ISD::BITCAST, dl, VT, Imm);
5235     SDValue ExtVec = DAG.getNode(ISD::BITCAST, dl, MVT::v8i1, Imm);
5236     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, ExtVec,
5237                         DAG.getIntPtrConstant(0, dl));
5238   }
5239
5240   // Vector has one or more non-const elements
5241   uint64_t Immediate = 0;
5242   SmallVector<unsigned, 16> NonConstIdx;
5243   bool IsSplat = true;
5244   bool HasConstElts = false;
5245   int SplatIdx = -1;
5246   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5247     SDValue In = Op.getOperand(idx);
5248     if (In.getOpcode() == ISD::UNDEF)
5249       continue;
5250     if (!isa<ConstantSDNode>(In)) 
5251       NonConstIdx.push_back(idx);
5252     else {
5253       Immediate |= cast<ConstantSDNode>(In)->getZExtValue() << idx;
5254       HasConstElts = true;
5255     }
5256     if (SplatIdx == -1)
5257       SplatIdx = idx;
5258     else if (In != Op.getOperand(SplatIdx))
5259       IsSplat = false;
5260   }
5261
5262   // for splat use " (select i1 splat_elt, all-ones, all-zeroes)"
5263   if (IsSplat)
5264     return DAG.getNode(ISD::SELECT, dl, VT, Op.getOperand(SplatIdx),
5265                        DAG.getConstant(1, dl, VT),
5266                        DAG.getConstant(0, dl, VT));
5267
5268   // insert elements one by one
5269   SDValue DstVec;
5270   SDValue Imm;
5271   if (Immediate) {
5272     MVT ImmVT = MVT::getIntegerVT(std::max((int)VT.getSizeInBits(), 8));
5273     Imm = DAG.getConstant(Immediate, dl, ImmVT);
5274   }
5275   else if (HasConstElts)
5276     Imm = DAG.getConstant(0, dl, VT);
5277   else 
5278     Imm = DAG.getUNDEF(VT);
5279   if (Imm.getValueSizeInBits() == VT.getSizeInBits())
5280     DstVec = DAG.getNode(ISD::BITCAST, dl, VT, Imm);
5281   else {
5282     SDValue ExtVec = DAG.getNode(ISD::BITCAST, dl, MVT::v8i1, Imm);
5283     DstVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, ExtVec,
5284                          DAG.getIntPtrConstant(0, dl));
5285   }
5286
5287   for (unsigned i = 0; i < NonConstIdx.size(); ++i) {
5288     unsigned InsertIdx = NonConstIdx[i];
5289     DstVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5290                          Op.getOperand(InsertIdx),
5291                          DAG.getIntPtrConstant(InsertIdx, dl));
5292   }
5293   return DstVec;
5294 }
5295
5296 /// \brief Return true if \p N implements a horizontal binop and return the
5297 /// operands for the horizontal binop into V0 and V1.
5298 ///
5299 /// This is a helper function of LowerToHorizontalOp().
5300 /// This function checks that the build_vector \p N in input implements a
5301 /// horizontal operation. Parameter \p Opcode defines the kind of horizontal
5302 /// operation to match.
5303 /// For example, if \p Opcode is equal to ISD::ADD, then this function
5304 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
5305 /// is equal to ISD::SUB, then this function checks if this is a horizontal
5306 /// arithmetic sub.
5307 ///
5308 /// This function only analyzes elements of \p N whose indices are
5309 /// in range [BaseIdx, LastIdx).
5310 static bool isHorizontalBinOp(const BuildVectorSDNode *N, unsigned Opcode,
5311                               SelectionDAG &DAG,
5312                               unsigned BaseIdx, unsigned LastIdx,
5313                               SDValue &V0, SDValue &V1) {
5314   EVT VT = N->getValueType(0);
5315
5316   assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
5317   assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
5318          "Invalid Vector in input!");
5319
5320   bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
5321   bool CanFold = true;
5322   unsigned ExpectedVExtractIdx = BaseIdx;
5323   unsigned NumElts = LastIdx - BaseIdx;
5324   V0 = DAG.getUNDEF(VT);
5325   V1 = DAG.getUNDEF(VT);
5326
5327   // Check if N implements a horizontal binop.
5328   for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
5329     SDValue Op = N->getOperand(i + BaseIdx);
5330
5331     // Skip UNDEFs.
5332     if (Op->getOpcode() == ISD::UNDEF) {
5333       // Update the expected vector extract index.
5334       if (i * 2 == NumElts)
5335         ExpectedVExtractIdx = BaseIdx;
5336       ExpectedVExtractIdx += 2;
5337       continue;
5338     }
5339
5340     CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
5341
5342     if (!CanFold)
5343       break;
5344
5345     SDValue Op0 = Op.getOperand(0);
5346     SDValue Op1 = Op.getOperand(1);
5347
5348     // Try to match the following pattern:
5349     // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
5350     CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5351         Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5352         Op0.getOperand(0) == Op1.getOperand(0) &&
5353         isa<ConstantSDNode>(Op0.getOperand(1)) &&
5354         isa<ConstantSDNode>(Op1.getOperand(1)));
5355     if (!CanFold)
5356       break;
5357
5358     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5359     unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
5360
5361     if (i * 2 < NumElts) {
5362       if (V0.getOpcode() == ISD::UNDEF) {
5363         V0 = Op0.getOperand(0);
5364         if (V0.getValueType() != VT)
5365           return false;
5366       }
5367     } else {
5368       if (V1.getOpcode() == ISD::UNDEF) {
5369         V1 = Op0.getOperand(0);
5370         if (V1.getValueType() != VT)
5371           return false;
5372       }
5373       if (i * 2 == NumElts)
5374         ExpectedVExtractIdx = BaseIdx;
5375     }
5376
5377     SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
5378     if (I0 == ExpectedVExtractIdx)
5379       CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
5380     else if (IsCommutable && I1 == ExpectedVExtractIdx) {
5381       // Try to match the following dag sequence:
5382       // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
5383       CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
5384     } else
5385       CanFold = false;
5386
5387     ExpectedVExtractIdx += 2;
5388   }
5389
5390   return CanFold;
5391 }
5392
5393 /// \brief Emit a sequence of two 128-bit horizontal add/sub followed by
5394 /// a concat_vector.
5395 ///
5396 /// This is a helper function of LowerToHorizontalOp().
5397 /// This function expects two 256-bit vectors called V0 and V1.
5398 /// At first, each vector is split into two separate 128-bit vectors.
5399 /// Then, the resulting 128-bit vectors are used to implement two
5400 /// horizontal binary operations.
5401 ///
5402 /// The kind of horizontal binary operation is defined by \p X86Opcode.
5403 ///
5404 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
5405 /// the two new horizontal binop.
5406 /// When Mode is set, the first horizontal binop dag node would take as input
5407 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
5408 /// horizontal binop dag node would take as input the lower 128-bit of V1
5409 /// and the upper 128-bit of V1.
5410 ///   Example:
5411 ///     HADD V0_LO, V0_HI
5412 ///     HADD V1_LO, V1_HI
5413 ///
5414 /// Otherwise, the first horizontal binop dag node takes as input the lower
5415 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
5416 /// dag node takes the the upper 128-bit of V0 and the upper 128-bit of V1.
5417 ///   Example:
5418 ///     HADD V0_LO, V1_LO
5419 ///     HADD V0_HI, V1_HI
5420 ///
5421 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
5422 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
5423 /// the upper 128-bits of the result.
5424 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
5425                                      SDLoc DL, SelectionDAG &DAG,
5426                                      unsigned X86Opcode, bool Mode,
5427                                      bool isUndefLO, bool isUndefHI) {
5428   EVT VT = V0.getValueType();
5429   assert(VT.is256BitVector() && VT == V1.getValueType() &&
5430          "Invalid nodes in input!");
5431
5432   unsigned NumElts = VT.getVectorNumElements();
5433   SDValue V0_LO = Extract128BitVector(V0, 0, DAG, DL);
5434   SDValue V0_HI = Extract128BitVector(V0, NumElts/2, DAG, DL);
5435   SDValue V1_LO = Extract128BitVector(V1, 0, DAG, DL);
5436   SDValue V1_HI = Extract128BitVector(V1, NumElts/2, DAG, DL);
5437   EVT NewVT = V0_LO.getValueType();
5438
5439   SDValue LO = DAG.getUNDEF(NewVT);
5440   SDValue HI = DAG.getUNDEF(NewVT);
5441
5442   if (Mode) {
5443     // Don't emit a horizontal binop if the result is expected to be UNDEF.
5444     if (!isUndefLO && V0->getOpcode() != ISD::UNDEF)
5445       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
5446     if (!isUndefHI && V1->getOpcode() != ISD::UNDEF)
5447       HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
5448   } else {
5449     // Don't emit a horizontal binop if the result is expected to be UNDEF.
5450     if (!isUndefLO && (V0_LO->getOpcode() != ISD::UNDEF ||
5451                        V1_LO->getOpcode() != ISD::UNDEF))
5452       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
5453
5454     if (!isUndefHI && (V0_HI->getOpcode() != ISD::UNDEF ||
5455                        V1_HI->getOpcode() != ISD::UNDEF))
5456       HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
5457   }
5458
5459   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
5460 }
5461
5462 /// Try to fold a build_vector that performs an 'addsub' to an X86ISD::ADDSUB
5463 /// node.
5464 static SDValue LowerToAddSub(const BuildVectorSDNode *BV,
5465                              const X86Subtarget *Subtarget, SelectionDAG &DAG) {
5466   EVT VT = BV->getValueType(0);
5467   if ((!Subtarget->hasSSE3() || (VT != MVT::v4f32 && VT != MVT::v2f64)) &&
5468       (!Subtarget->hasAVX() || (VT != MVT::v8f32 && VT != MVT::v4f64)))
5469     return SDValue();
5470
5471   SDLoc DL(BV);
5472   unsigned NumElts = VT.getVectorNumElements();
5473   SDValue InVec0 = DAG.getUNDEF(VT);
5474   SDValue InVec1 = DAG.getUNDEF(VT);
5475
5476   assert((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v4f32 ||
5477           VT == MVT::v2f64) && "build_vector with an invalid type found!");
5478
5479   // Odd-numbered elements in the input build vector are obtained from
5480   // adding two integer/float elements.
5481   // Even-numbered elements in the input build vector are obtained from
5482   // subtracting two integer/float elements.
5483   unsigned ExpectedOpcode = ISD::FSUB;
5484   unsigned NextExpectedOpcode = ISD::FADD;
5485   bool AddFound = false;
5486   bool SubFound = false;
5487
5488   for (unsigned i = 0, e = NumElts; i != e; ++i) {
5489     SDValue Op = BV->getOperand(i);
5490
5491     // Skip 'undef' values.
5492     unsigned Opcode = Op.getOpcode();
5493     if (Opcode == ISD::UNDEF) {
5494       std::swap(ExpectedOpcode, NextExpectedOpcode);
5495       continue;
5496     }
5497
5498     // Early exit if we found an unexpected opcode.
5499     if (Opcode != ExpectedOpcode)
5500       return SDValue();
5501
5502     SDValue Op0 = Op.getOperand(0);
5503     SDValue Op1 = Op.getOperand(1);
5504
5505     // Try to match the following pattern:
5506     // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
5507     // Early exit if we cannot match that sequence.
5508     if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5509         Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5510         !isa<ConstantSDNode>(Op0.getOperand(1)) ||
5511         !isa<ConstantSDNode>(Op1.getOperand(1)) ||
5512         Op0.getOperand(1) != Op1.getOperand(1))
5513       return SDValue();
5514
5515     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5516     if (I0 != i)
5517       return SDValue();
5518
5519     // We found a valid add/sub node. Update the information accordingly.
5520     if (i & 1)
5521       AddFound = true;
5522     else
5523       SubFound = true;
5524
5525     // Update InVec0 and InVec1.
5526     if (InVec0.getOpcode() == ISD::UNDEF) {
5527       InVec0 = Op0.getOperand(0);
5528       if (InVec0.getValueType() != VT)
5529         return SDValue();
5530     }
5531     if (InVec1.getOpcode() == ISD::UNDEF) {
5532       InVec1 = Op1.getOperand(0);
5533       if (InVec1.getValueType() != VT)
5534         return SDValue();
5535     }
5536
5537     // Make sure that operands in input to each add/sub node always
5538     // come from a same pair of vectors.
5539     if (InVec0 != Op0.getOperand(0)) {
5540       if (ExpectedOpcode == ISD::FSUB)
5541         return SDValue();
5542
5543       // FADD is commutable. Try to commute the operands
5544       // and then test again.
5545       std::swap(Op0, Op1);
5546       if (InVec0 != Op0.getOperand(0))
5547         return SDValue();
5548     }
5549
5550     if (InVec1 != Op1.getOperand(0))
5551       return SDValue();
5552
5553     // Update the pair of expected opcodes.
5554     std::swap(ExpectedOpcode, NextExpectedOpcode);
5555   }
5556
5557   // Don't try to fold this build_vector into an ADDSUB if the inputs are undef.
5558   if (AddFound && SubFound && InVec0.getOpcode() != ISD::UNDEF &&
5559       InVec1.getOpcode() != ISD::UNDEF)
5560     return DAG.getNode(X86ISD::ADDSUB, DL, VT, InVec0, InVec1);
5561
5562   return SDValue();
5563 }
5564
5565 /// Lower BUILD_VECTOR to a horizontal add/sub operation if possible.
5566 static SDValue LowerToHorizontalOp(const BuildVectorSDNode *BV,
5567                                    const X86Subtarget *Subtarget,
5568                                    SelectionDAG &DAG) {
5569   EVT VT = BV->getValueType(0);
5570   unsigned NumElts = VT.getVectorNumElements();
5571   unsigned NumUndefsLO = 0;
5572   unsigned NumUndefsHI = 0;
5573   unsigned Half = NumElts/2;
5574
5575   // Count the number of UNDEF operands in the build_vector in input.
5576   for (unsigned i = 0, e = Half; i != e; ++i)
5577     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
5578       NumUndefsLO++;
5579
5580   for (unsigned i = Half, e = NumElts; i != e; ++i)
5581     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
5582       NumUndefsHI++;
5583
5584   // Early exit if this is either a build_vector of all UNDEFs or all the
5585   // operands but one are UNDEF.
5586   if (NumUndefsLO + NumUndefsHI + 1 >= NumElts)
5587     return SDValue();
5588
5589   SDLoc DL(BV);
5590   SDValue InVec0, InVec1;
5591   if ((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) {
5592     // Try to match an SSE3 float HADD/HSUB.
5593     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
5594       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
5595
5596     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
5597       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
5598   } else if ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) {
5599     // Try to match an SSSE3 integer HADD/HSUB.
5600     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
5601       return DAG.getNode(X86ISD::HADD, DL, VT, InVec0, InVec1);
5602
5603     if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
5604       return DAG.getNode(X86ISD::HSUB, DL, VT, InVec0, InVec1);
5605   }
5606
5607   if (!Subtarget->hasAVX())
5608     return SDValue();
5609
5610   if ((VT == MVT::v8f32 || VT == MVT::v4f64)) {
5611     // Try to match an AVX horizontal add/sub of packed single/double
5612     // precision floating point values from 256-bit vectors.
5613     SDValue InVec2, InVec3;
5614     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, Half, InVec0, InVec1) &&
5615         isHorizontalBinOp(BV, ISD::FADD, DAG, Half, NumElts, InVec2, InVec3) &&
5616         ((InVec0.getOpcode() == ISD::UNDEF ||
5617           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5618         ((InVec1.getOpcode() == ISD::UNDEF ||
5619           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5620       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
5621
5622     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, Half, InVec0, InVec1) &&
5623         isHorizontalBinOp(BV, ISD::FSUB, DAG, Half, NumElts, InVec2, InVec3) &&
5624         ((InVec0.getOpcode() == ISD::UNDEF ||
5625           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5626         ((InVec1.getOpcode() == ISD::UNDEF ||
5627           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5628       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
5629   } else if (VT == MVT::v8i32 || VT == MVT::v16i16) {
5630     // Try to match an AVX2 horizontal add/sub of signed integers.
5631     SDValue InVec2, InVec3;
5632     unsigned X86Opcode;
5633     bool CanFold = true;
5634
5635     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
5636         isHorizontalBinOp(BV, ISD::ADD, DAG, Half, NumElts, InVec2, InVec3) &&
5637         ((InVec0.getOpcode() == ISD::UNDEF ||
5638           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5639         ((InVec1.getOpcode() == ISD::UNDEF ||
5640           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5641       X86Opcode = X86ISD::HADD;
5642     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, Half, InVec0, InVec1) &&
5643         isHorizontalBinOp(BV, ISD::SUB, DAG, Half, NumElts, InVec2, InVec3) &&
5644         ((InVec0.getOpcode() == ISD::UNDEF ||
5645           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5646         ((InVec1.getOpcode() == ISD::UNDEF ||
5647           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5648       X86Opcode = X86ISD::HSUB;
5649     else
5650       CanFold = false;
5651
5652     if (CanFold) {
5653       // Fold this build_vector into a single horizontal add/sub.
5654       // Do this only if the target has AVX2.
5655       if (Subtarget->hasAVX2())
5656         return DAG.getNode(X86Opcode, DL, VT, InVec0, InVec1);
5657
5658       // Do not try to expand this build_vector into a pair of horizontal
5659       // add/sub if we can emit a pair of scalar add/sub.
5660       if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
5661         return SDValue();
5662
5663       // Convert this build_vector into a pair of horizontal binop followed by
5664       // a concat vector.
5665       bool isUndefLO = NumUndefsLO == Half;
5666       bool isUndefHI = NumUndefsHI == Half;
5667       return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, false,
5668                                    isUndefLO, isUndefHI);
5669     }
5670   }
5671
5672   if ((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
5673        VT == MVT::v16i16) && Subtarget->hasAVX()) {
5674     unsigned X86Opcode;
5675     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
5676       X86Opcode = X86ISD::HADD;
5677     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
5678       X86Opcode = X86ISD::HSUB;
5679     else if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
5680       X86Opcode = X86ISD::FHADD;
5681     else if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
5682       X86Opcode = X86ISD::FHSUB;
5683     else
5684       return SDValue();
5685
5686     // Don't try to expand this build_vector into a pair of horizontal add/sub
5687     // if we can simply emit a pair of scalar add/sub.
5688     if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
5689       return SDValue();
5690
5691     // Convert this build_vector into two horizontal add/sub followed by
5692     // a concat vector.
5693     bool isUndefLO = NumUndefsLO == Half;
5694     bool isUndefHI = NumUndefsHI == Half;
5695     return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
5696                                  isUndefLO, isUndefHI);
5697   }
5698
5699   return SDValue();
5700 }
5701
5702 SDValue
5703 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5704   SDLoc dl(Op);
5705
5706   MVT VT = Op.getSimpleValueType();
5707   MVT ExtVT = VT.getVectorElementType();
5708   unsigned NumElems = Op.getNumOperands();
5709
5710   // Generate vectors for predicate vectors.
5711   if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
5712     return LowerBUILD_VECTORvXi1(Op, DAG);
5713
5714   // Vectors containing all zeros can be matched by pxor and xorps later
5715   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5716     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5717     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5718     if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
5719       return Op;
5720
5721     return getZeroVector(VT, Subtarget, DAG, dl);
5722   }
5723
5724   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5725   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5726   // vpcmpeqd on 256-bit vectors.
5727   if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
5728     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
5729       return Op;
5730
5731     if (!VT.is512BitVector())
5732       return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
5733   }
5734
5735   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(Op.getNode());
5736   if (SDValue AddSub = LowerToAddSub(BV, Subtarget, DAG))
5737     return AddSub;
5738   if (SDValue HorizontalOp = LowerToHorizontalOp(BV, Subtarget, DAG))
5739     return HorizontalOp;
5740   if (SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG))
5741     return Broadcast;
5742
5743   unsigned EVTBits = ExtVT.getSizeInBits();
5744
5745   unsigned NumZero  = 0;
5746   unsigned NumNonZero = 0;
5747   unsigned NonZeros = 0;
5748   bool IsAllConstants = true;
5749   SmallSet<SDValue, 8> Values;
5750   for (unsigned i = 0; i < NumElems; ++i) {
5751     SDValue Elt = Op.getOperand(i);
5752     if (Elt.getOpcode() == ISD::UNDEF)
5753       continue;
5754     Values.insert(Elt);
5755     if (Elt.getOpcode() != ISD::Constant &&
5756         Elt.getOpcode() != ISD::ConstantFP)
5757       IsAllConstants = false;
5758     if (X86::isZeroNode(Elt))
5759       NumZero++;
5760     else {
5761       NonZeros |= (1 << i);
5762       NumNonZero++;
5763     }
5764   }
5765
5766   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
5767   if (NumNonZero == 0)
5768     return DAG.getUNDEF(VT);
5769
5770   // Special case for single non-zero, non-undef, element.
5771   if (NumNonZero == 1) {
5772     unsigned Idx = countTrailingZeros(NonZeros);
5773     SDValue Item = Op.getOperand(Idx);
5774
5775     // If this is an insertion of an i64 value on x86-32, and if the top bits of
5776     // the value are obviously zero, truncate the value to i32 and do the
5777     // insertion that way.  Only do this if the value is non-constant or if the
5778     // value is a constant being inserted into element 0.  It is cheaper to do
5779     // a constant pool load than it is to do a movd + shuffle.
5780     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5781         (!IsAllConstants || Idx == 0)) {
5782       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5783         // Handle SSE only.
5784         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5785         EVT VecVT = MVT::v4i32;
5786
5787         // Truncate the value (which may itself be a constant) to i32, and
5788         // convert it to a vector with movd (S2V+shuffle to zero extend).
5789         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5790         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5791         return DAG.getNode(
5792             ISD::BITCAST, dl, VT,
5793             getShuffleVectorZeroOrUndef(Item, Idx * 2, true, Subtarget, DAG));
5794       }
5795     }
5796
5797     // If we have a constant or non-constant insertion into the low element of
5798     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5799     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
5800     // depending on what the source datatype is.
5801     if (Idx == 0) {
5802       if (NumZero == 0)
5803         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5804
5805       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5806           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5807         if (VT.is512BitVector()) {
5808           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
5809           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
5810                              Item, DAG.getIntPtrConstant(0, dl));
5811         }
5812         assert((VT.is128BitVector() || VT.is256BitVector()) &&
5813                "Expected an SSE value type!");
5814         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5815         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5816         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5817       }
5818
5819       // We can't directly insert an i8 or i16 into a vector, so zero extend
5820       // it to i32 first.
5821       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5822         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5823         if (VT.is256BitVector()) {
5824           if (Subtarget->hasAVX()) {
5825             Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v8i32, Item);
5826             Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5827           } else {
5828             // Without AVX, we need to extend to a 128-bit vector and then
5829             // insert into the 256-bit vector.
5830             Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5831             SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
5832             Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
5833           }
5834         } else {
5835           assert(VT.is128BitVector() && "Expected an SSE value type!");
5836           Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5837           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5838         }
5839         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5840       }
5841     }
5842
5843     // Is it a vector logical left shift?
5844     if (NumElems == 2 && Idx == 1 &&
5845         X86::isZeroNode(Op.getOperand(0)) &&
5846         !X86::isZeroNode(Op.getOperand(1))) {
5847       unsigned NumBits = VT.getSizeInBits();
5848       return getVShift(true, VT,
5849                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5850                                    VT, Op.getOperand(1)),
5851                        NumBits/2, DAG, *this, dl);
5852     }
5853
5854     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5855       return SDValue();
5856
5857     // Otherwise, if this is a vector with i32 or f32 elements, and the element
5858     // is a non-constant being inserted into an element other than the low one,
5859     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
5860     // movd/movss) to move this into the low element, then shuffle it into
5861     // place.
5862     if (EVTBits == 32) {
5863       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5864       return getShuffleVectorZeroOrUndef(Item, Idx, NumZero > 0, Subtarget, DAG);
5865     }
5866   }
5867
5868   // Splat is obviously ok. Let legalizer expand it to a shuffle.
5869   if (Values.size() == 1) {
5870     if (EVTBits == 32) {
5871       // Instead of a shuffle like this:
5872       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
5873       // Check if it's possible to issue this instead.
5874       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
5875       unsigned Idx = countTrailingZeros(NonZeros);
5876       SDValue Item = Op.getOperand(Idx);
5877       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
5878         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
5879     }
5880     return SDValue();
5881   }
5882
5883   // A vector full of immediates; various special cases are already
5884   // handled, so this is best done with a single constant-pool load.
5885   if (IsAllConstants)
5886     return SDValue();
5887
5888   // For AVX-length vectors, see if we can use a vector load to get all of the
5889   // elements, otherwise build the individual 128-bit pieces and use
5890   // shuffles to put them in place.
5891   if (VT.is256BitVector() || VT.is512BitVector()) {
5892     SmallVector<SDValue, 64> V(Op->op_begin(), Op->op_begin() + NumElems);
5893
5894     // Check for a build vector of consecutive loads.
5895     if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
5896       return LD;
5897
5898     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
5899
5900     // Build both the lower and upper subvector.
5901     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
5902                                 makeArrayRef(&V[0], NumElems/2));
5903     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
5904                                 makeArrayRef(&V[NumElems / 2], NumElems/2));
5905
5906     // Recreate the wider vector with the lower and upper part.
5907     if (VT.is256BitVector())
5908       return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
5909     return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
5910   }
5911
5912   // Let legalizer expand 2-wide build_vectors.
5913   if (EVTBits == 64) {
5914     if (NumNonZero == 1) {
5915       // One half is zero or undef.
5916       unsigned Idx = countTrailingZeros(NonZeros);
5917       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
5918                                  Op.getOperand(Idx));
5919       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
5920     }
5921     return SDValue();
5922   }
5923
5924   // If element VT is < 32 bits, convert it to inserts into a zero vector.
5925   if (EVTBits == 8 && NumElems == 16)
5926     if (SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
5927                                         Subtarget, *this))
5928       return V;
5929
5930   if (EVTBits == 16 && NumElems == 8)
5931     if (SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
5932                                       Subtarget, *this))
5933       return V;
5934
5935   // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
5936   if (EVTBits == 32 && NumElems == 4)
5937     if (SDValue V = LowerBuildVectorv4x32(Op, DAG, Subtarget, *this))
5938       return V;
5939
5940   // If element VT is == 32 bits, turn it into a number of shuffles.
5941   SmallVector<SDValue, 8> V(NumElems);
5942   if (NumElems == 4 && NumZero > 0) {
5943     for (unsigned i = 0; i < 4; ++i) {
5944       bool isZero = !(NonZeros & (1 << i));
5945       if (isZero)
5946         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
5947       else
5948         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5949     }
5950
5951     for (unsigned i = 0; i < 2; ++i) {
5952       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
5953         default: break;
5954         case 0:
5955           V[i] = V[i*2];  // Must be a zero vector.
5956           break;
5957         case 1:
5958           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
5959           break;
5960         case 2:
5961           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
5962           break;
5963         case 3:
5964           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
5965           break;
5966       }
5967     }
5968
5969     bool Reverse1 = (NonZeros & 0x3) == 2;
5970     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
5971     int MaskVec[] = {
5972       Reverse1 ? 1 : 0,
5973       Reverse1 ? 0 : 1,
5974       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
5975       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
5976     };
5977     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
5978   }
5979
5980   if (Values.size() > 1 && VT.is128BitVector()) {
5981     // Check for a build vector of consecutive loads.
5982     for (unsigned i = 0; i < NumElems; ++i)
5983       V[i] = Op.getOperand(i);
5984
5985     // Check for elements which are consecutive loads.
5986     if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
5987       return LD;
5988
5989     // Check for a build vector from mostly shuffle plus few inserting.
5990     if (SDValue Sh = buildFromShuffleMostly(Op, DAG))
5991       return Sh;
5992
5993     // For SSE 4.1, use insertps to put the high elements into the low element.
5994     if (Subtarget->hasSSE41()) {
5995       SDValue Result;
5996       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
5997         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
5998       else
5999         Result = DAG.getUNDEF(VT);
6000
6001       for (unsigned i = 1; i < NumElems; ++i) {
6002         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6003         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6004                              Op.getOperand(i), DAG.getIntPtrConstant(i, dl));
6005       }
6006       return Result;
6007     }
6008
6009     // Otherwise, expand into a number of unpckl*, start by extending each of
6010     // our (non-undef) elements to the full vector width with the element in the
6011     // bottom slot of the vector (which generates no code for SSE).
6012     for (unsigned i = 0; i < NumElems; ++i) {
6013       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6014         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6015       else
6016         V[i] = DAG.getUNDEF(VT);
6017     }
6018
6019     // Next, we iteratively mix elements, e.g. for v4f32:
6020     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6021     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6022     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
6023     unsigned EltStride = NumElems >> 1;
6024     while (EltStride != 0) {
6025       for (unsigned i = 0; i < EltStride; ++i) {
6026         // If V[i+EltStride] is undef and this is the first round of mixing,
6027         // then it is safe to just drop this shuffle: V[i] is already in the
6028         // right place, the one element (since it's the first round) being
6029         // inserted as undef can be dropped.  This isn't safe for successive
6030         // rounds because they will permute elements within both vectors.
6031         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6032             EltStride == NumElems/2)
6033           continue;
6034
6035         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6036       }
6037       EltStride >>= 1;
6038     }
6039     return V[0];
6040   }
6041   return SDValue();
6042 }
6043
6044 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
6045 // to create 256-bit vectors from two other 128-bit ones.
6046 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6047   SDLoc dl(Op);
6048   MVT ResVT = Op.getSimpleValueType();
6049
6050   assert((ResVT.is256BitVector() ||
6051           ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6052
6053   SDValue V1 = Op.getOperand(0);
6054   SDValue V2 = Op.getOperand(1);
6055   unsigned NumElems = ResVT.getVectorNumElements();
6056   if (ResVT.is256BitVector())
6057     return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6058
6059   if (Op.getNumOperands() == 4) {
6060     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6061                                 ResVT.getVectorNumElements()/2);
6062     SDValue V3 = Op.getOperand(2);
6063     SDValue V4 = Op.getOperand(3);
6064     return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6065       Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6066   }
6067   return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6068 }
6069
6070 static SDValue LowerCONCAT_VECTORSvXi1(SDValue Op,
6071                                        const X86Subtarget *Subtarget,
6072                                        SelectionDAG & DAG) {
6073   SDLoc dl(Op);
6074   MVT ResVT = Op.getSimpleValueType();
6075   unsigned NumOfOperands = Op.getNumOperands();
6076
6077   assert(isPowerOf2_32(NumOfOperands) &&
6078          "Unexpected number of operands in CONCAT_VECTORS");
6079
6080   if (NumOfOperands > 2) {
6081     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6082                                   ResVT.getVectorNumElements()/2);
6083     SmallVector<SDValue, 2> Ops;
6084     for (unsigned i = 0; i < NumOfOperands/2; i++)
6085       Ops.push_back(Op.getOperand(i));
6086     SDValue Lo = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6087     Ops.clear();
6088     for (unsigned i = NumOfOperands/2; i < NumOfOperands; i++)
6089       Ops.push_back(Op.getOperand(i));
6090     SDValue Hi = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6091     return DAG.getNode(ISD::CONCAT_VECTORS, dl, ResVT, Lo, Hi);
6092   }
6093
6094   SDValue V1 = Op.getOperand(0);
6095   SDValue V2 = Op.getOperand(1);
6096   bool IsZeroV1 = ISD::isBuildVectorAllZeros(V1.getNode());
6097   bool IsZeroV2 = ISD::isBuildVectorAllZeros(V2.getNode());
6098
6099   if (IsZeroV1 && IsZeroV2)
6100     return getZeroVector(ResVT, Subtarget, DAG, dl);
6101
6102   SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
6103   SDValue Undef = DAG.getUNDEF(ResVT);
6104   unsigned NumElems = ResVT.getVectorNumElements();
6105   SDValue ShiftBits = DAG.getConstant(NumElems/2, dl, MVT::i8);
6106
6107   V2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V2, ZeroIdx);
6108   V2 = DAG.getNode(X86ISD::VSHLI, dl, ResVT, V2, ShiftBits);
6109   if (IsZeroV1)
6110     return V2;
6111
6112   V1 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V1, ZeroIdx);
6113   // Zero the upper bits of V1
6114   V1 = DAG.getNode(X86ISD::VSHLI, dl, ResVT, V1, ShiftBits);
6115   V1 = DAG.getNode(X86ISD::VSRLI, dl, ResVT, V1, ShiftBits);
6116   if (IsZeroV2)
6117     return V1;
6118   return DAG.getNode(ISD::OR, dl, ResVT, V1, V2);
6119 }
6120
6121 static SDValue LowerCONCAT_VECTORS(SDValue Op,
6122                                    const X86Subtarget *Subtarget,
6123                                    SelectionDAG &DAG) {
6124   MVT VT = Op.getSimpleValueType();
6125   if (VT.getVectorElementType() == MVT::i1)
6126     return LowerCONCAT_VECTORSvXi1(Op, Subtarget, DAG);
6127
6128   assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6129          (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6130           Op.getNumOperands() == 4)));
6131
6132   // AVX can use the vinsertf128 instruction to create 256-bit vectors
6133   // from two other 128-bit ones.
6134
6135   // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6136   return LowerAVXCONCAT_VECTORS(Op, DAG);
6137 }
6138
6139
6140 //===----------------------------------------------------------------------===//
6141 // Vector shuffle lowering
6142 //
6143 // This is an experimental code path for lowering vector shuffles on x86. It is
6144 // designed to handle arbitrary vector shuffles and blends, gracefully
6145 // degrading performance as necessary. It works hard to recognize idiomatic
6146 // shuffles and lower them to optimal instruction patterns without leaving
6147 // a framework that allows reasonably efficient handling of all vector shuffle
6148 // patterns.
6149 //===----------------------------------------------------------------------===//
6150
6151 /// \brief Tiny helper function to identify a no-op mask.
6152 ///
6153 /// This is a somewhat boring predicate function. It checks whether the mask
6154 /// array input, which is assumed to be a single-input shuffle mask of the kind
6155 /// used by the X86 shuffle instructions (not a fully general
6156 /// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
6157 /// in-place shuffle are 'no-op's.
6158 static bool isNoopShuffleMask(ArrayRef<int> Mask) {
6159   for (int i = 0, Size = Mask.size(); i < Size; ++i)
6160     if (Mask[i] != -1 && Mask[i] != i)
6161       return false;
6162   return true;
6163 }
6164
6165 /// \brief Helper function to classify a mask as a single-input mask.
6166 ///
6167 /// This isn't a generic single-input test because in the vector shuffle
6168 /// lowering we canonicalize single inputs to be the first input operand. This
6169 /// means we can more quickly test for a single input by only checking whether
6170 /// an input from the second operand exists. We also assume that the size of
6171 /// mask corresponds to the size of the input vectors which isn't true in the
6172 /// fully general case.
6173 static bool isSingleInputShuffleMask(ArrayRef<int> Mask) {
6174   for (int M : Mask)
6175     if (M >= (int)Mask.size())
6176       return false;
6177   return true;
6178 }
6179
6180 /// \brief Test whether there are elements crossing 128-bit lanes in this
6181 /// shuffle mask.
6182 ///
6183 /// X86 divides up its shuffles into in-lane and cross-lane shuffle operations
6184 /// and we routinely test for these.
6185 static bool is128BitLaneCrossingShuffleMask(MVT VT, ArrayRef<int> Mask) {
6186   int LaneSize = 128 / VT.getScalarSizeInBits();
6187   int Size = Mask.size();
6188   for (int i = 0; i < Size; ++i)
6189     if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
6190       return true;
6191   return false;
6192 }
6193
6194 /// \brief Test whether a shuffle mask is equivalent within each 128-bit lane.
6195 ///
6196 /// This checks a shuffle mask to see if it is performing the same
6197 /// 128-bit lane-relative shuffle in each 128-bit lane. This trivially implies
6198 /// that it is also not lane-crossing. It may however involve a blend from the
6199 /// same lane of a second vector.
6200 ///
6201 /// The specific repeated shuffle mask is populated in \p RepeatedMask, as it is
6202 /// non-trivial to compute in the face of undef lanes. The representation is
6203 /// *not* suitable for use with existing 128-bit shuffles as it will contain
6204 /// entries from both V1 and V2 inputs to the wider mask.
6205 static bool
6206 is128BitLaneRepeatedShuffleMask(MVT VT, ArrayRef<int> Mask,
6207                                 SmallVectorImpl<int> &RepeatedMask) {
6208   int LaneSize = 128 / VT.getScalarSizeInBits();
6209   RepeatedMask.resize(LaneSize, -1);
6210   int Size = Mask.size();
6211   for (int i = 0; i < Size; ++i) {
6212     if (Mask[i] < 0)
6213       continue;
6214     if ((Mask[i] % Size) / LaneSize != i / LaneSize)
6215       // This entry crosses lanes, so there is no way to model this shuffle.
6216       return false;
6217
6218     // Ok, handle the in-lane shuffles by detecting if and when they repeat.
6219     if (RepeatedMask[i % LaneSize] == -1)
6220       // This is the first non-undef entry in this slot of a 128-bit lane.
6221       RepeatedMask[i % LaneSize] =
6222           Mask[i] < Size ? Mask[i] % LaneSize : Mask[i] % LaneSize + Size;
6223     else if (RepeatedMask[i % LaneSize] + (i / LaneSize) * LaneSize != Mask[i])
6224       // Found a mismatch with the repeated mask.
6225       return false;
6226   }
6227   return true;
6228 }
6229
6230 /// \brief Checks whether a shuffle mask is equivalent to an explicit list of
6231 /// arguments.
6232 ///
6233 /// This is a fast way to test a shuffle mask against a fixed pattern:
6234 ///
6235 ///   if (isShuffleEquivalent(Mask, 3, 2, {1, 0})) { ... }
6236 ///
6237 /// It returns true if the mask is exactly as wide as the argument list, and
6238 /// each element of the mask is either -1 (signifying undef) or the value given
6239 /// in the argument.
6240 static bool isShuffleEquivalent(SDValue V1, SDValue V2, ArrayRef<int> Mask,
6241                                 ArrayRef<int> ExpectedMask) {
6242   if (Mask.size() != ExpectedMask.size())
6243     return false;
6244
6245   int Size = Mask.size();
6246
6247   // If the values are build vectors, we can look through them to find
6248   // equivalent inputs that make the shuffles equivalent.
6249   auto *BV1 = dyn_cast<BuildVectorSDNode>(V1);
6250   auto *BV2 = dyn_cast<BuildVectorSDNode>(V2);
6251
6252   for (int i = 0; i < Size; ++i)
6253     if (Mask[i] != -1 && Mask[i] != ExpectedMask[i]) {
6254       auto *MaskBV = Mask[i] < Size ? BV1 : BV2;
6255       auto *ExpectedBV = ExpectedMask[i] < Size ? BV1 : BV2;
6256       if (!MaskBV || !ExpectedBV ||
6257           MaskBV->getOperand(Mask[i] % Size) !=
6258               ExpectedBV->getOperand(ExpectedMask[i] % Size))
6259         return false;
6260     }
6261
6262   return true;
6263 }
6264
6265 /// \brief Get a 4-lane 8-bit shuffle immediate for a mask.
6266 ///
6267 /// This helper function produces an 8-bit shuffle immediate corresponding to
6268 /// the ubiquitous shuffle encoding scheme used in x86 instructions for
6269 /// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
6270 /// example.
6271 ///
6272 /// NB: We rely heavily on "undef" masks preserving the input lane.
6273 static SDValue getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask, SDLoc DL,
6274                                           SelectionDAG &DAG) {
6275   assert(Mask.size() == 4 && "Only 4-lane shuffle masks");
6276   assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!");
6277   assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!");
6278   assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!");
6279   assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!");
6280
6281   unsigned Imm = 0;
6282   Imm |= (Mask[0] == -1 ? 0 : Mask[0]) << 0;
6283   Imm |= (Mask[1] == -1 ? 1 : Mask[1]) << 2;
6284   Imm |= (Mask[2] == -1 ? 2 : Mask[2]) << 4;
6285   Imm |= (Mask[3] == -1 ? 3 : Mask[3]) << 6;
6286   return DAG.getConstant(Imm, DL, MVT::i8);
6287 }
6288
6289 /// \brief Try to emit a blend instruction for a shuffle using bit math.
6290 ///
6291 /// This is used as a fallback approach when first class blend instructions are
6292 /// unavailable. Currently it is only suitable for integer vectors, but could
6293 /// be generalized for floating point vectors if desirable.
6294 static SDValue lowerVectorShuffleAsBitBlend(SDLoc DL, MVT VT, SDValue V1,
6295                                             SDValue V2, ArrayRef<int> Mask,
6296                                             SelectionDAG &DAG) {
6297   assert(VT.isInteger() && "Only supports integer vector types!");
6298   MVT EltVT = VT.getScalarType();
6299   int NumEltBits = EltVT.getSizeInBits();
6300   SDValue Zero = DAG.getConstant(0, DL, EltVT);
6301   SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
6302                                     EltVT);
6303   SmallVector<SDValue, 16> MaskOps;
6304   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6305     if (Mask[i] != -1 && Mask[i] != i && Mask[i] != i + Size)
6306       return SDValue(); // Shuffled input!
6307     MaskOps.push_back(Mask[i] < Size ? AllOnes : Zero);
6308   }
6309
6310   SDValue V1Mask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, MaskOps);
6311   V1 = DAG.getNode(ISD::AND, DL, VT, V1, V1Mask);
6312   // We have to cast V2 around.
6313   MVT MaskVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
6314   V2 = DAG.getNode(ISD::BITCAST, DL, VT,
6315                    DAG.getNode(X86ISD::ANDNP, DL, MaskVT,
6316                                DAG.getNode(ISD::BITCAST, DL, MaskVT, V1Mask),
6317                                DAG.getNode(ISD::BITCAST, DL, MaskVT, V2)));
6318   return DAG.getNode(ISD::OR, DL, VT, V1, V2);
6319 }
6320
6321 /// \brief Try to emit a blend instruction for a shuffle.
6322 ///
6323 /// This doesn't do any checks for the availability of instructions for blending
6324 /// these values. It relies on the availability of the X86ISD::BLENDI pattern to
6325 /// be matched in the backend with the type given. What it does check for is
6326 /// that the shuffle mask is in fact a blend.
6327 static SDValue lowerVectorShuffleAsBlend(SDLoc DL, MVT VT, SDValue V1,
6328                                          SDValue V2, ArrayRef<int> Mask,
6329                                          const X86Subtarget *Subtarget,
6330                                          SelectionDAG &DAG) {
6331   unsigned BlendMask = 0;
6332   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6333     if (Mask[i] >= Size) {
6334       if (Mask[i] != i + Size)
6335         return SDValue(); // Shuffled V2 input!
6336       BlendMask |= 1u << i;
6337       continue;
6338     }
6339     if (Mask[i] >= 0 && Mask[i] != i)
6340       return SDValue(); // Shuffled V1 input!
6341   }
6342   switch (VT.SimpleTy) {
6343   case MVT::v2f64:
6344   case MVT::v4f32:
6345   case MVT::v4f64:
6346   case MVT::v8f32:
6347     return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V2,
6348                        DAG.getConstant(BlendMask, DL, MVT::i8));
6349
6350   case MVT::v4i64:
6351   case MVT::v8i32:
6352     assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6353     // FALLTHROUGH
6354   case MVT::v2i64:
6355   case MVT::v4i32:
6356     // If we have AVX2 it is faster to use VPBLENDD when the shuffle fits into
6357     // that instruction.
6358     if (Subtarget->hasAVX2()) {
6359       // Scale the blend by the number of 32-bit dwords per element.
6360       int Scale =  VT.getScalarSizeInBits() / 32;
6361       BlendMask = 0;
6362       for (int i = 0, Size = Mask.size(); i < Size; ++i)
6363         if (Mask[i] >= Size)
6364           for (int j = 0; j < Scale; ++j)
6365             BlendMask |= 1u << (i * Scale + j);
6366
6367       MVT BlendVT = VT.getSizeInBits() > 128 ? MVT::v8i32 : MVT::v4i32;
6368       V1 = DAG.getNode(ISD::BITCAST, DL, BlendVT, V1);
6369       V2 = DAG.getNode(ISD::BITCAST, DL, BlendVT, V2);
6370       return DAG.getNode(ISD::BITCAST, DL, VT,
6371                          DAG.getNode(X86ISD::BLENDI, DL, BlendVT, V1, V2,
6372                                      DAG.getConstant(BlendMask, DL, MVT::i8)));
6373     }
6374     // FALLTHROUGH
6375   case MVT::v8i16: {
6376     // For integer shuffles we need to expand the mask and cast the inputs to
6377     // v8i16s prior to blending.
6378     int Scale = 8 / VT.getVectorNumElements();
6379     BlendMask = 0;
6380     for (int i = 0, Size = Mask.size(); i < Size; ++i)
6381       if (Mask[i] >= Size)
6382         for (int j = 0; j < Scale; ++j)
6383           BlendMask |= 1u << (i * Scale + j);
6384
6385     V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1);
6386     V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V2);
6387     return DAG.getNode(ISD::BITCAST, DL, VT,
6388                        DAG.getNode(X86ISD::BLENDI, DL, MVT::v8i16, V1, V2,
6389                                    DAG.getConstant(BlendMask, DL, MVT::i8)));
6390   }
6391
6392   case MVT::v16i16: {
6393     assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6394     SmallVector<int, 8> RepeatedMask;
6395     if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
6396       // We can lower these with PBLENDW which is mirrored across 128-bit lanes.
6397       assert(RepeatedMask.size() == 8 && "Repeated mask size doesn't match!");
6398       BlendMask = 0;
6399       for (int i = 0; i < 8; ++i)
6400         if (RepeatedMask[i] >= 16)
6401           BlendMask |= 1u << i;
6402       return DAG.getNode(X86ISD::BLENDI, DL, MVT::v16i16, V1, V2,
6403                          DAG.getConstant(BlendMask, DL, MVT::i8));
6404     }
6405   }
6406     // FALLTHROUGH
6407   case MVT::v16i8:
6408   case MVT::v32i8: {
6409     assert((VT.getSizeInBits() == 128 || Subtarget->hasAVX2()) &&
6410            "256-bit byte-blends require AVX2 support!");
6411
6412     // Scale the blend by the number of bytes per element.
6413     int Scale = VT.getScalarSizeInBits() / 8;
6414
6415     // This form of blend is always done on bytes. Compute the byte vector
6416     // type.
6417     MVT BlendVT = MVT::getVectorVT(MVT::i8, VT.getSizeInBits() / 8);
6418
6419     // Compute the VSELECT mask. Note that VSELECT is really confusing in the
6420     // mix of LLVM's code generator and the x86 backend. We tell the code
6421     // generator that boolean values in the elements of an x86 vector register
6422     // are -1 for true and 0 for false. We then use the LLVM semantics of 'true'
6423     // mapping a select to operand #1, and 'false' mapping to operand #2. The
6424     // reality in x86 is that vector masks (pre-AVX-512) use only the high bit
6425     // of the element (the remaining are ignored) and 0 in that high bit would
6426     // mean operand #1 while 1 in the high bit would mean operand #2. So while
6427     // the LLVM model for boolean values in vector elements gets the relevant
6428     // bit set, it is set backwards and over constrained relative to x86's
6429     // actual model.
6430     SmallVector<SDValue, 32> VSELECTMask;
6431     for (int i = 0, Size = Mask.size(); i < Size; ++i)
6432       for (int j = 0; j < Scale; ++j)
6433         VSELECTMask.push_back(
6434             Mask[i] < 0 ? DAG.getUNDEF(MVT::i8)
6435                         : DAG.getConstant(Mask[i] < Size ? -1 : 0, DL,
6436                                           MVT::i8));
6437
6438     V1 = DAG.getNode(ISD::BITCAST, DL, BlendVT, V1);
6439     V2 = DAG.getNode(ISD::BITCAST, DL, BlendVT, V2);
6440     return DAG.getNode(
6441         ISD::BITCAST, DL, VT,
6442         DAG.getNode(ISD::VSELECT, DL, BlendVT,
6443                     DAG.getNode(ISD::BUILD_VECTOR, DL, BlendVT, VSELECTMask),
6444                     V1, V2));
6445   }
6446
6447   default:
6448     llvm_unreachable("Not a supported integer vector type!");
6449   }
6450 }
6451
6452 /// \brief Try to lower as a blend of elements from two inputs followed by
6453 /// a single-input permutation.
6454 ///
6455 /// This matches the pattern where we can blend elements from two inputs and
6456 /// then reduce the shuffle to a single-input permutation.
6457 static SDValue lowerVectorShuffleAsBlendAndPermute(SDLoc DL, MVT VT, SDValue V1,
6458                                                    SDValue V2,
6459                                                    ArrayRef<int> Mask,
6460                                                    SelectionDAG &DAG) {
6461   // We build up the blend mask while checking whether a blend is a viable way
6462   // to reduce the shuffle.
6463   SmallVector<int, 32> BlendMask(Mask.size(), -1);
6464   SmallVector<int, 32> PermuteMask(Mask.size(), -1);
6465
6466   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6467     if (Mask[i] < 0)
6468       continue;
6469
6470     assert(Mask[i] < Size * 2 && "Shuffle input is out of bounds.");
6471
6472     if (BlendMask[Mask[i] % Size] == -1)
6473       BlendMask[Mask[i] % Size] = Mask[i];
6474     else if (BlendMask[Mask[i] % Size] != Mask[i])
6475       return SDValue(); // Can't blend in the needed input!
6476
6477     PermuteMask[i] = Mask[i] % Size;
6478   }
6479
6480   SDValue V = DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
6481   return DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), PermuteMask);
6482 }
6483
6484 /// \brief Generic routine to decompose a shuffle and blend into indepndent
6485 /// blends and permutes.
6486 ///
6487 /// This matches the extremely common pattern for handling combined
6488 /// shuffle+blend operations on newer X86 ISAs where we have very fast blend
6489 /// operations. It will try to pick the best arrangement of shuffles and
6490 /// blends.
6491 static SDValue lowerVectorShuffleAsDecomposedShuffleBlend(SDLoc DL, MVT VT,
6492                                                           SDValue V1,
6493                                                           SDValue V2,
6494                                                           ArrayRef<int> Mask,
6495                                                           SelectionDAG &DAG) {
6496   // Shuffle the input elements into the desired positions in V1 and V2 and
6497   // blend them together.
6498   SmallVector<int, 32> V1Mask(Mask.size(), -1);
6499   SmallVector<int, 32> V2Mask(Mask.size(), -1);
6500   SmallVector<int, 32> BlendMask(Mask.size(), -1);
6501   for (int i = 0, Size = Mask.size(); i < Size; ++i)
6502     if (Mask[i] >= 0 && Mask[i] < Size) {
6503       V1Mask[i] = Mask[i];
6504       BlendMask[i] = i;
6505     } else if (Mask[i] >= Size) {
6506       V2Mask[i] = Mask[i] - Size;
6507       BlendMask[i] = i + Size;
6508     }
6509
6510   // Try to lower with the simpler initial blend strategy unless one of the
6511   // input shuffles would be a no-op. We prefer to shuffle inputs as the
6512   // shuffle may be able to fold with a load or other benefit. However, when
6513   // we'll have to do 2x as many shuffles in order to achieve this, blending
6514   // first is a better strategy.
6515   if (!isNoopShuffleMask(V1Mask) && !isNoopShuffleMask(V2Mask))
6516     if (SDValue BlendPerm =
6517             lowerVectorShuffleAsBlendAndPermute(DL, VT, V1, V2, Mask, DAG))
6518       return BlendPerm;
6519
6520   V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
6521   V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
6522   return DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
6523 }
6524
6525 /// \brief Try to lower a vector shuffle as a byte rotation.
6526 ///
6527 /// SSSE3 has a generic PALIGNR instruction in x86 that will do an arbitrary
6528 /// byte-rotation of the concatenation of two vectors; pre-SSSE3 can use
6529 /// a PSRLDQ/PSLLDQ/POR pattern to get a similar effect. This routine will
6530 /// try to generically lower a vector shuffle through such an pattern. It
6531 /// does not check for the profitability of lowering either as PALIGNR or
6532 /// PSRLDQ/PSLLDQ/POR, only whether the mask is valid to lower in that form.
6533 /// This matches shuffle vectors that look like:
6534 ///
6535 ///   v8i16 [11, 12, 13, 14, 15, 0, 1, 2]
6536 ///
6537 /// Essentially it concatenates V1 and V2, shifts right by some number of
6538 /// elements, and takes the low elements as the result. Note that while this is
6539 /// specified as a *right shift* because x86 is little-endian, it is a *left
6540 /// rotate* of the vector lanes.
6541 static SDValue lowerVectorShuffleAsByteRotate(SDLoc DL, MVT VT, SDValue V1,
6542                                               SDValue V2,
6543                                               ArrayRef<int> Mask,
6544                                               const X86Subtarget *Subtarget,
6545                                               SelectionDAG &DAG) {
6546   assert(!isNoopShuffleMask(Mask) && "We shouldn't lower no-op shuffles!");
6547
6548   int NumElts = Mask.size();
6549   int NumLanes = VT.getSizeInBits() / 128;
6550   int NumLaneElts = NumElts / NumLanes;
6551
6552   // We need to detect various ways of spelling a rotation:
6553   //   [11, 12, 13, 14, 15,  0,  1,  2]
6554   //   [-1, 12, 13, 14, -1, -1,  1, -1]
6555   //   [-1, -1, -1, -1, -1, -1,  1,  2]
6556   //   [ 3,  4,  5,  6,  7,  8,  9, 10]
6557   //   [-1,  4,  5,  6, -1, -1,  9, -1]
6558   //   [-1,  4,  5,  6, -1, -1, -1, -1]
6559   int Rotation = 0;
6560   SDValue Lo, Hi;
6561   for (int l = 0; l < NumElts; l += NumLaneElts) {
6562     for (int i = 0; i < NumLaneElts; ++i) {
6563       if (Mask[l + i] == -1)
6564         continue;
6565       assert(Mask[l + i] >= 0 && "Only -1 is a valid negative mask element!");
6566
6567       // Get the mod-Size index and lane correct it.
6568       int LaneIdx = (Mask[l + i] % NumElts) - l;
6569       // Make sure it was in this lane.
6570       if (LaneIdx < 0 || LaneIdx >= NumLaneElts)
6571         return SDValue();
6572
6573       // Determine where a rotated vector would have started.
6574       int StartIdx = i - LaneIdx;
6575       if (StartIdx == 0)
6576         // The identity rotation isn't interesting, stop.
6577         return SDValue();
6578
6579       // If we found the tail of a vector the rotation must be the missing
6580       // front. If we found the head of a vector, it must be how much of the
6581       // head.
6582       int CandidateRotation = StartIdx < 0 ? -StartIdx : NumLaneElts - StartIdx;
6583
6584       if (Rotation == 0)
6585         Rotation = CandidateRotation;
6586       else if (Rotation != CandidateRotation)
6587         // The rotations don't match, so we can't match this mask.
6588         return SDValue();
6589
6590       // Compute which value this mask is pointing at.
6591       SDValue MaskV = Mask[l + i] < NumElts ? V1 : V2;
6592
6593       // Compute which of the two target values this index should be assigned
6594       // to. This reflects whether the high elements are remaining or the low
6595       // elements are remaining.
6596       SDValue &TargetV = StartIdx < 0 ? Hi : Lo;
6597
6598       // Either set up this value if we've not encountered it before, or check
6599       // that it remains consistent.
6600       if (!TargetV)
6601         TargetV = MaskV;
6602       else if (TargetV != MaskV)
6603         // This may be a rotation, but it pulls from the inputs in some
6604         // unsupported interleaving.
6605         return SDValue();
6606     }
6607   }
6608
6609   // Check that we successfully analyzed the mask, and normalize the results.
6610   assert(Rotation != 0 && "Failed to locate a viable rotation!");
6611   assert((Lo || Hi) && "Failed to find a rotated input vector!");
6612   if (!Lo)
6613     Lo = Hi;
6614   else if (!Hi)
6615     Hi = Lo;
6616
6617   // The actual rotate instruction rotates bytes, so we need to scale the
6618   // rotation based on how many bytes are in the vector lane.
6619   int Scale = 16 / NumLaneElts;
6620
6621   // SSSE3 targets can use the palignr instruction.
6622   if (Subtarget->hasSSSE3()) {
6623     // Cast the inputs to i8 vector of correct length to match PALIGNR.
6624     MVT AlignVT = MVT::getVectorVT(MVT::i8, 16 * NumLanes);
6625     Lo = DAG.getNode(ISD::BITCAST, DL, AlignVT, Lo);
6626     Hi = DAG.getNode(ISD::BITCAST, DL, AlignVT, Hi);
6627
6628     return DAG.getNode(ISD::BITCAST, DL, VT,
6629                        DAG.getNode(X86ISD::PALIGNR, DL, AlignVT, Hi, Lo,
6630                                    DAG.getConstant(Rotation * Scale, DL,
6631                                                    MVT::i8)));
6632   }
6633
6634   assert(VT.getSizeInBits() == 128 &&
6635          "Rotate-based lowering only supports 128-bit lowering!");
6636   assert(Mask.size() <= 16 &&
6637          "Can shuffle at most 16 bytes in a 128-bit vector!");
6638
6639   // Default SSE2 implementation
6640   int LoByteShift = 16 - Rotation * Scale;
6641   int HiByteShift = Rotation * Scale;
6642
6643   // Cast the inputs to v2i64 to match PSLLDQ/PSRLDQ.
6644   Lo = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Lo);
6645   Hi = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Hi);
6646
6647   SDValue LoShift = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v2i64, Lo,
6648                                 DAG.getConstant(LoByteShift, DL, MVT::i8));
6649   SDValue HiShift = DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v2i64, Hi,
6650                                 DAG.getConstant(HiByteShift, DL, MVT::i8));
6651   return DAG.getNode(ISD::BITCAST, DL, VT,
6652                      DAG.getNode(ISD::OR, DL, MVT::v2i64, LoShift, HiShift));
6653 }
6654
6655 /// \brief Compute whether each element of a shuffle is zeroable.
6656 ///
6657 /// A "zeroable" vector shuffle element is one which can be lowered to zero.
6658 /// Either it is an undef element in the shuffle mask, the element of the input
6659 /// referenced is undef, or the element of the input referenced is known to be
6660 /// zero. Many x86 shuffles can zero lanes cheaply and we often want to handle
6661 /// as many lanes with this technique as possible to simplify the remaining
6662 /// shuffle.
6663 static SmallBitVector computeZeroableShuffleElements(ArrayRef<int> Mask,
6664                                                      SDValue V1, SDValue V2) {
6665   SmallBitVector Zeroable(Mask.size(), false);
6666
6667   while (V1.getOpcode() == ISD::BITCAST)
6668     V1 = V1->getOperand(0);
6669   while (V2.getOpcode() == ISD::BITCAST)
6670     V2 = V2->getOperand(0);
6671
6672   bool V1IsZero = ISD::isBuildVectorAllZeros(V1.getNode());
6673   bool V2IsZero = ISD::isBuildVectorAllZeros(V2.getNode());
6674
6675   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6676     int M = Mask[i];
6677     // Handle the easy cases.
6678     if (M < 0 || (M >= 0 && M < Size && V1IsZero) || (M >= Size && V2IsZero)) {
6679       Zeroable[i] = true;
6680       continue;
6681     }
6682
6683     // If this is an index into a build_vector node (which has the same number
6684     // of elements), dig out the input value and use it.
6685     SDValue V = M < Size ? V1 : V2;
6686     if (V.getOpcode() != ISD::BUILD_VECTOR || Size != (int)V.getNumOperands())
6687       continue;
6688
6689     SDValue Input = V.getOperand(M % Size);
6690     // The UNDEF opcode check really should be dead code here, but not quite
6691     // worth asserting on (it isn't invalid, just unexpected).
6692     if (Input.getOpcode() == ISD::UNDEF || X86::isZeroNode(Input))
6693       Zeroable[i] = true;
6694   }
6695
6696   return Zeroable;
6697 }
6698
6699 /// \brief Try to emit a bitmask instruction for a shuffle.
6700 ///
6701 /// This handles cases where we can model a blend exactly as a bitmask due to
6702 /// one of the inputs being zeroable.
6703 static SDValue lowerVectorShuffleAsBitMask(SDLoc DL, MVT VT, SDValue V1,
6704                                            SDValue V2, ArrayRef<int> Mask,
6705                                            SelectionDAG &DAG) {
6706   MVT EltVT = VT.getScalarType();
6707   int NumEltBits = EltVT.getSizeInBits();
6708   MVT IntEltVT = MVT::getIntegerVT(NumEltBits);
6709   SDValue Zero = DAG.getConstant(0, DL, IntEltVT);
6710   SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
6711                                     IntEltVT);
6712   if (EltVT.isFloatingPoint()) {
6713     Zero = DAG.getNode(ISD::BITCAST, DL, EltVT, Zero);
6714     AllOnes = DAG.getNode(ISD::BITCAST, DL, EltVT, AllOnes);
6715   }
6716   SmallVector<SDValue, 16> VMaskOps(Mask.size(), Zero);
6717   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6718   SDValue V;
6719   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6720     if (Zeroable[i])
6721       continue;
6722     if (Mask[i] % Size != i)
6723       return SDValue(); // Not a blend.
6724     if (!V)
6725       V = Mask[i] < Size ? V1 : V2;
6726     else if (V != (Mask[i] < Size ? V1 : V2))
6727       return SDValue(); // Can only let one input through the mask.
6728
6729     VMaskOps[i] = AllOnes;
6730   }
6731   if (!V)
6732     return SDValue(); // No non-zeroable elements!
6733
6734   SDValue VMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, VMaskOps);
6735   V = DAG.getNode(VT.isFloatingPoint()
6736                   ? (unsigned) X86ISD::FAND : (unsigned) ISD::AND,
6737                   DL, VT, V, VMask);
6738   return V;
6739 }
6740
6741 /// \brief Try to lower a vector shuffle as a bit shift (shifts in zeros).
6742 ///
6743 /// Attempts to match a shuffle mask against the PSLL(W/D/Q/DQ) and
6744 /// PSRL(W/D/Q/DQ) SSE2 and AVX2 logical bit-shift instructions. The function
6745 /// matches elements from one of the input vectors shuffled to the left or
6746 /// right with zeroable elements 'shifted in'. It handles both the strictly
6747 /// bit-wise element shifts and the byte shift across an entire 128-bit double
6748 /// quad word lane.
6749 ///
6750 /// PSHL : (little-endian) left bit shift.
6751 /// [ zz, 0, zz,  2 ]
6752 /// [ -1, 4, zz, -1 ]
6753 /// PSRL : (little-endian) right bit shift.
6754 /// [  1, zz,  3, zz]
6755 /// [ -1, -1,  7, zz]
6756 /// PSLLDQ : (little-endian) left byte shift
6757 /// [ zz,  0,  1,  2,  3,  4,  5,  6]
6758 /// [ zz, zz, -1, -1,  2,  3,  4, -1]
6759 /// [ zz, zz, zz, zz, zz, zz, -1,  1]
6760 /// PSRLDQ : (little-endian) right byte shift
6761 /// [  5, 6,  7, zz, zz, zz, zz, zz]
6762 /// [ -1, 5,  6,  7, zz, zz, zz, zz]
6763 /// [  1, 2, -1, -1, -1, -1, zz, zz]
6764 static SDValue lowerVectorShuffleAsShift(SDLoc DL, MVT VT, SDValue V1,
6765                                          SDValue V2, ArrayRef<int> Mask,
6766                                          SelectionDAG &DAG) {
6767   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6768
6769   int Size = Mask.size();
6770   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
6771
6772   auto CheckZeros = [&](int Shift, int Scale, bool Left) {
6773     for (int i = 0; i < Size; i += Scale)
6774       for (int j = 0; j < Shift; ++j)
6775         if (!Zeroable[i + j + (Left ? 0 : (Scale - Shift))])
6776           return false;
6777
6778     return true;
6779   };
6780
6781   auto MatchShift = [&](int Shift, int Scale, bool Left, SDValue V) {
6782     for (int i = 0; i != Size; i += Scale) {
6783       unsigned Pos = Left ? i + Shift : i;
6784       unsigned Low = Left ? i : i + Shift;
6785       unsigned Len = Scale - Shift;
6786       if (!isSequentialOrUndefInRange(Mask, Pos, Len,
6787                                       Low + (V == V1 ? 0 : Size)))
6788         return SDValue();
6789     }
6790
6791     int ShiftEltBits = VT.getScalarSizeInBits() * Scale;
6792     bool ByteShift = ShiftEltBits > 64;
6793     unsigned OpCode = Left ? (ByteShift ? X86ISD::VSHLDQ : X86ISD::VSHLI)
6794                            : (ByteShift ? X86ISD::VSRLDQ : X86ISD::VSRLI);
6795     int ShiftAmt = Shift * VT.getScalarSizeInBits() / (ByteShift ? 8 : 1);
6796
6797     // Normalize the scale for byte shifts to still produce an i64 element
6798     // type.
6799     Scale = ByteShift ? Scale / 2 : Scale;
6800
6801     // We need to round trip through the appropriate type for the shift.
6802     MVT ShiftSVT = MVT::getIntegerVT(VT.getScalarSizeInBits() * Scale);
6803     MVT ShiftVT = MVT::getVectorVT(ShiftSVT, Size / Scale);
6804     assert(DAG.getTargetLoweringInfo().isTypeLegal(ShiftVT) &&
6805            "Illegal integer vector type");
6806     V = DAG.getNode(ISD::BITCAST, DL, ShiftVT, V);
6807
6808     V = DAG.getNode(OpCode, DL, ShiftVT, V,
6809                     DAG.getConstant(ShiftAmt, DL, MVT::i8));
6810     return DAG.getNode(ISD::BITCAST, DL, VT, V);
6811   };
6812
6813   // SSE/AVX supports logical shifts up to 64-bit integers - so we can just
6814   // keep doubling the size of the integer elements up to that. We can
6815   // then shift the elements of the integer vector by whole multiples of
6816   // their width within the elements of the larger integer vector. Test each
6817   // multiple to see if we can find a match with the moved element indices
6818   // and that the shifted in elements are all zeroable.
6819   for (int Scale = 2; Scale * VT.getScalarSizeInBits() <= 128; Scale *= 2)
6820     for (int Shift = 1; Shift != Scale; ++Shift)
6821       for (bool Left : {true, false})
6822         if (CheckZeros(Shift, Scale, Left))
6823           for (SDValue V : {V1, V2})
6824             if (SDValue Match = MatchShift(Shift, Scale, Left, V))
6825               return Match;
6826
6827   // no match
6828   return SDValue();
6829 }
6830
6831 /// \brief Lower a vector shuffle as a zero or any extension.
6832 ///
6833 /// Given a specific number of elements, element bit width, and extension
6834 /// stride, produce either a zero or any extension based on the available
6835 /// features of the subtarget.
6836 static SDValue lowerVectorShuffleAsSpecificZeroOrAnyExtend(
6837     SDLoc DL, MVT VT, int Scale, bool AnyExt, SDValue InputV,
6838     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
6839   assert(Scale > 1 && "Need a scale to extend.");
6840   int NumElements = VT.getVectorNumElements();
6841   int EltBits = VT.getScalarSizeInBits();
6842   assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
6843          "Only 8, 16, and 32 bit elements can be extended.");
6844   assert(Scale * EltBits <= 64 && "Cannot zero extend past 64 bits.");
6845
6846   // Found a valid zext mask! Try various lowering strategies based on the
6847   // input type and available ISA extensions.
6848   if (Subtarget->hasSSE41()) {
6849     MVT ExtVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits * Scale),
6850                                  NumElements / Scale);
6851     return DAG.getNode(ISD::BITCAST, DL, VT,
6852                        DAG.getNode(X86ISD::VZEXT, DL, ExtVT, InputV));
6853   }
6854
6855   // For any extends we can cheat for larger element sizes and use shuffle
6856   // instructions that can fold with a load and/or copy.
6857   if (AnyExt && EltBits == 32) {
6858     int PSHUFDMask[4] = {0, -1, 1, -1};
6859     return DAG.getNode(
6860         ISD::BITCAST, DL, VT,
6861         DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
6862                     DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, InputV),
6863                     getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
6864   }
6865   if (AnyExt && EltBits == 16 && Scale > 2) {
6866     int PSHUFDMask[4] = {0, -1, 0, -1};
6867     InputV = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
6868                          DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, InputV),
6869                          getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG));
6870     int PSHUFHWMask[4] = {1, -1, -1, -1};
6871     return DAG.getNode(
6872         ISD::BITCAST, DL, VT,
6873         DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16,
6874                     DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, InputV),
6875                     getV4X86ShuffleImm8ForMask(PSHUFHWMask, DL, DAG)));
6876   }
6877
6878   // If this would require more than 2 unpack instructions to expand, use
6879   // pshufb when available. We can only use more than 2 unpack instructions
6880   // when zero extending i8 elements which also makes it easier to use pshufb.
6881   if (Scale > 4 && EltBits == 8 && Subtarget->hasSSSE3()) {
6882     assert(NumElements == 16 && "Unexpected byte vector width!");
6883     SDValue PSHUFBMask[16];
6884     for (int i = 0; i < 16; ++i)
6885       PSHUFBMask[i] =
6886           DAG.getConstant((i % Scale == 0) ? i / Scale : 0x80, DL, MVT::i8);
6887     InputV = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, InputV);
6888     return DAG.getNode(ISD::BITCAST, DL, VT,
6889                        DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, InputV,
6890                                    DAG.getNode(ISD::BUILD_VECTOR, DL,
6891                                                MVT::v16i8, PSHUFBMask)));
6892   }
6893
6894   // Otherwise emit a sequence of unpacks.
6895   do {
6896     MVT InputVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits), NumElements);
6897     SDValue Ext = AnyExt ? DAG.getUNDEF(InputVT)
6898                          : getZeroVector(InputVT, Subtarget, DAG, DL);
6899     InputV = DAG.getNode(ISD::BITCAST, DL, InputVT, InputV);
6900     InputV = DAG.getNode(X86ISD::UNPCKL, DL, InputVT, InputV, Ext);
6901     Scale /= 2;
6902     EltBits *= 2;
6903     NumElements /= 2;
6904   } while (Scale > 1);
6905   return DAG.getNode(ISD::BITCAST, DL, VT, InputV);
6906 }
6907
6908 /// \brief Try to lower a vector shuffle as a zero extension on any microarch.
6909 ///
6910 /// This routine will try to do everything in its power to cleverly lower
6911 /// a shuffle which happens to match the pattern of a zero extend. It doesn't
6912 /// check for the profitability of this lowering,  it tries to aggressively
6913 /// match this pattern. It will use all of the micro-architectural details it
6914 /// can to emit an efficient lowering. It handles both blends with all-zero
6915 /// inputs to explicitly zero-extend and undef-lanes (sometimes undef due to
6916 /// masking out later).
6917 ///
6918 /// The reason we have dedicated lowering for zext-style shuffles is that they
6919 /// are both incredibly common and often quite performance sensitive.
6920 static SDValue lowerVectorShuffleAsZeroOrAnyExtend(
6921     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
6922     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
6923   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6924
6925   int Bits = VT.getSizeInBits();
6926   int NumElements = VT.getVectorNumElements();
6927   assert(VT.getScalarSizeInBits() <= 32 &&
6928          "Exceeds 32-bit integer zero extension limit");
6929   assert((int)Mask.size() == NumElements && "Unexpected shuffle mask size");
6930
6931   // Define a helper function to check a particular ext-scale and lower to it if
6932   // valid.
6933   auto Lower = [&](int Scale) -> SDValue {
6934     SDValue InputV;
6935     bool AnyExt = true;
6936     for (int i = 0; i < NumElements; ++i) {
6937       if (Mask[i] == -1)
6938         continue; // Valid anywhere but doesn't tell us anything.
6939       if (i % Scale != 0) {
6940         // Each of the extended elements need to be zeroable.
6941         if (!Zeroable[i])
6942           return SDValue();
6943
6944         // We no longer are in the anyext case.
6945         AnyExt = false;
6946         continue;
6947       }
6948
6949       // Each of the base elements needs to be consecutive indices into the
6950       // same input vector.
6951       SDValue V = Mask[i] < NumElements ? V1 : V2;
6952       if (!InputV)
6953         InputV = V;
6954       else if (InputV != V)
6955         return SDValue(); // Flip-flopping inputs.
6956
6957       if (Mask[i] % NumElements != i / Scale)
6958         return SDValue(); // Non-consecutive strided elements.
6959     }
6960
6961     // If we fail to find an input, we have a zero-shuffle which should always
6962     // have already been handled.
6963     // FIXME: Maybe handle this here in case during blending we end up with one?
6964     if (!InputV)
6965       return SDValue();
6966
6967     return lowerVectorShuffleAsSpecificZeroOrAnyExtend(
6968         DL, VT, Scale, AnyExt, InputV, Subtarget, DAG);
6969   };
6970
6971   // The widest scale possible for extending is to a 64-bit integer.
6972   assert(Bits % 64 == 0 &&
6973          "The number of bits in a vector must be divisible by 64 on x86!");
6974   int NumExtElements = Bits / 64;
6975
6976   // Each iteration, try extending the elements half as much, but into twice as
6977   // many elements.
6978   for (; NumExtElements < NumElements; NumExtElements *= 2) {
6979     assert(NumElements % NumExtElements == 0 &&
6980            "The input vector size must be divisible by the extended size.");
6981     if (SDValue V = Lower(NumElements / NumExtElements))
6982       return V;
6983   }
6984
6985   // General extends failed, but 128-bit vectors may be able to use MOVQ.
6986   if (Bits != 128)
6987     return SDValue();
6988
6989   // Returns one of the source operands if the shuffle can be reduced to a
6990   // MOVQ, copying the lower 64-bits and zero-extending to the upper 64-bits.
6991   auto CanZExtLowHalf = [&]() {
6992     for (int i = NumElements / 2; i != NumElements; ++i)
6993       if (!Zeroable[i])
6994         return SDValue();
6995     if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, 0))
6996       return V1;
6997     if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, NumElements))
6998       return V2;
6999     return SDValue();
7000   };
7001
7002   if (SDValue V = CanZExtLowHalf()) {
7003     V = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, V);
7004     V = DAG.getNode(X86ISD::VZEXT_MOVL, DL, MVT::v2i64, V);
7005     return DAG.getNode(ISD::BITCAST, DL, VT, V);
7006   }
7007
7008   // No viable ext lowering found.
7009   return SDValue();
7010 }
7011
7012 /// \brief Try to get a scalar value for a specific element of a vector.
7013 ///
7014 /// Looks through BUILD_VECTOR and SCALAR_TO_VECTOR nodes to find a scalar.
7015 static SDValue getScalarValueForVectorElement(SDValue V, int Idx,
7016                                               SelectionDAG &DAG) {
7017   MVT VT = V.getSimpleValueType();
7018   MVT EltVT = VT.getVectorElementType();
7019   while (V.getOpcode() == ISD::BITCAST)
7020     V = V.getOperand(0);
7021   // If the bitcasts shift the element size, we can't extract an equivalent
7022   // element from it.
7023   MVT NewVT = V.getSimpleValueType();
7024   if (!NewVT.isVector() || NewVT.getScalarSizeInBits() != VT.getScalarSizeInBits())
7025     return SDValue();
7026
7027   if (V.getOpcode() == ISD::BUILD_VECTOR ||
7028       (Idx == 0 && V.getOpcode() == ISD::SCALAR_TO_VECTOR)) {
7029     // Ensure the scalar operand is the same size as the destination.
7030     // FIXME: Add support for scalar truncation where possible.
7031     SDValue S = V.getOperand(Idx);
7032     if (EltVT.getSizeInBits() == S.getSimpleValueType().getSizeInBits())
7033       return DAG.getNode(ISD::BITCAST, SDLoc(V), EltVT, S);
7034   }
7035
7036   return SDValue();
7037 }
7038
7039 /// \brief Helper to test for a load that can be folded with x86 shuffles.
7040 ///
7041 /// This is particularly important because the set of instructions varies
7042 /// significantly based on whether the operand is a load or not.
7043 static bool isShuffleFoldableLoad(SDValue V) {
7044   while (V.getOpcode() == ISD::BITCAST)
7045     V = V.getOperand(0);
7046
7047   return ISD::isNON_EXTLoad(V.getNode());
7048 }
7049
7050 /// \brief Try to lower insertion of a single element into a zero vector.
7051 ///
7052 /// This is a common pattern that we have especially efficient patterns to lower
7053 /// across all subtarget feature sets.
7054 static SDValue lowerVectorShuffleAsElementInsertion(
7055     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7056     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7057   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7058   MVT ExtVT = VT;
7059   MVT EltVT = VT.getVectorElementType();
7060
7061   int V2Index = std::find_if(Mask.begin(), Mask.end(),
7062                              [&Mask](int M) { return M >= (int)Mask.size(); }) -
7063                 Mask.begin();
7064   bool IsV1Zeroable = true;
7065   for (int i = 0, Size = Mask.size(); i < Size; ++i)
7066     if (i != V2Index && !Zeroable[i]) {
7067       IsV1Zeroable = false;
7068       break;
7069     }
7070
7071   // Check for a single input from a SCALAR_TO_VECTOR node.
7072   // FIXME: All of this should be canonicalized into INSERT_VECTOR_ELT and
7073   // all the smarts here sunk into that routine. However, the current
7074   // lowering of BUILD_VECTOR makes that nearly impossible until the old
7075   // vector shuffle lowering is dead.
7076   if (SDValue V2S = getScalarValueForVectorElement(
7077           V2, Mask[V2Index] - Mask.size(), DAG)) {
7078     // We need to zext the scalar if it is smaller than an i32.
7079     V2S = DAG.getNode(ISD::BITCAST, DL, EltVT, V2S);
7080     if (EltVT == MVT::i8 || EltVT == MVT::i16) {
7081       // Using zext to expand a narrow element won't work for non-zero
7082       // insertions.
7083       if (!IsV1Zeroable)
7084         return SDValue();
7085
7086       // Zero-extend directly to i32.
7087       ExtVT = MVT::v4i32;
7088       V2S = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, V2S);
7089     }
7090     V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, ExtVT, V2S);
7091   } else if (Mask[V2Index] != (int)Mask.size() || EltVT == MVT::i8 ||
7092              EltVT == MVT::i16) {
7093     // Either not inserting from the low element of the input or the input
7094     // element size is too small to use VZEXT_MOVL to clear the high bits.
7095     return SDValue();
7096   }
7097
7098   if (!IsV1Zeroable) {
7099     // If V1 can't be treated as a zero vector we have fewer options to lower
7100     // this. We can't support integer vectors or non-zero targets cheaply, and
7101     // the V1 elements can't be permuted in any way.
7102     assert(VT == ExtVT && "Cannot change extended type when non-zeroable!");
7103     if (!VT.isFloatingPoint() || V2Index != 0)
7104       return SDValue();
7105     SmallVector<int, 8> V1Mask(Mask.begin(), Mask.end());
7106     V1Mask[V2Index] = -1;
7107     if (!isNoopShuffleMask(V1Mask))
7108       return SDValue();
7109     // This is essentially a special case blend operation, but if we have
7110     // general purpose blend operations, they are always faster. Bail and let
7111     // the rest of the lowering handle these as blends.
7112     if (Subtarget->hasSSE41())
7113       return SDValue();
7114
7115     // Otherwise, use MOVSD or MOVSS.
7116     assert((EltVT == MVT::f32 || EltVT == MVT::f64) &&
7117            "Only two types of floating point element types to handle!");
7118     return DAG.getNode(EltVT == MVT::f32 ? X86ISD::MOVSS : X86ISD::MOVSD, DL,
7119                        ExtVT, V1, V2);
7120   }
7121
7122   // This lowering only works for the low element with floating point vectors.
7123   if (VT.isFloatingPoint() && V2Index != 0)
7124     return SDValue();
7125
7126   V2 = DAG.getNode(X86ISD::VZEXT_MOVL, DL, ExtVT, V2);
7127   if (ExtVT != VT)
7128     V2 = DAG.getNode(ISD::BITCAST, DL, VT, V2);
7129
7130   if (V2Index != 0) {
7131     // If we have 4 or fewer lanes we can cheaply shuffle the element into
7132     // the desired position. Otherwise it is more efficient to do a vector
7133     // shift left. We know that we can do a vector shift left because all
7134     // the inputs are zero.
7135     if (VT.isFloatingPoint() || VT.getVectorNumElements() <= 4) {
7136       SmallVector<int, 4> V2Shuffle(Mask.size(), 1);
7137       V2Shuffle[V2Index] = 0;
7138       V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Shuffle);
7139     } else {
7140       V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, V2);
7141       V2 = DAG.getNode(
7142           X86ISD::VSHLDQ, DL, MVT::v2i64, V2,
7143           DAG.getConstant(
7144               V2Index * EltVT.getSizeInBits()/8, DL,
7145               DAG.getTargetLoweringInfo().getScalarShiftAmountTy(MVT::v2i64)));
7146       V2 = DAG.getNode(ISD::BITCAST, DL, VT, V2);
7147     }
7148   }
7149   return V2;
7150 }
7151
7152 /// \brief Try to lower broadcast of a single element.
7153 ///
7154 /// For convenience, this code also bundles all of the subtarget feature set
7155 /// filtering. While a little annoying to re-dispatch on type here, there isn't
7156 /// a convenient way to factor it out.
7157 static SDValue lowerVectorShuffleAsBroadcast(SDLoc DL, MVT VT, SDValue V,
7158                                              ArrayRef<int> Mask,
7159                                              const X86Subtarget *Subtarget,
7160                                              SelectionDAG &DAG) {
7161   if (!Subtarget->hasAVX())
7162     return SDValue();
7163   if (VT.isInteger() && !Subtarget->hasAVX2())
7164     return SDValue();
7165
7166   // Check that the mask is a broadcast.
7167   int BroadcastIdx = -1;
7168   for (int M : Mask)
7169     if (M >= 0 && BroadcastIdx == -1)
7170       BroadcastIdx = M;
7171     else if (M >= 0 && M != BroadcastIdx)
7172       return SDValue();
7173
7174   assert(BroadcastIdx < (int)Mask.size() && "We only expect to be called with "
7175                                             "a sorted mask where the broadcast "
7176                                             "comes from V1.");
7177
7178   // Go up the chain of (vector) values to find a scalar load that we can
7179   // combine with the broadcast.
7180   for (;;) {
7181     switch (V.getOpcode()) {
7182     case ISD::CONCAT_VECTORS: {
7183       int OperandSize = Mask.size() / V.getNumOperands();
7184       V = V.getOperand(BroadcastIdx / OperandSize);
7185       BroadcastIdx %= OperandSize;
7186       continue;
7187     }
7188
7189     case ISD::INSERT_SUBVECTOR: {
7190       SDValue VOuter = V.getOperand(0), VInner = V.getOperand(1);
7191       auto ConstantIdx = dyn_cast<ConstantSDNode>(V.getOperand(2));
7192       if (!ConstantIdx)
7193         break;
7194
7195       int BeginIdx = (int)ConstantIdx->getZExtValue();
7196       int EndIdx =
7197           BeginIdx + (int)VInner.getValueType().getVectorNumElements();
7198       if (BroadcastIdx >= BeginIdx && BroadcastIdx < EndIdx) {
7199         BroadcastIdx -= BeginIdx;
7200         V = VInner;
7201       } else {
7202         V = VOuter;
7203       }
7204       continue;
7205     }
7206     }
7207     break;
7208   }
7209
7210   // Check if this is a broadcast of a scalar. We special case lowering
7211   // for scalars so that we can more effectively fold with loads.
7212   if (V.getOpcode() == ISD::BUILD_VECTOR ||
7213       (V.getOpcode() == ISD::SCALAR_TO_VECTOR && BroadcastIdx == 0)) {
7214     V = V.getOperand(BroadcastIdx);
7215
7216     // If the scalar isn't a load, we can't broadcast from it in AVX1.
7217     // Only AVX2 has register broadcasts.
7218     if (!Subtarget->hasAVX2() && !isShuffleFoldableLoad(V))
7219       return SDValue();
7220   } else if (BroadcastIdx != 0 || !Subtarget->hasAVX2()) {
7221     // We can't broadcast from a vector register without AVX2, and we can only
7222     // broadcast from the zero-element of a vector register.
7223     return SDValue();
7224   }
7225
7226   return DAG.getNode(X86ISD::VBROADCAST, DL, VT, V);
7227 }
7228
7229 // Check for whether we can use INSERTPS to perform the shuffle. We only use
7230 // INSERTPS when the V1 elements are already in the correct locations
7231 // because otherwise we can just always use two SHUFPS instructions which
7232 // are much smaller to encode than a SHUFPS and an INSERTPS. We can also
7233 // perform INSERTPS if a single V1 element is out of place and all V2
7234 // elements are zeroable.
7235 static SDValue lowerVectorShuffleAsInsertPS(SDValue Op, SDValue V1, SDValue V2,
7236                                             ArrayRef<int> Mask,
7237                                             SelectionDAG &DAG) {
7238   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
7239   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7240   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7241   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7242
7243   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7244
7245   unsigned ZMask = 0;
7246   int V1DstIndex = -1;
7247   int V2DstIndex = -1;
7248   bool V1UsedInPlace = false;
7249
7250   for (int i = 0; i < 4; ++i) {
7251     // Synthesize a zero mask from the zeroable elements (includes undefs).
7252     if (Zeroable[i]) {
7253       ZMask |= 1 << i;
7254       continue;
7255     }
7256
7257     // Flag if we use any V1 inputs in place.
7258     if (i == Mask[i]) {
7259       V1UsedInPlace = true;
7260       continue;
7261     }
7262
7263     // We can only insert a single non-zeroable element.
7264     if (V1DstIndex != -1 || V2DstIndex != -1)
7265       return SDValue();
7266
7267     if (Mask[i] < 4) {
7268       // V1 input out of place for insertion.
7269       V1DstIndex = i;
7270     } else {
7271       // V2 input for insertion.
7272       V2DstIndex = i;
7273     }
7274   }
7275
7276   // Don't bother if we have no (non-zeroable) element for insertion.
7277   if (V1DstIndex == -1 && V2DstIndex == -1)
7278     return SDValue();
7279
7280   // Determine element insertion src/dst indices. The src index is from the
7281   // start of the inserted vector, not the start of the concatenated vector.
7282   unsigned V2SrcIndex = 0;
7283   if (V1DstIndex != -1) {
7284     // If we have a V1 input out of place, we use V1 as the V2 element insertion
7285     // and don't use the original V2 at all.
7286     V2SrcIndex = Mask[V1DstIndex];
7287     V2DstIndex = V1DstIndex;
7288     V2 = V1;
7289   } else {
7290     V2SrcIndex = Mask[V2DstIndex] - 4;
7291   }
7292
7293   // If no V1 inputs are used in place, then the result is created only from
7294   // the zero mask and the V2 insertion - so remove V1 dependency.
7295   if (!V1UsedInPlace)
7296     V1 = DAG.getUNDEF(MVT::v4f32);
7297
7298   unsigned InsertPSMask = V2SrcIndex << 6 | V2DstIndex << 4 | ZMask;
7299   assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
7300
7301   // Insert the V2 element into the desired position.
7302   SDLoc DL(Op);
7303   return DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
7304                      DAG.getConstant(InsertPSMask, DL, MVT::i8));
7305 }
7306
7307 /// \brief Try to lower a shuffle as a permute of the inputs followed by an
7308 /// UNPCK instruction.
7309 ///
7310 /// This specifically targets cases where we end up with alternating between
7311 /// the two inputs, and so can permute them into something that feeds a single
7312 /// UNPCK instruction. Note that this routine only targets integer vectors
7313 /// because for floating point vectors we have a generalized SHUFPS lowering
7314 /// strategy that handles everything that doesn't *exactly* match an unpack,
7315 /// making this clever lowering unnecessary.
7316 static SDValue lowerVectorShuffleAsUnpack(SDLoc DL, MVT VT, SDValue V1,
7317                                           SDValue V2, ArrayRef<int> Mask,
7318                                           SelectionDAG &DAG) {
7319   assert(!VT.isFloatingPoint() &&
7320          "This routine only supports integer vectors.");
7321   assert(!isSingleInputShuffleMask(Mask) &&
7322          "This routine should only be used when blending two inputs.");
7323   assert(Mask.size() >= 2 && "Single element masks are invalid.");
7324
7325   int Size = Mask.size();
7326
7327   int NumLoInputs = std::count_if(Mask.begin(), Mask.end(), [Size](int M) {
7328     return M >= 0 && M % Size < Size / 2;
7329   });
7330   int NumHiInputs = std::count_if(
7331       Mask.begin(), Mask.end(), [Size](int M) { return M % Size >= Size / 2; });
7332
7333   bool UnpackLo = NumLoInputs >= NumHiInputs;
7334
7335   auto TryUnpack = [&](MVT UnpackVT, int Scale) {
7336     SmallVector<int, 32> V1Mask(Mask.size(), -1);
7337     SmallVector<int, 32> V2Mask(Mask.size(), -1);
7338
7339     for (int i = 0; i < Size; ++i) {
7340       if (Mask[i] < 0)
7341         continue;
7342
7343       // Each element of the unpack contains Scale elements from this mask.
7344       int UnpackIdx = i / Scale;
7345
7346       // We only handle the case where V1 feeds the first slots of the unpack.
7347       // We rely on canonicalization to ensure this is the case.
7348       if ((UnpackIdx % 2 == 0) != (Mask[i] < Size))
7349         return SDValue();
7350
7351       // Setup the mask for this input. The indexing is tricky as we have to
7352       // handle the unpack stride.
7353       SmallVectorImpl<int> &VMask = (UnpackIdx % 2 == 0) ? V1Mask : V2Mask;
7354       VMask[(UnpackIdx / 2) * Scale + i % Scale + (UnpackLo ? 0 : Size / 2)] =
7355           Mask[i] % Size;
7356     }
7357
7358     // If we will have to shuffle both inputs to use the unpack, check whether
7359     // we can just unpack first and shuffle the result. If so, skip this unpack.
7360     if ((NumLoInputs == 0 || NumHiInputs == 0) && !isNoopShuffleMask(V1Mask) &&
7361         !isNoopShuffleMask(V2Mask))
7362       return SDValue();
7363
7364     // Shuffle the inputs into place.
7365     V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
7366     V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
7367
7368     // Cast the inputs to the type we will use to unpack them.
7369     V1 = DAG.getNode(ISD::BITCAST, DL, UnpackVT, V1);
7370     V2 = DAG.getNode(ISD::BITCAST, DL, UnpackVT, V2);
7371
7372     // Unpack the inputs and cast the result back to the desired type.
7373     return DAG.getNode(ISD::BITCAST, DL, VT,
7374                        DAG.getNode(UnpackLo ? X86ISD::UNPCKL : X86ISD::UNPCKH,
7375                                    DL, UnpackVT, V1, V2));
7376   };
7377
7378   // We try each unpack from the largest to the smallest to try and find one
7379   // that fits this mask.
7380   int OrigNumElements = VT.getVectorNumElements();
7381   int OrigScalarSize = VT.getScalarSizeInBits();
7382   for (int ScalarSize = 64; ScalarSize >= OrigScalarSize; ScalarSize /= 2) {
7383     int Scale = ScalarSize / OrigScalarSize;
7384     int NumElements = OrigNumElements / Scale;
7385     MVT UnpackVT = MVT::getVectorVT(MVT::getIntegerVT(ScalarSize), NumElements);
7386     if (SDValue Unpack = TryUnpack(UnpackVT, Scale))
7387       return Unpack;
7388   }
7389
7390   // If none of the unpack-rooted lowerings worked (or were profitable) try an
7391   // initial unpack.
7392   if (NumLoInputs == 0 || NumHiInputs == 0) {
7393     assert((NumLoInputs > 0 || NumHiInputs > 0) &&
7394            "We have to have *some* inputs!");
7395     int HalfOffset = NumLoInputs == 0 ? Size / 2 : 0;
7396
7397     // FIXME: We could consider the total complexity of the permute of each
7398     // possible unpacking. Or at the least we should consider how many
7399     // half-crossings are created.
7400     // FIXME: We could consider commuting the unpacks.
7401
7402     SmallVector<int, 32> PermMask;
7403     PermMask.assign(Size, -1);
7404     for (int i = 0; i < Size; ++i) {
7405       if (Mask[i] < 0)
7406         continue;
7407
7408       assert(Mask[i] % Size >= HalfOffset && "Found input from wrong half!");
7409
7410       PermMask[i] =
7411           2 * ((Mask[i] % Size) - HalfOffset) + (Mask[i] < Size ? 0 : 1);
7412     }
7413     return DAG.getVectorShuffle(
7414         VT, DL, DAG.getNode(NumLoInputs == 0 ? X86ISD::UNPCKH : X86ISD::UNPCKL,
7415                             DL, VT, V1, V2),
7416         DAG.getUNDEF(VT), PermMask);
7417   }
7418
7419   return SDValue();
7420 }
7421
7422 /// \brief Handle lowering of 2-lane 64-bit floating point shuffles.
7423 ///
7424 /// This is the basis function for the 2-lane 64-bit shuffles as we have full
7425 /// support for floating point shuffles but not integer shuffles. These
7426 /// instructions will incur a domain crossing penalty on some chips though so
7427 /// it is better to avoid lowering through this for integer vectors where
7428 /// possible.
7429 static SDValue lowerV2F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7430                                        const X86Subtarget *Subtarget,
7431                                        SelectionDAG &DAG) {
7432   SDLoc DL(Op);
7433   assert(Op.getSimpleValueType() == MVT::v2f64 && "Bad shuffle type!");
7434   assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7435   assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7436   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7437   ArrayRef<int> Mask = SVOp->getMask();
7438   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7439
7440   if (isSingleInputShuffleMask(Mask)) {
7441     // Use low duplicate instructions for masks that match their pattern.
7442     if (Subtarget->hasSSE3())
7443       if (isShuffleEquivalent(V1, V2, Mask, {0, 0}))
7444         return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v2f64, V1);
7445
7446     // Straight shuffle of a single input vector. Simulate this by using the
7447     // single input as both of the "inputs" to this instruction..
7448     unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
7449
7450     if (Subtarget->hasAVX()) {
7451       // If we have AVX, we can use VPERMILPS which will allow folding a load
7452       // into the shuffle.
7453       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v2f64, V1,
7454                          DAG.getConstant(SHUFPDMask, DL, MVT::i8));
7455     }
7456
7457     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V1,
7458                        DAG.getConstant(SHUFPDMask, DL, MVT::i8));
7459   }
7460   assert(Mask[0] >= 0 && Mask[0] < 2 && "Non-canonicalized blend!");
7461   assert(Mask[1] >= 2 && "Non-canonicalized blend!");
7462
7463   // If we have a single input, insert that into V1 if we can do so cheaply.
7464   if ((Mask[0] >= 2) + (Mask[1] >= 2) == 1) {
7465     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7466             DL, MVT::v2f64, V1, V2, Mask, Subtarget, DAG))
7467       return Insertion;
7468     // Try inverting the insertion since for v2 masks it is easy to do and we
7469     // can't reliably sort the mask one way or the other.
7470     int InverseMask[2] = {Mask[0] < 0 ? -1 : (Mask[0] ^ 2),
7471                           Mask[1] < 0 ? -1 : (Mask[1] ^ 2)};
7472     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7473             DL, MVT::v2f64, V2, V1, InverseMask, Subtarget, DAG))
7474       return Insertion;
7475   }
7476
7477   // Try to use one of the special instruction patterns to handle two common
7478   // blend patterns if a zero-blend above didn't work.
7479   if (isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
7480       isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7481     if (SDValue V1S = getScalarValueForVectorElement(V1, Mask[0], DAG))
7482       // We can either use a special instruction to load over the low double or
7483       // to move just the low double.
7484       return DAG.getNode(
7485           isShuffleFoldableLoad(V1S) ? X86ISD::MOVLPD : X86ISD::MOVSD,
7486           DL, MVT::v2f64, V2,
7487           DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64, V1S));
7488
7489   if (Subtarget->hasSSE41())
7490     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2f64, V1, V2, Mask,
7491                                                   Subtarget, DAG))
7492       return Blend;
7493
7494   // Use dedicated unpack instructions for masks that match their pattern.
7495   if (isShuffleEquivalent(V1, V2, Mask, {0, 2}))
7496     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2f64, V1, V2);
7497   if (isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7498     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2f64, V1, V2);
7499
7500   unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
7501   return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V2,
7502                      DAG.getConstant(SHUFPDMask, DL, MVT::i8));
7503 }
7504
7505 /// \brief Handle lowering of 2-lane 64-bit integer shuffles.
7506 ///
7507 /// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
7508 /// the integer unit to minimize domain crossing penalties. However, for blends
7509 /// it falls back to the floating point shuffle operation with appropriate bit
7510 /// casting.
7511 static SDValue lowerV2I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7512                                        const X86Subtarget *Subtarget,
7513                                        SelectionDAG &DAG) {
7514   SDLoc DL(Op);
7515   assert(Op.getSimpleValueType() == MVT::v2i64 && "Bad shuffle type!");
7516   assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7517   assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7518   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7519   ArrayRef<int> Mask = SVOp->getMask();
7520   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7521
7522   if (isSingleInputShuffleMask(Mask)) {
7523     // Check for being able to broadcast a single element.
7524     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v2i64, V1,
7525                                                           Mask, Subtarget, DAG))
7526       return Broadcast;
7527
7528     // Straight shuffle of a single input vector. For everything from SSE2
7529     // onward this has a single fast instruction with no scary immediates.
7530     // We have to map the mask as it is actually a v4i32 shuffle instruction.
7531     V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V1);
7532     int WidenedMask[4] = {
7533         std::max(Mask[0], 0) * 2, std::max(Mask[0], 0) * 2 + 1,
7534         std::max(Mask[1], 0) * 2, std::max(Mask[1], 0) * 2 + 1};
7535     return DAG.getNode(
7536         ISD::BITCAST, DL, MVT::v2i64,
7537         DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
7538                     getV4X86ShuffleImm8ForMask(WidenedMask, DL, DAG)));
7539   }
7540   assert(Mask[0] != -1 && "No undef lanes in multi-input v2 shuffles!");
7541   assert(Mask[1] != -1 && "No undef lanes in multi-input v2 shuffles!");
7542   assert(Mask[0] < 2 && "We sort V1 to be the first input.");
7543   assert(Mask[1] >= 2 && "We sort V2 to be the second input.");
7544
7545   // If we have a blend of two PACKUS operations an the blend aligns with the
7546   // low and half halves, we can just merge the PACKUS operations. This is
7547   // particularly important as it lets us merge shuffles that this routine itself
7548   // creates.
7549   auto GetPackNode = [](SDValue V) {
7550     while (V.getOpcode() == ISD::BITCAST)
7551       V = V.getOperand(0);
7552
7553     return V.getOpcode() == X86ISD::PACKUS ? V : SDValue();
7554   };
7555   if (SDValue V1Pack = GetPackNode(V1))
7556     if (SDValue V2Pack = GetPackNode(V2))
7557       return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7558                          DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8,
7559                                      Mask[0] == 0 ? V1Pack.getOperand(0)
7560                                                   : V1Pack.getOperand(1),
7561                                      Mask[1] == 2 ? V2Pack.getOperand(0)
7562                                                   : V2Pack.getOperand(1)));
7563
7564   // Try to use shift instructions.
7565   if (SDValue Shift =
7566           lowerVectorShuffleAsShift(DL, MVT::v2i64, V1, V2, Mask, DAG))
7567     return Shift;
7568
7569   // When loading a scalar and then shuffling it into a vector we can often do
7570   // the insertion cheaply.
7571   if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7572           DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
7573     return Insertion;
7574   // Try inverting the insertion since for v2 masks it is easy to do and we
7575   // can't reliably sort the mask one way or the other.
7576   int InverseMask[2] = {Mask[0] ^ 2, Mask[1] ^ 2};
7577   if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7578           DL, MVT::v2i64, V2, V1, InverseMask, Subtarget, DAG))
7579     return Insertion;
7580
7581   // We have different paths for blend lowering, but they all must use the
7582   // *exact* same predicate.
7583   bool IsBlendSupported = Subtarget->hasSSE41();
7584   if (IsBlendSupported)
7585     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2i64, V1, V2, Mask,
7586                                                   Subtarget, DAG))
7587       return Blend;
7588
7589   // Use dedicated unpack instructions for masks that match their pattern.
7590   if (isShuffleEquivalent(V1, V2, Mask, {0, 2}))
7591     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, V1, V2);
7592   if (isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7593     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2i64, V1, V2);
7594
7595   // Try to use byte rotation instructions.
7596   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
7597   if (Subtarget->hasSSSE3())
7598     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
7599             DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
7600       return Rotate;
7601
7602   // If we have direct support for blends, we should lower by decomposing into
7603   // a permute. That will be faster than the domain cross.
7604   if (IsBlendSupported)
7605     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v2i64, V1, V2,
7606                                                       Mask, DAG);
7607
7608   // We implement this with SHUFPD which is pretty lame because it will likely
7609   // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
7610   // However, all the alternatives are still more cycles and newer chips don't
7611   // have this problem. It would be really nice if x86 had better shuffles here.
7612   V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V1);
7613   V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V2);
7614   return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7615                      DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
7616 }
7617
7618 /// \brief Test whether this can be lowered with a single SHUFPS instruction.
7619 ///
7620 /// This is used to disable more specialized lowerings when the shufps lowering
7621 /// will happen to be efficient.
7622 static bool isSingleSHUFPSMask(ArrayRef<int> Mask) {
7623   // This routine only handles 128-bit shufps.
7624   assert(Mask.size() == 4 && "Unsupported mask size!");
7625
7626   // To lower with a single SHUFPS we need to have the low half and high half
7627   // each requiring a single input.
7628   if (Mask[0] != -1 && Mask[1] != -1 && (Mask[0] < 4) != (Mask[1] < 4))
7629     return false;
7630   if (Mask[2] != -1 && Mask[3] != -1 && (Mask[2] < 4) != (Mask[3] < 4))
7631     return false;
7632
7633   return true;
7634 }
7635
7636 /// \brief Lower a vector shuffle using the SHUFPS instruction.
7637 ///
7638 /// This is a helper routine dedicated to lowering vector shuffles using SHUFPS.
7639 /// It makes no assumptions about whether this is the *best* lowering, it simply
7640 /// uses it.
7641 static SDValue lowerVectorShuffleWithSHUFPS(SDLoc DL, MVT VT,
7642                                             ArrayRef<int> Mask, SDValue V1,
7643                                             SDValue V2, SelectionDAG &DAG) {
7644   SDValue LowV = V1, HighV = V2;
7645   int NewMask[4] = {Mask[0], Mask[1], Mask[2], Mask[3]};
7646
7647   int NumV2Elements =
7648       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7649
7650   if (NumV2Elements == 1) {
7651     int V2Index =
7652         std::find_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; }) -
7653         Mask.begin();
7654
7655     // Compute the index adjacent to V2Index and in the same half by toggling
7656     // the low bit.
7657     int V2AdjIndex = V2Index ^ 1;
7658
7659     if (Mask[V2AdjIndex] == -1) {
7660       // Handles all the cases where we have a single V2 element and an undef.
7661       // This will only ever happen in the high lanes because we commute the
7662       // vector otherwise.
7663       if (V2Index < 2)
7664         std::swap(LowV, HighV);
7665       NewMask[V2Index] -= 4;
7666     } else {
7667       // Handle the case where the V2 element ends up adjacent to a V1 element.
7668       // To make this work, blend them together as the first step.
7669       int V1Index = V2AdjIndex;
7670       int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
7671       V2 = DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
7672                        getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
7673
7674       // Now proceed to reconstruct the final blend as we have the necessary
7675       // high or low half formed.
7676       if (V2Index < 2) {
7677         LowV = V2;
7678         HighV = V1;
7679       } else {
7680         HighV = V2;
7681       }
7682       NewMask[V1Index] = 2; // We put the V1 element in V2[2].
7683       NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
7684     }
7685   } else if (NumV2Elements == 2) {
7686     if (Mask[0] < 4 && Mask[1] < 4) {
7687       // Handle the easy case where we have V1 in the low lanes and V2 in the
7688       // high lanes.
7689       NewMask[2] -= 4;
7690       NewMask[3] -= 4;
7691     } else if (Mask[2] < 4 && Mask[3] < 4) {
7692       // We also handle the reversed case because this utility may get called
7693       // when we detect a SHUFPS pattern but can't easily commute the shuffle to
7694       // arrange things in the right direction.
7695       NewMask[0] -= 4;
7696       NewMask[1] -= 4;
7697       HighV = V1;
7698       LowV = V2;
7699     } else {
7700       // We have a mixture of V1 and V2 in both low and high lanes. Rather than
7701       // trying to place elements directly, just blend them and set up the final
7702       // shuffle to place them.
7703
7704       // The first two blend mask elements are for V1, the second two are for
7705       // V2.
7706       int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
7707                           Mask[2] < 4 ? Mask[2] : Mask[3],
7708                           (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
7709                           (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
7710       V1 = DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
7711                        getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
7712
7713       // Now we do a normal shuffle of V1 by giving V1 as both operands to
7714       // a blend.
7715       LowV = HighV = V1;
7716       NewMask[0] = Mask[0] < 4 ? 0 : 2;
7717       NewMask[1] = Mask[0] < 4 ? 2 : 0;
7718       NewMask[2] = Mask[2] < 4 ? 1 : 3;
7719       NewMask[3] = Mask[2] < 4 ? 3 : 1;
7720     }
7721   }
7722   return DAG.getNode(X86ISD::SHUFP, DL, VT, LowV, HighV,
7723                      getV4X86ShuffleImm8ForMask(NewMask, DL, DAG));
7724 }
7725
7726 /// \brief Lower 4-lane 32-bit floating point shuffles.
7727 ///
7728 /// Uses instructions exclusively from the floating point unit to minimize
7729 /// domain crossing penalties, as these are sufficient to implement all v4f32
7730 /// shuffles.
7731 static SDValue lowerV4F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7732                                        const X86Subtarget *Subtarget,
7733                                        SelectionDAG &DAG) {
7734   SDLoc DL(Op);
7735   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
7736   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7737   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7738   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7739   ArrayRef<int> Mask = SVOp->getMask();
7740   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7741
7742   int NumV2Elements =
7743       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7744
7745   if (NumV2Elements == 0) {
7746     // Check for being able to broadcast a single element.
7747     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f32, V1,
7748                                                           Mask, Subtarget, DAG))
7749       return Broadcast;
7750
7751     // Use even/odd duplicate instructions for masks that match their pattern.
7752     if (Subtarget->hasSSE3()) {
7753       if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
7754         return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v4f32, V1);
7755       if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3}))
7756         return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v4f32, V1);
7757     }
7758
7759     if (Subtarget->hasAVX()) {
7760       // If we have AVX, we can use VPERMILPS which will allow folding a load
7761       // into the shuffle.
7762       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f32, V1,
7763                          getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
7764     }
7765
7766     // Otherwise, use a straight shuffle of a single input vector. We pass the
7767     // input vector to both operands to simulate this with a SHUFPS.
7768     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
7769                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
7770   }
7771
7772   // There are special ways we can lower some single-element blends. However, we
7773   // have custom ways we can lower more complex single-element blends below that
7774   // we defer to if both this and BLENDPS fail to match, so restrict this to
7775   // when the V2 input is targeting element 0 of the mask -- that is the fast
7776   // case here.
7777   if (NumV2Elements == 1 && Mask[0] >= 4)
7778     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4f32, V1, V2,
7779                                                          Mask, Subtarget, DAG))
7780       return V;
7781
7782   if (Subtarget->hasSSE41()) {
7783     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f32, V1, V2, Mask,
7784                                                   Subtarget, DAG))
7785       return Blend;
7786
7787     // Use INSERTPS if we can complete the shuffle efficiently.
7788     if (SDValue V = lowerVectorShuffleAsInsertPS(Op, V1, V2, Mask, DAG))
7789       return V;
7790
7791     if (!isSingleSHUFPSMask(Mask))
7792       if (SDValue BlendPerm = lowerVectorShuffleAsBlendAndPermute(
7793               DL, MVT::v4f32, V1, V2, Mask, DAG))
7794         return BlendPerm;
7795   }
7796
7797   // Use dedicated unpack instructions for masks that match their pattern.
7798   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 1, 5}))
7799     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V1, V2);
7800   if (isShuffleEquivalent(V1, V2, Mask, {2, 6, 3, 7}))
7801     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V1, V2);
7802   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 5, 1}))
7803     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V2, V1);
7804   if (isShuffleEquivalent(V1, V2, Mask, {6, 2, 7, 3}))
7805     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V2, V1);
7806
7807   // Otherwise fall back to a SHUFPS lowering strategy.
7808   return lowerVectorShuffleWithSHUFPS(DL, MVT::v4f32, Mask, V1, V2, DAG);
7809 }
7810
7811 /// \brief Lower 4-lane i32 vector shuffles.
7812 ///
7813 /// We try to handle these with integer-domain shuffles where we can, but for
7814 /// blends we use the floating point domain blend instructions.
7815 static SDValue lowerV4I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7816                                        const X86Subtarget *Subtarget,
7817                                        SelectionDAG &DAG) {
7818   SDLoc DL(Op);
7819   assert(Op.getSimpleValueType() == MVT::v4i32 && "Bad shuffle type!");
7820   assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
7821   assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
7822   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7823   ArrayRef<int> Mask = SVOp->getMask();
7824   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7825
7826   // Whenever we can lower this as a zext, that instruction is strictly faster
7827   // than any alternative. It also allows us to fold memory operands into the
7828   // shuffle in many cases.
7829   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v4i32, V1, V2,
7830                                                          Mask, Subtarget, DAG))
7831     return ZExt;
7832
7833   int NumV2Elements =
7834       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7835
7836   if (NumV2Elements == 0) {
7837     // Check for being able to broadcast a single element.
7838     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i32, V1,
7839                                                           Mask, Subtarget, DAG))
7840       return Broadcast;
7841
7842     // Straight shuffle of a single input vector. For everything from SSE2
7843     // onward this has a single fast instruction with no scary immediates.
7844     // We coerce the shuffle pattern to be compatible with UNPCK instructions
7845     // but we aren't actually going to use the UNPCK instruction because doing
7846     // so prevents folding a load into this instruction or making a copy.
7847     const int UnpackLoMask[] = {0, 0, 1, 1};
7848     const int UnpackHiMask[] = {2, 2, 3, 3};
7849     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 1, 1}))
7850       Mask = UnpackLoMask;
7851     else if (isShuffleEquivalent(V1, V2, Mask, {2, 2, 3, 3}))
7852       Mask = UnpackHiMask;
7853
7854     return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
7855                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
7856   }
7857
7858   // Try to use shift instructions.
7859   if (SDValue Shift =
7860           lowerVectorShuffleAsShift(DL, MVT::v4i32, V1, V2, Mask, DAG))
7861     return Shift;
7862
7863   // There are special ways we can lower some single-element blends.
7864   if (NumV2Elements == 1)
7865     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4i32, V1, V2,
7866                                                          Mask, Subtarget, DAG))
7867       return V;
7868
7869   // We have different paths for blend lowering, but they all must use the
7870   // *exact* same predicate.
7871   bool IsBlendSupported = Subtarget->hasSSE41();
7872   if (IsBlendSupported)
7873     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i32, V1, V2, Mask,
7874                                                   Subtarget, DAG))
7875       return Blend;
7876
7877   if (SDValue Masked =
7878           lowerVectorShuffleAsBitMask(DL, MVT::v4i32, V1, V2, Mask, DAG))
7879     return Masked;
7880
7881   // Use dedicated unpack instructions for masks that match their pattern.
7882   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 1, 5}))
7883     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V1, V2);
7884   if (isShuffleEquivalent(V1, V2, Mask, {2, 6, 3, 7}))
7885     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V1, V2);
7886   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 5, 1}))
7887     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V2, V1);
7888   if (isShuffleEquivalent(V1, V2, Mask, {6, 2, 7, 3}))
7889     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V2, V1);
7890
7891   // Try to use byte rotation instructions.
7892   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
7893   if (Subtarget->hasSSSE3())
7894     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
7895             DL, MVT::v4i32, V1, V2, Mask, Subtarget, DAG))
7896       return Rotate;
7897
7898   // If we have direct support for blends, we should lower by decomposing into
7899   // a permute. That will be faster than the domain cross.
7900   if (IsBlendSupported)
7901     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i32, V1, V2,
7902                                                       Mask, DAG);
7903
7904   // Try to lower by permuting the inputs into an unpack instruction.
7905   if (SDValue Unpack =
7906           lowerVectorShuffleAsUnpack(DL, MVT::v4i32, V1, V2, Mask, DAG))
7907     return Unpack;
7908
7909   // We implement this with SHUFPS because it can blend from two vectors.
7910   // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
7911   // up the inputs, bypassing domain shift penalties that we would encur if we
7912   // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
7913   // relevant.
7914   return DAG.getNode(ISD::BITCAST, DL, MVT::v4i32,
7915                      DAG.getVectorShuffle(
7916                          MVT::v4f32, DL,
7917                          DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V1),
7918                          DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V2), Mask));
7919 }
7920
7921 /// \brief Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
7922 /// shuffle lowering, and the most complex part.
7923 ///
7924 /// The lowering strategy is to try to form pairs of input lanes which are
7925 /// targeted at the same half of the final vector, and then use a dword shuffle
7926 /// to place them onto the right half, and finally unpack the paired lanes into
7927 /// their final position.
7928 ///
7929 /// The exact breakdown of how to form these dword pairs and align them on the
7930 /// correct sides is really tricky. See the comments within the function for
7931 /// more of the details.
7932 ///
7933 /// This code also handles repeated 128-bit lanes of v8i16 shuffles, but each
7934 /// lane must shuffle the *exact* same way. In fact, you must pass a v8 Mask to
7935 /// this routine for it to work correctly. To shuffle a 256-bit or 512-bit i16
7936 /// vector, form the analogous 128-bit 8-element Mask.
7937 static SDValue lowerV8I16GeneralSingleInputVectorShuffle(
7938     SDLoc DL, MVT VT, SDValue V, MutableArrayRef<int> Mask,
7939     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7940   assert(VT.getScalarType() == MVT::i16 && "Bad input type!");
7941   MVT PSHUFDVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
7942
7943   assert(Mask.size() == 8 && "Shuffle mask length doen't match!");
7944   MutableArrayRef<int> LoMask = Mask.slice(0, 4);
7945   MutableArrayRef<int> HiMask = Mask.slice(4, 4);
7946
7947   SmallVector<int, 4> LoInputs;
7948   std::copy_if(LoMask.begin(), LoMask.end(), std::back_inserter(LoInputs),
7949                [](int M) { return M >= 0; });
7950   std::sort(LoInputs.begin(), LoInputs.end());
7951   LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()), LoInputs.end());
7952   SmallVector<int, 4> HiInputs;
7953   std::copy_if(HiMask.begin(), HiMask.end(), std::back_inserter(HiInputs),
7954                [](int M) { return M >= 0; });
7955   std::sort(HiInputs.begin(), HiInputs.end());
7956   HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()), HiInputs.end());
7957   int NumLToL =
7958       std::lower_bound(LoInputs.begin(), LoInputs.end(), 4) - LoInputs.begin();
7959   int NumHToL = LoInputs.size() - NumLToL;
7960   int NumLToH =
7961       std::lower_bound(HiInputs.begin(), HiInputs.end(), 4) - HiInputs.begin();
7962   int NumHToH = HiInputs.size() - NumLToH;
7963   MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
7964   MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
7965   MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
7966   MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
7967
7968   // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
7969   // such inputs we can swap two of the dwords across the half mark and end up
7970   // with <=2 inputs to each half in each half. Once there, we can fall through
7971   // to the generic code below. For example:
7972   //
7973   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
7974   // Mask:  [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
7975   //
7976   // However in some very rare cases we have a 1-into-3 or 3-into-1 on one half
7977   // and an existing 2-into-2 on the other half. In this case we may have to
7978   // pre-shuffle the 2-into-2 half to avoid turning it into a 3-into-1 or
7979   // 1-into-3 which could cause us to cycle endlessly fixing each side in turn.
7980   // Fortunately, we don't have to handle anything but a 2-into-2 pattern
7981   // because any other situation (including a 3-into-1 or 1-into-3 in the other
7982   // half than the one we target for fixing) will be fixed when we re-enter this
7983   // path. We will also combine away any sequence of PSHUFD instructions that
7984   // result into a single instruction. Here is an example of the tricky case:
7985   //
7986   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
7987   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -THIS-IS-BAD!!!!-> [5, 7, 1, 0, 4, 7, 5, 3]
7988   //
7989   // This now has a 1-into-3 in the high half! Instead, we do two shuffles:
7990   //
7991   // Input: [a, b, c, d, e, f, g, h] PSHUFHW[0,2,1,3]-> [a, b, c, d, e, g, f, h]
7992   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -----------------> [3, 7, 1, 0, 2, 7, 3, 6]
7993   //
7994   // Input: [a, b, c, d, e, g, f, h] -PSHUFD[0,2,1,3]-> [a, b, e, g, c, d, f, h]
7995   // Mask:  [3, 7, 1, 0, 2, 7, 3, 6] -----------------> [5, 7, 1, 0, 4, 7, 5, 6]
7996   //
7997   // The result is fine to be handled by the generic logic.
7998   auto balanceSides = [&](ArrayRef<int> AToAInputs, ArrayRef<int> BToAInputs,
7999                           ArrayRef<int> BToBInputs, ArrayRef<int> AToBInputs,
8000                           int AOffset, int BOffset) {
8001     assert((AToAInputs.size() == 3 || AToAInputs.size() == 1) &&
8002            "Must call this with A having 3 or 1 inputs from the A half.");
8003     assert((BToAInputs.size() == 1 || BToAInputs.size() == 3) &&
8004            "Must call this with B having 1 or 3 inputs from the B half.");
8005     assert(AToAInputs.size() + BToAInputs.size() == 4 &&
8006            "Must call this with either 3:1 or 1:3 inputs (summing to 4).");
8007
8008     // Compute the index of dword with only one word among the three inputs in
8009     // a half by taking the sum of the half with three inputs and subtracting
8010     // the sum of the actual three inputs. The difference is the remaining
8011     // slot.
8012     int ADWord, BDWord;
8013     int &TripleDWord = AToAInputs.size() == 3 ? ADWord : BDWord;
8014     int &OneInputDWord = AToAInputs.size() == 3 ? BDWord : ADWord;
8015     int TripleInputOffset = AToAInputs.size() == 3 ? AOffset : BOffset;
8016     ArrayRef<int> TripleInputs = AToAInputs.size() == 3 ? AToAInputs : BToAInputs;
8017     int OneInput = AToAInputs.size() == 3 ? BToAInputs[0] : AToAInputs[0];
8018     int TripleInputSum = 0 + 1 + 2 + 3 + (4 * TripleInputOffset);
8019     int TripleNonInputIdx =
8020         TripleInputSum - std::accumulate(TripleInputs.begin(), TripleInputs.end(), 0);
8021     TripleDWord = TripleNonInputIdx / 2;
8022
8023     // We use xor with one to compute the adjacent DWord to whichever one the
8024     // OneInput is in.
8025     OneInputDWord = (OneInput / 2) ^ 1;
8026
8027     // Check for one tricky case: We're fixing a 3<-1 or a 1<-3 shuffle for AToA
8028     // and BToA inputs. If there is also such a problem with the BToB and AToB
8029     // inputs, we don't try to fix it necessarily -- we'll recurse and see it in
8030     // the next pass. However, if we have a 2<-2 in the BToB and AToB inputs, it
8031     // is essential that we don't *create* a 3<-1 as then we might oscillate.
8032     if (BToBInputs.size() == 2 && AToBInputs.size() == 2) {
8033       // Compute how many inputs will be flipped by swapping these DWords. We
8034       // need
8035       // to balance this to ensure we don't form a 3-1 shuffle in the other
8036       // half.
8037       int NumFlippedAToBInputs =
8038           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord) +
8039           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord + 1);
8040       int NumFlippedBToBInputs =
8041           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord) +
8042           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord + 1);
8043       if ((NumFlippedAToBInputs == 1 &&
8044            (NumFlippedBToBInputs == 0 || NumFlippedBToBInputs == 2)) ||
8045           (NumFlippedBToBInputs == 1 &&
8046            (NumFlippedAToBInputs == 0 || NumFlippedAToBInputs == 2))) {
8047         // We choose whether to fix the A half or B half based on whether that
8048         // half has zero flipped inputs. At zero, we may not be able to fix it
8049         // with that half. We also bias towards fixing the B half because that
8050         // will more commonly be the high half, and we have to bias one way.
8051         auto FixFlippedInputs = [&V, &DL, &Mask, &DAG](int PinnedIdx, int DWord,
8052                                                        ArrayRef<int> Inputs) {
8053           int FixIdx = PinnedIdx ^ 1; // The adjacent slot to the pinned slot.
8054           bool IsFixIdxInput = std::find(Inputs.begin(), Inputs.end(),
8055                                          PinnedIdx ^ 1) != Inputs.end();
8056           // Determine whether the free index is in the flipped dword or the
8057           // unflipped dword based on where the pinned index is. We use this bit
8058           // in an xor to conditionally select the adjacent dword.
8059           int FixFreeIdx = 2 * (DWord ^ (PinnedIdx / 2 == DWord));
8060           bool IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
8061                                              FixFreeIdx) != Inputs.end();
8062           if (IsFixIdxInput == IsFixFreeIdxInput)
8063             FixFreeIdx += 1;
8064           IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
8065                                         FixFreeIdx) != Inputs.end();
8066           assert(IsFixIdxInput != IsFixFreeIdxInput &&
8067                  "We need to be changing the number of flipped inputs!");
8068           int PSHUFHalfMask[] = {0, 1, 2, 3};
8069           std::swap(PSHUFHalfMask[FixFreeIdx % 4], PSHUFHalfMask[FixIdx % 4]);
8070           V = DAG.getNode(FixIdx < 4 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW, DL,
8071                           MVT::v8i16, V,
8072                           getV4X86ShuffleImm8ForMask(PSHUFHalfMask, DL, DAG));
8073
8074           for (int &M : Mask)
8075             if (M != -1 && M == FixIdx)
8076               M = FixFreeIdx;
8077             else if (M != -1 && M == FixFreeIdx)
8078               M = FixIdx;
8079         };
8080         if (NumFlippedBToBInputs != 0) {
8081           int BPinnedIdx =
8082               BToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
8083           FixFlippedInputs(BPinnedIdx, BDWord, BToBInputs);
8084         } else {
8085           assert(NumFlippedAToBInputs != 0 && "Impossible given predicates!");
8086           int APinnedIdx =
8087               AToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
8088           FixFlippedInputs(APinnedIdx, ADWord, AToBInputs);
8089         }
8090       }
8091     }
8092
8093     int PSHUFDMask[] = {0, 1, 2, 3};
8094     PSHUFDMask[ADWord] = BDWord;
8095     PSHUFDMask[BDWord] = ADWord;
8096     V = DAG.getNode(ISD::BITCAST, DL, VT,
8097                     DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT,
8098                                 DAG.getNode(ISD::BITCAST, DL, PSHUFDVT, V),
8099                                 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL,
8100                                                            DAG)));
8101
8102     // Adjust the mask to match the new locations of A and B.
8103     for (int &M : Mask)
8104       if (M != -1 && M/2 == ADWord)
8105         M = 2 * BDWord + M % 2;
8106       else if (M != -1 && M/2 == BDWord)
8107         M = 2 * ADWord + M % 2;
8108
8109     // Recurse back into this routine to re-compute state now that this isn't
8110     // a 3 and 1 problem.
8111     return lowerV8I16GeneralSingleInputVectorShuffle(DL, VT, V, Mask, Subtarget,
8112                                                      DAG);
8113   };
8114   if ((NumLToL == 3 && NumHToL == 1) || (NumLToL == 1 && NumHToL == 3))
8115     return balanceSides(LToLInputs, HToLInputs, HToHInputs, LToHInputs, 0, 4);
8116   else if ((NumHToH == 3 && NumLToH == 1) || (NumHToH == 1 && NumLToH == 3))
8117     return balanceSides(HToHInputs, LToHInputs, LToLInputs, HToLInputs, 4, 0);
8118
8119   // At this point there are at most two inputs to the low and high halves from
8120   // each half. That means the inputs can always be grouped into dwords and
8121   // those dwords can then be moved to the correct half with a dword shuffle.
8122   // We use at most one low and one high word shuffle to collect these paired
8123   // inputs into dwords, and finally a dword shuffle to place them.
8124   int PSHUFLMask[4] = {-1, -1, -1, -1};
8125   int PSHUFHMask[4] = {-1, -1, -1, -1};
8126   int PSHUFDMask[4] = {-1, -1, -1, -1};
8127
8128   // First fix the masks for all the inputs that are staying in their
8129   // original halves. This will then dictate the targets of the cross-half
8130   // shuffles.
8131   auto fixInPlaceInputs =
8132       [&PSHUFDMask](ArrayRef<int> InPlaceInputs, ArrayRef<int> IncomingInputs,
8133                     MutableArrayRef<int> SourceHalfMask,
8134                     MutableArrayRef<int> HalfMask, int HalfOffset) {
8135     if (InPlaceInputs.empty())
8136       return;
8137     if (InPlaceInputs.size() == 1) {
8138       SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8139           InPlaceInputs[0] - HalfOffset;
8140       PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
8141       return;
8142     }
8143     if (IncomingInputs.empty()) {
8144       // Just fix all of the in place inputs.
8145       for (int Input : InPlaceInputs) {
8146         SourceHalfMask[Input - HalfOffset] = Input - HalfOffset;
8147         PSHUFDMask[Input / 2] = Input / 2;
8148       }
8149       return;
8150     }
8151
8152     assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!");
8153     SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8154         InPlaceInputs[0] - HalfOffset;
8155     // Put the second input next to the first so that they are packed into
8156     // a dword. We find the adjacent index by toggling the low bit.
8157     int AdjIndex = InPlaceInputs[0] ^ 1;
8158     SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
8159     std::replace(HalfMask.begin(), HalfMask.end(), InPlaceInputs[1], AdjIndex);
8160     PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
8161   };
8162   fixInPlaceInputs(LToLInputs, HToLInputs, PSHUFLMask, LoMask, 0);
8163   fixInPlaceInputs(HToHInputs, LToHInputs, PSHUFHMask, HiMask, 4);
8164
8165   // Now gather the cross-half inputs and place them into a free dword of
8166   // their target half.
8167   // FIXME: This operation could almost certainly be simplified dramatically to
8168   // look more like the 3-1 fixing operation.
8169   auto moveInputsToRightHalf = [&PSHUFDMask](
8170       MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
8171       MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
8172       MutableArrayRef<int> FinalSourceHalfMask, int SourceOffset,
8173       int DestOffset) {
8174     auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
8175       return SourceHalfMask[Word] != -1 && SourceHalfMask[Word] != Word;
8176     };
8177     auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
8178                                                int Word) {
8179       int LowWord = Word & ~1;
8180       int HighWord = Word | 1;
8181       return isWordClobbered(SourceHalfMask, LowWord) ||
8182              isWordClobbered(SourceHalfMask, HighWord);
8183     };
8184
8185     if (IncomingInputs.empty())
8186       return;
8187
8188     if (ExistingInputs.empty()) {
8189       // Map any dwords with inputs from them into the right half.
8190       for (int Input : IncomingInputs) {
8191         // If the source half mask maps over the inputs, turn those into
8192         // swaps and use the swapped lane.
8193         if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
8194           if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] == -1) {
8195             SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
8196                 Input - SourceOffset;
8197             // We have to swap the uses in our half mask in one sweep.
8198             for (int &M : HalfMask)
8199               if (M == SourceHalfMask[Input - SourceOffset] + SourceOffset)
8200                 M = Input;
8201               else if (M == Input)
8202                 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8203           } else {
8204             assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==
8205                        Input - SourceOffset &&
8206                    "Previous placement doesn't match!");
8207           }
8208           // Note that this correctly re-maps both when we do a swap and when
8209           // we observe the other side of the swap above. We rely on that to
8210           // avoid swapping the members of the input list directly.
8211           Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8212         }
8213
8214         // Map the input's dword into the correct half.
8215         if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] == -1)
8216           PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
8217         else
8218           assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==
8219                      Input / 2 &&
8220                  "Previous placement doesn't match!");
8221       }
8222
8223       // And just directly shift any other-half mask elements to be same-half
8224       // as we will have mirrored the dword containing the element into the
8225       // same position within that half.
8226       for (int &M : HalfMask)
8227         if (M >= SourceOffset && M < SourceOffset + 4) {
8228           M = M - SourceOffset + DestOffset;
8229           assert(M >= 0 && "This should never wrap below zero!");
8230         }
8231       return;
8232     }
8233
8234     // Ensure we have the input in a viable dword of its current half. This
8235     // is particularly tricky because the original position may be clobbered
8236     // by inputs being moved and *staying* in that half.
8237     if (IncomingInputs.size() == 1) {
8238       if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8239         int InputFixed = std::find(std::begin(SourceHalfMask),
8240                                    std::end(SourceHalfMask), -1) -
8241                          std::begin(SourceHalfMask) + SourceOffset;
8242         SourceHalfMask[InputFixed - SourceOffset] =
8243             IncomingInputs[0] - SourceOffset;
8244         std::replace(HalfMask.begin(), HalfMask.end(), IncomingInputs[0],
8245                      InputFixed);
8246         IncomingInputs[0] = InputFixed;
8247       }
8248     } else if (IncomingInputs.size() == 2) {
8249       if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
8250           isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8251         // We have two non-adjacent or clobbered inputs we need to extract from
8252         // the source half. To do this, we need to map them into some adjacent
8253         // dword slot in the source mask.
8254         int InputsFixed[2] = {IncomingInputs[0] - SourceOffset,
8255                               IncomingInputs[1] - SourceOffset};
8256
8257         // If there is a free slot in the source half mask adjacent to one of
8258         // the inputs, place the other input in it. We use (Index XOR 1) to
8259         // compute an adjacent index.
8260         if (!isWordClobbered(SourceHalfMask, InputsFixed[0]) &&
8261             SourceHalfMask[InputsFixed[0] ^ 1] == -1) {
8262           SourceHalfMask[InputsFixed[0]] = InputsFixed[0];
8263           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8264           InputsFixed[1] = InputsFixed[0] ^ 1;
8265         } else if (!isWordClobbered(SourceHalfMask, InputsFixed[1]) &&
8266                    SourceHalfMask[InputsFixed[1] ^ 1] == -1) {
8267           SourceHalfMask[InputsFixed[1]] = InputsFixed[1];
8268           SourceHalfMask[InputsFixed[1] ^ 1] = InputsFixed[0];
8269           InputsFixed[0] = InputsFixed[1] ^ 1;
8270         } else if (SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] == -1 &&
8271                    SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] == -1) {
8272           // The two inputs are in the same DWord but it is clobbered and the
8273           // adjacent DWord isn't used at all. Move both inputs to the free
8274           // slot.
8275           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] = InputsFixed[0];
8276           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] = InputsFixed[1];
8277           InputsFixed[0] = 2 * ((InputsFixed[0] / 2) ^ 1);
8278           InputsFixed[1] = 2 * ((InputsFixed[0] / 2) ^ 1) + 1;
8279         } else {
8280           // The only way we hit this point is if there is no clobbering
8281           // (because there are no off-half inputs to this half) and there is no
8282           // free slot adjacent to one of the inputs. In this case, we have to
8283           // swap an input with a non-input.
8284           for (int i = 0; i < 4; ++i)
8285             assert((SourceHalfMask[i] == -1 || SourceHalfMask[i] == i) &&
8286                    "We can't handle any clobbers here!");
8287           assert(InputsFixed[1] != (InputsFixed[0] ^ 1) &&
8288                  "Cannot have adjacent inputs here!");
8289
8290           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8291           SourceHalfMask[InputsFixed[1]] = InputsFixed[0] ^ 1;
8292
8293           // We also have to update the final source mask in this case because
8294           // it may need to undo the above swap.
8295           for (int &M : FinalSourceHalfMask)
8296             if (M == (InputsFixed[0] ^ 1) + SourceOffset)
8297               M = InputsFixed[1] + SourceOffset;
8298             else if (M == InputsFixed[1] + SourceOffset)
8299               M = (InputsFixed[0] ^ 1) + SourceOffset;
8300
8301           InputsFixed[1] = InputsFixed[0] ^ 1;
8302         }
8303
8304         // Point everything at the fixed inputs.
8305         for (int &M : HalfMask)
8306           if (M == IncomingInputs[0])
8307             M = InputsFixed[0] + SourceOffset;
8308           else if (M == IncomingInputs[1])
8309             M = InputsFixed[1] + SourceOffset;
8310
8311         IncomingInputs[0] = InputsFixed[0] + SourceOffset;
8312         IncomingInputs[1] = InputsFixed[1] + SourceOffset;
8313       }
8314     } else {
8315       llvm_unreachable("Unhandled input size!");
8316     }
8317
8318     // Now hoist the DWord down to the right half.
8319     int FreeDWord = (PSHUFDMask[DestOffset / 2] == -1 ? 0 : 1) + DestOffset / 2;
8320     assert(PSHUFDMask[FreeDWord] == -1 && "DWord not free");
8321     PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
8322     for (int &M : HalfMask)
8323       for (int Input : IncomingInputs)
8324         if (M == Input)
8325           M = FreeDWord * 2 + Input % 2;
8326   };
8327   moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask, HiMask,
8328                         /*SourceOffset*/ 4, /*DestOffset*/ 0);
8329   moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask, LoMask,
8330                         /*SourceOffset*/ 0, /*DestOffset*/ 4);
8331
8332   // Now enact all the shuffles we've computed to move the inputs into their
8333   // target half.
8334   if (!isNoopShuffleMask(PSHUFLMask))
8335     V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
8336                     getV4X86ShuffleImm8ForMask(PSHUFLMask, DL, DAG));
8337   if (!isNoopShuffleMask(PSHUFHMask))
8338     V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
8339                     getV4X86ShuffleImm8ForMask(PSHUFHMask, DL, DAG));
8340   if (!isNoopShuffleMask(PSHUFDMask))
8341     V = DAG.getNode(ISD::BITCAST, DL, VT,
8342                     DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT,
8343                                 DAG.getNode(ISD::BITCAST, DL, PSHUFDVT, V),
8344                                 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL,
8345                                                            DAG)));
8346
8347   // At this point, each half should contain all its inputs, and we can then
8348   // just shuffle them into their final position.
8349   assert(std::count_if(LoMask.begin(), LoMask.end(),
8350                        [](int M) { return M >= 4; }) == 0 &&
8351          "Failed to lift all the high half inputs to the low mask!");
8352   assert(std::count_if(HiMask.begin(), HiMask.end(),
8353                        [](int M) { return M >= 0 && M < 4; }) == 0 &&
8354          "Failed to lift all the low half inputs to the high mask!");
8355
8356   // Do a half shuffle for the low mask.
8357   if (!isNoopShuffleMask(LoMask))
8358     V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
8359                     getV4X86ShuffleImm8ForMask(LoMask, DL, DAG));
8360
8361   // Do a half shuffle with the high mask after shifting its values down.
8362   for (int &M : HiMask)
8363     if (M >= 0)
8364       M -= 4;
8365   if (!isNoopShuffleMask(HiMask))
8366     V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
8367                     getV4X86ShuffleImm8ForMask(HiMask, DL, DAG));
8368
8369   return V;
8370 }
8371
8372 /// \brief Helper to form a PSHUFB-based shuffle+blend.
8373 static SDValue lowerVectorShuffleAsPSHUFB(SDLoc DL, MVT VT, SDValue V1,
8374                                           SDValue V2, ArrayRef<int> Mask,
8375                                           SelectionDAG &DAG, bool &V1InUse,
8376                                           bool &V2InUse) {
8377   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
8378   SDValue V1Mask[16];
8379   SDValue V2Mask[16];
8380   V1InUse = false;
8381   V2InUse = false;
8382
8383   int Size = Mask.size();
8384   int Scale = 16 / Size;
8385   for (int i = 0; i < 16; ++i) {
8386     if (Mask[i / Scale] == -1) {
8387       V1Mask[i] = V2Mask[i] = DAG.getUNDEF(MVT::i8);
8388     } else {
8389       const int ZeroMask = 0x80;
8390       int V1Idx = Mask[i / Scale] < Size ? Mask[i / Scale] * Scale + i % Scale
8391                                           : ZeroMask;
8392       int V2Idx = Mask[i / Scale] < Size
8393                       ? ZeroMask
8394                       : (Mask[i / Scale] - Size) * Scale + i % Scale;
8395       if (Zeroable[i / Scale])
8396         V1Idx = V2Idx = ZeroMask;
8397       V1Mask[i] = DAG.getConstant(V1Idx, DL, MVT::i8);
8398       V2Mask[i] = DAG.getConstant(V2Idx, DL, MVT::i8);
8399       V1InUse |= (ZeroMask != V1Idx);
8400       V2InUse |= (ZeroMask != V2Idx);
8401     }
8402   }
8403
8404   if (V1InUse)
8405     V1 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
8406                      DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, V1),
8407                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V1Mask));
8408   if (V2InUse)
8409     V2 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
8410                      DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, V2),
8411                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V2Mask));
8412
8413   // If we need shuffled inputs from both, blend the two.
8414   SDValue V;
8415   if (V1InUse && V2InUse)
8416     V = DAG.getNode(ISD::OR, DL, MVT::v16i8, V1, V2);
8417   else
8418     V = V1InUse ? V1 : V2;
8419
8420   // Cast the result back to the correct type.
8421   return DAG.getNode(ISD::BITCAST, DL, VT, V);
8422 }
8423
8424 /// \brief Generic lowering of 8-lane i16 shuffles.
8425 ///
8426 /// This handles both single-input shuffles and combined shuffle/blends with
8427 /// two inputs. The single input shuffles are immediately delegated to
8428 /// a dedicated lowering routine.
8429 ///
8430 /// The blends are lowered in one of three fundamental ways. If there are few
8431 /// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
8432 /// of the input is significantly cheaper when lowered as an interleaving of
8433 /// the two inputs, try to interleave them. Otherwise, blend the low and high
8434 /// halves of the inputs separately (making them have relatively few inputs)
8435 /// and then concatenate them.
8436 static SDValue lowerV8I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8437                                        const X86Subtarget *Subtarget,
8438                                        SelectionDAG &DAG) {
8439   SDLoc DL(Op);
8440   assert(Op.getSimpleValueType() == MVT::v8i16 && "Bad shuffle type!");
8441   assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
8442   assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
8443   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8444   ArrayRef<int> OrigMask = SVOp->getMask();
8445   int MaskStorage[8] = {OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
8446                         OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7]};
8447   MutableArrayRef<int> Mask(MaskStorage);
8448
8449   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
8450
8451   // Whenever we can lower this as a zext, that instruction is strictly faster
8452   // than any alternative.
8453   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
8454           DL, MVT::v8i16, V1, V2, OrigMask, Subtarget, DAG))
8455     return ZExt;
8456
8457   auto isV1 = [](int M) { return M >= 0 && M < 8; };
8458   (void)isV1;
8459   auto isV2 = [](int M) { return M >= 8; };
8460
8461   int NumV2Inputs = std::count_if(Mask.begin(), Mask.end(), isV2);
8462
8463   if (NumV2Inputs == 0) {
8464     // Check for being able to broadcast a single element.
8465     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i16, V1,
8466                                                           Mask, Subtarget, DAG))
8467       return Broadcast;
8468
8469     // Try to use shift instructions.
8470     if (SDValue Shift =
8471             lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V1, Mask, DAG))
8472       return Shift;
8473
8474     // Use dedicated unpack instructions for masks that match their pattern.
8475     if (isShuffleEquivalent(V1, V1, Mask, {0, 0, 1, 1, 2, 2, 3, 3}))
8476       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V1, V1);
8477     if (isShuffleEquivalent(V1, V1, Mask, {4, 4, 5, 5, 6, 6, 7, 7}))
8478       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V1, V1);
8479
8480     // Try to use byte rotation instructions.
8481     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(DL, MVT::v8i16, V1, V1,
8482                                                         Mask, Subtarget, DAG))
8483       return Rotate;
8484
8485     return lowerV8I16GeneralSingleInputVectorShuffle(DL, MVT::v8i16, V1, Mask,
8486                                                      Subtarget, DAG);
8487   }
8488
8489   assert(std::any_of(Mask.begin(), Mask.end(), isV1) &&
8490          "All single-input shuffles should be canonicalized to be V1-input "
8491          "shuffles.");
8492
8493   // Try to use shift instructions.
8494   if (SDValue Shift =
8495           lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V2, Mask, DAG))
8496     return Shift;
8497
8498   // There are special ways we can lower some single-element blends.
8499   if (NumV2Inputs == 1)
8500     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v8i16, V1, V2,
8501                                                          Mask, Subtarget, DAG))
8502       return V;
8503
8504   // We have different paths for blend lowering, but they all must use the
8505   // *exact* same predicate.
8506   bool IsBlendSupported = Subtarget->hasSSE41();
8507   if (IsBlendSupported)
8508     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i16, V1, V2, Mask,
8509                                                   Subtarget, DAG))
8510       return Blend;
8511
8512   if (SDValue Masked =
8513           lowerVectorShuffleAsBitMask(DL, MVT::v8i16, V1, V2, Mask, DAG))
8514     return Masked;
8515
8516   // Use dedicated unpack instructions for masks that match their pattern.
8517   if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 2, 10, 3, 11}))
8518     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V1, V2);
8519   if (isShuffleEquivalent(V1, V2, Mask, {4, 12, 5, 13, 6, 14, 7, 15}))
8520     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V1, V2);
8521
8522   // Try to use byte rotation instructions.
8523   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8524           DL, MVT::v8i16, V1, V2, Mask, Subtarget, DAG))
8525     return Rotate;
8526
8527   if (SDValue BitBlend =
8528           lowerVectorShuffleAsBitBlend(DL, MVT::v8i16, V1, V2, Mask, DAG))
8529     return BitBlend;
8530
8531   if (SDValue Unpack =
8532           lowerVectorShuffleAsUnpack(DL, MVT::v8i16, V1, V2, Mask, DAG))
8533     return Unpack;
8534
8535   // If we can't directly blend but can use PSHUFB, that will be better as it
8536   // can both shuffle and set up the inefficient blend.
8537   if (!IsBlendSupported && Subtarget->hasSSSE3()) {
8538     bool V1InUse, V2InUse;
8539     return lowerVectorShuffleAsPSHUFB(DL, MVT::v8i16, V1, V2, Mask, DAG,
8540                                       V1InUse, V2InUse);
8541   }
8542
8543   // We can always bit-blend if we have to so the fallback strategy is to
8544   // decompose into single-input permutes and blends.
8545   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i16, V1, V2,
8546                                                       Mask, DAG);
8547 }
8548
8549 /// \brief Check whether a compaction lowering can be done by dropping even
8550 /// elements and compute how many times even elements must be dropped.
8551 ///
8552 /// This handles shuffles which take every Nth element where N is a power of
8553 /// two. Example shuffle masks:
8554 ///
8555 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14,  0,  2,  4,  6,  8, 10, 12, 14
8556 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30
8557 ///  N = 2:  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12
8558 ///  N = 2:  0,  4,  8, 12, 16, 20, 24, 28,  0,  4,  8, 12, 16, 20, 24, 28
8559 ///  N = 3:  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8
8560 ///  N = 3:  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24
8561 ///
8562 /// Any of these lanes can of course be undef.
8563 ///
8564 /// This routine only supports N <= 3.
8565 /// FIXME: Evaluate whether either AVX or AVX-512 have any opportunities here
8566 /// for larger N.
8567 ///
8568 /// \returns N above, or the number of times even elements must be dropped if
8569 /// there is such a number. Otherwise returns zero.
8570 static int canLowerByDroppingEvenElements(ArrayRef<int> Mask) {
8571   // Figure out whether we're looping over two inputs or just one.
8572   bool IsSingleInput = isSingleInputShuffleMask(Mask);
8573
8574   // The modulus for the shuffle vector entries is based on whether this is
8575   // a single input or not.
8576   int ShuffleModulus = Mask.size() * (IsSingleInput ? 1 : 2);
8577   assert(isPowerOf2_32((uint32_t)ShuffleModulus) &&
8578          "We should only be called with masks with a power-of-2 size!");
8579
8580   uint64_t ModMask = (uint64_t)ShuffleModulus - 1;
8581
8582   // We track whether the input is viable for all power-of-2 strides 2^1, 2^2,
8583   // and 2^3 simultaneously. This is because we may have ambiguity with
8584   // partially undef inputs.
8585   bool ViableForN[3] = {true, true, true};
8586
8587   for (int i = 0, e = Mask.size(); i < e; ++i) {
8588     // Ignore undef lanes, we'll optimistically collapse them to the pattern we
8589     // want.
8590     if (Mask[i] == -1)
8591       continue;
8592
8593     bool IsAnyViable = false;
8594     for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
8595       if (ViableForN[j]) {
8596         uint64_t N = j + 1;
8597
8598         // The shuffle mask must be equal to (i * 2^N) % M.
8599         if ((uint64_t)Mask[i] == (((uint64_t)i << N) & ModMask))
8600           IsAnyViable = true;
8601         else
8602           ViableForN[j] = false;
8603       }
8604     // Early exit if we exhaust the possible powers of two.
8605     if (!IsAnyViable)
8606       break;
8607   }
8608
8609   for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
8610     if (ViableForN[j])
8611       return j + 1;
8612
8613   // Return 0 as there is no viable power of two.
8614   return 0;
8615 }
8616
8617 /// \brief Generic lowering of v16i8 shuffles.
8618 ///
8619 /// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
8620 /// detect any complexity reducing interleaving. If that doesn't help, it uses
8621 /// UNPCK to spread the i8 elements across two i16-element vectors, and uses
8622 /// the existing lowering for v8i16 blends on each half, finally PACK-ing them
8623 /// back together.
8624 static SDValue lowerV16I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8625                                        const X86Subtarget *Subtarget,
8626                                        SelectionDAG &DAG) {
8627   SDLoc DL(Op);
8628   assert(Op.getSimpleValueType() == MVT::v16i8 && "Bad shuffle type!");
8629   assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
8630   assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
8631   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8632   ArrayRef<int> Mask = SVOp->getMask();
8633   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
8634
8635   // Try to use shift instructions.
8636   if (SDValue Shift =
8637           lowerVectorShuffleAsShift(DL, MVT::v16i8, V1, V2, Mask, DAG))
8638     return Shift;
8639
8640   // Try to use byte rotation instructions.
8641   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8642           DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
8643     return Rotate;
8644
8645   // Try to use a zext lowering.
8646   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
8647           DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
8648     return ZExt;
8649
8650   int NumV2Elements =
8651       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 16; });
8652
8653   // For single-input shuffles, there are some nicer lowering tricks we can use.
8654   if (NumV2Elements == 0) {
8655     // Check for being able to broadcast a single element.
8656     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i8, V1,
8657                                                           Mask, Subtarget, DAG))
8658       return Broadcast;
8659
8660     // Check whether we can widen this to an i16 shuffle by duplicating bytes.
8661     // Notably, this handles splat and partial-splat shuffles more efficiently.
8662     // However, it only makes sense if the pre-duplication shuffle simplifies
8663     // things significantly. Currently, this means we need to be able to
8664     // express the pre-duplication shuffle as an i16 shuffle.
8665     //
8666     // FIXME: We should check for other patterns which can be widened into an
8667     // i16 shuffle as well.
8668     auto canWidenViaDuplication = [](ArrayRef<int> Mask) {
8669       for (int i = 0; i < 16; i += 2)
8670         if (Mask[i] != -1 && Mask[i + 1] != -1 && Mask[i] != Mask[i + 1])
8671           return false;
8672
8673       return true;
8674     };
8675     auto tryToWidenViaDuplication = [&]() -> SDValue {
8676       if (!canWidenViaDuplication(Mask))
8677         return SDValue();
8678       SmallVector<int, 4> LoInputs;
8679       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(LoInputs),
8680                    [](int M) { return M >= 0 && M < 8; });
8681       std::sort(LoInputs.begin(), LoInputs.end());
8682       LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()),
8683                      LoInputs.end());
8684       SmallVector<int, 4> HiInputs;
8685       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(HiInputs),
8686                    [](int M) { return M >= 8; });
8687       std::sort(HiInputs.begin(), HiInputs.end());
8688       HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()),
8689                      HiInputs.end());
8690
8691       bool TargetLo = LoInputs.size() >= HiInputs.size();
8692       ArrayRef<int> InPlaceInputs = TargetLo ? LoInputs : HiInputs;
8693       ArrayRef<int> MovingInputs = TargetLo ? HiInputs : LoInputs;
8694
8695       int PreDupI16Shuffle[] = {-1, -1, -1, -1, -1, -1, -1, -1};
8696       SmallDenseMap<int, int, 8> LaneMap;
8697       for (int I : InPlaceInputs) {
8698         PreDupI16Shuffle[I/2] = I/2;
8699         LaneMap[I] = I;
8700       }
8701       int j = TargetLo ? 0 : 4, je = j + 4;
8702       for (int i = 0, ie = MovingInputs.size(); i < ie; ++i) {
8703         // Check if j is already a shuffle of this input. This happens when
8704         // there are two adjacent bytes after we move the low one.
8705         if (PreDupI16Shuffle[j] != MovingInputs[i] / 2) {
8706           // If we haven't yet mapped the input, search for a slot into which
8707           // we can map it.
8708           while (j < je && PreDupI16Shuffle[j] != -1)
8709             ++j;
8710
8711           if (j == je)
8712             // We can't place the inputs into a single half with a simple i16 shuffle, so bail.
8713             return SDValue();
8714
8715           // Map this input with the i16 shuffle.
8716           PreDupI16Shuffle[j] = MovingInputs[i] / 2;
8717         }
8718
8719         // Update the lane map based on the mapping we ended up with.
8720         LaneMap[MovingInputs[i]] = 2 * j + MovingInputs[i] % 2;
8721       }
8722       V1 = DAG.getNode(
8723           ISD::BITCAST, DL, MVT::v16i8,
8724           DAG.getVectorShuffle(MVT::v8i16, DL,
8725                                DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1),
8726                                DAG.getUNDEF(MVT::v8i16), PreDupI16Shuffle));
8727
8728       // Unpack the bytes to form the i16s that will be shuffled into place.
8729       V1 = DAG.getNode(TargetLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
8730                        MVT::v16i8, V1, V1);
8731
8732       int PostDupI16Shuffle[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8733       for (int i = 0; i < 16; ++i)
8734         if (Mask[i] != -1) {
8735           int MappedMask = LaneMap[Mask[i]] - (TargetLo ? 0 : 8);
8736           assert(MappedMask < 8 && "Invalid v8 shuffle mask!");
8737           if (PostDupI16Shuffle[i / 2] == -1)
8738             PostDupI16Shuffle[i / 2] = MappedMask;
8739           else
8740             assert(PostDupI16Shuffle[i / 2] == MappedMask &&
8741                    "Conflicting entrties in the original shuffle!");
8742         }
8743       return DAG.getNode(
8744           ISD::BITCAST, DL, MVT::v16i8,
8745           DAG.getVectorShuffle(MVT::v8i16, DL,
8746                                DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1),
8747                                DAG.getUNDEF(MVT::v8i16), PostDupI16Shuffle));
8748     };
8749     if (SDValue V = tryToWidenViaDuplication())
8750       return V;
8751   }
8752
8753   // Use dedicated unpack instructions for masks that match their pattern.
8754   if (isShuffleEquivalent(V1, V2, Mask, {// Low half.
8755                                          0, 16, 1, 17, 2, 18, 3, 19,
8756                                          // High half.
8757                                          4, 20, 5, 21, 6, 22, 7, 23}))
8758     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V1, V2);
8759   if (isShuffleEquivalent(V1, V2, Mask, {// Low half.
8760                                          8, 24, 9, 25, 10, 26, 11, 27,
8761                                          // High half.
8762                                          12, 28, 13, 29, 14, 30, 15, 31}))
8763     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V1, V2);
8764
8765   // Check for SSSE3 which lets us lower all v16i8 shuffles much more directly
8766   // with PSHUFB. It is important to do this before we attempt to generate any
8767   // blends but after all of the single-input lowerings. If the single input
8768   // lowerings can find an instruction sequence that is faster than a PSHUFB, we
8769   // want to preserve that and we can DAG combine any longer sequences into
8770   // a PSHUFB in the end. But once we start blending from multiple inputs,
8771   // the complexity of DAG combining bad patterns back into PSHUFB is too high,
8772   // and there are *very* few patterns that would actually be faster than the
8773   // PSHUFB approach because of its ability to zero lanes.
8774   //
8775   // FIXME: The only exceptions to the above are blends which are exact
8776   // interleavings with direct instructions supporting them. We currently don't
8777   // handle those well here.
8778   if (Subtarget->hasSSSE3()) {
8779     bool V1InUse = false;
8780     bool V2InUse = false;
8781
8782     SDValue PSHUFB = lowerVectorShuffleAsPSHUFB(DL, MVT::v16i8, V1, V2, Mask,
8783                                                 DAG, V1InUse, V2InUse);
8784
8785     // If both V1 and V2 are in use and we can use a direct blend or an unpack,
8786     // do so. This avoids using them to handle blends-with-zero which is
8787     // important as a single pshufb is significantly faster for that.
8788     if (V1InUse && V2InUse) {
8789       if (Subtarget->hasSSE41())
8790         if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i8, V1, V2,
8791                                                       Mask, Subtarget, DAG))
8792           return Blend;
8793
8794       // We can use an unpack to do the blending rather than an or in some
8795       // cases. Even though the or may be (very minorly) more efficient, we
8796       // preference this lowering because there are common cases where part of
8797       // the complexity of the shuffles goes away when we do the final blend as
8798       // an unpack.
8799       // FIXME: It might be worth trying to detect if the unpack-feeding
8800       // shuffles will both be pshufb, in which case we shouldn't bother with
8801       // this.
8802       if (SDValue Unpack =
8803               lowerVectorShuffleAsUnpack(DL, MVT::v16i8, V1, V2, Mask, DAG))
8804         return Unpack;
8805     }
8806
8807     return PSHUFB;
8808   }
8809
8810   // There are special ways we can lower some single-element blends.
8811   if (NumV2Elements == 1)
8812     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v16i8, V1, V2,
8813                                                          Mask, Subtarget, DAG))
8814       return V;
8815
8816   if (SDValue BitBlend =
8817           lowerVectorShuffleAsBitBlend(DL, MVT::v16i8, V1, V2, Mask, DAG))
8818     return BitBlend;
8819
8820   // Check whether a compaction lowering can be done. This handles shuffles
8821   // which take every Nth element for some even N. See the helper function for
8822   // details.
8823   //
8824   // We special case these as they can be particularly efficiently handled with
8825   // the PACKUSB instruction on x86 and they show up in common patterns of
8826   // rearranging bytes to truncate wide elements.
8827   if (int NumEvenDrops = canLowerByDroppingEvenElements(Mask)) {
8828     // NumEvenDrops is the power of two stride of the elements. Another way of
8829     // thinking about it is that we need to drop the even elements this many
8830     // times to get the original input.
8831     bool IsSingleInput = isSingleInputShuffleMask(Mask);
8832
8833     // First we need to zero all the dropped bytes.
8834     assert(NumEvenDrops <= 3 &&
8835            "No support for dropping even elements more than 3 times.");
8836     // We use the mask type to pick which bytes are preserved based on how many
8837     // elements are dropped.
8838     MVT MaskVTs[] = { MVT::v8i16, MVT::v4i32, MVT::v2i64 };
8839     SDValue ByteClearMask =
8840         DAG.getNode(ISD::BITCAST, DL, MVT::v16i8,
8841                     DAG.getConstant(0xFF, DL, MaskVTs[NumEvenDrops - 1]));
8842     V1 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V1, ByteClearMask);
8843     if (!IsSingleInput)
8844       V2 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V2, ByteClearMask);
8845
8846     // Now pack things back together.
8847     V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1);
8848     V2 = IsSingleInput ? V1 : DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V2);
8849     SDValue Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, V1, V2);
8850     for (int i = 1; i < NumEvenDrops; ++i) {
8851       Result = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, Result);
8852       Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, Result, Result);
8853     }
8854
8855     return Result;
8856   }
8857
8858   // Handle multi-input cases by blending single-input shuffles.
8859   if (NumV2Elements > 0)
8860     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v16i8, V1, V2,
8861                                                       Mask, DAG);
8862
8863   // The fallback path for single-input shuffles widens this into two v8i16
8864   // vectors with unpacks, shuffles those, and then pulls them back together
8865   // with a pack.
8866   SDValue V = V1;
8867
8868   int LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8869   int HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8870   for (int i = 0; i < 16; ++i)
8871     if (Mask[i] >= 0)
8872       (i < 8 ? LoBlendMask[i] : HiBlendMask[i % 8]) = Mask[i];
8873
8874   SDValue Zero = getZeroVector(MVT::v8i16, Subtarget, DAG, DL);
8875
8876   SDValue VLoHalf, VHiHalf;
8877   // Check if any of the odd lanes in the v16i8 are used. If not, we can mask
8878   // them out and avoid using UNPCK{L,H} to extract the elements of V as
8879   // i16s.
8880   if (std::none_of(std::begin(LoBlendMask), std::end(LoBlendMask),
8881                    [](int M) { return M >= 0 && M % 2 == 1; }) &&
8882       std::none_of(std::begin(HiBlendMask), std::end(HiBlendMask),
8883                    [](int M) { return M >= 0 && M % 2 == 1; })) {
8884     // Use a mask to drop the high bytes.
8885     VLoHalf = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V);
8886     VLoHalf = DAG.getNode(ISD::AND, DL, MVT::v8i16, VLoHalf,
8887                      DAG.getConstant(0x00FF, DL, MVT::v8i16));
8888
8889     // This will be a single vector shuffle instead of a blend so nuke VHiHalf.
8890     VHiHalf = DAG.getUNDEF(MVT::v8i16);
8891
8892     // Squash the masks to point directly into VLoHalf.
8893     for (int &M : LoBlendMask)
8894       if (M >= 0)
8895         M /= 2;
8896     for (int &M : HiBlendMask)
8897       if (M >= 0)
8898         M /= 2;
8899   } else {
8900     // Otherwise just unpack the low half of V into VLoHalf and the high half into
8901     // VHiHalf so that we can blend them as i16s.
8902     VLoHalf = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
8903                      DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V, Zero));
8904     VHiHalf = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
8905                      DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V, Zero));
8906   }
8907
8908   SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, LoBlendMask);
8909   SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, HiBlendMask);
8910
8911   return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
8912 }
8913
8914 /// \brief Dispatching routine to lower various 128-bit x86 vector shuffles.
8915 ///
8916 /// This routine breaks down the specific type of 128-bit shuffle and
8917 /// dispatches to the lowering routines accordingly.
8918 static SDValue lower128BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8919                                         MVT VT, const X86Subtarget *Subtarget,
8920                                         SelectionDAG &DAG) {
8921   switch (VT.SimpleTy) {
8922   case MVT::v2i64:
8923     return lowerV2I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
8924   case MVT::v2f64:
8925     return lowerV2F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
8926   case MVT::v4i32:
8927     return lowerV4I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
8928   case MVT::v4f32:
8929     return lowerV4F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
8930   case MVT::v8i16:
8931     return lowerV8I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
8932   case MVT::v16i8:
8933     return lowerV16I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
8934
8935   default:
8936     llvm_unreachable("Unimplemented!");
8937   }
8938 }
8939
8940 /// \brief Helper function to test whether a shuffle mask could be
8941 /// simplified by widening the elements being shuffled.
8942 ///
8943 /// Appends the mask for wider elements in WidenedMask if valid. Otherwise
8944 /// leaves it in an unspecified state.
8945 ///
8946 /// NOTE: This must handle normal vector shuffle masks and *target* vector
8947 /// shuffle masks. The latter have the special property of a '-2' representing
8948 /// a zero-ed lane of a vector.
8949 static bool canWidenShuffleElements(ArrayRef<int> Mask,
8950                                     SmallVectorImpl<int> &WidenedMask) {
8951   for (int i = 0, Size = Mask.size(); i < Size; i += 2) {
8952     // If both elements are undef, its trivial.
8953     if (Mask[i] == SM_SentinelUndef && Mask[i + 1] == SM_SentinelUndef) {
8954       WidenedMask.push_back(SM_SentinelUndef);
8955       continue;
8956     }
8957
8958     // Check for an undef mask and a mask value properly aligned to fit with
8959     // a pair of values. If we find such a case, use the non-undef mask's value.
8960     if (Mask[i] == SM_SentinelUndef && Mask[i + 1] >= 0 && Mask[i + 1] % 2 == 1) {
8961       WidenedMask.push_back(Mask[i + 1] / 2);
8962       continue;
8963     }
8964     if (Mask[i + 1] == SM_SentinelUndef && Mask[i] >= 0 && Mask[i] % 2 == 0) {
8965       WidenedMask.push_back(Mask[i] / 2);
8966       continue;
8967     }
8968
8969     // When zeroing, we need to spread the zeroing across both lanes to widen.
8970     if (Mask[i] == SM_SentinelZero || Mask[i + 1] == SM_SentinelZero) {
8971       if ((Mask[i] == SM_SentinelZero || Mask[i] == SM_SentinelUndef) &&
8972           (Mask[i + 1] == SM_SentinelZero || Mask[i + 1] == SM_SentinelUndef)) {
8973         WidenedMask.push_back(SM_SentinelZero);
8974         continue;
8975       }
8976       return false;
8977     }
8978
8979     // Finally check if the two mask values are adjacent and aligned with
8980     // a pair.
8981     if (Mask[i] != SM_SentinelUndef && Mask[i] % 2 == 0 && Mask[i] + 1 == Mask[i + 1]) {
8982       WidenedMask.push_back(Mask[i] / 2);
8983       continue;
8984     }
8985
8986     // Otherwise we can't safely widen the elements used in this shuffle.
8987     return false;
8988   }
8989   assert(WidenedMask.size() == Mask.size() / 2 &&
8990          "Incorrect size of mask after widening the elements!");
8991
8992   return true;
8993 }
8994
8995 /// \brief Generic routine to split vector shuffle into half-sized shuffles.
8996 ///
8997 /// This routine just extracts two subvectors, shuffles them independently, and
8998 /// then concatenates them back together. This should work effectively with all
8999 /// AVX vector shuffle types.
9000 static SDValue splitAndLowerVectorShuffle(SDLoc DL, MVT VT, SDValue V1,
9001                                           SDValue V2, ArrayRef<int> Mask,
9002                                           SelectionDAG &DAG) {
9003   assert(VT.getSizeInBits() >= 256 &&
9004          "Only for 256-bit or wider vector shuffles!");
9005   assert(V1.getSimpleValueType() == VT && "Bad operand type!");
9006   assert(V2.getSimpleValueType() == VT && "Bad operand type!");
9007
9008   ArrayRef<int> LoMask = Mask.slice(0, Mask.size() / 2);
9009   ArrayRef<int> HiMask = Mask.slice(Mask.size() / 2);
9010
9011   int NumElements = VT.getVectorNumElements();
9012   int SplitNumElements = NumElements / 2;
9013   MVT ScalarVT = VT.getScalarType();
9014   MVT SplitVT = MVT::getVectorVT(ScalarVT, NumElements / 2);
9015
9016   // Rather than splitting build-vectors, just build two narrower build
9017   // vectors. This helps shuffling with splats and zeros.
9018   auto SplitVector = [&](SDValue V) {
9019     while (V.getOpcode() == ISD::BITCAST)
9020       V = V->getOperand(0);
9021
9022     MVT OrigVT = V.getSimpleValueType();
9023     int OrigNumElements = OrigVT.getVectorNumElements();
9024     int OrigSplitNumElements = OrigNumElements / 2;
9025     MVT OrigScalarVT = OrigVT.getScalarType();
9026     MVT OrigSplitVT = MVT::getVectorVT(OrigScalarVT, OrigNumElements / 2);
9027
9028     SDValue LoV, HiV;
9029
9030     auto *BV = dyn_cast<BuildVectorSDNode>(V);
9031     if (!BV) {
9032       LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
9033                         DAG.getIntPtrConstant(0, DL));
9034       HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
9035                         DAG.getIntPtrConstant(OrigSplitNumElements, DL));
9036     } else {
9037
9038       SmallVector<SDValue, 16> LoOps, HiOps;
9039       for (int i = 0; i < OrigSplitNumElements; ++i) {
9040         LoOps.push_back(BV->getOperand(i));
9041         HiOps.push_back(BV->getOperand(i + OrigSplitNumElements));
9042       }
9043       LoV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, LoOps);
9044       HiV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, HiOps);
9045     }
9046     return std::make_pair(DAG.getNode(ISD::BITCAST, DL, SplitVT, LoV),
9047                           DAG.getNode(ISD::BITCAST, DL, SplitVT, HiV));
9048   };
9049
9050   SDValue LoV1, HiV1, LoV2, HiV2;
9051   std::tie(LoV1, HiV1) = SplitVector(V1);
9052   std::tie(LoV2, HiV2) = SplitVector(V2);
9053
9054   // Now create two 4-way blends of these half-width vectors.
9055   auto HalfBlend = [&](ArrayRef<int> HalfMask) {
9056     bool UseLoV1 = false, UseHiV1 = false, UseLoV2 = false, UseHiV2 = false;
9057     SmallVector<int, 32> V1BlendMask, V2BlendMask, BlendMask;
9058     for (int i = 0; i < SplitNumElements; ++i) {
9059       int M = HalfMask[i];
9060       if (M >= NumElements) {
9061         if (M >= NumElements + SplitNumElements)
9062           UseHiV2 = true;
9063         else
9064           UseLoV2 = true;
9065         V2BlendMask.push_back(M - NumElements);
9066         V1BlendMask.push_back(-1);
9067         BlendMask.push_back(SplitNumElements + i);
9068       } else if (M >= 0) {
9069         if (M >= SplitNumElements)
9070           UseHiV1 = true;
9071         else
9072           UseLoV1 = true;
9073         V2BlendMask.push_back(-1);
9074         V1BlendMask.push_back(M);
9075         BlendMask.push_back(i);
9076       } else {
9077         V2BlendMask.push_back(-1);
9078         V1BlendMask.push_back(-1);
9079         BlendMask.push_back(-1);
9080       }
9081     }
9082
9083     // Because the lowering happens after all combining takes place, we need to
9084     // manually combine these blend masks as much as possible so that we create
9085     // a minimal number of high-level vector shuffle nodes.
9086
9087     // First try just blending the halves of V1 or V2.
9088     if (!UseLoV1 && !UseHiV1 && !UseLoV2 && !UseHiV2)
9089       return DAG.getUNDEF(SplitVT);
9090     if (!UseLoV2 && !UseHiV2)
9091       return DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9092     if (!UseLoV1 && !UseHiV1)
9093       return DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9094
9095     SDValue V1Blend, V2Blend;
9096     if (UseLoV1 && UseHiV1) {
9097       V1Blend =
9098         DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9099     } else {
9100       // We only use half of V1 so map the usage down into the final blend mask.
9101       V1Blend = UseLoV1 ? LoV1 : HiV1;
9102       for (int i = 0; i < SplitNumElements; ++i)
9103         if (BlendMask[i] >= 0 && BlendMask[i] < SplitNumElements)
9104           BlendMask[i] = V1BlendMask[i] - (UseLoV1 ? 0 : SplitNumElements);
9105     }
9106     if (UseLoV2 && UseHiV2) {
9107       V2Blend =
9108         DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9109     } else {
9110       // We only use half of V2 so map the usage down into the final blend mask.
9111       V2Blend = UseLoV2 ? LoV2 : HiV2;
9112       for (int i = 0; i < SplitNumElements; ++i)
9113         if (BlendMask[i] >= SplitNumElements)
9114           BlendMask[i] = V2BlendMask[i] + (UseLoV2 ? SplitNumElements : 0);
9115     }
9116     return DAG.getVectorShuffle(SplitVT, DL, V1Blend, V2Blend, BlendMask);
9117   };
9118   SDValue Lo = HalfBlend(LoMask);
9119   SDValue Hi = HalfBlend(HiMask);
9120   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
9121 }
9122
9123 /// \brief Either split a vector in halves or decompose the shuffles and the
9124 /// blend.
9125 ///
9126 /// This is provided as a good fallback for many lowerings of non-single-input
9127 /// shuffles with more than one 128-bit lane. In those cases, we want to select
9128 /// between splitting the shuffle into 128-bit components and stitching those
9129 /// back together vs. extracting the single-input shuffles and blending those
9130 /// results.
9131 static SDValue lowerVectorShuffleAsSplitOrBlend(SDLoc DL, MVT VT, SDValue V1,
9132                                                 SDValue V2, ArrayRef<int> Mask,
9133                                                 SelectionDAG &DAG) {
9134   assert(!isSingleInputShuffleMask(Mask) && "This routine must not be used to "
9135                                             "lower single-input shuffles as it "
9136                                             "could then recurse on itself.");
9137   int Size = Mask.size();
9138
9139   // If this can be modeled as a broadcast of two elements followed by a blend,
9140   // prefer that lowering. This is especially important because broadcasts can
9141   // often fold with memory operands.
9142   auto DoBothBroadcast = [&] {
9143     int V1BroadcastIdx = -1, V2BroadcastIdx = -1;
9144     for (int M : Mask)
9145       if (M >= Size) {
9146         if (V2BroadcastIdx == -1)
9147           V2BroadcastIdx = M - Size;
9148         else if (M - Size != V2BroadcastIdx)
9149           return false;
9150       } else if (M >= 0) {
9151         if (V1BroadcastIdx == -1)
9152           V1BroadcastIdx = M;
9153         else if (M != V1BroadcastIdx)
9154           return false;
9155       }
9156     return true;
9157   };
9158   if (DoBothBroadcast())
9159     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask,
9160                                                       DAG);
9161
9162   // If the inputs all stem from a single 128-bit lane of each input, then we
9163   // split them rather than blending because the split will decompose to
9164   // unusually few instructions.
9165   int LaneCount = VT.getSizeInBits() / 128;
9166   int LaneSize = Size / LaneCount;
9167   SmallBitVector LaneInputs[2];
9168   LaneInputs[0].resize(LaneCount, false);
9169   LaneInputs[1].resize(LaneCount, false);
9170   for (int i = 0; i < Size; ++i)
9171     if (Mask[i] >= 0)
9172       LaneInputs[Mask[i] / Size][(Mask[i] % Size) / LaneSize] = true;
9173   if (LaneInputs[0].count() <= 1 && LaneInputs[1].count() <= 1)
9174     return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9175
9176   // Otherwise, just fall back to decomposed shuffles and a blend. This requires
9177   // that the decomposed single-input shuffles don't end up here.
9178   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9179 }
9180
9181 /// \brief Lower a vector shuffle crossing multiple 128-bit lanes as
9182 /// a permutation and blend of those lanes.
9183 ///
9184 /// This essentially blends the out-of-lane inputs to each lane into the lane
9185 /// from a permuted copy of the vector. This lowering strategy results in four
9186 /// instructions in the worst case for a single-input cross lane shuffle which
9187 /// is lower than any other fully general cross-lane shuffle strategy I'm aware
9188 /// of. Special cases for each particular shuffle pattern should be handled
9189 /// prior to trying this lowering.
9190 static SDValue lowerVectorShuffleAsLanePermuteAndBlend(SDLoc DL, MVT VT,
9191                                                        SDValue V1, SDValue V2,
9192                                                        ArrayRef<int> Mask,
9193                                                        SelectionDAG &DAG) {
9194   // FIXME: This should probably be generalized for 512-bit vectors as well.
9195   assert(VT.getSizeInBits() == 256 && "Only for 256-bit vector shuffles!");
9196   int LaneSize = Mask.size() / 2;
9197
9198   // If there are only inputs from one 128-bit lane, splitting will in fact be
9199   // less expensive. The flags track whether the given lane contains an element
9200   // that crosses to another lane.
9201   bool LaneCrossing[2] = {false, false};
9202   for (int i = 0, Size = Mask.size(); i < Size; ++i)
9203     if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
9204       LaneCrossing[(Mask[i] % Size) / LaneSize] = true;
9205   if (!LaneCrossing[0] || !LaneCrossing[1])
9206     return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9207
9208   if (isSingleInputShuffleMask(Mask)) {
9209     SmallVector<int, 32> FlippedBlendMask;
9210     for (int i = 0, Size = Mask.size(); i < Size; ++i)
9211       FlippedBlendMask.push_back(
9212           Mask[i] < 0 ? -1 : (((Mask[i] % Size) / LaneSize == i / LaneSize)
9213                                   ? Mask[i]
9214                                   : Mask[i] % LaneSize +
9215                                         (i / LaneSize) * LaneSize + Size));
9216
9217     // Flip the vector, and blend the results which should now be in-lane. The
9218     // VPERM2X128 mask uses the low 2 bits for the low source and bits 4 and
9219     // 5 for the high source. The value 3 selects the high half of source 2 and
9220     // the value 2 selects the low half of source 2. We only use source 2 to
9221     // allow folding it into a memory operand.
9222     unsigned PERMMask = 3 | 2 << 4;
9223     SDValue Flipped = DAG.getNode(X86ISD::VPERM2X128, DL, VT, DAG.getUNDEF(VT),
9224                                   V1, DAG.getConstant(PERMMask, DL, MVT::i8));
9225     return DAG.getVectorShuffle(VT, DL, V1, Flipped, FlippedBlendMask);
9226   }
9227
9228   // This now reduces to two single-input shuffles of V1 and V2 which at worst
9229   // will be handled by the above logic and a blend of the results, much like
9230   // other patterns in AVX.
9231   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9232 }
9233
9234 /// \brief Handle lowering 2-lane 128-bit shuffles.
9235 static SDValue lowerV2X128VectorShuffle(SDLoc DL, MVT VT, SDValue V1,
9236                                         SDValue V2, ArrayRef<int> Mask,
9237                                         const X86Subtarget *Subtarget,
9238                                         SelectionDAG &DAG) {
9239   // TODO: If minimizing size and one of the inputs is a zero vector and the
9240   // the zero vector has only one use, we could use a VPERM2X128 to save the
9241   // instruction bytes needed to explicitly generate the zero vector.
9242
9243   // Blends are faster and handle all the non-lane-crossing cases.
9244   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, VT, V1, V2, Mask,
9245                                                 Subtarget, DAG))
9246     return Blend;
9247
9248   bool IsV1Zero = ISD::isBuildVectorAllZeros(V1.getNode());
9249   bool IsV2Zero = ISD::isBuildVectorAllZeros(V2.getNode());
9250
9251   // If either input operand is a zero vector, use VPERM2X128 because its mask
9252   // allows us to replace the zero input with an implicit zero.
9253   if (!IsV1Zero && !IsV2Zero) {
9254     // Check for patterns which can be matched with a single insert of a 128-bit
9255     // subvector.
9256     bool OnlyUsesV1 = isShuffleEquivalent(V1, V2, Mask, {0, 1, 0, 1});
9257     if (OnlyUsesV1 || isShuffleEquivalent(V1, V2, Mask, {0, 1, 4, 5})) {
9258       MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(),
9259                                    VT.getVectorNumElements() / 2);
9260       SDValue LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V1,
9261                                 DAG.getIntPtrConstant(0, DL));
9262       SDValue HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT,
9263                                 OnlyUsesV1 ? V1 : V2,
9264                                 DAG.getIntPtrConstant(0, DL));
9265       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LoV, HiV);
9266     }
9267   }
9268
9269   // Otherwise form a 128-bit permutation. After accounting for undefs,
9270   // convert the 64-bit shuffle mask selection values into 128-bit
9271   // selection bits by dividing the indexes by 2 and shifting into positions
9272   // defined by a vperm2*128 instruction's immediate control byte.
9273
9274   // The immediate permute control byte looks like this:
9275   //    [1:0] - select 128 bits from sources for low half of destination
9276   //    [2]   - ignore
9277   //    [3]   - zero low half of destination
9278   //    [5:4] - select 128 bits from sources for high half of destination
9279   //    [6]   - ignore
9280   //    [7]   - zero high half of destination
9281
9282   int MaskLO = Mask[0];
9283   if (MaskLO == SM_SentinelUndef)
9284     MaskLO = Mask[1] == SM_SentinelUndef ? 0 : Mask[1];
9285
9286   int MaskHI = Mask[2];
9287   if (MaskHI == SM_SentinelUndef)
9288     MaskHI = Mask[3] == SM_SentinelUndef ? 0 : Mask[3];
9289
9290   unsigned PermMask = MaskLO / 2 | (MaskHI / 2) << 4;
9291
9292   // If either input is a zero vector, replace it with an undef input.
9293   // Shuffle mask values <  4 are selecting elements of V1.
9294   // Shuffle mask values >= 4 are selecting elements of V2.
9295   // Adjust each half of the permute mask by clearing the half that was
9296   // selecting the zero vector and setting the zero mask bit.
9297   if (IsV1Zero) {
9298     V1 = DAG.getUNDEF(VT);
9299     if (MaskLO < 4)
9300       PermMask = (PermMask & 0xf0) | 0x08;
9301     if (MaskHI < 4)
9302       PermMask = (PermMask & 0x0f) | 0x80;
9303   }
9304   if (IsV2Zero) {
9305     V2 = DAG.getUNDEF(VT);
9306     if (MaskLO >= 4)
9307       PermMask = (PermMask & 0xf0) | 0x08;
9308     if (MaskHI >= 4)
9309       PermMask = (PermMask & 0x0f) | 0x80;
9310   }
9311
9312   return DAG.getNode(X86ISD::VPERM2X128, DL, VT, V1, V2,
9313                      DAG.getConstant(PermMask, DL, MVT::i8));
9314 }
9315
9316 /// \brief Lower a vector shuffle by first fixing the 128-bit lanes and then
9317 /// shuffling each lane.
9318 ///
9319 /// This will only succeed when the result of fixing the 128-bit lanes results
9320 /// in a single-input non-lane-crossing shuffle with a repeating shuffle mask in
9321 /// each 128-bit lanes. This handles many cases where we can quickly blend away
9322 /// the lane crosses early and then use simpler shuffles within each lane.
9323 ///
9324 /// FIXME: It might be worthwhile at some point to support this without
9325 /// requiring the 128-bit lane-relative shuffles to be repeating, but currently
9326 /// in x86 only floating point has interesting non-repeating shuffles, and even
9327 /// those are still *marginally* more expensive.
9328 static SDValue lowerVectorShuffleByMerging128BitLanes(
9329     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
9330     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
9331   assert(!isSingleInputShuffleMask(Mask) &&
9332          "This is only useful with multiple inputs.");
9333
9334   int Size = Mask.size();
9335   int LaneSize = 128 / VT.getScalarSizeInBits();
9336   int NumLanes = Size / LaneSize;
9337   assert(NumLanes > 1 && "Only handles 256-bit and wider shuffles.");
9338
9339   // See if we can build a hypothetical 128-bit lane-fixing shuffle mask. Also
9340   // check whether the in-128-bit lane shuffles share a repeating pattern.
9341   SmallVector<int, 4> Lanes;
9342   Lanes.resize(NumLanes, -1);
9343   SmallVector<int, 4> InLaneMask;
9344   InLaneMask.resize(LaneSize, -1);
9345   for (int i = 0; i < Size; ++i) {
9346     if (Mask[i] < 0)
9347       continue;
9348
9349     int j = i / LaneSize;
9350
9351     if (Lanes[j] < 0) {
9352       // First entry we've seen for this lane.
9353       Lanes[j] = Mask[i] / LaneSize;
9354     } else if (Lanes[j] != Mask[i] / LaneSize) {
9355       // This doesn't match the lane selected previously!
9356       return SDValue();
9357     }
9358
9359     // Check that within each lane we have a consistent shuffle mask.
9360     int k = i % LaneSize;
9361     if (InLaneMask[k] < 0) {
9362       InLaneMask[k] = Mask[i] % LaneSize;
9363     } else if (InLaneMask[k] != Mask[i] % LaneSize) {
9364       // This doesn't fit a repeating in-lane mask.
9365       return SDValue();
9366     }
9367   }
9368
9369   // First shuffle the lanes into place.
9370   MVT LaneVT = MVT::getVectorVT(VT.isFloatingPoint() ? MVT::f64 : MVT::i64,
9371                                 VT.getSizeInBits() / 64);
9372   SmallVector<int, 8> LaneMask;
9373   LaneMask.resize(NumLanes * 2, -1);
9374   for (int i = 0; i < NumLanes; ++i)
9375     if (Lanes[i] >= 0) {
9376       LaneMask[2 * i + 0] = 2*Lanes[i] + 0;
9377       LaneMask[2 * i + 1] = 2*Lanes[i] + 1;
9378     }
9379
9380   V1 = DAG.getNode(ISD::BITCAST, DL, LaneVT, V1);
9381   V2 = DAG.getNode(ISD::BITCAST, DL, LaneVT, V2);
9382   SDValue LaneShuffle = DAG.getVectorShuffle(LaneVT, DL, V1, V2, LaneMask);
9383
9384   // Cast it back to the type we actually want.
9385   LaneShuffle = DAG.getNode(ISD::BITCAST, DL, VT, LaneShuffle);
9386
9387   // Now do a simple shuffle that isn't lane crossing.
9388   SmallVector<int, 8> NewMask;
9389   NewMask.resize(Size, -1);
9390   for (int i = 0; i < Size; ++i)
9391     if (Mask[i] >= 0)
9392       NewMask[i] = (i / LaneSize) * LaneSize + Mask[i] % LaneSize;
9393   assert(!is128BitLaneCrossingShuffleMask(VT, NewMask) &&
9394          "Must not introduce lane crosses at this point!");
9395
9396   return DAG.getVectorShuffle(VT, DL, LaneShuffle, DAG.getUNDEF(VT), NewMask);
9397 }
9398
9399 /// \brief Test whether the specified input (0 or 1) is in-place blended by the
9400 /// given mask.
9401 ///
9402 /// This returns true if the elements from a particular input are already in the
9403 /// slot required by the given mask and require no permutation.
9404 static bool isShuffleMaskInputInPlace(int Input, ArrayRef<int> Mask) {
9405   assert((Input == 0 || Input == 1) && "Only two inputs to shuffles.");
9406   int Size = Mask.size();
9407   for (int i = 0; i < Size; ++i)
9408     if (Mask[i] >= 0 && Mask[i] / Size == Input && Mask[i] % Size != i)
9409       return false;
9410
9411   return true;
9412 }
9413
9414 /// \brief Handle lowering of 4-lane 64-bit floating point shuffles.
9415 ///
9416 /// Also ends up handling lowering of 4-lane 64-bit integer shuffles when AVX2
9417 /// isn't available.
9418 static SDValue lowerV4F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9419                                        const X86Subtarget *Subtarget,
9420                                        SelectionDAG &DAG) {
9421   SDLoc DL(Op);
9422   assert(V1.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
9423   assert(V2.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
9424   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9425   ArrayRef<int> Mask = SVOp->getMask();
9426   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
9427
9428   SmallVector<int, 4> WidenedMask;
9429   if (canWidenShuffleElements(Mask, WidenedMask))
9430     return lowerV2X128VectorShuffle(DL, MVT::v4f64, V1, V2, Mask, Subtarget,
9431                                     DAG);
9432
9433   if (isSingleInputShuffleMask(Mask)) {
9434     // Check for being able to broadcast a single element.
9435     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f64, V1,
9436                                                           Mask, Subtarget, DAG))
9437       return Broadcast;
9438
9439     // Use low duplicate instructions for masks that match their pattern.
9440     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
9441       return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v4f64, V1);
9442
9443     if (!is128BitLaneCrossingShuffleMask(MVT::v4f64, Mask)) {
9444       // Non-half-crossing single input shuffles can be lowerid with an
9445       // interleaved permutation.
9446       unsigned VPERMILPMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1) |
9447                               ((Mask[2] == 3) << 2) | ((Mask[3] == 3) << 3);
9448       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f64, V1,
9449                          DAG.getConstant(VPERMILPMask, DL, MVT::i8));
9450     }
9451
9452     // With AVX2 we have direct support for this permutation.
9453     if (Subtarget->hasAVX2())
9454       return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4f64, V1,
9455                          getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
9456
9457     // Otherwise, fall back.
9458     return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v4f64, V1, V2, Mask,
9459                                                    DAG);
9460   }
9461
9462   // X86 has dedicated unpack instructions that can handle specific blend
9463   // operations: UNPCKH and UNPCKL.
9464   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 2, 6}))
9465     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V1, V2);
9466   if (isShuffleEquivalent(V1, V2, Mask, {1, 5, 3, 7}))
9467     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V1, V2);
9468   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 6, 2}))
9469     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V2, V1);
9470   if (isShuffleEquivalent(V1, V2, Mask, {5, 1, 7, 3}))
9471     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V2, V1);
9472
9473   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f64, V1, V2, Mask,
9474                                                 Subtarget, DAG))
9475     return Blend;
9476
9477   // Check if the blend happens to exactly fit that of SHUFPD.
9478   if ((Mask[0] == -1 || Mask[0] < 2) &&
9479       (Mask[1] == -1 || (Mask[1] >= 4 && Mask[1] < 6)) &&
9480       (Mask[2] == -1 || (Mask[2] >= 2 && Mask[2] < 4)) &&
9481       (Mask[3] == -1 || Mask[3] >= 6)) {
9482     unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 5) << 1) |
9483                           ((Mask[2] == 3) << 2) | ((Mask[3] == 7) << 3);
9484     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f64, V1, V2,
9485                        DAG.getConstant(SHUFPDMask, DL, MVT::i8));
9486   }
9487   if ((Mask[0] == -1 || (Mask[0] >= 4 && Mask[0] < 6)) &&
9488       (Mask[1] == -1 || Mask[1] < 2) &&
9489       (Mask[2] == -1 || Mask[2] >= 6) &&
9490       (Mask[3] == -1 || (Mask[3] >= 2 && Mask[3] < 4))) {
9491     unsigned SHUFPDMask = (Mask[0] == 5) | ((Mask[1] == 1) << 1) |
9492                           ((Mask[2] == 7) << 2) | ((Mask[3] == 3) << 3);
9493     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f64, V2, V1,
9494                        DAG.getConstant(SHUFPDMask, DL, MVT::i8));
9495   }
9496
9497   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9498   // shuffle. However, if we have AVX2 and either inputs are already in place,
9499   // we will be able to shuffle even across lanes the other input in a single
9500   // instruction so skip this pattern.
9501   if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
9502                                  isShuffleMaskInputInPlace(1, Mask))))
9503     if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9504             DL, MVT::v4f64, V1, V2, Mask, Subtarget, DAG))
9505       return Result;
9506
9507   // If we have AVX2 then we always want to lower with a blend because an v4 we
9508   // can fully permute the elements.
9509   if (Subtarget->hasAVX2())
9510     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4f64, V1, V2,
9511                                                       Mask, DAG);
9512
9513   // Otherwise fall back on generic lowering.
9514   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v4f64, V1, V2, Mask, DAG);
9515 }
9516
9517 /// \brief Handle lowering of 4-lane 64-bit integer shuffles.
9518 ///
9519 /// This routine is only called when we have AVX2 and thus a reasonable
9520 /// instruction set for v4i64 shuffling..
9521 static SDValue lowerV4I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9522                                        const X86Subtarget *Subtarget,
9523                                        SelectionDAG &DAG) {
9524   SDLoc DL(Op);
9525   assert(V1.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
9526   assert(V2.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
9527   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9528   ArrayRef<int> Mask = SVOp->getMask();
9529   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
9530   assert(Subtarget->hasAVX2() && "We can only lower v4i64 with AVX2!");
9531
9532   SmallVector<int, 4> WidenedMask;
9533   if (canWidenShuffleElements(Mask, WidenedMask))
9534     return lowerV2X128VectorShuffle(DL, MVT::v4i64, V1, V2, Mask, Subtarget,
9535                                     DAG);
9536
9537   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i64, V1, V2, Mask,
9538                                                 Subtarget, DAG))
9539     return Blend;
9540
9541   // Check for being able to broadcast a single element.
9542   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i64, V1,
9543                                                         Mask, Subtarget, DAG))
9544     return Broadcast;
9545
9546   // When the shuffle is mirrored between the 128-bit lanes of the unit, we can
9547   // use lower latency instructions that will operate on both 128-bit lanes.
9548   SmallVector<int, 2> RepeatedMask;
9549   if (is128BitLaneRepeatedShuffleMask(MVT::v4i64, Mask, RepeatedMask)) {
9550     if (isSingleInputShuffleMask(Mask)) {
9551       int PSHUFDMask[] = {-1, -1, -1, -1};
9552       for (int i = 0; i < 2; ++i)
9553         if (RepeatedMask[i] >= 0) {
9554           PSHUFDMask[2 * i] = 2 * RepeatedMask[i];
9555           PSHUFDMask[2 * i + 1] = 2 * RepeatedMask[i] + 1;
9556         }
9557       return DAG.getNode(
9558           ISD::BITCAST, DL, MVT::v4i64,
9559           DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32,
9560                       DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, V1),
9561                       getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
9562     }
9563   }
9564
9565   // AVX2 provides a direct instruction for permuting a single input across
9566   // lanes.
9567   if (isSingleInputShuffleMask(Mask))
9568     return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4i64, V1,
9569                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
9570
9571   // Try to use shift instructions.
9572   if (SDValue Shift =
9573           lowerVectorShuffleAsShift(DL, MVT::v4i64, V1, V2, Mask, DAG))
9574     return Shift;
9575
9576   // Use dedicated unpack instructions for masks that match their pattern.
9577   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 2, 6}))
9578     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V1, V2);
9579   if (isShuffleEquivalent(V1, V2, Mask, {1, 5, 3, 7}))
9580     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V1, V2);
9581   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 6, 2}))
9582     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V2, V1);
9583   if (isShuffleEquivalent(V1, V2, Mask, {5, 1, 7, 3}))
9584     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V2, V1);
9585
9586   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9587   // shuffle. However, if we have AVX2 and either inputs are already in place,
9588   // we will be able to shuffle even across lanes the other input in a single
9589   // instruction so skip this pattern.
9590   if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
9591                                  isShuffleMaskInputInPlace(1, Mask))))
9592     if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9593             DL, MVT::v4i64, V1, V2, Mask, Subtarget, DAG))
9594       return Result;
9595
9596   // Otherwise fall back on generic blend lowering.
9597   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i64, V1, V2,
9598                                                     Mask, DAG);
9599 }
9600
9601 /// \brief Handle lowering of 8-lane 32-bit floating point shuffles.
9602 ///
9603 /// Also ends up handling lowering of 8-lane 32-bit integer shuffles when AVX2
9604 /// isn't available.
9605 static SDValue lowerV8F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9606                                        const X86Subtarget *Subtarget,
9607                                        SelectionDAG &DAG) {
9608   SDLoc DL(Op);
9609   assert(V1.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
9610   assert(V2.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
9611   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9612   ArrayRef<int> Mask = SVOp->getMask();
9613   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9614
9615   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8f32, V1, V2, Mask,
9616                                                 Subtarget, DAG))
9617     return Blend;
9618
9619   // Check for being able to broadcast a single element.
9620   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8f32, V1,
9621                                                         Mask, Subtarget, DAG))
9622     return Broadcast;
9623
9624   // If the shuffle mask is repeated in each 128-bit lane, we have many more
9625   // options to efficiently lower the shuffle.
9626   SmallVector<int, 4> RepeatedMask;
9627   if (is128BitLaneRepeatedShuffleMask(MVT::v8f32, Mask, RepeatedMask)) {
9628     assert(RepeatedMask.size() == 4 &&
9629            "Repeated masks must be half the mask width!");
9630
9631     // Use even/odd duplicate instructions for masks that match their pattern.
9632     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2, 4, 4, 6, 6}))
9633       return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v8f32, V1);
9634     if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3, 5, 5, 7, 7}))
9635       return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v8f32, V1);
9636
9637     if (isSingleInputShuffleMask(Mask))
9638       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v8f32, V1,
9639                          getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
9640
9641     // Use dedicated unpack instructions for masks that match their pattern.
9642     if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 4, 12, 5, 13}))
9643       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V1, V2);
9644     if (isShuffleEquivalent(V1, V2, Mask, {2, 10, 3, 11, 6, 14, 7, 15}))
9645       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V1, V2);
9646     if (isShuffleEquivalent(V1, V2, Mask, {8, 0, 9, 1, 12, 4, 13, 5}))
9647       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V2, V1);
9648     if (isShuffleEquivalent(V1, V2, Mask, {10, 2, 11, 3, 14, 6, 15, 7}))
9649       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V2, V1);
9650
9651     // Otherwise, fall back to a SHUFPS sequence. Here it is important that we
9652     // have already handled any direct blends. We also need to squash the
9653     // repeated mask into a simulated v4f32 mask.
9654     for (int i = 0; i < 4; ++i)
9655       if (RepeatedMask[i] >= 8)
9656         RepeatedMask[i] -= 4;
9657     return lowerVectorShuffleWithSHUFPS(DL, MVT::v8f32, RepeatedMask, V1, V2, DAG);
9658   }
9659
9660   // If we have a single input shuffle with different shuffle patterns in the
9661   // two 128-bit lanes use the variable mask to VPERMILPS.
9662   if (isSingleInputShuffleMask(Mask)) {
9663     SDValue VPermMask[8];
9664     for (int i = 0; i < 8; ++i)
9665       VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
9666                                  : DAG.getConstant(Mask[i], DL, MVT::i32);
9667     if (!is128BitLaneCrossingShuffleMask(MVT::v8f32, Mask))
9668       return DAG.getNode(
9669           X86ISD::VPERMILPV, DL, MVT::v8f32, V1,
9670           DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask));
9671
9672     if (Subtarget->hasAVX2())
9673       return DAG.getNode(X86ISD::VPERMV, DL, MVT::v8f32,
9674                          DAG.getNode(ISD::BITCAST, DL, MVT::v8f32,
9675                                      DAG.getNode(ISD::BUILD_VECTOR, DL,
9676                                                  MVT::v8i32, VPermMask)),
9677                          V1);
9678
9679     // Otherwise, fall back.
9680     return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v8f32, V1, V2, Mask,
9681                                                    DAG);
9682   }
9683
9684   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9685   // shuffle.
9686   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9687           DL, MVT::v8f32, V1, V2, Mask, Subtarget, DAG))
9688     return Result;
9689
9690   // If we have AVX2 then we always want to lower with a blend because at v8 we
9691   // can fully permute the elements.
9692   if (Subtarget->hasAVX2())
9693     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8f32, V1, V2,
9694                                                       Mask, DAG);
9695
9696   // Otherwise fall back on generic lowering.
9697   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v8f32, V1, V2, Mask, DAG);
9698 }
9699
9700 /// \brief Handle lowering of 8-lane 32-bit integer shuffles.
9701 ///
9702 /// This routine is only called when we have AVX2 and thus a reasonable
9703 /// instruction set for v8i32 shuffling..
9704 static SDValue lowerV8I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9705                                        const X86Subtarget *Subtarget,
9706                                        SelectionDAG &DAG) {
9707   SDLoc DL(Op);
9708   assert(V1.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
9709   assert(V2.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
9710   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9711   ArrayRef<int> Mask = SVOp->getMask();
9712   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9713   assert(Subtarget->hasAVX2() && "We can only lower v8i32 with AVX2!");
9714
9715   // Whenever we can lower this as a zext, that instruction is strictly faster
9716   // than any alternative. It also allows us to fold memory operands into the
9717   // shuffle in many cases.
9718   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v8i32, V1, V2,
9719                                                          Mask, Subtarget, DAG))
9720     return ZExt;
9721
9722   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i32, V1, V2, Mask,
9723                                                 Subtarget, DAG))
9724     return Blend;
9725
9726   // Check for being able to broadcast a single element.
9727   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i32, V1,
9728                                                         Mask, Subtarget, DAG))
9729     return Broadcast;
9730
9731   // If the shuffle mask is repeated in each 128-bit lane we can use more
9732   // efficient instructions that mirror the shuffles across the two 128-bit
9733   // lanes.
9734   SmallVector<int, 4> RepeatedMask;
9735   if (is128BitLaneRepeatedShuffleMask(MVT::v8i32, Mask, RepeatedMask)) {
9736     assert(RepeatedMask.size() == 4 && "Unexpected repeated mask size!");
9737     if (isSingleInputShuffleMask(Mask))
9738       return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32, V1,
9739                          getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
9740
9741     // Use dedicated unpack instructions for masks that match their pattern.
9742     if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 4, 12, 5, 13}))
9743       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V1, V2);
9744     if (isShuffleEquivalent(V1, V2, Mask, {2, 10, 3, 11, 6, 14, 7, 15}))
9745       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V1, V2);
9746     if (isShuffleEquivalent(V1, V2, Mask, {8, 0, 9, 1, 12, 4, 13, 5}))
9747       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V2, V1);
9748     if (isShuffleEquivalent(V1, V2, Mask, {10, 2, 11, 3, 14, 6, 15, 7}))
9749       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V2, V1);
9750   }
9751
9752   // Try to use shift instructions.
9753   if (SDValue Shift =
9754           lowerVectorShuffleAsShift(DL, MVT::v8i32, V1, V2, Mask, DAG))
9755     return Shift;
9756
9757   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9758           DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
9759     return Rotate;
9760
9761   // If the shuffle patterns aren't repeated but it is a single input, directly
9762   // generate a cross-lane VPERMD instruction.
9763   if (isSingleInputShuffleMask(Mask)) {
9764     SDValue VPermMask[8];
9765     for (int i = 0; i < 8; ++i)
9766       VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
9767                                  : DAG.getConstant(Mask[i], DL, MVT::i32);
9768     return DAG.getNode(
9769         X86ISD::VPERMV, DL, MVT::v8i32,
9770         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask), V1);
9771   }
9772
9773   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9774   // shuffle.
9775   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9776           DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
9777     return Result;
9778
9779   // Otherwise fall back on generic blend lowering.
9780   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i32, V1, V2,
9781                                                     Mask, DAG);
9782 }
9783
9784 /// \brief Handle lowering of 16-lane 16-bit integer shuffles.
9785 ///
9786 /// This routine is only called when we have AVX2 and thus a reasonable
9787 /// instruction set for v16i16 shuffling..
9788 static SDValue lowerV16I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9789                                         const X86Subtarget *Subtarget,
9790                                         SelectionDAG &DAG) {
9791   SDLoc DL(Op);
9792   assert(V1.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
9793   assert(V2.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
9794   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9795   ArrayRef<int> Mask = SVOp->getMask();
9796   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
9797   assert(Subtarget->hasAVX2() && "We can only lower v16i16 with AVX2!");
9798
9799   // Whenever we can lower this as a zext, that instruction is strictly faster
9800   // than any alternative. It also allows us to fold memory operands into the
9801   // shuffle in many cases.
9802   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v16i16, V1, V2,
9803                                                          Mask, Subtarget, DAG))
9804     return ZExt;
9805
9806   // Check for being able to broadcast a single element.
9807   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i16, V1,
9808                                                         Mask, Subtarget, DAG))
9809     return Broadcast;
9810
9811   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i16, V1, V2, Mask,
9812                                                 Subtarget, DAG))
9813     return Blend;
9814
9815   // Use dedicated unpack instructions for masks that match their pattern.
9816   if (isShuffleEquivalent(V1, V2, Mask,
9817                           {// First 128-bit lane:
9818                            0, 16, 1, 17, 2, 18, 3, 19,
9819                            // Second 128-bit lane:
9820                            8, 24, 9, 25, 10, 26, 11, 27}))
9821     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i16, V1, V2);
9822   if (isShuffleEquivalent(V1, V2, Mask,
9823                           {// First 128-bit lane:
9824                            4, 20, 5, 21, 6, 22, 7, 23,
9825                            // Second 128-bit lane:
9826                            12, 28, 13, 29, 14, 30, 15, 31}))
9827     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i16, V1, V2);
9828
9829   // Try to use shift instructions.
9830   if (SDValue Shift =
9831           lowerVectorShuffleAsShift(DL, MVT::v16i16, V1, V2, Mask, DAG))
9832     return Shift;
9833
9834   // Try to use byte rotation instructions.
9835   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9836           DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
9837     return Rotate;
9838
9839   if (isSingleInputShuffleMask(Mask)) {
9840     // There are no generalized cross-lane shuffle operations available on i16
9841     // element types.
9842     if (is128BitLaneCrossingShuffleMask(MVT::v16i16, Mask))
9843       return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v16i16, V1, V2,
9844                                                      Mask, DAG);
9845
9846     SmallVector<int, 8> RepeatedMask;
9847     if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
9848       // As this is a single-input shuffle, the repeated mask should be
9849       // a strictly valid v8i16 mask that we can pass through to the v8i16
9850       // lowering to handle even the v16 case.
9851       return lowerV8I16GeneralSingleInputVectorShuffle(
9852           DL, MVT::v16i16, V1, RepeatedMask, Subtarget, DAG);
9853     }
9854
9855     SDValue PSHUFBMask[32];
9856     for (int i = 0; i < 16; ++i) {
9857       if (Mask[i] == -1) {
9858         PSHUFBMask[2 * i] = PSHUFBMask[2 * i + 1] = DAG.getUNDEF(MVT::i8);
9859         continue;
9860       }
9861
9862       int M = i < 8 ? Mask[i] : Mask[i] - 8;
9863       assert(M >= 0 && M < 8 && "Invalid single-input mask!");
9864       PSHUFBMask[2 * i] = DAG.getConstant(2 * M, DL, MVT::i8);
9865       PSHUFBMask[2 * i + 1] = DAG.getConstant(2 * M + 1, DL, MVT::i8);
9866     }
9867     return DAG.getNode(
9868         ISD::BITCAST, DL, MVT::v16i16,
9869         DAG.getNode(
9870             X86ISD::PSHUFB, DL, MVT::v32i8,
9871             DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, V1),
9872             DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, PSHUFBMask)));
9873   }
9874
9875   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9876   // shuffle.
9877   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9878           DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
9879     return Result;
9880
9881   // Otherwise fall back on generic lowering.
9882   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v16i16, V1, V2, Mask, DAG);
9883 }
9884
9885 /// \brief Handle lowering of 32-lane 8-bit integer shuffles.
9886 ///
9887 /// This routine is only called when we have AVX2 and thus a reasonable
9888 /// instruction set for v32i8 shuffling..
9889 static SDValue lowerV32I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9890                                        const X86Subtarget *Subtarget,
9891                                        SelectionDAG &DAG) {
9892   SDLoc DL(Op);
9893   assert(V1.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
9894   assert(V2.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
9895   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9896   ArrayRef<int> Mask = SVOp->getMask();
9897   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
9898   assert(Subtarget->hasAVX2() && "We can only lower v32i8 with AVX2!");
9899
9900   // Whenever we can lower this as a zext, that instruction is strictly faster
9901   // than any alternative. It also allows us to fold memory operands into the
9902   // shuffle in many cases.
9903   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v32i8, V1, V2,
9904                                                          Mask, Subtarget, DAG))
9905     return ZExt;
9906
9907   // Check for being able to broadcast a single element.
9908   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v32i8, V1,
9909                                                         Mask, Subtarget, DAG))
9910     return Broadcast;
9911
9912   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v32i8, V1, V2, Mask,
9913                                                 Subtarget, DAG))
9914     return Blend;
9915
9916   // Use dedicated unpack instructions for masks that match their pattern.
9917   // Note that these are repeated 128-bit lane unpacks, not unpacks across all
9918   // 256-bit lanes.
9919   if (isShuffleEquivalent(
9920           V1, V2, Mask,
9921           {// First 128-bit lane:
9922            0, 32, 1, 33, 2, 34, 3, 35, 4, 36, 5, 37, 6, 38, 7, 39,
9923            // Second 128-bit lane:
9924            16, 48, 17, 49, 18, 50, 19, 51, 20, 52, 21, 53, 22, 54, 23, 55}))
9925     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v32i8, V1, V2);
9926   if (isShuffleEquivalent(
9927           V1, V2, Mask,
9928           {// First 128-bit lane:
9929            8, 40, 9, 41, 10, 42, 11, 43, 12, 44, 13, 45, 14, 46, 15, 47,
9930            // Second 128-bit lane:
9931            24, 56, 25, 57, 26, 58, 27, 59, 28, 60, 29, 61, 30, 62, 31, 63}))
9932     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v32i8, V1, V2);
9933
9934   // Try to use shift instructions.
9935   if (SDValue Shift =
9936           lowerVectorShuffleAsShift(DL, MVT::v32i8, V1, V2, Mask, DAG))
9937     return Shift;
9938
9939   // Try to use byte rotation instructions.
9940   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9941           DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
9942     return Rotate;
9943
9944   if (isSingleInputShuffleMask(Mask)) {
9945     // There are no generalized cross-lane shuffle operations available on i8
9946     // element types.
9947     if (is128BitLaneCrossingShuffleMask(MVT::v32i8, Mask))
9948       return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v32i8, V1, V2,
9949                                                      Mask, DAG);
9950
9951     SDValue PSHUFBMask[32];
9952     for (int i = 0; i < 32; ++i)
9953       PSHUFBMask[i] =
9954           Mask[i] < 0
9955               ? DAG.getUNDEF(MVT::i8)
9956               : DAG.getConstant(Mask[i] < 16 ? Mask[i] : Mask[i] - 16, DL,
9957                                 MVT::i8);
9958
9959     return DAG.getNode(
9960         X86ISD::PSHUFB, DL, MVT::v32i8, V1,
9961         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, PSHUFBMask));
9962   }
9963
9964   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9965   // shuffle.
9966   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9967           DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
9968     return Result;
9969
9970   // Otherwise fall back on generic lowering.
9971   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v32i8, V1, V2, Mask, DAG);
9972 }
9973
9974 /// \brief High-level routine to lower various 256-bit x86 vector shuffles.
9975 ///
9976 /// This routine either breaks down the specific type of a 256-bit x86 vector
9977 /// shuffle or splits it into two 128-bit shuffles and fuses the results back
9978 /// together based on the available instructions.
9979 static SDValue lower256BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9980                                         MVT VT, const X86Subtarget *Subtarget,
9981                                         SelectionDAG &DAG) {
9982   SDLoc DL(Op);
9983   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9984   ArrayRef<int> Mask = SVOp->getMask();
9985
9986   // If we have a single input to the zero element, insert that into V1 if we
9987   // can do so cheaply.
9988   int NumElts = VT.getVectorNumElements();
9989   int NumV2Elements = std::count_if(Mask.begin(), Mask.end(), [NumElts](int M) {
9990     return M >= NumElts;
9991   });
9992
9993   if (NumV2Elements == 1 && Mask[0] >= NumElts)
9994     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
9995                               DL, VT, V1, V2, Mask, Subtarget, DAG))
9996       return Insertion;
9997
9998   // There is a really nice hard cut-over between AVX1 and AVX2 that means we can
9999   // check for those subtargets here and avoid much of the subtarget querying in
10000   // the per-vector-type lowering routines. With AVX1 we have essentially *zero*
10001   // ability to manipulate a 256-bit vector with integer types. Since we'll use
10002   // floating point types there eventually, just immediately cast everything to
10003   // a float and operate entirely in that domain.
10004   if (VT.isInteger() && !Subtarget->hasAVX2()) {
10005     int ElementBits = VT.getScalarSizeInBits();
10006     if (ElementBits < 32)
10007       // No floating point type available, decompose into 128-bit vectors.
10008       return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10009
10010     MVT FpVT = MVT::getVectorVT(MVT::getFloatingPointVT(ElementBits),
10011                                 VT.getVectorNumElements());
10012     V1 = DAG.getNode(ISD::BITCAST, DL, FpVT, V1);
10013     V2 = DAG.getNode(ISD::BITCAST, DL, FpVT, V2);
10014     return DAG.getNode(ISD::BITCAST, DL, VT,
10015                        DAG.getVectorShuffle(FpVT, DL, V1, V2, Mask));
10016   }
10017
10018   switch (VT.SimpleTy) {
10019   case MVT::v4f64:
10020     return lowerV4F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10021   case MVT::v4i64:
10022     return lowerV4I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10023   case MVT::v8f32:
10024     return lowerV8F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10025   case MVT::v8i32:
10026     return lowerV8I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10027   case MVT::v16i16:
10028     return lowerV16I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
10029   case MVT::v32i8:
10030     return lowerV32I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
10031
10032   default:
10033     llvm_unreachable("Not a valid 256-bit x86 vector type!");
10034   }
10035 }
10036
10037 /// \brief Handle lowering of 8-lane 64-bit floating point shuffles.
10038 static SDValue lowerV8F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10039                                        const X86Subtarget *Subtarget,
10040                                        SelectionDAG &DAG) {
10041   SDLoc DL(Op);
10042   assert(V1.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
10043   assert(V2.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
10044   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10045   ArrayRef<int> Mask = SVOp->getMask();
10046   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10047
10048   // X86 has dedicated unpack instructions that can handle specific blend
10049   // operations: UNPCKH and UNPCKL.
10050   if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 2, 10, 4, 12, 6, 14}))
10051     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f64, V1, V2);
10052   if (isShuffleEquivalent(V1, V2, Mask, {1, 9, 3, 11, 5, 13, 7, 15}))
10053     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f64, V1, V2);
10054
10055   // FIXME: Implement direct support for this type!
10056   return splitAndLowerVectorShuffle(DL, MVT::v8f64, V1, V2, Mask, DAG);
10057 }
10058
10059 /// \brief Handle lowering of 16-lane 32-bit floating point shuffles.
10060 static SDValue lowerV16F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10061                                        const X86Subtarget *Subtarget,
10062                                        SelectionDAG &DAG) {
10063   SDLoc DL(Op);
10064   assert(V1.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
10065   assert(V2.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
10066   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10067   ArrayRef<int> Mask = SVOp->getMask();
10068   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10069
10070   // Use dedicated unpack instructions for masks that match their pattern.
10071   if (isShuffleEquivalent(V1, V2, Mask,
10072                           {// First 128-bit lane.
10073                            0, 16, 1, 17, 4, 20, 5, 21,
10074                            // Second 128-bit lane.
10075                            8, 24, 9, 25, 12, 28, 13, 29}))
10076     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16f32, V1, V2);
10077   if (isShuffleEquivalent(V1, V2, Mask,
10078                           {// First 128-bit lane.
10079                            2, 18, 3, 19, 6, 22, 7, 23,
10080                            // Second 128-bit lane.
10081                            10, 26, 11, 27, 14, 30, 15, 31}))
10082     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16f32, V1, V2);
10083
10084   // FIXME: Implement direct support for this type!
10085   return splitAndLowerVectorShuffle(DL, MVT::v16f32, V1, V2, Mask, DAG);
10086 }
10087
10088 /// \brief Handle lowering of 8-lane 64-bit integer shuffles.
10089 static SDValue lowerV8I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10090                                        const X86Subtarget *Subtarget,
10091                                        SelectionDAG &DAG) {
10092   SDLoc DL(Op);
10093   assert(V1.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
10094   assert(V2.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
10095   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10096   ArrayRef<int> Mask = SVOp->getMask();
10097   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10098
10099   // X86 has dedicated unpack instructions that can handle specific blend
10100   // operations: UNPCKH and UNPCKL.
10101   if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 2, 10, 4, 12, 6, 14}))
10102     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i64, V1, V2);
10103   if (isShuffleEquivalent(V1, V2, Mask, {1, 9, 3, 11, 5, 13, 7, 15}))
10104     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i64, V1, V2);
10105
10106   // FIXME: Implement direct support for this type!
10107   return splitAndLowerVectorShuffle(DL, MVT::v8i64, V1, V2, Mask, DAG);
10108 }
10109
10110 /// \brief Handle lowering of 16-lane 32-bit integer shuffles.
10111 static SDValue lowerV16I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10112                                        const X86Subtarget *Subtarget,
10113                                        SelectionDAG &DAG) {
10114   SDLoc DL(Op);
10115   assert(V1.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
10116   assert(V2.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
10117   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10118   ArrayRef<int> Mask = SVOp->getMask();
10119   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10120
10121   // Use dedicated unpack instructions for masks that match their pattern.
10122   if (isShuffleEquivalent(V1, V2, Mask,
10123                           {// First 128-bit lane.
10124                            0, 16, 1, 17, 4, 20, 5, 21,
10125                            // Second 128-bit lane.
10126                            8, 24, 9, 25, 12, 28, 13, 29}))
10127     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i32, V1, V2);
10128   if (isShuffleEquivalent(V1, V2, Mask,
10129                           {// First 128-bit lane.
10130                            2, 18, 3, 19, 6, 22, 7, 23,
10131                            // Second 128-bit lane.
10132                            10, 26, 11, 27, 14, 30, 15, 31}))
10133     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i32, V1, V2);
10134
10135   // FIXME: Implement direct support for this type!
10136   return splitAndLowerVectorShuffle(DL, MVT::v16i32, V1, V2, Mask, DAG);
10137 }
10138
10139 /// \brief Handle lowering of 32-lane 16-bit integer shuffles.
10140 static SDValue lowerV32I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10141                                         const X86Subtarget *Subtarget,
10142                                         SelectionDAG &DAG) {
10143   SDLoc DL(Op);
10144   assert(V1.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10145   assert(V2.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10146   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10147   ArrayRef<int> Mask = SVOp->getMask();
10148   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
10149   assert(Subtarget->hasBWI() && "We can only lower v32i16 with AVX-512-BWI!");
10150
10151   // FIXME: Implement direct support for this type!
10152   return splitAndLowerVectorShuffle(DL, MVT::v32i16, V1, V2, Mask, DAG);
10153 }
10154
10155 /// \brief Handle lowering of 64-lane 8-bit integer shuffles.
10156 static SDValue lowerV64I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10157                                        const X86Subtarget *Subtarget,
10158                                        SelectionDAG &DAG) {
10159   SDLoc DL(Op);
10160   assert(V1.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10161   assert(V2.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10162   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10163   ArrayRef<int> Mask = SVOp->getMask();
10164   assert(Mask.size() == 64 && "Unexpected mask size for v64 shuffle!");
10165   assert(Subtarget->hasBWI() && "We can only lower v64i8 with AVX-512-BWI!");
10166
10167   // FIXME: Implement direct support for this type!
10168   return splitAndLowerVectorShuffle(DL, MVT::v64i8, V1, V2, Mask, DAG);
10169 }
10170
10171 /// \brief High-level routine to lower various 512-bit x86 vector shuffles.
10172 ///
10173 /// This routine either breaks down the specific type of a 512-bit x86 vector
10174 /// shuffle or splits it into two 256-bit shuffles and fuses the results back
10175 /// together based on the available instructions.
10176 static SDValue lower512BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10177                                         MVT VT, const X86Subtarget *Subtarget,
10178                                         SelectionDAG &DAG) {
10179   SDLoc DL(Op);
10180   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10181   ArrayRef<int> Mask = SVOp->getMask();
10182   assert(Subtarget->hasAVX512() &&
10183          "Cannot lower 512-bit vectors w/ basic ISA!");
10184
10185   // Check for being able to broadcast a single element.
10186   if (SDValue Broadcast =
10187           lowerVectorShuffleAsBroadcast(DL, VT, V1, Mask, Subtarget, DAG))
10188     return Broadcast;
10189
10190   // Dispatch to each element type for lowering. If we don't have supprot for
10191   // specific element type shuffles at 512 bits, immediately split them and
10192   // lower them. Each lowering routine of a given type is allowed to assume that
10193   // the requisite ISA extensions for that element type are available.
10194   switch (VT.SimpleTy) {
10195   case MVT::v8f64:
10196     return lowerV8F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10197   case MVT::v16f32:
10198     return lowerV16F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10199   case MVT::v8i64:
10200     return lowerV8I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10201   case MVT::v16i32:
10202     return lowerV16I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10203   case MVT::v32i16:
10204     if (Subtarget->hasBWI())
10205       return lowerV32I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
10206     break;
10207   case MVT::v64i8:
10208     if (Subtarget->hasBWI())
10209       return lowerV64I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
10210     break;
10211
10212   default:
10213     llvm_unreachable("Not a valid 512-bit x86 vector type!");
10214   }
10215
10216   // Otherwise fall back on splitting.
10217   return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10218 }
10219
10220 /// \brief Top-level lowering for x86 vector shuffles.
10221 ///
10222 /// This handles decomposition, canonicalization, and lowering of all x86
10223 /// vector shuffles. Most of the specific lowering strategies are encapsulated
10224 /// above in helper routines. The canonicalization attempts to widen shuffles
10225 /// to involve fewer lanes of wider elements, consolidate symmetric patterns
10226 /// s.t. only one of the two inputs needs to be tested, etc.
10227 static SDValue lowerVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
10228                                   SelectionDAG &DAG) {
10229   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10230   ArrayRef<int> Mask = SVOp->getMask();
10231   SDValue V1 = Op.getOperand(0);
10232   SDValue V2 = Op.getOperand(1);
10233   MVT VT = Op.getSimpleValueType();
10234   int NumElements = VT.getVectorNumElements();
10235   SDLoc dl(Op);
10236
10237   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
10238
10239   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
10240   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
10241   if (V1IsUndef && V2IsUndef)
10242     return DAG.getUNDEF(VT);
10243
10244   // When we create a shuffle node we put the UNDEF node to second operand,
10245   // but in some cases the first operand may be transformed to UNDEF.
10246   // In this case we should just commute the node.
10247   if (V1IsUndef)
10248     return DAG.getCommutedVectorShuffle(*SVOp);
10249
10250   // Check for non-undef masks pointing at an undef vector and make the masks
10251   // undef as well. This makes it easier to match the shuffle based solely on
10252   // the mask.
10253   if (V2IsUndef)
10254     for (int M : Mask)
10255       if (M >= NumElements) {
10256         SmallVector<int, 8> NewMask(Mask.begin(), Mask.end());
10257         for (int &M : NewMask)
10258           if (M >= NumElements)
10259             M = -1;
10260         return DAG.getVectorShuffle(VT, dl, V1, V2, NewMask);
10261       }
10262
10263   // We actually see shuffles that are entirely re-arrangements of a set of
10264   // zero inputs. This mostly happens while decomposing complex shuffles into
10265   // simple ones. Directly lower these as a buildvector of zeros.
10266   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
10267   if (Zeroable.all())
10268     return getZeroVector(VT, Subtarget, DAG, dl);
10269
10270   // Try to collapse shuffles into using a vector type with fewer elements but
10271   // wider element types. We cap this to not form integers or floating point
10272   // elements wider than 64 bits, but it might be interesting to form i128
10273   // integers to handle flipping the low and high halves of AVX 256-bit vectors.
10274   SmallVector<int, 16> WidenedMask;
10275   if (VT.getScalarSizeInBits() < 64 &&
10276       canWidenShuffleElements(Mask, WidenedMask)) {
10277     MVT NewEltVT = VT.isFloatingPoint()
10278                        ? MVT::getFloatingPointVT(VT.getScalarSizeInBits() * 2)
10279                        : MVT::getIntegerVT(VT.getScalarSizeInBits() * 2);
10280     MVT NewVT = MVT::getVectorVT(NewEltVT, VT.getVectorNumElements() / 2);
10281     // Make sure that the new vector type is legal. For example, v2f64 isn't
10282     // legal on SSE1.
10283     if (DAG.getTargetLoweringInfo().isTypeLegal(NewVT)) {
10284       V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
10285       V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
10286       return DAG.getNode(ISD::BITCAST, dl, VT,
10287                          DAG.getVectorShuffle(NewVT, dl, V1, V2, WidenedMask));
10288     }
10289   }
10290
10291   int NumV1Elements = 0, NumUndefElements = 0, NumV2Elements = 0;
10292   for (int M : SVOp->getMask())
10293     if (M < 0)
10294       ++NumUndefElements;
10295     else if (M < NumElements)
10296       ++NumV1Elements;
10297     else
10298       ++NumV2Elements;
10299
10300   // Commute the shuffle as needed such that more elements come from V1 than
10301   // V2. This allows us to match the shuffle pattern strictly on how many
10302   // elements come from V1 without handling the symmetric cases.
10303   if (NumV2Elements > NumV1Elements)
10304     return DAG.getCommutedVectorShuffle(*SVOp);
10305
10306   // When the number of V1 and V2 elements are the same, try to minimize the
10307   // number of uses of V2 in the low half of the vector. When that is tied,
10308   // ensure that the sum of indices for V1 is equal to or lower than the sum
10309   // indices for V2. When those are equal, try to ensure that the number of odd
10310   // indices for V1 is lower than the number of odd indices for V2.
10311   if (NumV1Elements == NumV2Elements) {
10312     int LowV1Elements = 0, LowV2Elements = 0;
10313     for (int M : SVOp->getMask().slice(0, NumElements / 2))
10314       if (M >= NumElements)
10315         ++LowV2Elements;
10316       else if (M >= 0)
10317         ++LowV1Elements;
10318     if (LowV2Elements > LowV1Elements) {
10319       return DAG.getCommutedVectorShuffle(*SVOp);
10320     } else if (LowV2Elements == LowV1Elements) {
10321       int SumV1Indices = 0, SumV2Indices = 0;
10322       for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
10323         if (SVOp->getMask()[i] >= NumElements)
10324           SumV2Indices += i;
10325         else if (SVOp->getMask()[i] >= 0)
10326           SumV1Indices += i;
10327       if (SumV2Indices < SumV1Indices) {
10328         return DAG.getCommutedVectorShuffle(*SVOp);
10329       } else if (SumV2Indices == SumV1Indices) {
10330         int NumV1OddIndices = 0, NumV2OddIndices = 0;
10331         for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
10332           if (SVOp->getMask()[i] >= NumElements)
10333             NumV2OddIndices += i % 2;
10334           else if (SVOp->getMask()[i] >= 0)
10335             NumV1OddIndices += i % 2;
10336         if (NumV2OddIndices < NumV1OddIndices)
10337           return DAG.getCommutedVectorShuffle(*SVOp);
10338       }
10339     }
10340   }
10341
10342   // For each vector width, delegate to a specialized lowering routine.
10343   if (VT.getSizeInBits() == 128)
10344     return lower128BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10345
10346   if (VT.getSizeInBits() == 256)
10347     return lower256BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10348
10349   // Force AVX-512 vectors to be scalarized for now.
10350   // FIXME: Implement AVX-512 support!
10351   if (VT.getSizeInBits() == 512)
10352     return lower512BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10353
10354   llvm_unreachable("Unimplemented!");
10355 }
10356
10357 // This function assumes its argument is a BUILD_VECTOR of constants or
10358 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
10359 // true.
10360 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
10361                                     unsigned &MaskValue) {
10362   MaskValue = 0;
10363   unsigned NumElems = BuildVector->getNumOperands();
10364   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
10365   unsigned NumLanes = (NumElems - 1) / 8 + 1;
10366   unsigned NumElemsInLane = NumElems / NumLanes;
10367
10368   // Blend for v16i16 should be symetric for the both lanes.
10369   for (unsigned i = 0; i < NumElemsInLane; ++i) {
10370     SDValue EltCond = BuildVector->getOperand(i);
10371     SDValue SndLaneEltCond =
10372         (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
10373
10374     int Lane1Cond = -1, Lane2Cond = -1;
10375     if (isa<ConstantSDNode>(EltCond))
10376       Lane1Cond = !isZero(EltCond);
10377     if (isa<ConstantSDNode>(SndLaneEltCond))
10378       Lane2Cond = !isZero(SndLaneEltCond);
10379
10380     if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
10381       // Lane1Cond != 0, means we want the first argument.
10382       // Lane1Cond == 0, means we want the second argument.
10383       // The encoding of this argument is 0 for the first argument, 1
10384       // for the second. Therefore, invert the condition.
10385       MaskValue |= !Lane1Cond << i;
10386     else if (Lane1Cond < 0)
10387       MaskValue |= !Lane2Cond << i;
10388     else
10389       return false;
10390   }
10391   return true;
10392 }
10393
10394 /// \brief Try to lower a VSELECT instruction to a vector shuffle.
10395 static SDValue lowerVSELECTtoVectorShuffle(SDValue Op,
10396                                            const X86Subtarget *Subtarget,
10397                                            SelectionDAG &DAG) {
10398   SDValue Cond = Op.getOperand(0);
10399   SDValue LHS = Op.getOperand(1);
10400   SDValue RHS = Op.getOperand(2);
10401   SDLoc dl(Op);
10402   MVT VT = Op.getSimpleValueType();
10403
10404   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
10405     return SDValue();
10406   auto *CondBV = cast<BuildVectorSDNode>(Cond);
10407
10408   // Only non-legal VSELECTs reach this lowering, convert those into generic
10409   // shuffles and re-use the shuffle lowering path for blends.
10410   SmallVector<int, 32> Mask;
10411   for (int i = 0, Size = VT.getVectorNumElements(); i < Size; ++i) {
10412     SDValue CondElt = CondBV->getOperand(i);
10413     Mask.push_back(
10414         isa<ConstantSDNode>(CondElt) ? i + (isZero(CondElt) ? Size : 0) : -1);
10415   }
10416   return DAG.getVectorShuffle(VT, dl, LHS, RHS, Mask);
10417 }
10418
10419 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
10420   // A vselect where all conditions and data are constants can be optimized into
10421   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
10422   if (ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(0).getNode()) &&
10423       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(1).getNode()) &&
10424       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(2).getNode()))
10425     return SDValue();
10426
10427   // Try to lower this to a blend-style vector shuffle. This can handle all
10428   // constant condition cases.
10429   if (SDValue BlendOp = lowerVSELECTtoVectorShuffle(Op, Subtarget, DAG))
10430     return BlendOp;
10431
10432   // Variable blends are only legal from SSE4.1 onward.
10433   if (!Subtarget->hasSSE41())
10434     return SDValue();
10435
10436   // Only some types will be legal on some subtargets. If we can emit a legal
10437   // VSELECT-matching blend, return Op, and but if we need to expand, return
10438   // a null value.
10439   switch (Op.getSimpleValueType().SimpleTy) {
10440   default:
10441     // Most of the vector types have blends past SSE4.1.
10442     return Op;
10443
10444   case MVT::v32i8:
10445     // The byte blends for AVX vectors were introduced only in AVX2.
10446     if (Subtarget->hasAVX2())
10447       return Op;
10448
10449     return SDValue();
10450
10451   case MVT::v8i16:
10452   case MVT::v16i16:
10453     // AVX-512 BWI and VLX features support VSELECT with i16 elements.
10454     if (Subtarget->hasBWI() && Subtarget->hasVLX())
10455       return Op;
10456
10457     // FIXME: We should custom lower this by fixing the condition and using i8
10458     // blends.
10459     return SDValue();
10460   }
10461 }
10462
10463 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
10464   MVT VT = Op.getSimpleValueType();
10465   SDLoc dl(Op);
10466
10467   if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
10468     return SDValue();
10469
10470   if (VT.getSizeInBits() == 8) {
10471     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
10472                                   Op.getOperand(0), Op.getOperand(1));
10473     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
10474                                   DAG.getValueType(VT));
10475     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10476   }
10477
10478   if (VT.getSizeInBits() == 16) {
10479     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10480     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
10481     if (Idx == 0)
10482       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
10483                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10484                                      DAG.getNode(ISD::BITCAST, dl,
10485                                                  MVT::v4i32,
10486                                                  Op.getOperand(0)),
10487                                      Op.getOperand(1)));
10488     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
10489                                   Op.getOperand(0), Op.getOperand(1));
10490     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
10491                                   DAG.getValueType(VT));
10492     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10493   }
10494
10495   if (VT == MVT::f32) {
10496     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
10497     // the result back to FR32 register. It's only worth matching if the
10498     // result has a single use which is a store or a bitcast to i32.  And in
10499     // the case of a store, it's not worth it if the index is a constant 0,
10500     // because a MOVSSmr can be used instead, which is smaller and faster.
10501     if (!Op.hasOneUse())
10502       return SDValue();
10503     SDNode *User = *Op.getNode()->use_begin();
10504     if ((User->getOpcode() != ISD::STORE ||
10505          (isa<ConstantSDNode>(Op.getOperand(1)) &&
10506           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
10507         (User->getOpcode() != ISD::BITCAST ||
10508          User->getValueType(0) != MVT::i32))
10509       return SDValue();
10510     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10511                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
10512                                               Op.getOperand(0)),
10513                                               Op.getOperand(1));
10514     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
10515   }
10516
10517   if (VT == MVT::i32 || VT == MVT::i64) {
10518     // ExtractPS/pextrq works with constant index.
10519     if (isa<ConstantSDNode>(Op.getOperand(1)))
10520       return Op;
10521   }
10522   return SDValue();
10523 }
10524
10525 /// Extract one bit from mask vector, like v16i1 or v8i1.
10526 /// AVX-512 feature.
10527 SDValue
10528 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
10529   SDValue Vec = Op.getOperand(0);
10530   SDLoc dl(Vec);
10531   MVT VecVT = Vec.getSimpleValueType();
10532   SDValue Idx = Op.getOperand(1);
10533   MVT EltVT = Op.getSimpleValueType();
10534
10535   assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
10536   assert((VecVT.getVectorNumElements() <= 16 || Subtarget->hasBWI()) &&
10537          "Unexpected vector type in ExtractBitFromMaskVector");
10538
10539   // variable index can't be handled in mask registers,
10540   // extend vector to VR512
10541   if (!isa<ConstantSDNode>(Idx)) {
10542     MVT ExtVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
10543     SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
10544     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
10545                               ExtVT.getVectorElementType(), Ext, Idx);
10546     return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
10547   }
10548
10549   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10550   const TargetRegisterClass* rc = getRegClassFor(VecVT);
10551   if (!Subtarget->hasDQI() && (VecVT.getVectorNumElements() <= 8))
10552     rc = getRegClassFor(MVT::v16i1);
10553   unsigned MaxSift = rc->getSize()*8 - 1;
10554   Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
10555                     DAG.getConstant(MaxSift - IdxVal, dl, MVT::i8));
10556   Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
10557                     DAG.getConstant(MaxSift, dl, MVT::i8));
10558   return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
10559                        DAG.getIntPtrConstant(0, dl));
10560 }
10561
10562 SDValue
10563 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
10564                                            SelectionDAG &DAG) const {
10565   SDLoc dl(Op);
10566   SDValue Vec = Op.getOperand(0);
10567   MVT VecVT = Vec.getSimpleValueType();
10568   SDValue Idx = Op.getOperand(1);
10569
10570   if (Op.getSimpleValueType() == MVT::i1)
10571     return ExtractBitFromMaskVector(Op, DAG);
10572
10573   if (!isa<ConstantSDNode>(Idx)) {
10574     if (VecVT.is512BitVector() ||
10575         (VecVT.is256BitVector() && Subtarget->hasInt256() &&
10576          VecVT.getVectorElementType().getSizeInBits() == 32)) {
10577
10578       MVT MaskEltVT =
10579         MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
10580       MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
10581                                     MaskEltVT.getSizeInBits());
10582
10583       Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
10584       SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
10585                                 getZeroVector(MaskVT, Subtarget, DAG, dl),
10586                                 Idx, DAG.getConstant(0, dl, getPointerTy()));
10587       SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
10588       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(),
10589                         Perm, DAG.getConstant(0, dl, getPointerTy()));
10590     }
10591     return SDValue();
10592   }
10593
10594   // If this is a 256-bit vector result, first extract the 128-bit vector and
10595   // then extract the element from the 128-bit vector.
10596   if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
10597
10598     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10599     // Get the 128-bit vector.
10600     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
10601     MVT EltVT = VecVT.getVectorElementType();
10602
10603     unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
10604
10605     //if (IdxVal >= NumElems/2)
10606     //  IdxVal -= NumElems/2;
10607     IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
10608     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
10609                        DAG.getConstant(IdxVal, dl, MVT::i32));
10610   }
10611
10612   assert(VecVT.is128BitVector() && "Unexpected vector length");
10613
10614   if (Subtarget->hasSSE41()) {
10615     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
10616     if (Res.getNode())
10617       return Res;
10618   }
10619
10620   MVT VT = Op.getSimpleValueType();
10621   // TODO: handle v16i8.
10622   if (VT.getSizeInBits() == 16) {
10623     SDValue Vec = Op.getOperand(0);
10624     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10625     if (Idx == 0)
10626       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
10627                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10628                                      DAG.getNode(ISD::BITCAST, dl,
10629                                                  MVT::v4i32, Vec),
10630                                      Op.getOperand(1)));
10631     // Transform it so it match pextrw which produces a 32-bit result.
10632     MVT EltVT = MVT::i32;
10633     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
10634                                   Op.getOperand(0), Op.getOperand(1));
10635     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
10636                                   DAG.getValueType(VT));
10637     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10638   }
10639
10640   if (VT.getSizeInBits() == 32) {
10641     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10642     if (Idx == 0)
10643       return Op;
10644
10645     // SHUFPS the element to the lowest double word, then movss.
10646     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
10647     MVT VVT = Op.getOperand(0).getSimpleValueType();
10648     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
10649                                        DAG.getUNDEF(VVT), Mask);
10650     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
10651                        DAG.getIntPtrConstant(0, dl));
10652   }
10653
10654   if (VT.getSizeInBits() == 64) {
10655     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
10656     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
10657     //        to match extract_elt for f64.
10658     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10659     if (Idx == 0)
10660       return Op;
10661
10662     // UNPCKHPD the element to the lowest double word, then movsd.
10663     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
10664     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
10665     int Mask[2] = { 1, -1 };
10666     MVT VVT = Op.getOperand(0).getSimpleValueType();
10667     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
10668                                        DAG.getUNDEF(VVT), Mask);
10669     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
10670                        DAG.getIntPtrConstant(0, dl));
10671   }
10672
10673   return SDValue();
10674 }
10675
10676 /// Insert one bit to mask vector, like v16i1 or v8i1.
10677 /// AVX-512 feature.
10678 SDValue
10679 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
10680   SDLoc dl(Op);
10681   SDValue Vec = Op.getOperand(0);
10682   SDValue Elt = Op.getOperand(1);
10683   SDValue Idx = Op.getOperand(2);
10684   MVT VecVT = Vec.getSimpleValueType();
10685
10686   if (!isa<ConstantSDNode>(Idx)) {
10687     // Non constant index. Extend source and destination,
10688     // insert element and then truncate the result.
10689     MVT ExtVecVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
10690     MVT ExtEltVT = (VecVT == MVT::v8i1 ?  MVT::i64 : MVT::i32);
10691     SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT,
10692       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
10693       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
10694     return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
10695   }
10696
10697   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10698   SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
10699   if (IdxVal)
10700     EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
10701                            DAG.getConstant(IdxVal, dl, MVT::i8));
10702   if (Vec.getOpcode() == ISD::UNDEF)
10703     return EltInVec;
10704   return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
10705 }
10706
10707 SDValue X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
10708                                                   SelectionDAG &DAG) const {
10709   MVT VT = Op.getSimpleValueType();
10710   MVT EltVT = VT.getVectorElementType();
10711
10712   if (EltVT == MVT::i1)
10713     return InsertBitToMaskVector(Op, DAG);
10714
10715   SDLoc dl(Op);
10716   SDValue N0 = Op.getOperand(0);
10717   SDValue N1 = Op.getOperand(1);
10718   SDValue N2 = Op.getOperand(2);
10719   if (!isa<ConstantSDNode>(N2))
10720     return SDValue();
10721   auto *N2C = cast<ConstantSDNode>(N2);
10722   unsigned IdxVal = N2C->getZExtValue();
10723
10724   // If the vector is wider than 128 bits, extract the 128-bit subvector, insert
10725   // into that, and then insert the subvector back into the result.
10726   if (VT.is256BitVector() || VT.is512BitVector()) {
10727     // With a 256-bit vector, we can insert into the zero element efficiently
10728     // using a blend if we have AVX or AVX2 and the right data type.
10729     if (VT.is256BitVector() && IdxVal == 0) {
10730       // TODO: It is worthwhile to cast integer to floating point and back
10731       // and incur a domain crossing penalty if that's what we'll end up
10732       // doing anyway after extracting to a 128-bit vector.
10733       if ((Subtarget->hasAVX() && (EltVT == MVT::f64 || EltVT == MVT::f32)) ||
10734           (Subtarget->hasAVX2() && EltVT == MVT::i32)) {
10735         SDValue N1Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, N1);
10736         N2 = DAG.getIntPtrConstant(1, dl);
10737         return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1Vec, N2);
10738       }
10739     }
10740
10741     // Get the desired 128-bit vector chunk.
10742     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
10743
10744     // Insert the element into the desired chunk.
10745     unsigned NumEltsIn128 = 128 / EltVT.getSizeInBits();
10746     unsigned IdxIn128 = IdxVal - (IdxVal / NumEltsIn128) * NumEltsIn128;
10747
10748     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
10749                     DAG.getConstant(IdxIn128, dl, MVT::i32));
10750
10751     // Insert the changed part back into the bigger vector
10752     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
10753   }
10754   assert(VT.is128BitVector() && "Only 128-bit vector types should be left!");
10755
10756   if (Subtarget->hasSSE41()) {
10757     if (EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) {
10758       unsigned Opc;
10759       if (VT == MVT::v8i16) {
10760         Opc = X86ISD::PINSRW;
10761       } else {
10762         assert(VT == MVT::v16i8);
10763         Opc = X86ISD::PINSRB;
10764       }
10765
10766       // Transform it so it match pinsr{b,w} which expects a GR32 as its second
10767       // argument.
10768       if (N1.getValueType() != MVT::i32)
10769         N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
10770       if (N2.getValueType() != MVT::i32)
10771         N2 = DAG.getIntPtrConstant(IdxVal, dl);
10772       return DAG.getNode(Opc, dl, VT, N0, N1, N2);
10773     }
10774
10775     if (EltVT == MVT::f32) {
10776       // Bits [7:6] of the constant are the source select. This will always be
10777       //   zero here. The DAG Combiner may combine an extract_elt index into
10778       //   these bits. For example (insert (extract, 3), 2) could be matched by
10779       //   putting the '3' into bits [7:6] of X86ISD::INSERTPS.
10780       // Bits [5:4] of the constant are the destination select. This is the
10781       //   value of the incoming immediate.
10782       // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
10783       //   combine either bitwise AND or insert of float 0.0 to set these bits.
10784
10785       const Function *F = DAG.getMachineFunction().getFunction();
10786       bool MinSize = F->hasFnAttribute(Attribute::MinSize);
10787       if (IdxVal == 0 && (!MinSize || !MayFoldLoad(N1))) {
10788         // If this is an insertion of 32-bits into the low 32-bits of
10789         // a vector, we prefer to generate a blend with immediate rather
10790         // than an insertps. Blends are simpler operations in hardware and so
10791         // will always have equal or better performance than insertps.
10792         // But if optimizing for size and there's a load folding opportunity,
10793         // generate insertps because blendps does not have a 32-bit memory
10794         // operand form.
10795         N2 = DAG.getIntPtrConstant(1, dl);
10796         N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
10797         return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1, N2);
10798       }
10799       N2 = DAG.getIntPtrConstant(IdxVal << 4, dl);
10800       // Create this as a scalar to vector..
10801       N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
10802       return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
10803     }
10804
10805     if (EltVT == MVT::i32 || EltVT == MVT::i64) {
10806       // PINSR* works with constant index.
10807       return Op;
10808     }
10809   }
10810
10811   if (EltVT == MVT::i8)
10812     return SDValue();
10813
10814   if (EltVT.getSizeInBits() == 16) {
10815     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
10816     // as its second argument.
10817     if (N1.getValueType() != MVT::i32)
10818       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
10819     if (N2.getValueType() != MVT::i32)
10820       N2 = DAG.getIntPtrConstant(IdxVal, dl);
10821     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
10822   }
10823   return SDValue();
10824 }
10825
10826 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
10827   SDLoc dl(Op);
10828   MVT OpVT = Op.getSimpleValueType();
10829
10830   // If this is a 256-bit vector result, first insert into a 128-bit
10831   // vector and then insert into the 256-bit vector.
10832   if (!OpVT.is128BitVector()) {
10833     // Insert into a 128-bit vector.
10834     unsigned SizeFactor = OpVT.getSizeInBits()/128;
10835     MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
10836                                  OpVT.getVectorNumElements() / SizeFactor);
10837
10838     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
10839
10840     // Insert the 128-bit vector.
10841     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
10842   }
10843
10844   if (OpVT == MVT::v1i64 &&
10845       Op.getOperand(0).getValueType() == MVT::i64)
10846     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
10847
10848   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
10849   assert(OpVT.is128BitVector() && "Expected an SSE type!");
10850   return DAG.getNode(ISD::BITCAST, dl, OpVT,
10851                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
10852 }
10853
10854 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
10855 // a simple subregister reference or explicit instructions to grab
10856 // upper bits of a vector.
10857 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
10858                                       SelectionDAG &DAG) {
10859   SDLoc dl(Op);
10860   SDValue In =  Op.getOperand(0);
10861   SDValue Idx = Op.getOperand(1);
10862   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10863   MVT ResVT   = Op.getSimpleValueType();
10864   MVT InVT    = In.getSimpleValueType();
10865
10866   if (Subtarget->hasFp256()) {
10867     if (ResVT.is128BitVector() &&
10868         (InVT.is256BitVector() || InVT.is512BitVector()) &&
10869         isa<ConstantSDNode>(Idx)) {
10870       return Extract128BitVector(In, IdxVal, DAG, dl);
10871     }
10872     if (ResVT.is256BitVector() && InVT.is512BitVector() &&
10873         isa<ConstantSDNode>(Idx)) {
10874       return Extract256BitVector(In, IdxVal, DAG, dl);
10875     }
10876   }
10877   return SDValue();
10878 }
10879
10880 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
10881 // simple superregister reference or explicit instructions to insert
10882 // the upper bits of a vector.
10883 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
10884                                      SelectionDAG &DAG) {
10885   if (!Subtarget->hasAVX())
10886     return SDValue();
10887
10888   SDLoc dl(Op);
10889   SDValue Vec = Op.getOperand(0);
10890   SDValue SubVec = Op.getOperand(1);
10891   SDValue Idx = Op.getOperand(2);
10892
10893   if (!isa<ConstantSDNode>(Idx))
10894     return SDValue();
10895
10896   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10897   MVT OpVT = Op.getSimpleValueType();
10898   MVT SubVecVT = SubVec.getSimpleValueType();
10899
10900   // Fold two 16-byte subvector loads into one 32-byte load:
10901   // (insert_subvector (insert_subvector undef, (load addr), 0),
10902   //                   (load addr + 16), Elts/2)
10903   // --> load32 addr
10904   if ((IdxVal == OpVT.getVectorNumElements() / 2) &&
10905       Vec.getOpcode() == ISD::INSERT_SUBVECTOR &&
10906       OpVT.is256BitVector() && SubVecVT.is128BitVector() &&
10907       !Subtarget->isUnalignedMem32Slow()) {
10908     SDValue SubVec2 = Vec.getOperand(1);
10909     if (auto *Idx2 = dyn_cast<ConstantSDNode>(Vec.getOperand(2))) {
10910       if (Idx2->getZExtValue() == 0) {
10911         SDValue Ops[] = { SubVec2, SubVec };
10912         SDValue LD = EltsFromConsecutiveLoads(OpVT, Ops, dl, DAG, false);
10913         if (LD.getNode())
10914           return LD;
10915       }
10916     }
10917   }
10918
10919   if ((OpVT.is256BitVector() || OpVT.is512BitVector()) &&
10920       SubVecVT.is128BitVector())
10921     return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
10922
10923   if (OpVT.is512BitVector() && SubVecVT.is256BitVector())
10924     return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
10925
10926   if (OpVT.getVectorElementType() == MVT::i1) {
10927     if (IdxVal == 0  && Vec.getOpcode() == ISD::UNDEF) // the operation is legal
10928       return Op;
10929     SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
10930     SDValue Undef = DAG.getUNDEF(OpVT);
10931     unsigned NumElems = OpVT.getVectorNumElements();
10932     SDValue ShiftBits = DAG.getConstant(NumElems/2, dl, MVT::i8);
10933
10934     if (IdxVal == OpVT.getVectorNumElements() / 2) {
10935       // Zero upper bits of the Vec
10936       Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
10937       Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
10938
10939       SDValue Vec2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef,
10940                                  SubVec, ZeroIdx);
10941       Vec2 = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec2, ShiftBits);
10942       return DAG.getNode(ISD::OR, dl, OpVT, Vec, Vec2);
10943     }
10944     if (IdxVal == 0) {
10945       SDValue Vec2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef,
10946                                  SubVec, ZeroIdx);
10947       // Zero upper bits of the Vec2
10948       Vec2 = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec2, ShiftBits);
10949       Vec2 = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec2, ShiftBits);
10950       // Zero lower bits of the Vec
10951       Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
10952       Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
10953       // Merge them together
10954       return DAG.getNode(ISD::OR, dl, OpVT, Vec, Vec2);
10955     }
10956   }
10957   return SDValue();
10958 }
10959
10960 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
10961 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
10962 // one of the above mentioned nodes. It has to be wrapped because otherwise
10963 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
10964 // be used to form addressing mode. These wrapped nodes will be selected
10965 // into MOV32ri.
10966 SDValue
10967 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
10968   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
10969
10970   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10971   // global base reg.
10972   unsigned char OpFlag = 0;
10973   unsigned WrapperKind = X86ISD::Wrapper;
10974   CodeModel::Model M = DAG.getTarget().getCodeModel();
10975
10976   if (Subtarget->isPICStyleRIPRel() &&
10977       (M == CodeModel::Small || M == CodeModel::Kernel))
10978     WrapperKind = X86ISD::WrapperRIP;
10979   else if (Subtarget->isPICStyleGOT())
10980     OpFlag = X86II::MO_GOTOFF;
10981   else if (Subtarget->isPICStyleStubPIC())
10982     OpFlag = X86II::MO_PIC_BASE_OFFSET;
10983
10984   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
10985                                              CP->getAlignment(),
10986                                              CP->getOffset(), OpFlag);
10987   SDLoc DL(CP);
10988   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10989   // With PIC, the address is actually $g + Offset.
10990   if (OpFlag) {
10991     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10992                          DAG.getNode(X86ISD::GlobalBaseReg,
10993                                      SDLoc(), getPointerTy()),
10994                          Result);
10995   }
10996
10997   return Result;
10998 }
10999
11000 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
11001   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
11002
11003   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11004   // global base reg.
11005   unsigned char OpFlag = 0;
11006   unsigned WrapperKind = X86ISD::Wrapper;
11007   CodeModel::Model M = DAG.getTarget().getCodeModel();
11008
11009   if (Subtarget->isPICStyleRIPRel() &&
11010       (M == CodeModel::Small || M == CodeModel::Kernel))
11011     WrapperKind = X86ISD::WrapperRIP;
11012   else if (Subtarget->isPICStyleGOT())
11013     OpFlag = X86II::MO_GOTOFF;
11014   else if (Subtarget->isPICStyleStubPIC())
11015     OpFlag = X86II::MO_PIC_BASE_OFFSET;
11016
11017   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
11018                                           OpFlag);
11019   SDLoc DL(JT);
11020   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
11021
11022   // With PIC, the address is actually $g + Offset.
11023   if (OpFlag)
11024     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11025                          DAG.getNode(X86ISD::GlobalBaseReg,
11026                                      SDLoc(), getPointerTy()),
11027                          Result);
11028
11029   return Result;
11030 }
11031
11032 SDValue
11033 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
11034   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
11035
11036   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11037   // global base reg.
11038   unsigned char OpFlag = 0;
11039   unsigned WrapperKind = X86ISD::Wrapper;
11040   CodeModel::Model M = DAG.getTarget().getCodeModel();
11041
11042   if (Subtarget->isPICStyleRIPRel() &&
11043       (M == CodeModel::Small || M == CodeModel::Kernel)) {
11044     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
11045       OpFlag = X86II::MO_GOTPCREL;
11046     WrapperKind = X86ISD::WrapperRIP;
11047   } else if (Subtarget->isPICStyleGOT()) {
11048     OpFlag = X86II::MO_GOT;
11049   } else if (Subtarget->isPICStyleStubPIC()) {
11050     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
11051   } else if (Subtarget->isPICStyleStubNoDynamic()) {
11052     OpFlag = X86II::MO_DARWIN_NONLAZY;
11053   }
11054
11055   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
11056
11057   SDLoc DL(Op);
11058   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
11059
11060   // With PIC, the address is actually $g + Offset.
11061   if (DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
11062       !Subtarget->is64Bit()) {
11063     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11064                          DAG.getNode(X86ISD::GlobalBaseReg,
11065                                      SDLoc(), getPointerTy()),
11066                          Result);
11067   }
11068
11069   // For symbols that require a load from a stub to get the address, emit the
11070   // load.
11071   if (isGlobalStubReference(OpFlag))
11072     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
11073                          MachinePointerInfo::getGOT(), false, false, false, 0);
11074
11075   return Result;
11076 }
11077
11078 SDValue
11079 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
11080   // Create the TargetBlockAddressAddress node.
11081   unsigned char OpFlags =
11082     Subtarget->ClassifyBlockAddressReference();
11083   CodeModel::Model M = DAG.getTarget().getCodeModel();
11084   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
11085   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
11086   SDLoc dl(Op);
11087   SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
11088                                              OpFlags);
11089
11090   if (Subtarget->isPICStyleRIPRel() &&
11091       (M == CodeModel::Small || M == CodeModel::Kernel))
11092     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
11093   else
11094     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
11095
11096   // With PIC, the address is actually $g + Offset.
11097   if (isGlobalRelativeToPICBase(OpFlags)) {
11098     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
11099                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
11100                          Result);
11101   }
11102
11103   return Result;
11104 }
11105
11106 SDValue
11107 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
11108                                       int64_t Offset, SelectionDAG &DAG) const {
11109   // Create the TargetGlobalAddress node, folding in the constant
11110   // offset if it is legal.
11111   unsigned char OpFlags =
11112       Subtarget->ClassifyGlobalReference(GV, DAG.getTarget());
11113   CodeModel::Model M = DAG.getTarget().getCodeModel();
11114   SDValue Result;
11115   if (OpFlags == X86II::MO_NO_FLAG &&
11116       X86::isOffsetSuitableForCodeModel(Offset, M)) {
11117     // A direct static reference to a global.
11118     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
11119     Offset = 0;
11120   } else {
11121     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
11122   }
11123
11124   if (Subtarget->isPICStyleRIPRel() &&
11125       (M == CodeModel::Small || M == CodeModel::Kernel))
11126     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
11127   else
11128     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
11129
11130   // With PIC, the address is actually $g + Offset.
11131   if (isGlobalRelativeToPICBase(OpFlags)) {
11132     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
11133                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
11134                          Result);
11135   }
11136
11137   // For globals that require a load from a stub to get the address, emit the
11138   // load.
11139   if (isGlobalStubReference(OpFlags))
11140     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
11141                          MachinePointerInfo::getGOT(), false, false, false, 0);
11142
11143   // If there was a non-zero offset that we didn't fold, create an explicit
11144   // addition for it.
11145   if (Offset != 0)
11146     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
11147                          DAG.getConstant(Offset, dl, getPointerTy()));
11148
11149   return Result;
11150 }
11151
11152 SDValue
11153 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
11154   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
11155   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
11156   return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
11157 }
11158
11159 static SDValue
11160 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
11161            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
11162            unsigned char OperandFlags, bool LocalDynamic = false) {
11163   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11164   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11165   SDLoc dl(GA);
11166   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11167                                            GA->getValueType(0),
11168                                            GA->getOffset(),
11169                                            OperandFlags);
11170
11171   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
11172                                            : X86ISD::TLSADDR;
11173
11174   if (InFlag) {
11175     SDValue Ops[] = { Chain,  TGA, *InFlag };
11176     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11177   } else {
11178     SDValue Ops[]  = { Chain, TGA };
11179     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11180   }
11181
11182   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
11183   MFI->setAdjustsStack(true);
11184   MFI->setHasCalls(true);
11185
11186   SDValue Flag = Chain.getValue(1);
11187   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
11188 }
11189
11190 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
11191 static SDValue
11192 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11193                                 const EVT PtrVT) {
11194   SDValue InFlag;
11195   SDLoc dl(GA);  // ? function entry point might be better
11196   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
11197                                    DAG.getNode(X86ISD::GlobalBaseReg,
11198                                                SDLoc(), PtrVT), InFlag);
11199   InFlag = Chain.getValue(1);
11200
11201   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
11202 }
11203
11204 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
11205 static SDValue
11206 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11207                                 const EVT PtrVT) {
11208   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
11209                     X86::RAX, X86II::MO_TLSGD);
11210 }
11211
11212 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
11213                                            SelectionDAG &DAG,
11214                                            const EVT PtrVT,
11215                                            bool is64Bit) {
11216   SDLoc dl(GA);
11217
11218   // Get the start address of the TLS block for this module.
11219   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
11220       .getInfo<X86MachineFunctionInfo>();
11221   MFI->incNumLocalDynamicTLSAccesses();
11222
11223   SDValue Base;
11224   if (is64Bit) {
11225     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
11226                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
11227   } else {
11228     SDValue InFlag;
11229     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
11230         DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
11231     InFlag = Chain.getValue(1);
11232     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
11233                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
11234   }
11235
11236   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
11237   // of Base.
11238
11239   // Build x@dtpoff.
11240   unsigned char OperandFlags = X86II::MO_DTPOFF;
11241   unsigned WrapperKind = X86ISD::Wrapper;
11242   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11243                                            GA->getValueType(0),
11244                                            GA->getOffset(), OperandFlags);
11245   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
11246
11247   // Add x@dtpoff with the base.
11248   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
11249 }
11250
11251 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
11252 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11253                                    const EVT PtrVT, TLSModel::Model model,
11254                                    bool is64Bit, bool isPIC) {
11255   SDLoc dl(GA);
11256
11257   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
11258   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
11259                                                          is64Bit ? 257 : 256));
11260
11261   SDValue ThreadPointer =
11262       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0, dl),
11263                   MachinePointerInfo(Ptr), false, false, false, 0);
11264
11265   unsigned char OperandFlags = 0;
11266   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
11267   // initialexec.
11268   unsigned WrapperKind = X86ISD::Wrapper;
11269   if (model == TLSModel::LocalExec) {
11270     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
11271   } else if (model == TLSModel::InitialExec) {
11272     if (is64Bit) {
11273       OperandFlags = X86II::MO_GOTTPOFF;
11274       WrapperKind = X86ISD::WrapperRIP;
11275     } else {
11276       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
11277     }
11278   } else {
11279     llvm_unreachable("Unexpected model");
11280   }
11281
11282   // emit "addl x@ntpoff,%eax" (local exec)
11283   // or "addl x@indntpoff,%eax" (initial exec)
11284   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
11285   SDValue TGA =
11286       DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
11287                                  GA->getOffset(), OperandFlags);
11288   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
11289
11290   if (model == TLSModel::InitialExec) {
11291     if (isPIC && !is64Bit) {
11292       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
11293                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
11294                            Offset);
11295     }
11296
11297     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
11298                          MachinePointerInfo::getGOT(), false, false, false, 0);
11299   }
11300
11301   // The address of the thread local variable is the add of the thread
11302   // pointer with the offset of the variable.
11303   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
11304 }
11305
11306 SDValue
11307 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
11308
11309   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
11310   const GlobalValue *GV = GA->getGlobal();
11311
11312   if (Subtarget->isTargetELF()) {
11313     TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
11314     switch (model) {
11315       case TLSModel::GeneralDynamic:
11316         if (Subtarget->is64Bit())
11317           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
11318         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
11319       case TLSModel::LocalDynamic:
11320         return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
11321                                            Subtarget->is64Bit());
11322       case TLSModel::InitialExec:
11323       case TLSModel::LocalExec:
11324         return LowerToTLSExecModel(
11325             GA, DAG, getPointerTy(), model, Subtarget->is64Bit(),
11326             DAG.getTarget().getRelocationModel() == Reloc::PIC_);
11327     }
11328     llvm_unreachable("Unknown TLS model.");
11329   }
11330
11331   if (Subtarget->isTargetDarwin()) {
11332     // Darwin only has one model of TLS.  Lower to that.
11333     unsigned char OpFlag = 0;
11334     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
11335                            X86ISD::WrapperRIP : X86ISD::Wrapper;
11336
11337     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11338     // global base reg.
11339     bool PIC32 = (DAG.getTarget().getRelocationModel() == Reloc::PIC_) &&
11340                  !Subtarget->is64Bit();
11341     if (PIC32)
11342       OpFlag = X86II::MO_TLVP_PIC_BASE;
11343     else
11344       OpFlag = X86II::MO_TLVP;
11345     SDLoc DL(Op);
11346     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
11347                                                 GA->getValueType(0),
11348                                                 GA->getOffset(), OpFlag);
11349     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
11350
11351     // With PIC32, the address is actually $g + Offset.
11352     if (PIC32)
11353       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11354                            DAG.getNode(X86ISD::GlobalBaseReg,
11355                                        SDLoc(), getPointerTy()),
11356                            Offset);
11357
11358     // Lowering the machine isd will make sure everything is in the right
11359     // location.
11360     SDValue Chain = DAG.getEntryNode();
11361     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11362     SDValue Args[] = { Chain, Offset };
11363     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
11364
11365     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
11366     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11367     MFI->setAdjustsStack(true);
11368
11369     // And our return value (tls address) is in the standard call return value
11370     // location.
11371     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
11372     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
11373                               Chain.getValue(1));
11374   }
11375
11376   if (Subtarget->isTargetKnownWindowsMSVC() ||
11377       Subtarget->isTargetWindowsGNU()) {
11378     // Just use the implicit TLS architecture
11379     // Need to generate someting similar to:
11380     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
11381     //                                  ; from TEB
11382     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
11383     //   mov     rcx, qword [rdx+rcx*8]
11384     //   mov     eax, .tls$:tlsvar
11385     //   [rax+rcx] contains the address
11386     // Windows 64bit: gs:0x58
11387     // Windows 32bit: fs:__tls_array
11388
11389     SDLoc dl(GA);
11390     SDValue Chain = DAG.getEntryNode();
11391
11392     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
11393     // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
11394     // use its literal value of 0x2C.
11395     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
11396                                         ? Type::getInt8PtrTy(*DAG.getContext(),
11397                                                              256)
11398                                         : Type::getInt32PtrTy(*DAG.getContext(),
11399                                                               257));
11400
11401     SDValue TlsArray =
11402         Subtarget->is64Bit()
11403             ? DAG.getIntPtrConstant(0x58, dl)
11404             : (Subtarget->isTargetWindowsGNU()
11405                    ? DAG.getIntPtrConstant(0x2C, dl)
11406                    : DAG.getExternalSymbol("_tls_array", getPointerTy()));
11407
11408     SDValue ThreadPointer =
11409         DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
11410                     MachinePointerInfo(Ptr), false, false, false, 0);
11411
11412     SDValue res;
11413     if (GV->getThreadLocalMode() == GlobalVariable::LocalExecTLSModel) {
11414       res = ThreadPointer;
11415     } else {
11416       // Load the _tls_index variable
11417       SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
11418       if (Subtarget->is64Bit())
11419         IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain, IDX,
11420                              MachinePointerInfo(), MVT::i32, false, false,
11421                              false, 0);
11422       else
11423         IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
11424                           false, false, false, 0);
11425
11426       SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()), dl,
11427                                       getPointerTy());
11428       IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
11429
11430       res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
11431     }
11432
11433     res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
11434                       false, false, false, 0);
11435
11436     // Get the offset of start of .tls section
11437     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11438                                              GA->getValueType(0),
11439                                              GA->getOffset(), X86II::MO_SECREL);
11440     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
11441
11442     // The address of the thread local variable is the add of the thread
11443     // pointer with the offset of the variable.
11444     return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
11445   }
11446
11447   llvm_unreachable("TLS not implemented for this target.");
11448 }
11449
11450 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
11451 /// and take a 2 x i32 value to shift plus a shift amount.
11452 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
11453   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
11454   MVT VT = Op.getSimpleValueType();
11455   unsigned VTBits = VT.getSizeInBits();
11456   SDLoc dl(Op);
11457   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
11458   SDValue ShOpLo = Op.getOperand(0);
11459   SDValue ShOpHi = Op.getOperand(1);
11460   SDValue ShAmt  = Op.getOperand(2);
11461   // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
11462   // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
11463   // during isel.
11464   SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
11465                                   DAG.getConstant(VTBits - 1, dl, MVT::i8));
11466   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
11467                                      DAG.getConstant(VTBits - 1, dl, MVT::i8))
11468                        : DAG.getConstant(0, dl, VT);
11469
11470   SDValue Tmp2, Tmp3;
11471   if (Op.getOpcode() == ISD::SHL_PARTS) {
11472     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
11473     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
11474   } else {
11475     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
11476     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
11477   }
11478
11479   // If the shift amount is larger or equal than the width of a part we can't
11480   // rely on the results of shld/shrd. Insert a test and select the appropriate
11481   // values for large shift amounts.
11482   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
11483                                 DAG.getConstant(VTBits, dl, MVT::i8));
11484   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11485                              AndNode, DAG.getConstant(0, dl, MVT::i8));
11486
11487   SDValue Hi, Lo;
11488   SDValue CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
11489   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
11490   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
11491
11492   if (Op.getOpcode() == ISD::SHL_PARTS) {
11493     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
11494     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
11495   } else {
11496     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
11497     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
11498   }
11499
11500   SDValue Ops[2] = { Lo, Hi };
11501   return DAG.getMergeValues(Ops, dl);
11502 }
11503
11504 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
11505                                            SelectionDAG &DAG) const {
11506   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
11507   SDLoc dl(Op);
11508
11509   if (SrcVT.isVector()) {
11510     if (SrcVT.getVectorElementType() == MVT::i1) {
11511       MVT IntegerVT = MVT::getVectorVT(MVT::i32, SrcVT.getVectorNumElements());
11512       return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
11513                          DAG.getNode(ISD::SIGN_EXTEND, dl, IntegerVT,
11514                                      Op.getOperand(0)));
11515     }
11516     return SDValue();
11517   }
11518
11519   assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
11520          "Unknown SINT_TO_FP to lower!");
11521
11522   // These are really Legal; return the operand so the caller accepts it as
11523   // Legal.
11524   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
11525     return Op;
11526   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
11527       Subtarget->is64Bit()) {
11528     return Op;
11529   }
11530
11531   unsigned Size = SrcVT.getSizeInBits()/8;
11532   MachineFunction &MF = DAG.getMachineFunction();
11533   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
11534   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11535   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11536                                StackSlot,
11537                                MachinePointerInfo::getFixedStack(SSFI),
11538                                false, false, 0);
11539   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
11540 }
11541
11542 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
11543                                      SDValue StackSlot,
11544                                      SelectionDAG &DAG) const {
11545   // Build the FILD
11546   SDLoc DL(Op);
11547   SDVTList Tys;
11548   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
11549   if (useSSE)
11550     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
11551   else
11552     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
11553
11554   unsigned ByteSize = SrcVT.getSizeInBits()/8;
11555
11556   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
11557   MachineMemOperand *MMO;
11558   if (FI) {
11559     int SSFI = FI->getIndex();
11560     MMO =
11561       DAG.getMachineFunction()
11562       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11563                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
11564   } else {
11565     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
11566     StackSlot = StackSlot.getOperand(1);
11567   }
11568   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
11569   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
11570                                            X86ISD::FILD, DL,
11571                                            Tys, Ops, SrcVT, MMO);
11572
11573   if (useSSE) {
11574     Chain = Result.getValue(1);
11575     SDValue InFlag = Result.getValue(2);
11576
11577     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
11578     // shouldn't be necessary except that RFP cannot be live across
11579     // multiple blocks. When stackifier is fixed, they can be uncoupled.
11580     MachineFunction &MF = DAG.getMachineFunction();
11581     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
11582     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
11583     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11584     Tys = DAG.getVTList(MVT::Other);
11585     SDValue Ops[] = {
11586       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
11587     };
11588     MachineMemOperand *MMO =
11589       DAG.getMachineFunction()
11590       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11591                             MachineMemOperand::MOStore, SSFISize, SSFISize);
11592
11593     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
11594                                     Ops, Op.getValueType(), MMO);
11595     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
11596                          MachinePointerInfo::getFixedStack(SSFI),
11597                          false, false, false, 0);
11598   }
11599
11600   return Result;
11601 }
11602
11603 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
11604 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
11605                                                SelectionDAG &DAG) const {
11606   // This algorithm is not obvious. Here it is what we're trying to output:
11607   /*
11608      movq       %rax,  %xmm0
11609      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
11610      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
11611      #ifdef __SSE3__
11612        haddpd   %xmm0, %xmm0
11613      #else
11614        pshufd   $0x4e, %xmm0, %xmm1
11615        addpd    %xmm1, %xmm0
11616      #endif
11617   */
11618
11619   SDLoc dl(Op);
11620   LLVMContext *Context = DAG.getContext();
11621
11622   // Build some magic constants.
11623   static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
11624   Constant *C0 = ConstantDataVector::get(*Context, CV0);
11625   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
11626
11627   SmallVector<Constant*,2> CV1;
11628   CV1.push_back(
11629     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11630                                       APInt(64, 0x4330000000000000ULL))));
11631   CV1.push_back(
11632     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11633                                       APInt(64, 0x4530000000000000ULL))));
11634   Constant *C1 = ConstantVector::get(CV1);
11635   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
11636
11637   // Load the 64-bit value into an XMM register.
11638   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
11639                             Op.getOperand(0));
11640   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
11641                               MachinePointerInfo::getConstantPool(),
11642                               false, false, false, 16);
11643   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
11644                               DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
11645                               CLod0);
11646
11647   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
11648                               MachinePointerInfo::getConstantPool(),
11649                               false, false, false, 16);
11650   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
11651   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
11652   SDValue Result;
11653
11654   if (Subtarget->hasSSE3()) {
11655     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
11656     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
11657   } else {
11658     SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
11659     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
11660                                            S2F, 0x4E, DAG);
11661     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
11662                          DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
11663                          Sub);
11664   }
11665
11666   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
11667                      DAG.getIntPtrConstant(0, dl));
11668 }
11669
11670 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
11671 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
11672                                                SelectionDAG &DAG) const {
11673   SDLoc dl(Op);
11674   // FP constant to bias correct the final result.
11675   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
11676                                    MVT::f64);
11677
11678   // Load the 32-bit value into an XMM register.
11679   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
11680                              Op.getOperand(0));
11681
11682   // Zero out the upper parts of the register.
11683   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
11684
11685   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
11686                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
11687                      DAG.getIntPtrConstant(0, dl));
11688
11689   // Or the load with the bias.
11690   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
11691                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
11692                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
11693                                                    MVT::v2f64, Load)),
11694                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
11695                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
11696                                                    MVT::v2f64, Bias)));
11697   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
11698                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
11699                    DAG.getIntPtrConstant(0, dl));
11700
11701   // Subtract the bias.
11702   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
11703
11704   // Handle final rounding.
11705   EVT DestVT = Op.getValueType();
11706
11707   if (DestVT.bitsLT(MVT::f64))
11708     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
11709                        DAG.getIntPtrConstant(0, dl));
11710   if (DestVT.bitsGT(MVT::f64))
11711     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
11712
11713   // Handle final rounding.
11714   return Sub;
11715 }
11716
11717 static SDValue lowerUINT_TO_FP_vXi32(SDValue Op, SelectionDAG &DAG,
11718                                      const X86Subtarget &Subtarget) {
11719   // The algorithm is the following:
11720   // #ifdef __SSE4_1__
11721   //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
11722   //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
11723   //                                 (uint4) 0x53000000, 0xaa);
11724   // #else
11725   //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
11726   //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
11727   // #endif
11728   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
11729   //     return (float4) lo + fhi;
11730
11731   SDLoc DL(Op);
11732   SDValue V = Op->getOperand(0);
11733   EVT VecIntVT = V.getValueType();
11734   bool Is128 = VecIntVT == MVT::v4i32;
11735   EVT VecFloatVT = Is128 ? MVT::v4f32 : MVT::v8f32;
11736   // If we convert to something else than the supported type, e.g., to v4f64,
11737   // abort early.
11738   if (VecFloatVT != Op->getValueType(0))
11739     return SDValue();
11740
11741   unsigned NumElts = VecIntVT.getVectorNumElements();
11742   assert((VecIntVT == MVT::v4i32 || VecIntVT == MVT::v8i32) &&
11743          "Unsupported custom type");
11744   assert(NumElts <= 8 && "The size of the constant array must be fixed");
11745
11746   // In the #idef/#else code, we have in common:
11747   // - The vector of constants:
11748   // -- 0x4b000000
11749   // -- 0x53000000
11750   // - A shift:
11751   // -- v >> 16
11752
11753   // Create the splat vector for 0x4b000000.
11754   SDValue CstLow = DAG.getConstant(0x4b000000, DL, MVT::i32);
11755   SDValue CstLowArray[] = {CstLow, CstLow, CstLow, CstLow,
11756                            CstLow, CstLow, CstLow, CstLow};
11757   SDValue VecCstLow = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
11758                                   makeArrayRef(&CstLowArray[0], NumElts));
11759   // Create the splat vector for 0x53000000.
11760   SDValue CstHigh = DAG.getConstant(0x53000000, DL, MVT::i32);
11761   SDValue CstHighArray[] = {CstHigh, CstHigh, CstHigh, CstHigh,
11762                             CstHigh, CstHigh, CstHigh, CstHigh};
11763   SDValue VecCstHigh = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
11764                                    makeArrayRef(&CstHighArray[0], NumElts));
11765
11766   // Create the right shift.
11767   SDValue CstShift = DAG.getConstant(16, DL, MVT::i32);
11768   SDValue CstShiftArray[] = {CstShift, CstShift, CstShift, CstShift,
11769                              CstShift, CstShift, CstShift, CstShift};
11770   SDValue VecCstShift = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
11771                                     makeArrayRef(&CstShiftArray[0], NumElts));
11772   SDValue HighShift = DAG.getNode(ISD::SRL, DL, VecIntVT, V, VecCstShift);
11773
11774   SDValue Low, High;
11775   if (Subtarget.hasSSE41()) {
11776     EVT VecI16VT = Is128 ? MVT::v8i16 : MVT::v16i16;
11777     //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
11778     SDValue VecCstLowBitcast =
11779         DAG.getNode(ISD::BITCAST, DL, VecI16VT, VecCstLow);
11780     SDValue VecBitcast = DAG.getNode(ISD::BITCAST, DL, VecI16VT, V);
11781     // Low will be bitcasted right away, so do not bother bitcasting back to its
11782     // original type.
11783     Low = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecBitcast,
11784                       VecCstLowBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
11785     //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
11786     //                                 (uint4) 0x53000000, 0xaa);
11787     SDValue VecCstHighBitcast =
11788         DAG.getNode(ISD::BITCAST, DL, VecI16VT, VecCstHigh);
11789     SDValue VecShiftBitcast =
11790         DAG.getNode(ISD::BITCAST, DL, VecI16VT, HighShift);
11791     // High will be bitcasted right away, so do not bother bitcasting back to
11792     // its original type.
11793     High = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecShiftBitcast,
11794                        VecCstHighBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
11795   } else {
11796     SDValue CstMask = DAG.getConstant(0xffff, DL, MVT::i32);
11797     SDValue VecCstMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT, CstMask,
11798                                      CstMask, CstMask, CstMask);
11799     //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
11800     SDValue LowAnd = DAG.getNode(ISD::AND, DL, VecIntVT, V, VecCstMask);
11801     Low = DAG.getNode(ISD::OR, DL, VecIntVT, LowAnd, VecCstLow);
11802
11803     //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
11804     High = DAG.getNode(ISD::OR, DL, VecIntVT, HighShift, VecCstHigh);
11805   }
11806
11807   // Create the vector constant for -(0x1.0p39f + 0x1.0p23f).
11808   SDValue CstFAdd = DAG.getConstantFP(
11809       APFloat(APFloat::IEEEsingle, APInt(32, 0xD3000080)), DL, MVT::f32);
11810   SDValue CstFAddArray[] = {CstFAdd, CstFAdd, CstFAdd, CstFAdd,
11811                             CstFAdd, CstFAdd, CstFAdd, CstFAdd};
11812   SDValue VecCstFAdd = DAG.getNode(ISD::BUILD_VECTOR, DL, VecFloatVT,
11813                                    makeArrayRef(&CstFAddArray[0], NumElts));
11814
11815   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
11816   SDValue HighBitcast = DAG.getNode(ISD::BITCAST, DL, VecFloatVT, High);
11817   SDValue FHigh =
11818       DAG.getNode(ISD::FADD, DL, VecFloatVT, HighBitcast, VecCstFAdd);
11819   //     return (float4) lo + fhi;
11820   SDValue LowBitcast = DAG.getNode(ISD::BITCAST, DL, VecFloatVT, Low);
11821   return DAG.getNode(ISD::FADD, DL, VecFloatVT, LowBitcast, FHigh);
11822 }
11823
11824 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
11825                                                SelectionDAG &DAG) const {
11826   SDValue N0 = Op.getOperand(0);
11827   MVT SVT = N0.getSimpleValueType();
11828   SDLoc dl(Op);
11829
11830   switch (SVT.SimpleTy) {
11831   default:
11832     llvm_unreachable("Custom UINT_TO_FP is not supported!");
11833   case MVT::v4i8:
11834   case MVT::v4i16:
11835   case MVT::v8i8:
11836   case MVT::v8i16: {
11837     MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
11838     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
11839                        DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
11840   }
11841   case MVT::v4i32:
11842   case MVT::v8i32:
11843     return lowerUINT_TO_FP_vXi32(Op, DAG, *Subtarget);
11844   case MVT::v16i8:
11845   case MVT::v16i16:
11846     if (Subtarget->hasAVX512())
11847       return DAG.getNode(ISD::UINT_TO_FP, dl, Op.getValueType(),
11848                          DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v16i32, N0));
11849   }
11850   llvm_unreachable(nullptr);
11851 }
11852
11853 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
11854                                            SelectionDAG &DAG) const {
11855   SDValue N0 = Op.getOperand(0);
11856   SDLoc dl(Op);
11857
11858   if (Op.getValueType().isVector())
11859     return lowerUINT_TO_FP_vec(Op, DAG);
11860
11861   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
11862   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
11863   // the optimization here.
11864   if (DAG.SignBitIsZero(N0))
11865     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
11866
11867   MVT SrcVT = N0.getSimpleValueType();
11868   MVT DstVT = Op.getSimpleValueType();
11869   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
11870     return LowerUINT_TO_FP_i64(Op, DAG);
11871   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
11872     return LowerUINT_TO_FP_i32(Op, DAG);
11873   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
11874     return SDValue();
11875
11876   // Make a 64-bit buffer, and use it to build an FILD.
11877   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
11878   if (SrcVT == MVT::i32) {
11879     SDValue WordOff = DAG.getConstant(4, dl, getPointerTy());
11880     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
11881                                      getPointerTy(), StackSlot, WordOff);
11882     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11883                                   StackSlot, MachinePointerInfo(),
11884                                   false, false, 0);
11885     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, dl, MVT::i32),
11886                                   OffsetSlot, MachinePointerInfo(),
11887                                   false, false, 0);
11888     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
11889     return Fild;
11890   }
11891
11892   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
11893   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11894                                StackSlot, MachinePointerInfo(),
11895                                false, false, 0);
11896   // For i64 source, we need to add the appropriate power of 2 if the input
11897   // was negative.  This is the same as the optimization in
11898   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
11899   // we must be careful to do the computation in x87 extended precision, not
11900   // in SSE. (The generic code can't know it's OK to do this, or how to.)
11901   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
11902   MachineMemOperand *MMO =
11903     DAG.getMachineFunction()
11904     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11905                           MachineMemOperand::MOLoad, 8, 8);
11906
11907   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
11908   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
11909   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
11910                                          MVT::i64, MMO);
11911
11912   APInt FF(32, 0x5F800000ULL);
11913
11914   // Check whether the sign bit is set.
11915   SDValue SignSet = DAG.getSetCC(dl,
11916                                  getSetCCResultType(*DAG.getContext(), MVT::i64),
11917                                  Op.getOperand(0),
11918                                  DAG.getConstant(0, dl, MVT::i64), ISD::SETLT);
11919
11920   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
11921   SDValue FudgePtr = DAG.getConstantPool(
11922                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
11923                                          getPointerTy());
11924
11925   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
11926   SDValue Zero = DAG.getIntPtrConstant(0, dl);
11927   SDValue Four = DAG.getIntPtrConstant(4, dl);
11928   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
11929                                Zero, Four);
11930   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
11931
11932   // Load the value out, extending it from f32 to f80.
11933   // FIXME: Avoid the extend by constructing the right constant pool?
11934   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
11935                                  FudgePtr, MachinePointerInfo::getConstantPool(),
11936                                  MVT::f32, false, false, false, 4);
11937   // Extend everything to 80 bits to force it to be done on x87.
11938   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
11939   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add,
11940                      DAG.getIntPtrConstant(0, dl));
11941 }
11942
11943 std::pair<SDValue,SDValue>
11944 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
11945                                     bool IsSigned, bool IsReplace) const {
11946   SDLoc DL(Op);
11947
11948   EVT DstTy = Op.getValueType();
11949
11950   if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
11951     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
11952     DstTy = MVT::i64;
11953   }
11954
11955   assert(DstTy.getSimpleVT() <= MVT::i64 &&
11956          DstTy.getSimpleVT() >= MVT::i16 &&
11957          "Unknown FP_TO_INT to lower!");
11958
11959   // These are really Legal.
11960   if (DstTy == MVT::i32 &&
11961       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
11962     return std::make_pair(SDValue(), SDValue());
11963   if (Subtarget->is64Bit() &&
11964       DstTy == MVT::i64 &&
11965       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
11966     return std::make_pair(SDValue(), SDValue());
11967
11968   // We lower FP->int64 either into FISTP64 followed by a load from a temporary
11969   // stack slot, or into the FTOL runtime function.
11970   MachineFunction &MF = DAG.getMachineFunction();
11971   unsigned MemSize = DstTy.getSizeInBits()/8;
11972   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
11973   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11974
11975   unsigned Opc;
11976   if (!IsSigned && isIntegerTypeFTOL(DstTy))
11977     Opc = X86ISD::WIN_FTOL;
11978   else
11979     switch (DstTy.getSimpleVT().SimpleTy) {
11980     default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
11981     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
11982     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
11983     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
11984     }
11985
11986   SDValue Chain = DAG.getEntryNode();
11987   SDValue Value = Op.getOperand(0);
11988   EVT TheVT = Op.getOperand(0).getValueType();
11989   // FIXME This causes a redundant load/store if the SSE-class value is already
11990   // in memory, such as if it is on the callstack.
11991   if (isScalarFPTypeInSSEReg(TheVT)) {
11992     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
11993     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
11994                          MachinePointerInfo::getFixedStack(SSFI),
11995                          false, false, 0);
11996     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
11997     SDValue Ops[] = {
11998       Chain, StackSlot, DAG.getValueType(TheVT)
11999     };
12000
12001     MachineMemOperand *MMO =
12002       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
12003                               MachineMemOperand::MOLoad, MemSize, MemSize);
12004     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
12005     Chain = Value.getValue(1);
12006     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
12007     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
12008   }
12009
12010   MachineMemOperand *MMO =
12011     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
12012                             MachineMemOperand::MOStore, MemSize, MemSize);
12013
12014   if (Opc != X86ISD::WIN_FTOL) {
12015     // Build the FP_TO_INT*_IN_MEM
12016     SDValue Ops[] = { Chain, Value, StackSlot };
12017     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
12018                                            Ops, DstTy, MMO);
12019     return std::make_pair(FIST, StackSlot);
12020   } else {
12021     SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
12022       DAG.getVTList(MVT::Other, MVT::Glue),
12023       Chain, Value);
12024     SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
12025       MVT::i32, ftol.getValue(1));
12026     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
12027       MVT::i32, eax.getValue(2));
12028     SDValue Ops[] = { eax, edx };
12029     SDValue pair = IsReplace
12030       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops)
12031       : DAG.getMergeValues(Ops, DL);
12032     return std::make_pair(pair, SDValue());
12033   }
12034 }
12035
12036 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
12037                               const X86Subtarget *Subtarget) {
12038   MVT VT = Op->getSimpleValueType(0);
12039   SDValue In = Op->getOperand(0);
12040   MVT InVT = In.getSimpleValueType();
12041   SDLoc dl(Op);
12042
12043   if (VT.is512BitVector() || InVT.getScalarType() == MVT::i1)
12044     return DAG.getNode(ISD::ZERO_EXTEND, dl, VT, In);
12045
12046   // Optimize vectors in AVX mode:
12047   //
12048   //   v8i16 -> v8i32
12049   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
12050   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
12051   //   Concat upper and lower parts.
12052   //
12053   //   v4i32 -> v4i64
12054   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
12055   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
12056   //   Concat upper and lower parts.
12057   //
12058
12059   if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
12060       ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
12061       ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
12062     return SDValue();
12063
12064   if (Subtarget->hasInt256())
12065     return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
12066
12067   SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
12068   SDValue Undef = DAG.getUNDEF(InVT);
12069   bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
12070   SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
12071   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
12072
12073   MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
12074                              VT.getVectorNumElements()/2);
12075
12076   OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
12077   OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
12078
12079   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
12080 }
12081
12082 static  SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
12083                                         SelectionDAG &DAG) {
12084   MVT VT = Op->getSimpleValueType(0);
12085   SDValue In = Op->getOperand(0);
12086   MVT InVT = In.getSimpleValueType();
12087   SDLoc DL(Op);
12088   unsigned int NumElts = VT.getVectorNumElements();
12089   if (NumElts != 8 && NumElts != 16)
12090     return SDValue();
12091
12092   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
12093     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
12094
12095   assert(InVT.getVectorElementType() == MVT::i1);
12096   MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
12097   SDValue One =
12098    DAG.getConstant(APInt(ExtVT.getScalarSizeInBits(), 1), DL, ExtVT);
12099   SDValue Zero =
12100    DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), DL, ExtVT);
12101
12102   SDValue V = DAG.getNode(ISD::VSELECT, DL, ExtVT, In, One, Zero);
12103   if (VT.is512BitVector())
12104     return V;
12105   return DAG.getNode(X86ISD::VTRUNC, DL, VT, V);
12106 }
12107
12108 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
12109                                SelectionDAG &DAG) {
12110   if (Subtarget->hasFp256()) {
12111     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
12112     if (Res.getNode())
12113       return Res;
12114   }
12115
12116   return SDValue();
12117 }
12118
12119 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
12120                                 SelectionDAG &DAG) {
12121   SDLoc DL(Op);
12122   MVT VT = Op.getSimpleValueType();
12123   SDValue In = Op.getOperand(0);
12124   MVT SVT = In.getSimpleValueType();
12125
12126   if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
12127     return LowerZERO_EXTEND_AVX512(Op, DAG);
12128
12129   if (Subtarget->hasFp256()) {
12130     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
12131     if (Res.getNode())
12132       return Res;
12133   }
12134
12135   assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
12136          VT.getVectorNumElements() != SVT.getVectorNumElements());
12137   return SDValue();
12138 }
12139
12140 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
12141   SDLoc DL(Op);
12142   MVT VT = Op.getSimpleValueType();
12143   SDValue In = Op.getOperand(0);
12144   MVT InVT = In.getSimpleValueType();
12145
12146   if (VT == MVT::i1) {
12147     assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
12148            "Invalid scalar TRUNCATE operation");
12149     if (InVT.getSizeInBits() >= 32)
12150       return SDValue();
12151     In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
12152     return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
12153   }
12154   assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
12155          "Invalid TRUNCATE operation");
12156
12157   // move vector to mask - truncate solution for SKX
12158   if (VT.getVectorElementType() == MVT::i1) {
12159     if (InVT.is512BitVector() && InVT.getScalarSizeInBits() <= 16 &&
12160         Subtarget->hasBWI())
12161       return Op; // legal, will go to VPMOVB2M, VPMOVW2M
12162     if ((InVT.is256BitVector() || InVT.is128BitVector()) 
12163         && InVT.getScalarSizeInBits() <= 16 &&
12164         Subtarget->hasBWI() && Subtarget->hasVLX())
12165       return Op; // legal, will go to VPMOVB2M, VPMOVW2M
12166     if (InVT.is512BitVector() && InVT.getScalarSizeInBits() >= 32 &&
12167         Subtarget->hasDQI())
12168       return Op; // legal, will go to VPMOVD2M, VPMOVQ2M
12169     if ((InVT.is256BitVector() || InVT.is128BitVector()) 
12170         && InVT.getScalarSizeInBits() >= 32 &&
12171         Subtarget->hasDQI() && Subtarget->hasVLX())
12172       return Op; // legal, will go to VPMOVB2M, VPMOVQ2M
12173   }
12174   if (InVT.is512BitVector() || VT.getVectorElementType() == MVT::i1) {
12175     if (VT.getVectorElementType().getSizeInBits() >=8)
12176       return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
12177
12178     assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
12179     unsigned NumElts = InVT.getVectorNumElements();
12180     assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
12181     if (InVT.getSizeInBits() < 512) {
12182       MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
12183       In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
12184       InVT = ExtVT;
12185     }
12186
12187     SDValue OneV =
12188      DAG.getConstant(APInt::getSignBit(InVT.getScalarSizeInBits()), DL, InVT);
12189     SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
12190     return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
12191   }
12192
12193   if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
12194     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
12195     if (Subtarget->hasInt256()) {
12196       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
12197       In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
12198       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
12199                                 ShufMask);
12200       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
12201                          DAG.getIntPtrConstant(0, DL));
12202     }
12203
12204     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12205                                DAG.getIntPtrConstant(0, DL));
12206     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12207                                DAG.getIntPtrConstant(2, DL));
12208     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
12209     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
12210     static const int ShufMask[] = {0, 2, 4, 6};
12211     return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
12212   }
12213
12214   if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
12215     // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
12216     if (Subtarget->hasInt256()) {
12217       In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
12218
12219       SmallVector<SDValue,32> pshufbMask;
12220       for (unsigned i = 0; i < 2; ++i) {
12221         pshufbMask.push_back(DAG.getConstant(0x0, DL, MVT::i8));
12222         pshufbMask.push_back(DAG.getConstant(0x1, DL, MVT::i8));
12223         pshufbMask.push_back(DAG.getConstant(0x4, DL, MVT::i8));
12224         pshufbMask.push_back(DAG.getConstant(0x5, DL, MVT::i8));
12225         pshufbMask.push_back(DAG.getConstant(0x8, DL, MVT::i8));
12226         pshufbMask.push_back(DAG.getConstant(0x9, DL, MVT::i8));
12227         pshufbMask.push_back(DAG.getConstant(0xc, DL, MVT::i8));
12228         pshufbMask.push_back(DAG.getConstant(0xd, DL, MVT::i8));
12229         for (unsigned j = 0; j < 8; ++j)
12230           pshufbMask.push_back(DAG.getConstant(0x80, DL, MVT::i8));
12231       }
12232       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
12233       In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
12234       In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
12235
12236       static const int ShufMask[] = {0,  2,  -1,  -1};
12237       In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, DAG.getUNDEF(MVT::v4i64),
12238                                 &ShufMask[0]);
12239       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12240                        DAG.getIntPtrConstant(0, DL));
12241       return DAG.getNode(ISD::BITCAST, DL, VT, In);
12242     }
12243
12244     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
12245                                DAG.getIntPtrConstant(0, DL));
12246
12247     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
12248                                DAG.getIntPtrConstant(4, DL));
12249
12250     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
12251     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
12252
12253     // The PSHUFB mask:
12254     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
12255                                    -1, -1, -1, -1, -1, -1, -1, -1};
12256
12257     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
12258     OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
12259     OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
12260
12261     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
12262     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
12263
12264     // The MOVLHPS Mask:
12265     static const int ShufMask2[] = {0, 1, 4, 5};
12266     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
12267     return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
12268   }
12269
12270   // Handle truncation of V256 to V128 using shuffles.
12271   if (!VT.is128BitVector() || !InVT.is256BitVector())
12272     return SDValue();
12273
12274   assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
12275
12276   unsigned NumElems = VT.getVectorNumElements();
12277   MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
12278
12279   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
12280   // Prepare truncation shuffle mask
12281   for (unsigned i = 0; i != NumElems; ++i)
12282     MaskVec[i] = i * 2;
12283   SDValue V = DAG.getVectorShuffle(NVT, DL,
12284                                    DAG.getNode(ISD::BITCAST, DL, NVT, In),
12285                                    DAG.getUNDEF(NVT), &MaskVec[0]);
12286   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
12287                      DAG.getIntPtrConstant(0, DL));
12288 }
12289
12290 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
12291                                            SelectionDAG &DAG) const {
12292   assert(!Op.getSimpleValueType().isVector());
12293
12294   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
12295     /*IsSigned=*/ true, /*IsReplace=*/ false);
12296   SDValue FIST = Vals.first, StackSlot = Vals.second;
12297   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
12298   if (!FIST.getNode()) return Op;
12299
12300   if (StackSlot.getNode())
12301     // Load the result.
12302     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
12303                        FIST, StackSlot, MachinePointerInfo(),
12304                        false, false, false, 0);
12305
12306   // The node is the result.
12307   return FIST;
12308 }
12309
12310 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
12311                                            SelectionDAG &DAG) const {
12312   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
12313     /*IsSigned=*/ false, /*IsReplace=*/ false);
12314   SDValue FIST = Vals.first, StackSlot = Vals.second;
12315   assert(FIST.getNode() && "Unexpected failure");
12316
12317   if (StackSlot.getNode())
12318     // Load the result.
12319     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
12320                        FIST, StackSlot, MachinePointerInfo(),
12321                        false, false, false, 0);
12322
12323   // The node is the result.
12324   return FIST;
12325 }
12326
12327 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
12328   SDLoc DL(Op);
12329   MVT VT = Op.getSimpleValueType();
12330   SDValue In = Op.getOperand(0);
12331   MVT SVT = In.getSimpleValueType();
12332
12333   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
12334
12335   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
12336                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
12337                                  In, DAG.getUNDEF(SVT)));
12338 }
12339
12340 /// The only differences between FABS and FNEG are the mask and the logic op.
12341 /// FNEG also has a folding opportunity for FNEG(FABS(x)).
12342 static SDValue LowerFABSorFNEG(SDValue Op, SelectionDAG &DAG) {
12343   assert((Op.getOpcode() == ISD::FABS || Op.getOpcode() == ISD::FNEG) &&
12344          "Wrong opcode for lowering FABS or FNEG.");
12345
12346   bool IsFABS = (Op.getOpcode() == ISD::FABS);
12347
12348   // If this is a FABS and it has an FNEG user, bail out to fold the combination
12349   // into an FNABS. We'll lower the FABS after that if it is still in use.
12350   if (IsFABS)
12351     for (SDNode *User : Op->uses())
12352       if (User->getOpcode() == ISD::FNEG)
12353         return Op;
12354
12355   SDValue Op0 = Op.getOperand(0);
12356   bool IsFNABS = !IsFABS && (Op0.getOpcode() == ISD::FABS);
12357
12358   SDLoc dl(Op);
12359   MVT VT = Op.getSimpleValueType();
12360   // Assume scalar op for initialization; update for vector if needed.
12361   // Note that there are no scalar bitwise logical SSE/AVX instructions, so we
12362   // generate a 16-byte vector constant and logic op even for the scalar case.
12363   // Using a 16-byte mask allows folding the load of the mask with
12364   // the logic op, so it can save (~4 bytes) on code size.
12365   MVT EltVT = VT;
12366   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
12367   // FIXME: Use function attribute "OptimizeForSize" and/or CodeGenOpt::Level to
12368   // decide if we should generate a 16-byte constant mask when we only need 4 or
12369   // 8 bytes for the scalar case.
12370   if (VT.isVector()) {
12371     EltVT = VT.getVectorElementType();
12372     NumElts = VT.getVectorNumElements();
12373   }
12374
12375   unsigned EltBits = EltVT.getSizeInBits();
12376   LLVMContext *Context = DAG.getContext();
12377   // For FABS, mask is 0x7f...; for FNEG, mask is 0x80...
12378   APInt MaskElt =
12379     IsFABS ? APInt::getSignedMaxValue(EltBits) : APInt::getSignBit(EltBits);
12380   Constant *C = ConstantInt::get(*Context, MaskElt);
12381   C = ConstantVector::getSplat(NumElts, C);
12382   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12383   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
12384   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
12385   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
12386                              MachinePointerInfo::getConstantPool(),
12387                              false, false, false, Alignment);
12388
12389   if (VT.isVector()) {
12390     // For a vector, cast operands to a vector type, perform the logic op,
12391     // and cast the result back to the original value type.
12392     MVT VecVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
12393     SDValue MaskCasted = DAG.getNode(ISD::BITCAST, dl, VecVT, Mask);
12394     SDValue Operand = IsFNABS ?
12395       DAG.getNode(ISD::BITCAST, dl, VecVT, Op0.getOperand(0)) :
12396       DAG.getNode(ISD::BITCAST, dl, VecVT, Op0);
12397     unsigned BitOp = IsFABS ? ISD::AND : IsFNABS ? ISD::OR : ISD::XOR;
12398     return DAG.getNode(ISD::BITCAST, dl, VT,
12399                        DAG.getNode(BitOp, dl, VecVT, Operand, MaskCasted));
12400   }
12401
12402   // If not vector, then scalar.
12403   unsigned BitOp = IsFABS ? X86ISD::FAND : IsFNABS ? X86ISD::FOR : X86ISD::FXOR;
12404   SDValue Operand = IsFNABS ? Op0.getOperand(0) : Op0;
12405   return DAG.getNode(BitOp, dl, VT, Operand, Mask);
12406 }
12407
12408 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
12409   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12410   LLVMContext *Context = DAG.getContext();
12411   SDValue Op0 = Op.getOperand(0);
12412   SDValue Op1 = Op.getOperand(1);
12413   SDLoc dl(Op);
12414   MVT VT = Op.getSimpleValueType();
12415   MVT SrcVT = Op1.getSimpleValueType();
12416
12417   // If second operand is smaller, extend it first.
12418   if (SrcVT.bitsLT(VT)) {
12419     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
12420     SrcVT = VT;
12421   }
12422   // And if it is bigger, shrink it first.
12423   if (SrcVT.bitsGT(VT)) {
12424     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1, dl));
12425     SrcVT = VT;
12426   }
12427
12428   // At this point the operands and the result should have the same
12429   // type, and that won't be f80 since that is not custom lowered.
12430
12431   const fltSemantics &Sem =
12432       VT == MVT::f64 ? APFloat::IEEEdouble : APFloat::IEEEsingle;
12433   const unsigned SizeInBits = VT.getSizeInBits();
12434
12435   SmallVector<Constant *, 4> CV(
12436       VT == MVT::f64 ? 2 : 4,
12437       ConstantFP::get(*Context, APFloat(Sem, APInt(SizeInBits, 0))));
12438
12439   // First, clear all bits but the sign bit from the second operand (sign).
12440   CV[0] = ConstantFP::get(*Context,
12441                           APFloat(Sem, APInt::getHighBitsSet(SizeInBits, 1)));
12442   Constant *C = ConstantVector::get(CV);
12443   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
12444   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
12445                               MachinePointerInfo::getConstantPool(),
12446                               false, false, false, 16);
12447   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
12448
12449   // Next, clear the sign bit from the first operand (magnitude).
12450   // If it's a constant, we can clear it here.
12451   if (ConstantFPSDNode *Op0CN = dyn_cast<ConstantFPSDNode>(Op0)) {
12452     APFloat APF = Op0CN->getValueAPF();
12453     // If the magnitude is a positive zero, the sign bit alone is enough.
12454     if (APF.isPosZero())
12455       return SignBit;
12456     APF.clearSign();
12457     CV[0] = ConstantFP::get(*Context, APF);
12458   } else {
12459     CV[0] = ConstantFP::get(
12460         *Context,
12461         APFloat(Sem, APInt::getLowBitsSet(SizeInBits, SizeInBits - 1)));
12462   }
12463   C = ConstantVector::get(CV);
12464   CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
12465   SDValue Val = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
12466                             MachinePointerInfo::getConstantPool(),
12467                             false, false, false, 16);
12468   // If the magnitude operand wasn't a constant, we need to AND out the sign.
12469   if (!isa<ConstantFPSDNode>(Op0))
12470     Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Val);
12471
12472   // OR the magnitude value with the sign bit.
12473   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
12474 }
12475
12476 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
12477   SDValue N0 = Op.getOperand(0);
12478   SDLoc dl(Op);
12479   MVT VT = Op.getSimpleValueType();
12480
12481   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
12482   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
12483                                   DAG.getConstant(1, dl, VT));
12484   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, dl, VT));
12485 }
12486
12487 // Check whether an OR'd tree is PTEST-able.
12488 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
12489                                       SelectionDAG &DAG) {
12490   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
12491
12492   if (!Subtarget->hasSSE41())
12493     return SDValue();
12494
12495   if (!Op->hasOneUse())
12496     return SDValue();
12497
12498   SDNode *N = Op.getNode();
12499   SDLoc DL(N);
12500
12501   SmallVector<SDValue, 8> Opnds;
12502   DenseMap<SDValue, unsigned> VecInMap;
12503   SmallVector<SDValue, 8> VecIns;
12504   EVT VT = MVT::Other;
12505
12506   // Recognize a special case where a vector is casted into wide integer to
12507   // test all 0s.
12508   Opnds.push_back(N->getOperand(0));
12509   Opnds.push_back(N->getOperand(1));
12510
12511   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
12512     SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
12513     // BFS traverse all OR'd operands.
12514     if (I->getOpcode() == ISD::OR) {
12515       Opnds.push_back(I->getOperand(0));
12516       Opnds.push_back(I->getOperand(1));
12517       // Re-evaluate the number of nodes to be traversed.
12518       e += 2; // 2 more nodes (LHS and RHS) are pushed.
12519       continue;
12520     }
12521
12522     // Quit if a non-EXTRACT_VECTOR_ELT
12523     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
12524       return SDValue();
12525
12526     // Quit if without a constant index.
12527     SDValue Idx = I->getOperand(1);
12528     if (!isa<ConstantSDNode>(Idx))
12529       return SDValue();
12530
12531     SDValue ExtractedFromVec = I->getOperand(0);
12532     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
12533     if (M == VecInMap.end()) {
12534       VT = ExtractedFromVec.getValueType();
12535       // Quit if not 128/256-bit vector.
12536       if (!VT.is128BitVector() && !VT.is256BitVector())
12537         return SDValue();
12538       // Quit if not the same type.
12539       if (VecInMap.begin() != VecInMap.end() &&
12540           VT != VecInMap.begin()->first.getValueType())
12541         return SDValue();
12542       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
12543       VecIns.push_back(ExtractedFromVec);
12544     }
12545     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
12546   }
12547
12548   assert((VT.is128BitVector() || VT.is256BitVector()) &&
12549          "Not extracted from 128-/256-bit vector.");
12550
12551   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
12552
12553   for (DenseMap<SDValue, unsigned>::const_iterator
12554         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
12555     // Quit if not all elements are used.
12556     if (I->second != FullMask)
12557       return SDValue();
12558   }
12559
12560   EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
12561
12562   // Cast all vectors into TestVT for PTEST.
12563   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
12564     VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
12565
12566   // If more than one full vectors are evaluated, OR them first before PTEST.
12567   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
12568     // Each iteration will OR 2 nodes and append the result until there is only
12569     // 1 node left, i.e. the final OR'd value of all vectors.
12570     SDValue LHS = VecIns[Slot];
12571     SDValue RHS = VecIns[Slot + 1];
12572     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
12573   }
12574
12575   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
12576                      VecIns.back(), VecIns.back());
12577 }
12578
12579 /// \brief return true if \c Op has a use that doesn't just read flags.
12580 static bool hasNonFlagsUse(SDValue Op) {
12581   for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
12582        ++UI) {
12583     SDNode *User = *UI;
12584     unsigned UOpNo = UI.getOperandNo();
12585     if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
12586       // Look pass truncate.
12587       UOpNo = User->use_begin().getOperandNo();
12588       User = *User->use_begin();
12589     }
12590
12591     if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
12592         !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
12593       return true;
12594   }
12595   return false;
12596 }
12597
12598 /// Emit nodes that will be selected as "test Op0,Op0", or something
12599 /// equivalent.
12600 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
12601                                     SelectionDAG &DAG) const {
12602   if (Op.getValueType() == MVT::i1) {
12603     SDValue ExtOp = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i8, Op);
12604     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, ExtOp,
12605                        DAG.getConstant(0, dl, MVT::i8));
12606   }
12607   // CF and OF aren't always set the way we want. Determine which
12608   // of these we need.
12609   bool NeedCF = false;
12610   bool NeedOF = false;
12611   switch (X86CC) {
12612   default: break;
12613   case X86::COND_A: case X86::COND_AE:
12614   case X86::COND_B: case X86::COND_BE:
12615     NeedCF = true;
12616     break;
12617   case X86::COND_G: case X86::COND_GE:
12618   case X86::COND_L: case X86::COND_LE:
12619   case X86::COND_O: case X86::COND_NO: {
12620     // Check if we really need to set the
12621     // Overflow flag. If NoSignedWrap is present
12622     // that is not actually needed.
12623     switch (Op->getOpcode()) {
12624     case ISD::ADD:
12625     case ISD::SUB:
12626     case ISD::MUL:
12627     case ISD::SHL: {
12628       const auto *BinNode = cast<BinaryWithFlagsSDNode>(Op.getNode());
12629       if (BinNode->Flags.hasNoSignedWrap())
12630         break;
12631     }
12632     default:
12633       NeedOF = true;
12634       break;
12635     }
12636     break;
12637   }
12638   }
12639   // See if we can use the EFLAGS value from the operand instead of
12640   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
12641   // we prove that the arithmetic won't overflow, we can't use OF or CF.
12642   if (Op.getResNo() != 0 || NeedOF || NeedCF) {
12643     // Emit a CMP with 0, which is the TEST pattern.
12644     //if (Op.getValueType() == MVT::i1)
12645     //  return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
12646     //                     DAG.getConstant(0, MVT::i1));
12647     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
12648                        DAG.getConstant(0, dl, Op.getValueType()));
12649   }
12650   unsigned Opcode = 0;
12651   unsigned NumOperands = 0;
12652
12653   // Truncate operations may prevent the merge of the SETCC instruction
12654   // and the arithmetic instruction before it. Attempt to truncate the operands
12655   // of the arithmetic instruction and use a reduced bit-width instruction.
12656   bool NeedTruncation = false;
12657   SDValue ArithOp = Op;
12658   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
12659     SDValue Arith = Op->getOperand(0);
12660     // Both the trunc and the arithmetic op need to have one user each.
12661     if (Arith->hasOneUse())
12662       switch (Arith.getOpcode()) {
12663         default: break;
12664         case ISD::ADD:
12665         case ISD::SUB:
12666         case ISD::AND:
12667         case ISD::OR:
12668         case ISD::XOR: {
12669           NeedTruncation = true;
12670           ArithOp = Arith;
12671         }
12672       }
12673   }
12674
12675   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
12676   // which may be the result of a CAST.  We use the variable 'Op', which is the
12677   // non-casted variable when we check for possible users.
12678   switch (ArithOp.getOpcode()) {
12679   case ISD::ADD:
12680     // Due to an isel shortcoming, be conservative if this add is likely to be
12681     // selected as part of a load-modify-store instruction. When the root node
12682     // in a match is a store, isel doesn't know how to remap non-chain non-flag
12683     // uses of other nodes in the match, such as the ADD in this case. This
12684     // leads to the ADD being left around and reselected, with the result being
12685     // two adds in the output.  Alas, even if none our users are stores, that
12686     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
12687     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
12688     // climbing the DAG back to the root, and it doesn't seem to be worth the
12689     // effort.
12690     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
12691          UE = Op.getNode()->use_end(); UI != UE; ++UI)
12692       if (UI->getOpcode() != ISD::CopyToReg &&
12693           UI->getOpcode() != ISD::SETCC &&
12694           UI->getOpcode() != ISD::STORE)
12695         goto default_case;
12696
12697     if (ConstantSDNode *C =
12698         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
12699       // An add of one will be selected as an INC.
12700       if (C->getAPIntValue() == 1 && !Subtarget->slowIncDec()) {
12701         Opcode = X86ISD::INC;
12702         NumOperands = 1;
12703         break;
12704       }
12705
12706       // An add of negative one (subtract of one) will be selected as a DEC.
12707       if (C->getAPIntValue().isAllOnesValue() && !Subtarget->slowIncDec()) {
12708         Opcode = X86ISD::DEC;
12709         NumOperands = 1;
12710         break;
12711       }
12712     }
12713
12714     // Otherwise use a regular EFLAGS-setting add.
12715     Opcode = X86ISD::ADD;
12716     NumOperands = 2;
12717     break;
12718   case ISD::SHL:
12719   case ISD::SRL:
12720     // If we have a constant logical shift that's only used in a comparison
12721     // against zero turn it into an equivalent AND. This allows turning it into
12722     // a TEST instruction later.
12723     if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
12724         isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
12725       EVT VT = Op.getValueType();
12726       unsigned BitWidth = VT.getSizeInBits();
12727       unsigned ShAmt = Op->getConstantOperandVal(1);
12728       if (ShAmt >= BitWidth) // Avoid undefined shifts.
12729         break;
12730       APInt Mask = ArithOp.getOpcode() == ISD::SRL
12731                        ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
12732                        : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
12733       if (!Mask.isSignedIntN(32)) // Avoid large immediates.
12734         break;
12735       SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
12736                                 DAG.getConstant(Mask, dl, VT));
12737       DAG.ReplaceAllUsesWith(Op, New);
12738       Op = New;
12739     }
12740     break;
12741
12742   case ISD::AND:
12743     // If the primary and result isn't used, don't bother using X86ISD::AND,
12744     // because a TEST instruction will be better.
12745     if (!hasNonFlagsUse(Op))
12746       break;
12747     // FALL THROUGH
12748   case ISD::SUB:
12749   case ISD::OR:
12750   case ISD::XOR:
12751     // Due to the ISEL shortcoming noted above, be conservative if this op is
12752     // likely to be selected as part of a load-modify-store instruction.
12753     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
12754            UE = Op.getNode()->use_end(); UI != UE; ++UI)
12755       if (UI->getOpcode() == ISD::STORE)
12756         goto default_case;
12757
12758     // Otherwise use a regular EFLAGS-setting instruction.
12759     switch (ArithOp.getOpcode()) {
12760     default: llvm_unreachable("unexpected operator!");
12761     case ISD::SUB: Opcode = X86ISD::SUB; break;
12762     case ISD::XOR: Opcode = X86ISD::XOR; break;
12763     case ISD::AND: Opcode = X86ISD::AND; break;
12764     case ISD::OR: {
12765       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
12766         SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
12767         if (EFLAGS.getNode())
12768           return EFLAGS;
12769       }
12770       Opcode = X86ISD::OR;
12771       break;
12772     }
12773     }
12774
12775     NumOperands = 2;
12776     break;
12777   case X86ISD::ADD:
12778   case X86ISD::SUB:
12779   case X86ISD::INC:
12780   case X86ISD::DEC:
12781   case X86ISD::OR:
12782   case X86ISD::XOR:
12783   case X86ISD::AND:
12784     return SDValue(Op.getNode(), 1);
12785   default:
12786   default_case:
12787     break;
12788   }
12789
12790   // If we found that truncation is beneficial, perform the truncation and
12791   // update 'Op'.
12792   if (NeedTruncation) {
12793     EVT VT = Op.getValueType();
12794     SDValue WideVal = Op->getOperand(0);
12795     EVT WideVT = WideVal.getValueType();
12796     unsigned ConvertedOp = 0;
12797     // Use a target machine opcode to prevent further DAGCombine
12798     // optimizations that may separate the arithmetic operations
12799     // from the setcc node.
12800     switch (WideVal.getOpcode()) {
12801       default: break;
12802       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
12803       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
12804       case ISD::AND: ConvertedOp = X86ISD::AND; break;
12805       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
12806       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
12807     }
12808
12809     if (ConvertedOp) {
12810       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12811       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
12812         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
12813         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
12814         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
12815       }
12816     }
12817   }
12818
12819   if (Opcode == 0)
12820     // Emit a CMP with 0, which is the TEST pattern.
12821     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
12822                        DAG.getConstant(0, dl, Op.getValueType()));
12823
12824   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
12825   SmallVector<SDValue, 4> Ops(Op->op_begin(), Op->op_begin() + NumOperands);
12826
12827   SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
12828   DAG.ReplaceAllUsesWith(Op, New);
12829   return SDValue(New.getNode(), 1);
12830 }
12831
12832 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
12833 /// equivalent.
12834 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
12835                                    SDLoc dl, SelectionDAG &DAG) const {
12836   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
12837     if (C->getAPIntValue() == 0)
12838       return EmitTest(Op0, X86CC, dl, DAG);
12839
12840      if (Op0.getValueType() == MVT::i1)
12841        llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
12842   }
12843
12844   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
12845        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
12846     // Do the comparison at i32 if it's smaller, besides the Atom case.
12847     // This avoids subregister aliasing issues. Keep the smaller reference
12848     // if we're optimizing for size, however, as that'll allow better folding
12849     // of memory operations.
12850     if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
12851         !DAG.getMachineFunction().getFunction()->hasFnAttribute(
12852             Attribute::MinSize) &&
12853         !Subtarget->isAtom()) {
12854       unsigned ExtendOp =
12855           isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
12856       Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
12857       Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
12858     }
12859     // Use SUB instead of CMP to enable CSE between SUB and CMP.
12860     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
12861     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
12862                               Op0, Op1);
12863     return SDValue(Sub.getNode(), 1);
12864   }
12865   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
12866 }
12867
12868 /// Convert a comparison if required by the subtarget.
12869 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
12870                                                  SelectionDAG &DAG) const {
12871   // If the subtarget does not support the FUCOMI instruction, floating-point
12872   // comparisons have to be converted.
12873   if (Subtarget->hasCMov() ||
12874       Cmp.getOpcode() != X86ISD::CMP ||
12875       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
12876       !Cmp.getOperand(1).getValueType().isFloatingPoint())
12877     return Cmp;
12878
12879   // The instruction selector will select an FUCOM instruction instead of
12880   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
12881   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
12882   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
12883   SDLoc dl(Cmp);
12884   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
12885   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
12886   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
12887                             DAG.getConstant(8, dl, MVT::i8));
12888   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
12889   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
12890 }
12891
12892 /// The minimum architected relative accuracy is 2^-12. We need one
12893 /// Newton-Raphson step to have a good float result (24 bits of precision).
12894 SDValue X86TargetLowering::getRsqrtEstimate(SDValue Op,
12895                                             DAGCombinerInfo &DCI,
12896                                             unsigned &RefinementSteps,
12897                                             bool &UseOneConstNR) const {
12898   EVT VT = Op.getValueType();
12899   const char *RecipOp;
12900
12901   // SSE1 has rsqrtss and rsqrtps. AVX adds a 256-bit variant for rsqrtps.
12902   // TODO: Add support for AVX512 (v16f32).
12903   // It is likely not profitable to do this for f64 because a double-precision
12904   // rsqrt estimate with refinement on x86 prior to FMA requires at least 16
12905   // instructions: convert to single, rsqrtss, convert back to double, refine
12906   // (3 steps = at least 13 insts). If an 'rsqrtsd' variant was added to the ISA
12907   // along with FMA, this could be a throughput win.
12908   if (VT == MVT::f32 && Subtarget->hasSSE1())
12909     RecipOp = "sqrtf";
12910   else if ((VT == MVT::v4f32 && Subtarget->hasSSE1()) ||
12911            (VT == MVT::v8f32 && Subtarget->hasAVX()))
12912     RecipOp = "vec-sqrtf";
12913   else
12914     return SDValue();
12915   
12916   TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
12917   if (!Recips.isEnabled(RecipOp))
12918     return SDValue();
12919   
12920   RefinementSteps = Recips.getRefinementSteps(RecipOp);
12921   UseOneConstNR = false;
12922   return DCI.DAG.getNode(X86ISD::FRSQRT, SDLoc(Op), VT, Op);
12923 }
12924
12925 /// The minimum architected relative accuracy is 2^-12. We need one
12926 /// Newton-Raphson step to have a good float result (24 bits of precision).
12927 SDValue X86TargetLowering::getRecipEstimate(SDValue Op,
12928                                             DAGCombinerInfo &DCI,
12929                                             unsigned &RefinementSteps) const {
12930   EVT VT = Op.getValueType();
12931   const char *RecipOp;
12932   
12933   // SSE1 has rcpss and rcpps. AVX adds a 256-bit variant for rcpps.
12934   // TODO: Add support for AVX512 (v16f32).
12935   // It is likely not profitable to do this for f64 because a double-precision
12936   // reciprocal estimate with refinement on x86 prior to FMA requires
12937   // 15 instructions: convert to single, rcpss, convert back to double, refine
12938   // (3 steps = 12 insts). If an 'rcpsd' variant was added to the ISA
12939   // along with FMA, this could be a throughput win.
12940   if (VT == MVT::f32 && Subtarget->hasSSE1())
12941     RecipOp = "divf";
12942   else if ((VT == MVT::v4f32 && Subtarget->hasSSE1()) ||
12943            (VT == MVT::v8f32 && Subtarget->hasAVX()))
12944     RecipOp = "vec-divf";
12945   else
12946     return SDValue();
12947   
12948   TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
12949   if (!Recips.isEnabled(RecipOp))
12950     return SDValue();
12951
12952   RefinementSteps = Recips.getRefinementSteps(RecipOp);
12953   return DCI.DAG.getNode(X86ISD::FRCP, SDLoc(Op), VT, Op);
12954 }
12955
12956 /// If we have at least two divisions that use the same divisor, convert to
12957 /// multplication by a reciprocal. This may need to be adjusted for a given
12958 /// CPU if a division's cost is not at least twice the cost of a multiplication.
12959 /// This is because we still need one division to calculate the reciprocal and
12960 /// then we need two multiplies by that reciprocal as replacements for the
12961 /// original divisions.
12962 bool X86TargetLowering::combineRepeatedFPDivisors(unsigned NumUsers) const {
12963   return NumUsers > 1;
12964 }
12965
12966 static bool isAllOnes(SDValue V) {
12967   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
12968   return C && C->isAllOnesValue();
12969 }
12970
12971 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
12972 /// if it's possible.
12973 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
12974                                      SDLoc dl, SelectionDAG &DAG) const {
12975   SDValue Op0 = And.getOperand(0);
12976   SDValue Op1 = And.getOperand(1);
12977   if (Op0.getOpcode() == ISD::TRUNCATE)
12978     Op0 = Op0.getOperand(0);
12979   if (Op1.getOpcode() == ISD::TRUNCATE)
12980     Op1 = Op1.getOperand(0);
12981
12982   SDValue LHS, RHS;
12983   if (Op1.getOpcode() == ISD::SHL)
12984     std::swap(Op0, Op1);
12985   if (Op0.getOpcode() == ISD::SHL) {
12986     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
12987       if (And00C->getZExtValue() == 1) {
12988         // If we looked past a truncate, check that it's only truncating away
12989         // known zeros.
12990         unsigned BitWidth = Op0.getValueSizeInBits();
12991         unsigned AndBitWidth = And.getValueSizeInBits();
12992         if (BitWidth > AndBitWidth) {
12993           APInt Zeros, Ones;
12994           DAG.computeKnownBits(Op0, Zeros, Ones);
12995           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
12996             return SDValue();
12997         }
12998         LHS = Op1;
12999         RHS = Op0.getOperand(1);
13000       }
13001   } else if (Op1.getOpcode() == ISD::Constant) {
13002     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
13003     uint64_t AndRHSVal = AndRHS->getZExtValue();
13004     SDValue AndLHS = Op0;
13005
13006     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
13007       LHS = AndLHS.getOperand(0);
13008       RHS = AndLHS.getOperand(1);
13009     }
13010
13011     // Use BT if the immediate can't be encoded in a TEST instruction.
13012     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
13013       LHS = AndLHS;
13014       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), dl, LHS.getValueType());
13015     }
13016   }
13017
13018   if (LHS.getNode()) {
13019     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
13020     // instruction.  Since the shift amount is in-range-or-undefined, we know
13021     // that doing a bittest on the i32 value is ok.  We extend to i32 because
13022     // the encoding for the i16 version is larger than the i32 version.
13023     // Also promote i16 to i32 for performance / code size reason.
13024     if (LHS.getValueType() == MVT::i8 ||
13025         LHS.getValueType() == MVT::i16)
13026       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
13027
13028     // If the operand types disagree, extend the shift amount to match.  Since
13029     // BT ignores high bits (like shifts) we can use anyextend.
13030     if (LHS.getValueType() != RHS.getValueType())
13031       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
13032
13033     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
13034     X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
13035     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13036                        DAG.getConstant(Cond, dl, MVT::i8), BT);
13037   }
13038
13039   return SDValue();
13040 }
13041
13042 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
13043 /// mask CMPs.
13044 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
13045                               SDValue &Op1) {
13046   unsigned SSECC;
13047   bool Swap = false;
13048
13049   // SSE Condition code mapping:
13050   //  0 - EQ
13051   //  1 - LT
13052   //  2 - LE
13053   //  3 - UNORD
13054   //  4 - NEQ
13055   //  5 - NLT
13056   //  6 - NLE
13057   //  7 - ORD
13058   switch (SetCCOpcode) {
13059   default: llvm_unreachable("Unexpected SETCC condition");
13060   case ISD::SETOEQ:
13061   case ISD::SETEQ:  SSECC = 0; break;
13062   case ISD::SETOGT:
13063   case ISD::SETGT:  Swap = true; // Fallthrough
13064   case ISD::SETLT:
13065   case ISD::SETOLT: SSECC = 1; break;
13066   case ISD::SETOGE:
13067   case ISD::SETGE:  Swap = true; // Fallthrough
13068   case ISD::SETLE:
13069   case ISD::SETOLE: SSECC = 2; break;
13070   case ISD::SETUO:  SSECC = 3; break;
13071   case ISD::SETUNE:
13072   case ISD::SETNE:  SSECC = 4; break;
13073   case ISD::SETULE: Swap = true; // Fallthrough
13074   case ISD::SETUGE: SSECC = 5; break;
13075   case ISD::SETULT: Swap = true; // Fallthrough
13076   case ISD::SETUGT: SSECC = 6; break;
13077   case ISD::SETO:   SSECC = 7; break;
13078   case ISD::SETUEQ:
13079   case ISD::SETONE: SSECC = 8; break;
13080   }
13081   if (Swap)
13082     std::swap(Op0, Op1);
13083
13084   return SSECC;
13085 }
13086
13087 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
13088 // ones, and then concatenate the result back.
13089 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
13090   MVT VT = Op.getSimpleValueType();
13091
13092   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
13093          "Unsupported value type for operation");
13094
13095   unsigned NumElems = VT.getVectorNumElements();
13096   SDLoc dl(Op);
13097   SDValue CC = Op.getOperand(2);
13098
13099   // Extract the LHS vectors
13100   SDValue LHS = Op.getOperand(0);
13101   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
13102   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
13103
13104   // Extract the RHS vectors
13105   SDValue RHS = Op.getOperand(1);
13106   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
13107   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
13108
13109   // Issue the operation on the smaller types and concatenate the result back
13110   MVT EltVT = VT.getVectorElementType();
13111   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13112   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
13113                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
13114                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
13115 }
13116
13117 static SDValue LowerBoolVSETCC_AVX512(SDValue Op, SelectionDAG &DAG) {
13118   SDValue Op0 = Op.getOperand(0);
13119   SDValue Op1 = Op.getOperand(1);
13120   SDValue CC = Op.getOperand(2);
13121   MVT VT = Op.getSimpleValueType();
13122   SDLoc dl(Op);
13123
13124   assert(Op0.getValueType().getVectorElementType() == MVT::i1 &&
13125          "Unexpected type for boolean compare operation");
13126   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13127   SDValue NotOp0 = DAG.getNode(ISD::XOR, dl, VT, Op0,
13128                                DAG.getConstant(-1, dl, VT));
13129   SDValue NotOp1 = DAG.getNode(ISD::XOR, dl, VT, Op1,
13130                                DAG.getConstant(-1, dl, VT));
13131   switch (SetCCOpcode) {
13132   default: llvm_unreachable("Unexpected SETCC condition");
13133   case ISD::SETNE:
13134     // (x != y) -> ~(x ^ y)
13135     return DAG.getNode(ISD::XOR, dl, VT,
13136                        DAG.getNode(ISD::XOR, dl, VT, Op0, Op1),
13137                        DAG.getConstant(-1, dl, VT));
13138   case ISD::SETEQ:
13139     // (x == y) -> (x ^ y)
13140     return DAG.getNode(ISD::XOR, dl, VT, Op0, Op1);
13141   case ISD::SETUGT:
13142   case ISD::SETGT:
13143     // (x > y) -> (x & ~y)
13144     return DAG.getNode(ISD::AND, dl, VT, Op0, NotOp1);
13145   case ISD::SETULT:
13146   case ISD::SETLT:
13147     // (x < y) -> (~x & y)
13148     return DAG.getNode(ISD::AND, dl, VT, NotOp0, Op1);
13149   case ISD::SETULE:
13150   case ISD::SETLE:
13151     // (x <= y) -> (~x | y)
13152     return DAG.getNode(ISD::OR, dl, VT, NotOp0, Op1);
13153   case ISD::SETUGE:
13154   case ISD::SETGE:
13155     // (x >=y) -> (x | ~y)
13156     return DAG.getNode(ISD::OR, dl, VT, Op0, NotOp1);
13157   }
13158 }
13159
13160 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
13161                                      const X86Subtarget *Subtarget) {
13162   SDValue Op0 = Op.getOperand(0);
13163   SDValue Op1 = Op.getOperand(1);
13164   SDValue CC = Op.getOperand(2);
13165   MVT VT = Op.getSimpleValueType();
13166   SDLoc dl(Op);
13167
13168   assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 8 &&
13169          Op.getValueType().getScalarType() == MVT::i1 &&
13170          "Cannot set masked compare for this operation");
13171
13172   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13173   unsigned  Opc = 0;
13174   bool Unsigned = false;
13175   bool Swap = false;
13176   unsigned SSECC;
13177   switch (SetCCOpcode) {
13178   default: llvm_unreachable("Unexpected SETCC condition");
13179   case ISD::SETNE:  SSECC = 4; break;
13180   case ISD::SETEQ:  Opc = X86ISD::PCMPEQM; break;
13181   case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
13182   case ISD::SETLT:  Swap = true; //fall-through
13183   case ISD::SETGT:  Opc = X86ISD::PCMPGTM; break;
13184   case ISD::SETULT: SSECC = 1; Unsigned = true; break;
13185   case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
13186   case ISD::SETGE:  Swap = true; SSECC = 2; break; // LE + swap
13187   case ISD::SETULE: Unsigned = true; //fall-through
13188   case ISD::SETLE:  SSECC = 2; break;
13189   }
13190
13191   if (Swap)
13192     std::swap(Op0, Op1);
13193   if (Opc)
13194     return DAG.getNode(Opc, dl, VT, Op0, Op1);
13195   Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
13196   return DAG.getNode(Opc, dl, VT, Op0, Op1,
13197                      DAG.getConstant(SSECC, dl, MVT::i8));
13198 }
13199
13200 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
13201 /// operand \p Op1.  If non-trivial (for example because it's not constant)
13202 /// return an empty value.
13203 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
13204 {
13205   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
13206   if (!BV)
13207     return SDValue();
13208
13209   MVT VT = Op1.getSimpleValueType();
13210   MVT EVT = VT.getVectorElementType();
13211   unsigned n = VT.getVectorNumElements();
13212   SmallVector<SDValue, 8> ULTOp1;
13213
13214   for (unsigned i = 0; i < n; ++i) {
13215     ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
13216     if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
13217       return SDValue();
13218
13219     // Avoid underflow.
13220     APInt Val = Elt->getAPIntValue();
13221     if (Val == 0)
13222       return SDValue();
13223
13224     ULTOp1.push_back(DAG.getConstant(Val - 1, dl, EVT));
13225   }
13226
13227   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
13228 }
13229
13230 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
13231                            SelectionDAG &DAG) {
13232   SDValue Op0 = Op.getOperand(0);
13233   SDValue Op1 = Op.getOperand(1);
13234   SDValue CC = Op.getOperand(2);
13235   MVT VT = Op.getSimpleValueType();
13236   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13237   bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
13238   SDLoc dl(Op);
13239
13240   if (isFP) {
13241 #ifndef NDEBUG
13242     MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
13243     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
13244 #endif
13245
13246     unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
13247     unsigned Opc = X86ISD::CMPP;
13248     if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
13249       assert(VT.getVectorNumElements() <= 16);
13250       Opc = X86ISD::CMPM;
13251     }
13252     // In the two special cases we can't handle, emit two comparisons.
13253     if (SSECC == 8) {
13254       unsigned CC0, CC1;
13255       unsigned CombineOpc;
13256       if (SetCCOpcode == ISD::SETUEQ) {
13257         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
13258       } else {
13259         assert(SetCCOpcode == ISD::SETONE);
13260         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
13261       }
13262
13263       SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
13264                                  DAG.getConstant(CC0, dl, MVT::i8));
13265       SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
13266                                  DAG.getConstant(CC1, dl, MVT::i8));
13267       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
13268     }
13269     // Handle all other FP comparisons here.
13270     return DAG.getNode(Opc, dl, VT, Op0, Op1,
13271                        DAG.getConstant(SSECC, dl, MVT::i8));
13272   }
13273
13274   // Break 256-bit integer vector compare into smaller ones.
13275   if (VT.is256BitVector() && !Subtarget->hasInt256())
13276     return Lower256IntVSETCC(Op, DAG);
13277
13278   EVT OpVT = Op1.getValueType();
13279   if (OpVT.getVectorElementType() == MVT::i1)
13280     return LowerBoolVSETCC_AVX512(Op, DAG);
13281
13282   bool MaskResult = (VT.getVectorElementType() == MVT::i1);
13283   if (Subtarget->hasAVX512()) {
13284     if (Op1.getValueType().is512BitVector() ||
13285         (Subtarget->hasBWI() && Subtarget->hasVLX()) ||
13286         (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
13287       return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
13288
13289     // In AVX-512 architecture setcc returns mask with i1 elements,
13290     // But there is no compare instruction for i8 and i16 elements in KNL.
13291     // We are not talking about 512-bit operands in this case, these
13292     // types are illegal.
13293     if (MaskResult &&
13294         (OpVT.getVectorElementType().getSizeInBits() < 32 &&
13295          OpVT.getVectorElementType().getSizeInBits() >= 8))
13296       return DAG.getNode(ISD::TRUNCATE, dl, VT,
13297                          DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
13298   }
13299
13300   // We are handling one of the integer comparisons here.  Since SSE only has
13301   // GT and EQ comparisons for integer, swapping operands and multiple
13302   // operations may be required for some comparisons.
13303   unsigned Opc;
13304   bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
13305   bool Subus = false;
13306
13307   switch (SetCCOpcode) {
13308   default: llvm_unreachable("Unexpected SETCC condition");
13309   case ISD::SETNE:  Invert = true;
13310   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
13311   case ISD::SETLT:  Swap = true;
13312   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
13313   case ISD::SETGE:  Swap = true;
13314   case ISD::SETLE:  Opc = X86ISD::PCMPGT;
13315                     Invert = true; break;
13316   case ISD::SETULT: Swap = true;
13317   case ISD::SETUGT: Opc = X86ISD::PCMPGT;
13318                     FlipSigns = true; break;
13319   case ISD::SETUGE: Swap = true;
13320   case ISD::SETULE: Opc = X86ISD::PCMPGT;
13321                     FlipSigns = true; Invert = true; break;
13322   }
13323
13324   // Special case: Use min/max operations for SETULE/SETUGE
13325   MVT VET = VT.getVectorElementType();
13326   bool hasMinMax =
13327        (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
13328     || (Subtarget->hasSSE2()  && (VET == MVT::i8));
13329
13330   if (hasMinMax) {
13331     switch (SetCCOpcode) {
13332     default: break;
13333     case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
13334     case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
13335     }
13336
13337     if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
13338   }
13339
13340   bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
13341   if (!MinMax && hasSubus) {
13342     // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
13343     // Op0 u<= Op1:
13344     //   t = psubus Op0, Op1
13345     //   pcmpeq t, <0..0>
13346     switch (SetCCOpcode) {
13347     default: break;
13348     case ISD::SETULT: {
13349       // If the comparison is against a constant we can turn this into a
13350       // setule.  With psubus, setule does not require a swap.  This is
13351       // beneficial because the constant in the register is no longer
13352       // destructed as the destination so it can be hoisted out of a loop.
13353       // Only do this pre-AVX since vpcmp* is no longer destructive.
13354       if (Subtarget->hasAVX())
13355         break;
13356       SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
13357       if (ULEOp1.getNode()) {
13358         Op1 = ULEOp1;
13359         Subus = true; Invert = false; Swap = false;
13360       }
13361       break;
13362     }
13363     // Psubus is better than flip-sign because it requires no inversion.
13364     case ISD::SETUGE: Subus = true; Invert = false; Swap = true;  break;
13365     case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
13366     }
13367
13368     if (Subus) {
13369       Opc = X86ISD::SUBUS;
13370       FlipSigns = false;
13371     }
13372   }
13373
13374   if (Swap)
13375     std::swap(Op0, Op1);
13376
13377   // Check that the operation in question is available (most are plain SSE2,
13378   // but PCMPGTQ and PCMPEQQ have different requirements).
13379   if (VT == MVT::v2i64) {
13380     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
13381       assert(Subtarget->hasSSE2() && "Don't know how to lower!");
13382
13383       // First cast everything to the right type.
13384       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
13385       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
13386
13387       // Since SSE has no unsigned integer comparisons, we need to flip the sign
13388       // bits of the inputs before performing those operations. The lower
13389       // compare is always unsigned.
13390       SDValue SB;
13391       if (FlipSigns) {
13392         SB = DAG.getConstant(0x80000000U, dl, MVT::v4i32);
13393       } else {
13394         SDValue Sign = DAG.getConstant(0x80000000U, dl, MVT::i32);
13395         SDValue Zero = DAG.getConstant(0x00000000U, dl, MVT::i32);
13396         SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
13397                          Sign, Zero, Sign, Zero);
13398       }
13399       Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
13400       Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
13401
13402       // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
13403       SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
13404       SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
13405
13406       // Create masks for only the low parts/high parts of the 64 bit integers.
13407       static const int MaskHi[] = { 1, 1, 3, 3 };
13408       static const int MaskLo[] = { 0, 0, 2, 2 };
13409       SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
13410       SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
13411       SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
13412
13413       SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
13414       Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
13415
13416       if (Invert)
13417         Result = DAG.getNOT(dl, Result, MVT::v4i32);
13418
13419       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
13420     }
13421
13422     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
13423       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
13424       // pcmpeqd + pshufd + pand.
13425       assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
13426
13427       // First cast everything to the right type.
13428       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
13429       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
13430
13431       // Do the compare.
13432       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
13433
13434       // Make sure the lower and upper halves are both all-ones.
13435       static const int Mask[] = { 1, 0, 3, 2 };
13436       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
13437       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
13438
13439       if (Invert)
13440         Result = DAG.getNOT(dl, Result, MVT::v4i32);
13441
13442       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
13443     }
13444   }
13445
13446   // Since SSE has no unsigned integer comparisons, we need to flip the sign
13447   // bits of the inputs before performing those operations.
13448   if (FlipSigns) {
13449     EVT EltVT = VT.getVectorElementType();
13450     SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), dl,
13451                                  VT);
13452     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
13453     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
13454   }
13455
13456   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
13457
13458   // If the logical-not of the result is required, perform that now.
13459   if (Invert)
13460     Result = DAG.getNOT(dl, Result, VT);
13461
13462   if (MinMax)
13463     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
13464
13465   if (Subus)
13466     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
13467                          getZeroVector(VT, Subtarget, DAG, dl));
13468
13469   return Result;
13470 }
13471
13472 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
13473
13474   MVT VT = Op.getSimpleValueType();
13475
13476   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
13477
13478   assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
13479          && "SetCC type must be 8-bit or 1-bit integer");
13480   SDValue Op0 = Op.getOperand(0);
13481   SDValue Op1 = Op.getOperand(1);
13482   SDLoc dl(Op);
13483   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
13484
13485   // Optimize to BT if possible.
13486   // Lower (X & (1 << N)) == 0 to BT(X, N).
13487   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
13488   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
13489   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
13490       Op1.getOpcode() == ISD::Constant &&
13491       cast<ConstantSDNode>(Op1)->isNullValue() &&
13492       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13493     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
13494     if (NewSetCC.getNode()) {
13495       if (VT == MVT::i1)
13496         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewSetCC);
13497       return NewSetCC;
13498     }
13499   }
13500
13501   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
13502   // these.
13503   if (Op1.getOpcode() == ISD::Constant &&
13504       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
13505        cast<ConstantSDNode>(Op1)->isNullValue()) &&
13506       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13507
13508     // If the input is a setcc, then reuse the input setcc or use a new one with
13509     // the inverted condition.
13510     if (Op0.getOpcode() == X86ISD::SETCC) {
13511       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
13512       bool Invert = (CC == ISD::SETNE) ^
13513         cast<ConstantSDNode>(Op1)->isNullValue();
13514       if (!Invert)
13515         return Op0;
13516
13517       CCode = X86::GetOppositeBranchCondition(CCode);
13518       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13519                                   DAG.getConstant(CCode, dl, MVT::i8),
13520                                   Op0.getOperand(1));
13521       if (VT == MVT::i1)
13522         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
13523       return SetCC;
13524     }
13525   }
13526   if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
13527       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
13528       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13529
13530     ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
13531     return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, dl, MVT::i1), NewCC);
13532   }
13533
13534   bool isFP = Op1.getSimpleValueType().isFloatingPoint();
13535   unsigned X86CC = TranslateX86CC(CC, dl, isFP, Op0, Op1, DAG);
13536   if (X86CC == X86::COND_INVALID)
13537     return SDValue();
13538
13539   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
13540   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
13541   SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13542                               DAG.getConstant(X86CC, dl, MVT::i8), EFLAGS);
13543   if (VT == MVT::i1)
13544     return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
13545   return SetCC;
13546 }
13547
13548 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
13549 static bool isX86LogicalCmp(SDValue Op) {
13550   unsigned Opc = Op.getNode()->getOpcode();
13551   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
13552       Opc == X86ISD::SAHF)
13553     return true;
13554   if (Op.getResNo() == 1 &&
13555       (Opc == X86ISD::ADD ||
13556        Opc == X86ISD::SUB ||
13557        Opc == X86ISD::ADC ||
13558        Opc == X86ISD::SBB ||
13559        Opc == X86ISD::SMUL ||
13560        Opc == X86ISD::UMUL ||
13561        Opc == X86ISD::INC ||
13562        Opc == X86ISD::DEC ||
13563        Opc == X86ISD::OR ||
13564        Opc == X86ISD::XOR ||
13565        Opc == X86ISD::AND))
13566     return true;
13567
13568   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
13569     return true;
13570
13571   return false;
13572 }
13573
13574 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
13575   if (V.getOpcode() != ISD::TRUNCATE)
13576     return false;
13577
13578   SDValue VOp0 = V.getOperand(0);
13579   unsigned InBits = VOp0.getValueSizeInBits();
13580   unsigned Bits = V.getValueSizeInBits();
13581   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
13582 }
13583
13584 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
13585   bool addTest = true;
13586   SDValue Cond  = Op.getOperand(0);
13587   SDValue Op1 = Op.getOperand(1);
13588   SDValue Op2 = Op.getOperand(2);
13589   SDLoc DL(Op);
13590   EVT VT = Op1.getValueType();
13591   SDValue CC;
13592
13593   // Lower FP selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
13594   // are available or VBLENDV if AVX is available.
13595   // Otherwise FP cmovs get lowered into a less efficient branch sequence later.
13596   if (Cond.getOpcode() == ISD::SETCC &&
13597       ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
13598        (Subtarget->hasSSE1() && VT == MVT::f32)) &&
13599       VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
13600     SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
13601     int SSECC = translateX86FSETCC(
13602         cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
13603
13604     if (SSECC != 8) {
13605       if (Subtarget->hasAVX512()) {
13606         SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
13607                                   DAG.getConstant(SSECC, DL, MVT::i8));
13608         return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
13609       }
13610
13611       SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
13612                                 DAG.getConstant(SSECC, DL, MVT::i8));
13613
13614       // If we have AVX, we can use a variable vector select (VBLENDV) instead
13615       // of 3 logic instructions for size savings and potentially speed.
13616       // Unfortunately, there is no scalar form of VBLENDV.
13617
13618       // If either operand is a constant, don't try this. We can expect to
13619       // optimize away at least one of the logic instructions later in that
13620       // case, so that sequence would be faster than a variable blend.
13621
13622       // BLENDV was introduced with SSE 4.1, but the 2 register form implicitly
13623       // uses XMM0 as the selection register. That may need just as many
13624       // instructions as the AND/ANDN/OR sequence due to register moves, so
13625       // don't bother.
13626
13627       if (Subtarget->hasAVX() &&
13628           !isa<ConstantFPSDNode>(Op1) && !isa<ConstantFPSDNode>(Op2)) {
13629
13630         // Convert to vectors, do a VSELECT, and convert back to scalar.
13631         // All of the conversions should be optimized away.
13632
13633         EVT VecVT = VT == MVT::f32 ? MVT::v4f32 : MVT::v2f64;
13634         SDValue VOp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op1);
13635         SDValue VOp2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op2);
13636         SDValue VCmp = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Cmp);
13637
13638         EVT VCmpVT = VT == MVT::f32 ? MVT::v4i32 : MVT::v2i64;
13639         VCmp = DAG.getNode(ISD::BITCAST, DL, VCmpVT, VCmp);
13640
13641         SDValue VSel = DAG.getNode(ISD::VSELECT, DL, VecVT, VCmp, VOp1, VOp2);
13642
13643         return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
13644                            VSel, DAG.getIntPtrConstant(0, DL));
13645       }
13646       SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
13647       SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
13648       return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
13649     }
13650   }
13651
13652     if (VT.isVector() && VT.getScalarType() == MVT::i1) {
13653       SDValue Op1Scalar;
13654       if (ISD::isBuildVectorOfConstantSDNodes(Op1.getNode()))
13655         Op1Scalar = ConvertI1VectorToInterger(Op1, DAG);
13656       else if (Op1.getOpcode() == ISD::BITCAST && Op1.getOperand(0))
13657         Op1Scalar = Op1.getOperand(0);
13658       SDValue Op2Scalar;
13659       if (ISD::isBuildVectorOfConstantSDNodes(Op2.getNode()))
13660         Op2Scalar = ConvertI1VectorToInterger(Op2, DAG);
13661       else if (Op2.getOpcode() == ISD::BITCAST && Op2.getOperand(0))
13662         Op2Scalar = Op2.getOperand(0);
13663       if (Op1Scalar.getNode() && Op2Scalar.getNode()) {
13664         SDValue newSelect = DAG.getNode(ISD::SELECT, DL, 
13665                                         Op1Scalar.getValueType(),
13666                                         Cond, Op1Scalar, Op2Scalar);
13667         if (newSelect.getValueSizeInBits() == VT.getSizeInBits())
13668           return DAG.getNode(ISD::BITCAST, DL, VT, newSelect);
13669         SDValue ExtVec = DAG.getNode(ISD::BITCAST, DL, MVT::v8i1, newSelect);
13670         return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, ExtVec,
13671                            DAG.getIntPtrConstant(0, DL));
13672     }
13673   }
13674
13675   if (VT == MVT::v4i1 || VT == MVT::v2i1) {
13676     SDValue zeroConst = DAG.getIntPtrConstant(0, DL);
13677     Op1 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
13678                       DAG.getUNDEF(MVT::v8i1), Op1, zeroConst);
13679     Op2 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
13680                       DAG.getUNDEF(MVT::v8i1), Op2, zeroConst);
13681     SDValue newSelect = DAG.getNode(ISD::SELECT, DL, MVT::v8i1,
13682                                     Cond, Op1, Op2);
13683     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, newSelect, zeroConst);
13684   }
13685
13686   if (Cond.getOpcode() == ISD::SETCC) {
13687     SDValue NewCond = LowerSETCC(Cond, DAG);
13688     if (NewCond.getNode())
13689       Cond = NewCond;
13690   }
13691
13692   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
13693   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
13694   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
13695   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
13696   if (Cond.getOpcode() == X86ISD::SETCC &&
13697       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
13698       isZero(Cond.getOperand(1).getOperand(1))) {
13699     SDValue Cmp = Cond.getOperand(1);
13700
13701     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
13702
13703     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
13704         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
13705       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
13706
13707       SDValue CmpOp0 = Cmp.getOperand(0);
13708       // Apply further optimizations for special cases
13709       // (select (x != 0), -1, 0) -> neg & sbb
13710       // (select (x == 0), 0, -1) -> neg & sbb
13711       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
13712         if (YC->isNullValue() &&
13713             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
13714           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
13715           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
13716                                     DAG.getConstant(0, DL,
13717                                                     CmpOp0.getValueType()),
13718                                     CmpOp0);
13719           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
13720                                     DAG.getConstant(X86::COND_B, DL, MVT::i8),
13721                                     SDValue(Neg.getNode(), 1));
13722           return Res;
13723         }
13724
13725       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
13726                         CmpOp0, DAG.getConstant(1, DL, CmpOp0.getValueType()));
13727       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
13728
13729       SDValue Res =   // Res = 0 or -1.
13730         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
13731                     DAG.getConstant(X86::COND_B, DL, MVT::i8), Cmp);
13732
13733       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
13734         Res = DAG.getNOT(DL, Res, Res.getValueType());
13735
13736       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
13737       if (!N2C || !N2C->isNullValue())
13738         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
13739       return Res;
13740     }
13741   }
13742
13743   // Look past (and (setcc_carry (cmp ...)), 1).
13744   if (Cond.getOpcode() == ISD::AND &&
13745       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
13746     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
13747     if (C && C->getAPIntValue() == 1)
13748       Cond = Cond.getOperand(0);
13749   }
13750
13751   // If condition flag is set by a X86ISD::CMP, then use it as the condition
13752   // setting operand in place of the X86ISD::SETCC.
13753   unsigned CondOpcode = Cond.getOpcode();
13754   if (CondOpcode == X86ISD::SETCC ||
13755       CondOpcode == X86ISD::SETCC_CARRY) {
13756     CC = Cond.getOperand(0);
13757
13758     SDValue Cmp = Cond.getOperand(1);
13759     unsigned Opc = Cmp.getOpcode();
13760     MVT VT = Op.getSimpleValueType();
13761
13762     bool IllegalFPCMov = false;
13763     if (VT.isFloatingPoint() && !VT.isVector() &&
13764         !isScalarFPTypeInSSEReg(VT))  // FPStack?
13765       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
13766
13767     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
13768         Opc == X86ISD::BT) { // FIXME
13769       Cond = Cmp;
13770       addTest = false;
13771     }
13772   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
13773              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
13774              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
13775               Cond.getOperand(0).getValueType() != MVT::i8)) {
13776     SDValue LHS = Cond.getOperand(0);
13777     SDValue RHS = Cond.getOperand(1);
13778     unsigned X86Opcode;
13779     unsigned X86Cond;
13780     SDVTList VTs;
13781     switch (CondOpcode) {
13782     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
13783     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
13784     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
13785     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
13786     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
13787     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
13788     default: llvm_unreachable("unexpected overflowing operator");
13789     }
13790     if (CondOpcode == ISD::UMULO)
13791       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
13792                           MVT::i32);
13793     else
13794       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
13795
13796     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
13797
13798     if (CondOpcode == ISD::UMULO)
13799       Cond = X86Op.getValue(2);
13800     else
13801       Cond = X86Op.getValue(1);
13802
13803     CC = DAG.getConstant(X86Cond, DL, MVT::i8);
13804     addTest = false;
13805   }
13806
13807   if (addTest) {
13808     // Look pass the truncate if the high bits are known zero.
13809     if (isTruncWithZeroHighBitsInput(Cond, DAG))
13810         Cond = Cond.getOperand(0);
13811
13812     // We know the result of AND is compared against zero. Try to match
13813     // it to BT.
13814     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
13815       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
13816       if (NewSetCC.getNode()) {
13817         CC = NewSetCC.getOperand(0);
13818         Cond = NewSetCC.getOperand(1);
13819         addTest = false;
13820       }
13821     }
13822   }
13823
13824   if (addTest) {
13825     CC = DAG.getConstant(X86::COND_NE, DL, MVT::i8);
13826     Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
13827   }
13828
13829   // a <  b ? -1 :  0 -> RES = ~setcc_carry
13830   // a <  b ?  0 : -1 -> RES = setcc_carry
13831   // a >= b ? -1 :  0 -> RES = setcc_carry
13832   // a >= b ?  0 : -1 -> RES = ~setcc_carry
13833   if (Cond.getOpcode() == X86ISD::SUB) {
13834     Cond = ConvertCmpIfNecessary(Cond, DAG);
13835     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
13836
13837     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
13838         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
13839       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
13840                                 DAG.getConstant(X86::COND_B, DL, MVT::i8),
13841                                 Cond);
13842       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
13843         return DAG.getNOT(DL, Res, Res.getValueType());
13844       return Res;
13845     }
13846   }
13847
13848   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
13849   // widen the cmov and push the truncate through. This avoids introducing a new
13850   // branch during isel and doesn't add any extensions.
13851   if (Op.getValueType() == MVT::i8 &&
13852       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
13853     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
13854     if (T1.getValueType() == T2.getValueType() &&
13855         // Blacklist CopyFromReg to avoid partial register stalls.
13856         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
13857       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
13858       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
13859       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
13860     }
13861   }
13862
13863   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
13864   // condition is true.
13865   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
13866   SDValue Ops[] = { Op2, Op1, CC, Cond };
13867   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
13868 }
13869
13870 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op, const X86Subtarget *Subtarget,
13871                                        SelectionDAG &DAG) {
13872   MVT VT = Op->getSimpleValueType(0);
13873   SDValue In = Op->getOperand(0);
13874   MVT InVT = In.getSimpleValueType();
13875   MVT VTElt = VT.getVectorElementType();
13876   MVT InVTElt = InVT.getVectorElementType();
13877   SDLoc dl(Op);
13878
13879   // SKX processor
13880   if ((InVTElt == MVT::i1) &&
13881       (((Subtarget->hasBWI() && Subtarget->hasVLX() &&
13882         VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() <= 16)) ||
13883
13884        ((Subtarget->hasBWI() && VT.is512BitVector() &&
13885         VTElt.getSizeInBits() <= 16)) ||
13886
13887        ((Subtarget->hasDQI() && Subtarget->hasVLX() &&
13888         VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() >= 32)) ||
13889
13890        ((Subtarget->hasDQI() && VT.is512BitVector() &&
13891         VTElt.getSizeInBits() >= 32))))
13892     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
13893
13894   unsigned int NumElts = VT.getVectorNumElements();
13895
13896   if (NumElts != 8 && NumElts != 16)
13897     return SDValue();
13898
13899   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1) {
13900     if (In.getOpcode() == X86ISD::VSEXT || In.getOpcode() == X86ISD::VZEXT)
13901       return DAG.getNode(In.getOpcode(), dl, VT, In.getOperand(0));
13902     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
13903   }
13904
13905   assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
13906   MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
13907   SDValue NegOne =
13908    DAG.getConstant(APInt::getAllOnesValue(ExtVT.getScalarSizeInBits()), dl,
13909                    ExtVT);
13910   SDValue Zero =
13911    DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), dl, ExtVT);
13912
13913   SDValue V = DAG.getNode(ISD::VSELECT, dl, ExtVT, In, NegOne, Zero);
13914   if (VT.is512BitVector())
13915     return V;
13916   return DAG.getNode(X86ISD::VTRUNC, dl, VT, V);
13917 }
13918
13919 static SDValue LowerSIGN_EXTEND_VECTOR_INREG(SDValue Op,
13920                                              const X86Subtarget *Subtarget,
13921                                              SelectionDAG &DAG) {
13922   SDValue In = Op->getOperand(0);
13923   MVT VT = Op->getSimpleValueType(0);
13924   MVT InVT = In.getSimpleValueType();
13925   assert(VT.getSizeInBits() == InVT.getSizeInBits());
13926
13927   MVT InSVT = InVT.getScalarType();
13928   assert(VT.getScalarType().getScalarSizeInBits() > InSVT.getScalarSizeInBits());
13929
13930   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
13931     return SDValue();
13932   if (InSVT != MVT::i32 && InSVT != MVT::i16 && InSVT != MVT::i8)
13933     return SDValue();
13934
13935   SDLoc dl(Op);
13936
13937   // SSE41 targets can use the pmovsx* instructions directly.
13938   if (Subtarget->hasSSE41())
13939     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
13940
13941   // pre-SSE41 targets unpack lower lanes and then sign-extend using SRAI.
13942   SDValue Curr = In;
13943   MVT CurrVT = InVT;
13944
13945   // As SRAI is only available on i16/i32 types, we expand only up to i32
13946   // and handle i64 separately.
13947   while (CurrVT != VT && CurrVT.getScalarType() != MVT::i32) {
13948     Curr = DAG.getNode(X86ISD::UNPCKL, dl, CurrVT, DAG.getUNDEF(CurrVT), Curr);
13949     MVT CurrSVT = MVT::getIntegerVT(CurrVT.getScalarSizeInBits() * 2);
13950     CurrVT = MVT::getVectorVT(CurrSVT, CurrVT.getVectorNumElements() / 2);
13951     Curr = DAG.getNode(ISD::BITCAST, dl, CurrVT, Curr);
13952   }
13953
13954   SDValue SignExt = Curr;
13955   if (CurrVT != InVT) {
13956     unsigned SignExtShift =
13957         CurrVT.getScalarSizeInBits() - InSVT.getScalarSizeInBits();
13958     SignExt = DAG.getNode(X86ISD::VSRAI, dl, CurrVT, Curr,
13959                           DAG.getConstant(SignExtShift, dl, MVT::i8));
13960   }
13961
13962   if (CurrVT == VT)
13963     return SignExt;
13964
13965   if (VT == MVT::v2i64 && CurrVT == MVT::v4i32) {
13966     SDValue Sign = DAG.getNode(X86ISD::VSRAI, dl, CurrVT, Curr,
13967                                DAG.getConstant(31, dl, MVT::i8));
13968     SDValue Ext = DAG.getVectorShuffle(CurrVT, dl, SignExt, Sign, {0, 4, 1, 5});
13969     return DAG.getNode(ISD::BITCAST, dl, VT, Ext);
13970   }
13971
13972   return SDValue();
13973 }
13974
13975 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
13976                                 SelectionDAG &DAG) {
13977   MVT VT = Op->getSimpleValueType(0);
13978   SDValue In = Op->getOperand(0);
13979   MVT InVT = In.getSimpleValueType();
13980   SDLoc dl(Op);
13981
13982   if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
13983     return LowerSIGN_EXTEND_AVX512(Op, Subtarget, DAG);
13984
13985   if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
13986       (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
13987       (VT != MVT::v16i16 || InVT != MVT::v16i8))
13988     return SDValue();
13989
13990   if (Subtarget->hasInt256())
13991     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
13992
13993   // Optimize vectors in AVX mode
13994   // Sign extend  v8i16 to v8i32 and
13995   //              v4i32 to v4i64
13996   //
13997   // Divide input vector into two parts
13998   // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
13999   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
14000   // concat the vectors to original VT
14001
14002   unsigned NumElems = InVT.getVectorNumElements();
14003   SDValue Undef = DAG.getUNDEF(InVT);
14004
14005   SmallVector<int,8> ShufMask1(NumElems, -1);
14006   for (unsigned i = 0; i != NumElems/2; ++i)
14007     ShufMask1[i] = i;
14008
14009   SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
14010
14011   SmallVector<int,8> ShufMask2(NumElems, -1);
14012   for (unsigned i = 0; i != NumElems/2; ++i)
14013     ShufMask2[i] = i + NumElems/2;
14014
14015   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
14016
14017   MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
14018                                 VT.getVectorNumElements()/2);
14019
14020   OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
14021   OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
14022
14023   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
14024 }
14025
14026 // Lower vector extended loads using a shuffle. If SSSE3 is not available we
14027 // may emit an illegal shuffle but the expansion is still better than scalar
14028 // code. We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise
14029 // we'll emit a shuffle and a arithmetic shift.
14030 // FIXME: Is the expansion actually better than scalar code? It doesn't seem so.
14031 // TODO: It is possible to support ZExt by zeroing the undef values during
14032 // the shuffle phase or after the shuffle.
14033 static SDValue LowerExtendedLoad(SDValue Op, const X86Subtarget *Subtarget,
14034                                  SelectionDAG &DAG) {
14035   MVT RegVT = Op.getSimpleValueType();
14036   assert(RegVT.isVector() && "We only custom lower vector sext loads.");
14037   assert(RegVT.isInteger() &&
14038          "We only custom lower integer vector sext loads.");
14039
14040   // Nothing useful we can do without SSE2 shuffles.
14041   assert(Subtarget->hasSSE2() && "We only custom lower sext loads with SSE2.");
14042
14043   LoadSDNode *Ld = cast<LoadSDNode>(Op.getNode());
14044   SDLoc dl(Ld);
14045   EVT MemVT = Ld->getMemoryVT();
14046   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14047   unsigned RegSz = RegVT.getSizeInBits();
14048
14049   ISD::LoadExtType Ext = Ld->getExtensionType();
14050
14051   assert((Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)
14052          && "Only anyext and sext are currently implemented.");
14053   assert(MemVT != RegVT && "Cannot extend to the same type");
14054   assert(MemVT.isVector() && "Must load a vector from memory");
14055
14056   unsigned NumElems = RegVT.getVectorNumElements();
14057   unsigned MemSz = MemVT.getSizeInBits();
14058   assert(RegSz > MemSz && "Register size must be greater than the mem size");
14059
14060   if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256()) {
14061     // The only way in which we have a legal 256-bit vector result but not the
14062     // integer 256-bit operations needed to directly lower a sextload is if we
14063     // have AVX1 but not AVX2. In that case, we can always emit a sextload to
14064     // a 128-bit vector and a normal sign_extend to 256-bits that should get
14065     // correctly legalized. We do this late to allow the canonical form of
14066     // sextload to persist throughout the rest of the DAG combiner -- it wants
14067     // to fold together any extensions it can, and so will fuse a sign_extend
14068     // of an sextload into a sextload targeting a wider value.
14069     SDValue Load;
14070     if (MemSz == 128) {
14071       // Just switch this to a normal load.
14072       assert(TLI.isTypeLegal(MemVT) && "If the memory type is a 128-bit type, "
14073                                        "it must be a legal 128-bit vector "
14074                                        "type!");
14075       Load = DAG.getLoad(MemVT, dl, Ld->getChain(), Ld->getBasePtr(),
14076                   Ld->getPointerInfo(), Ld->isVolatile(), Ld->isNonTemporal(),
14077                   Ld->isInvariant(), Ld->getAlignment());
14078     } else {
14079       assert(MemSz < 128 &&
14080              "Can't extend a type wider than 128 bits to a 256 bit vector!");
14081       // Do an sext load to a 128-bit vector type. We want to use the same
14082       // number of elements, but elements half as wide. This will end up being
14083       // recursively lowered by this routine, but will succeed as we definitely
14084       // have all the necessary features if we're using AVX1.
14085       EVT HalfEltVT =
14086           EVT::getIntegerVT(*DAG.getContext(), RegVT.getScalarSizeInBits() / 2);
14087       EVT HalfVecVT = EVT::getVectorVT(*DAG.getContext(), HalfEltVT, NumElems);
14088       Load =
14089           DAG.getExtLoad(Ext, dl, HalfVecVT, Ld->getChain(), Ld->getBasePtr(),
14090                          Ld->getPointerInfo(), MemVT, Ld->isVolatile(),
14091                          Ld->isNonTemporal(), Ld->isInvariant(),
14092                          Ld->getAlignment());
14093     }
14094
14095     // Replace chain users with the new chain.
14096     assert(Load->getNumValues() == 2 && "Loads must carry a chain!");
14097     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Load.getValue(1));
14098
14099     // Finally, do a normal sign-extend to the desired register.
14100     return DAG.getSExtOrTrunc(Load, dl, RegVT);
14101   }
14102
14103   // All sizes must be a power of two.
14104   assert(isPowerOf2_32(RegSz * MemSz * NumElems) &&
14105          "Non-power-of-two elements are not custom lowered!");
14106
14107   // Attempt to load the original value using scalar loads.
14108   // Find the largest scalar type that divides the total loaded size.
14109   MVT SclrLoadTy = MVT::i8;
14110   for (MVT Tp : MVT::integer_valuetypes()) {
14111     if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
14112       SclrLoadTy = Tp;
14113     }
14114   }
14115
14116   // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
14117   if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
14118       (64 <= MemSz))
14119     SclrLoadTy = MVT::f64;
14120
14121   // Calculate the number of scalar loads that we need to perform
14122   // in order to load our vector from memory.
14123   unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
14124
14125   assert((Ext != ISD::SEXTLOAD || NumLoads == 1) &&
14126          "Can only lower sext loads with a single scalar load!");
14127
14128   unsigned loadRegZize = RegSz;
14129   if (Ext == ISD::SEXTLOAD && RegSz >= 256)
14130     loadRegZize = 128;
14131
14132   // Represent our vector as a sequence of elements which are the
14133   // largest scalar that we can load.
14134   EVT LoadUnitVecVT = EVT::getVectorVT(
14135       *DAG.getContext(), SclrLoadTy, loadRegZize / SclrLoadTy.getSizeInBits());
14136
14137   // Represent the data using the same element type that is stored in
14138   // memory. In practice, we ''widen'' MemVT.
14139   EVT WideVecVT =
14140       EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
14141                        loadRegZize / MemVT.getScalarType().getSizeInBits());
14142
14143   assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
14144          "Invalid vector type");
14145
14146   // We can't shuffle using an illegal type.
14147   assert(TLI.isTypeLegal(WideVecVT) &&
14148          "We only lower types that form legal widened vector types");
14149
14150   SmallVector<SDValue, 8> Chains;
14151   SDValue Ptr = Ld->getBasePtr();
14152   SDValue Increment =
14153       DAG.getConstant(SclrLoadTy.getSizeInBits() / 8, dl, TLI.getPointerTy());
14154   SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
14155
14156   for (unsigned i = 0; i < NumLoads; ++i) {
14157     // Perform a single load.
14158     SDValue ScalarLoad =
14159         DAG.getLoad(SclrLoadTy, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
14160                     Ld->isVolatile(), Ld->isNonTemporal(), Ld->isInvariant(),
14161                     Ld->getAlignment());
14162     Chains.push_back(ScalarLoad.getValue(1));
14163     // Create the first element type using SCALAR_TO_VECTOR in order to avoid
14164     // another round of DAGCombining.
14165     if (i == 0)
14166       Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
14167     else
14168       Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
14169                         ScalarLoad, DAG.getIntPtrConstant(i, dl));
14170
14171     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
14172   }
14173
14174   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
14175
14176   // Bitcast the loaded value to a vector of the original element type, in
14177   // the size of the target vector type.
14178   SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
14179   unsigned SizeRatio = RegSz / MemSz;
14180
14181   if (Ext == ISD::SEXTLOAD) {
14182     // If we have SSE4.1, we can directly emit a VSEXT node.
14183     if (Subtarget->hasSSE41()) {
14184       SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
14185       DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14186       return Sext;
14187     }
14188
14189     // Otherwise we'll shuffle the small elements in the high bits of the
14190     // larger type and perform an arithmetic shift. If the shift is not legal
14191     // it's better to scalarize.
14192     assert(TLI.isOperationLegalOrCustom(ISD::SRA, RegVT) &&
14193            "We can't implement a sext load without an arithmetic right shift!");
14194
14195     // Redistribute the loaded elements into the different locations.
14196     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
14197     for (unsigned i = 0; i != NumElems; ++i)
14198       ShuffleVec[i * SizeRatio + SizeRatio - 1] = i;
14199
14200     SDValue Shuff = DAG.getVectorShuffle(
14201         WideVecVT, dl, SlicedVec, DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
14202
14203     Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
14204
14205     // Build the arithmetic shift.
14206     unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
14207                    MemVT.getVectorElementType().getSizeInBits();
14208     Shuff =
14209         DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
14210                     DAG.getConstant(Amt, dl, RegVT));
14211
14212     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14213     return Shuff;
14214   }
14215
14216   // Redistribute the loaded elements into the different locations.
14217   SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
14218   for (unsigned i = 0; i != NumElems; ++i)
14219     ShuffleVec[i * SizeRatio] = i;
14220
14221   SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
14222                                        DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
14223
14224   // Bitcast to the requested type.
14225   Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
14226   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14227   return Shuff;
14228 }
14229
14230 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
14231 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
14232 // from the AND / OR.
14233 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
14234   Opc = Op.getOpcode();
14235   if (Opc != ISD::OR && Opc != ISD::AND)
14236     return false;
14237   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
14238           Op.getOperand(0).hasOneUse() &&
14239           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
14240           Op.getOperand(1).hasOneUse());
14241 }
14242
14243 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
14244 // 1 and that the SETCC node has a single use.
14245 static bool isXor1OfSetCC(SDValue Op) {
14246   if (Op.getOpcode() != ISD::XOR)
14247     return false;
14248   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
14249   if (N1C && N1C->getAPIntValue() == 1) {
14250     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
14251       Op.getOperand(0).hasOneUse();
14252   }
14253   return false;
14254 }
14255
14256 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
14257   bool addTest = true;
14258   SDValue Chain = Op.getOperand(0);
14259   SDValue Cond  = Op.getOperand(1);
14260   SDValue Dest  = Op.getOperand(2);
14261   SDLoc dl(Op);
14262   SDValue CC;
14263   bool Inverted = false;
14264
14265   if (Cond.getOpcode() == ISD::SETCC) {
14266     // Check for setcc([su]{add,sub,mul}o == 0).
14267     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
14268         isa<ConstantSDNode>(Cond.getOperand(1)) &&
14269         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
14270         Cond.getOperand(0).getResNo() == 1 &&
14271         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
14272          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
14273          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
14274          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
14275          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
14276          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
14277       Inverted = true;
14278       Cond = Cond.getOperand(0);
14279     } else {
14280       SDValue NewCond = LowerSETCC(Cond, DAG);
14281       if (NewCond.getNode())
14282         Cond = NewCond;
14283     }
14284   }
14285 #if 0
14286   // FIXME: LowerXALUO doesn't handle these!!
14287   else if (Cond.getOpcode() == X86ISD::ADD  ||
14288            Cond.getOpcode() == X86ISD::SUB  ||
14289            Cond.getOpcode() == X86ISD::SMUL ||
14290            Cond.getOpcode() == X86ISD::UMUL)
14291     Cond = LowerXALUO(Cond, DAG);
14292 #endif
14293
14294   // Look pass (and (setcc_carry (cmp ...)), 1).
14295   if (Cond.getOpcode() == ISD::AND &&
14296       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
14297     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
14298     if (C && C->getAPIntValue() == 1)
14299       Cond = Cond.getOperand(0);
14300   }
14301
14302   // If condition flag is set by a X86ISD::CMP, then use it as the condition
14303   // setting operand in place of the X86ISD::SETCC.
14304   unsigned CondOpcode = Cond.getOpcode();
14305   if (CondOpcode == X86ISD::SETCC ||
14306       CondOpcode == X86ISD::SETCC_CARRY) {
14307     CC = Cond.getOperand(0);
14308
14309     SDValue Cmp = Cond.getOperand(1);
14310     unsigned Opc = Cmp.getOpcode();
14311     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
14312     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
14313       Cond = Cmp;
14314       addTest = false;
14315     } else {
14316       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
14317       default: break;
14318       case X86::COND_O:
14319       case X86::COND_B:
14320         // These can only come from an arithmetic instruction with overflow,
14321         // e.g. SADDO, UADDO.
14322         Cond = Cond.getNode()->getOperand(1);
14323         addTest = false;
14324         break;
14325       }
14326     }
14327   }
14328   CondOpcode = Cond.getOpcode();
14329   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
14330       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
14331       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
14332        Cond.getOperand(0).getValueType() != MVT::i8)) {
14333     SDValue LHS = Cond.getOperand(0);
14334     SDValue RHS = Cond.getOperand(1);
14335     unsigned X86Opcode;
14336     unsigned X86Cond;
14337     SDVTList VTs;
14338     // Keep this in sync with LowerXALUO, otherwise we might create redundant
14339     // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
14340     // X86ISD::INC).
14341     switch (CondOpcode) {
14342     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
14343     case ISD::SADDO:
14344       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
14345         if (C->isOne()) {
14346           X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
14347           break;
14348         }
14349       X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
14350     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
14351     case ISD::SSUBO:
14352       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
14353         if (C->isOne()) {
14354           X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
14355           break;
14356         }
14357       X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
14358     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
14359     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
14360     default: llvm_unreachable("unexpected overflowing operator");
14361     }
14362     if (Inverted)
14363       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
14364     if (CondOpcode == ISD::UMULO)
14365       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
14366                           MVT::i32);
14367     else
14368       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
14369
14370     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
14371
14372     if (CondOpcode == ISD::UMULO)
14373       Cond = X86Op.getValue(2);
14374     else
14375       Cond = X86Op.getValue(1);
14376
14377     CC = DAG.getConstant(X86Cond, dl, MVT::i8);
14378     addTest = false;
14379   } else {
14380     unsigned CondOpc;
14381     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
14382       SDValue Cmp = Cond.getOperand(0).getOperand(1);
14383       if (CondOpc == ISD::OR) {
14384         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
14385         // two branches instead of an explicit OR instruction with a
14386         // separate test.
14387         if (Cmp == Cond.getOperand(1).getOperand(1) &&
14388             isX86LogicalCmp(Cmp)) {
14389           CC = Cond.getOperand(0).getOperand(0);
14390           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14391                               Chain, Dest, CC, Cmp);
14392           CC = Cond.getOperand(1).getOperand(0);
14393           Cond = Cmp;
14394           addTest = false;
14395         }
14396       } else { // ISD::AND
14397         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
14398         // two branches instead of an explicit AND instruction with a
14399         // separate test. However, we only do this if this block doesn't
14400         // have a fall-through edge, because this requires an explicit
14401         // jmp when the condition is false.
14402         if (Cmp == Cond.getOperand(1).getOperand(1) &&
14403             isX86LogicalCmp(Cmp) &&
14404             Op.getNode()->hasOneUse()) {
14405           X86::CondCode CCode =
14406             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
14407           CCode = X86::GetOppositeBranchCondition(CCode);
14408           CC = DAG.getConstant(CCode, dl, MVT::i8);
14409           SDNode *User = *Op.getNode()->use_begin();
14410           // Look for an unconditional branch following this conditional branch.
14411           // We need this because we need to reverse the successors in order
14412           // to implement FCMP_OEQ.
14413           if (User->getOpcode() == ISD::BR) {
14414             SDValue FalseBB = User->getOperand(1);
14415             SDNode *NewBR =
14416               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14417             assert(NewBR == User);
14418             (void)NewBR;
14419             Dest = FalseBB;
14420
14421             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14422                                 Chain, Dest, CC, Cmp);
14423             X86::CondCode CCode =
14424               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
14425             CCode = X86::GetOppositeBranchCondition(CCode);
14426             CC = DAG.getConstant(CCode, dl, MVT::i8);
14427             Cond = Cmp;
14428             addTest = false;
14429           }
14430         }
14431       }
14432     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
14433       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
14434       // It should be transformed during dag combiner except when the condition
14435       // is set by a arithmetics with overflow node.
14436       X86::CondCode CCode =
14437         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
14438       CCode = X86::GetOppositeBranchCondition(CCode);
14439       CC = DAG.getConstant(CCode, dl, MVT::i8);
14440       Cond = Cond.getOperand(0).getOperand(1);
14441       addTest = false;
14442     } else if (Cond.getOpcode() == ISD::SETCC &&
14443                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
14444       // For FCMP_OEQ, we can emit
14445       // two branches instead of an explicit AND instruction with a
14446       // separate test. However, we only do this if this block doesn't
14447       // have a fall-through edge, because this requires an explicit
14448       // jmp when the condition is false.
14449       if (Op.getNode()->hasOneUse()) {
14450         SDNode *User = *Op.getNode()->use_begin();
14451         // Look for an unconditional branch following this conditional branch.
14452         // We need this because we need to reverse the successors in order
14453         // to implement FCMP_OEQ.
14454         if (User->getOpcode() == ISD::BR) {
14455           SDValue FalseBB = User->getOperand(1);
14456           SDNode *NewBR =
14457             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14458           assert(NewBR == User);
14459           (void)NewBR;
14460           Dest = FalseBB;
14461
14462           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
14463                                     Cond.getOperand(0), Cond.getOperand(1));
14464           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14465           CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
14466           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14467                               Chain, Dest, CC, Cmp);
14468           CC = DAG.getConstant(X86::COND_P, dl, MVT::i8);
14469           Cond = Cmp;
14470           addTest = false;
14471         }
14472       }
14473     } else if (Cond.getOpcode() == ISD::SETCC &&
14474                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
14475       // For FCMP_UNE, we can emit
14476       // two branches instead of an explicit AND instruction with a
14477       // separate test. However, we only do this if this block doesn't
14478       // have a fall-through edge, because this requires an explicit
14479       // jmp when the condition is false.
14480       if (Op.getNode()->hasOneUse()) {
14481         SDNode *User = *Op.getNode()->use_begin();
14482         // Look for an unconditional branch following this conditional branch.
14483         // We need this because we need to reverse the successors in order
14484         // to implement FCMP_UNE.
14485         if (User->getOpcode() == ISD::BR) {
14486           SDValue FalseBB = User->getOperand(1);
14487           SDNode *NewBR =
14488             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14489           assert(NewBR == User);
14490           (void)NewBR;
14491
14492           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
14493                                     Cond.getOperand(0), Cond.getOperand(1));
14494           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14495           CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
14496           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14497                               Chain, Dest, CC, Cmp);
14498           CC = DAG.getConstant(X86::COND_NP, dl, MVT::i8);
14499           Cond = Cmp;
14500           addTest = false;
14501           Dest = FalseBB;
14502         }
14503       }
14504     }
14505   }
14506
14507   if (addTest) {
14508     // Look pass the truncate if the high bits are known zero.
14509     if (isTruncWithZeroHighBitsInput(Cond, DAG))
14510         Cond = Cond.getOperand(0);
14511
14512     // We know the result of AND is compared against zero. Try to match
14513     // it to BT.
14514     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
14515       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
14516       if (NewSetCC.getNode()) {
14517         CC = NewSetCC.getOperand(0);
14518         Cond = NewSetCC.getOperand(1);
14519         addTest = false;
14520       }
14521     }
14522   }
14523
14524   if (addTest) {
14525     X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
14526     CC = DAG.getConstant(X86Cond, dl, MVT::i8);
14527     Cond = EmitTest(Cond, X86Cond, dl, DAG);
14528   }
14529   Cond = ConvertCmpIfNecessary(Cond, DAG);
14530   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14531                      Chain, Dest, CC, Cond);
14532 }
14533
14534 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
14535 // Calls to _alloca are needed to probe the stack when allocating more than 4k
14536 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
14537 // that the guard pages used by the OS virtual memory manager are allocated in
14538 // correct sequence.
14539 SDValue
14540 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
14541                                            SelectionDAG &DAG) const {
14542   MachineFunction &MF = DAG.getMachineFunction();
14543   bool SplitStack = MF.shouldSplitStack();
14544   bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMachO()) ||
14545                SplitStack;
14546   SDLoc dl(Op);
14547
14548   if (!Lower) {
14549     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14550     SDNode* Node = Op.getNode();
14551
14552     unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
14553     assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
14554         " not tell us which reg is the stack pointer!");
14555     EVT VT = Node->getValueType(0);
14556     SDValue Tmp1 = SDValue(Node, 0);
14557     SDValue Tmp2 = SDValue(Node, 1);
14558     SDValue Tmp3 = Node->getOperand(2);
14559     SDValue Chain = Tmp1.getOperand(0);
14560
14561     // Chain the dynamic stack allocation so that it doesn't modify the stack
14562     // pointer when other instructions are using the stack.
14563     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, dl, true),
14564         SDLoc(Node));
14565
14566     SDValue Size = Tmp2.getOperand(1);
14567     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
14568     Chain = SP.getValue(1);
14569     unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
14570     const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
14571     unsigned StackAlign = TFI.getStackAlignment();
14572     Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
14573     if (Align > StackAlign)
14574       Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
14575           DAG.getConstant(-(uint64_t)Align, dl, VT));
14576     Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
14577
14578     Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, dl, true),
14579         DAG.getIntPtrConstant(0, dl, true), SDValue(),
14580         SDLoc(Node));
14581
14582     SDValue Ops[2] = { Tmp1, Tmp2 };
14583     return DAG.getMergeValues(Ops, dl);
14584   }
14585
14586   // Get the inputs.
14587   SDValue Chain = Op.getOperand(0);
14588   SDValue Size  = Op.getOperand(1);
14589   unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
14590   EVT VT = Op.getNode()->getValueType(0);
14591
14592   bool Is64Bit = Subtarget->is64Bit();
14593   EVT SPTy = getPointerTy();
14594
14595   if (SplitStack) {
14596     MachineRegisterInfo &MRI = MF.getRegInfo();
14597
14598     if (Is64Bit) {
14599       // The 64 bit implementation of segmented stacks needs to clobber both r10
14600       // r11. This makes it impossible to use it along with nested parameters.
14601       const Function *F = MF.getFunction();
14602
14603       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
14604            I != E; ++I)
14605         if (I->hasNestAttr())
14606           report_fatal_error("Cannot use segmented stacks with functions that "
14607                              "have nested arguments.");
14608     }
14609
14610     const TargetRegisterClass *AddrRegClass =
14611       getRegClassFor(getPointerTy());
14612     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
14613     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
14614     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
14615                                 DAG.getRegister(Vreg, SPTy));
14616     SDValue Ops1[2] = { Value, Chain };
14617     return DAG.getMergeValues(Ops1, dl);
14618   } else {
14619     SDValue Flag;
14620     const unsigned Reg = (Subtarget->isTarget64BitLP64() ? X86::RAX : X86::EAX);
14621
14622     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
14623     Flag = Chain.getValue(1);
14624     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
14625
14626     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
14627
14628     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
14629     unsigned SPReg = RegInfo->getStackRegister();
14630     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
14631     Chain = SP.getValue(1);
14632
14633     if (Align) {
14634       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
14635                        DAG.getConstant(-(uint64_t)Align, dl, VT));
14636       Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
14637     }
14638
14639     SDValue Ops1[2] = { SP, Chain };
14640     return DAG.getMergeValues(Ops1, dl);
14641   }
14642 }
14643
14644 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
14645   MachineFunction &MF = DAG.getMachineFunction();
14646   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
14647
14648   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
14649   SDLoc DL(Op);
14650
14651   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
14652     // vastart just stores the address of the VarArgsFrameIndex slot into the
14653     // memory location argument.
14654     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
14655                                    getPointerTy());
14656     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
14657                         MachinePointerInfo(SV), false, false, 0);
14658   }
14659
14660   // __va_list_tag:
14661   //   gp_offset         (0 - 6 * 8)
14662   //   fp_offset         (48 - 48 + 8 * 16)
14663   //   overflow_arg_area (point to parameters coming in memory).
14664   //   reg_save_area
14665   SmallVector<SDValue, 8> MemOps;
14666   SDValue FIN = Op.getOperand(1);
14667   // Store gp_offset
14668   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
14669                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
14670                                                DL, MVT::i32),
14671                                FIN, MachinePointerInfo(SV), false, false, 0);
14672   MemOps.push_back(Store);
14673
14674   // Store fp_offset
14675   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
14676                     FIN, DAG.getIntPtrConstant(4, DL));
14677   Store = DAG.getStore(Op.getOperand(0), DL,
14678                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(), DL,
14679                                        MVT::i32),
14680                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
14681   MemOps.push_back(Store);
14682
14683   // Store ptr to overflow_arg_area
14684   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
14685                     FIN, DAG.getIntPtrConstant(4, DL));
14686   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
14687                                     getPointerTy());
14688   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
14689                        MachinePointerInfo(SV, 8),
14690                        false, false, 0);
14691   MemOps.push_back(Store);
14692
14693   // Store ptr to reg_save_area.
14694   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
14695                     FIN, DAG.getIntPtrConstant(8, DL));
14696   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
14697                                     getPointerTy());
14698   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
14699                        MachinePointerInfo(SV, 16), false, false, 0);
14700   MemOps.push_back(Store);
14701   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
14702 }
14703
14704 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
14705   assert(Subtarget->is64Bit() &&
14706          "LowerVAARG only handles 64-bit va_arg!");
14707   assert((Subtarget->isTargetLinux() ||
14708           Subtarget->isTargetDarwin()) &&
14709           "Unhandled target in LowerVAARG");
14710   assert(Op.getNode()->getNumOperands() == 4);
14711   SDValue Chain = Op.getOperand(0);
14712   SDValue SrcPtr = Op.getOperand(1);
14713   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
14714   unsigned Align = Op.getConstantOperandVal(3);
14715   SDLoc dl(Op);
14716
14717   EVT ArgVT = Op.getNode()->getValueType(0);
14718   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
14719   uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
14720   uint8_t ArgMode;
14721
14722   // Decide which area this value should be read from.
14723   // TODO: Implement the AMD64 ABI in its entirety. This simple
14724   // selection mechanism works only for the basic types.
14725   if (ArgVT == MVT::f80) {
14726     llvm_unreachable("va_arg for f80 not yet implemented");
14727   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
14728     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
14729   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
14730     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
14731   } else {
14732     llvm_unreachable("Unhandled argument type in LowerVAARG");
14733   }
14734
14735   if (ArgMode == 2) {
14736     // Sanity Check: Make sure using fp_offset makes sense.
14737     assert(!Subtarget->useSoftFloat() &&
14738            !(DAG.getMachineFunction().getFunction()->hasFnAttribute(
14739                Attribute::NoImplicitFloat)) &&
14740            Subtarget->hasSSE1());
14741   }
14742
14743   // Insert VAARG_64 node into the DAG
14744   // VAARG_64 returns two values: Variable Argument Address, Chain
14745   SDValue InstOps[] = {Chain, SrcPtr, DAG.getConstant(ArgSize, dl, MVT::i32),
14746                        DAG.getConstant(ArgMode, dl, MVT::i8),
14747                        DAG.getConstant(Align, dl, MVT::i32)};
14748   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
14749   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
14750                                           VTs, InstOps, MVT::i64,
14751                                           MachinePointerInfo(SV),
14752                                           /*Align=*/0,
14753                                           /*Volatile=*/false,
14754                                           /*ReadMem=*/true,
14755                                           /*WriteMem=*/true);
14756   Chain = VAARG.getValue(1);
14757
14758   // Load the next argument and return it
14759   return DAG.getLoad(ArgVT, dl,
14760                      Chain,
14761                      VAARG,
14762                      MachinePointerInfo(),
14763                      false, false, false, 0);
14764 }
14765
14766 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
14767                            SelectionDAG &DAG) {
14768   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
14769   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
14770   SDValue Chain = Op.getOperand(0);
14771   SDValue DstPtr = Op.getOperand(1);
14772   SDValue SrcPtr = Op.getOperand(2);
14773   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
14774   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
14775   SDLoc DL(Op);
14776
14777   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
14778                        DAG.getIntPtrConstant(24, DL), 8, /*isVolatile*/false,
14779                        false, false,
14780                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
14781 }
14782
14783 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
14784 // amount is a constant. Takes immediate version of shift as input.
14785 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
14786                                           SDValue SrcOp, uint64_t ShiftAmt,
14787                                           SelectionDAG &DAG) {
14788   MVT ElementType = VT.getVectorElementType();
14789
14790   // Fold this packed shift into its first operand if ShiftAmt is 0.
14791   if (ShiftAmt == 0)
14792     return SrcOp;
14793
14794   // Check for ShiftAmt >= element width
14795   if (ShiftAmt >= ElementType.getSizeInBits()) {
14796     if (Opc == X86ISD::VSRAI)
14797       ShiftAmt = ElementType.getSizeInBits() - 1;
14798     else
14799       return DAG.getConstant(0, dl, VT);
14800   }
14801
14802   assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
14803          && "Unknown target vector shift-by-constant node");
14804
14805   // Fold this packed vector shift into a build vector if SrcOp is a
14806   // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
14807   if (VT == SrcOp.getSimpleValueType() &&
14808       ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
14809     SmallVector<SDValue, 8> Elts;
14810     unsigned NumElts = SrcOp->getNumOperands();
14811     ConstantSDNode *ND;
14812
14813     switch(Opc) {
14814     default: llvm_unreachable(nullptr);
14815     case X86ISD::VSHLI:
14816       for (unsigned i=0; i!=NumElts; ++i) {
14817         SDValue CurrentOp = SrcOp->getOperand(i);
14818         if (CurrentOp->getOpcode() == ISD::UNDEF) {
14819           Elts.push_back(CurrentOp);
14820           continue;
14821         }
14822         ND = cast<ConstantSDNode>(CurrentOp);
14823         const APInt &C = ND->getAPIntValue();
14824         Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), dl, ElementType));
14825       }
14826       break;
14827     case X86ISD::VSRLI:
14828       for (unsigned i=0; i!=NumElts; ++i) {
14829         SDValue CurrentOp = SrcOp->getOperand(i);
14830         if (CurrentOp->getOpcode() == ISD::UNDEF) {
14831           Elts.push_back(CurrentOp);
14832           continue;
14833         }
14834         ND = cast<ConstantSDNode>(CurrentOp);
14835         const APInt &C = ND->getAPIntValue();
14836         Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), dl, ElementType));
14837       }
14838       break;
14839     case X86ISD::VSRAI:
14840       for (unsigned i=0; i!=NumElts; ++i) {
14841         SDValue CurrentOp = SrcOp->getOperand(i);
14842         if (CurrentOp->getOpcode() == ISD::UNDEF) {
14843           Elts.push_back(CurrentOp);
14844           continue;
14845         }
14846         ND = cast<ConstantSDNode>(CurrentOp);
14847         const APInt &C = ND->getAPIntValue();
14848         Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), dl, ElementType));
14849       }
14850       break;
14851     }
14852
14853     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
14854   }
14855
14856   return DAG.getNode(Opc, dl, VT, SrcOp,
14857                      DAG.getConstant(ShiftAmt, dl, MVT::i8));
14858 }
14859
14860 // getTargetVShiftNode - Handle vector element shifts where the shift amount
14861 // may or may not be a constant. Takes immediate version of shift as input.
14862 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
14863                                    SDValue SrcOp, SDValue ShAmt,
14864                                    SelectionDAG &DAG) {
14865   MVT SVT = ShAmt.getSimpleValueType();
14866   assert((SVT == MVT::i32 || SVT == MVT::i64) && "Unexpected value type!");
14867
14868   // Catch shift-by-constant.
14869   if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
14870     return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
14871                                       CShAmt->getZExtValue(), DAG);
14872
14873   // Change opcode to non-immediate version
14874   switch (Opc) {
14875     default: llvm_unreachable("Unknown target vector shift node");
14876     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
14877     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
14878     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
14879   }
14880
14881   const X86Subtarget &Subtarget =
14882       static_cast<const X86Subtarget &>(DAG.getSubtarget());
14883   if (Subtarget.hasSSE41() && ShAmt.getOpcode() == ISD::ZERO_EXTEND &&
14884       ShAmt.getOperand(0).getSimpleValueType() == MVT::i16) {
14885     // Let the shuffle legalizer expand this shift amount node.
14886     SDValue Op0 = ShAmt.getOperand(0);
14887     Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(Op0), MVT::v8i16, Op0);
14888     ShAmt = getShuffleVectorZeroOrUndef(Op0, 0, true, &Subtarget, DAG);
14889   } else {
14890     // Need to build a vector containing shift amount.
14891     // SSE/AVX packed shifts only use the lower 64-bit of the shift count.
14892     SmallVector<SDValue, 4> ShOps;
14893     ShOps.push_back(ShAmt);
14894     if (SVT == MVT::i32) {
14895       ShOps.push_back(DAG.getConstant(0, dl, SVT));
14896       ShOps.push_back(DAG.getUNDEF(SVT));
14897     }
14898     ShOps.push_back(DAG.getUNDEF(SVT));
14899
14900     MVT BVT = SVT == MVT::i32 ? MVT::v4i32 : MVT::v2i64;
14901     ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, BVT, ShOps);
14902   }
14903
14904   // The return type has to be a 128-bit type with the same element
14905   // type as the input type.
14906   MVT EltVT = VT.getVectorElementType();
14907   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
14908
14909   ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
14910   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
14911 }
14912
14913 /// \brief Return (and \p Op, \p Mask) for compare instructions or
14914 /// (vselect \p Mask, \p Op, \p PreservedSrc) for others along with the
14915 /// necessary casting for \p Mask when lowering masking intrinsics.
14916 static SDValue getVectorMaskingNode(SDValue Op, SDValue Mask,
14917                                     SDValue PreservedSrc,
14918                                     const X86Subtarget *Subtarget,
14919                                     SelectionDAG &DAG) {
14920     EVT VT = Op.getValueType();
14921     EVT MaskVT = EVT::getVectorVT(*DAG.getContext(),
14922                                   MVT::i1, VT.getVectorNumElements());
14923     EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
14924                                      Mask.getValueType().getSizeInBits());
14925     SDLoc dl(Op);
14926
14927     assert(MaskVT.isSimple() && "invalid mask type");
14928
14929     if (isAllOnes(Mask))
14930       return Op;
14931
14932     // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
14933     // are extracted by EXTRACT_SUBVECTOR.
14934     SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
14935                               DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
14936                               DAG.getIntPtrConstant(0, dl));
14937
14938     switch (Op.getOpcode()) {
14939       default: break;
14940       case X86ISD::PCMPEQM:
14941       case X86ISD::PCMPGTM:
14942       case X86ISD::CMPM:
14943       case X86ISD::CMPMU:
14944         return DAG.getNode(ISD::AND, dl, VT, Op, VMask);
14945     }
14946     if (PreservedSrc.getOpcode() == ISD::UNDEF)
14947       PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
14948     return DAG.getNode(ISD::VSELECT, dl, VT, VMask, Op, PreservedSrc);
14949 }
14950
14951 /// \brief Creates an SDNode for a predicated scalar operation.
14952 /// \returns (X86vselect \p Mask, \p Op, \p PreservedSrc).
14953 /// The mask is comming as MVT::i8 and it should be truncated
14954 /// to MVT::i1 while lowering masking intrinsics.
14955 /// The main difference between ScalarMaskingNode and VectorMaskingNode is using
14956 /// "X86select" instead of "vselect". We just can't create the "vselect" node for
14957 /// a scalar instruction.
14958 static SDValue getScalarMaskingNode(SDValue Op, SDValue Mask,
14959                                     SDValue PreservedSrc,
14960                                     const X86Subtarget *Subtarget,
14961                                     SelectionDAG &DAG) {
14962     if (isAllOnes(Mask))
14963       return Op;
14964
14965     EVT VT = Op.getValueType();
14966     SDLoc dl(Op);
14967     // The mask should be of type MVT::i1
14968     SDValue IMask = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Mask);
14969
14970     if (PreservedSrc.getOpcode() == ISD::UNDEF)
14971       PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
14972     return DAG.getNode(X86ISD::SELECT, dl, VT, IMask, Op, PreservedSrc);
14973 }
14974
14975 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
14976                                        SelectionDAG &DAG) {
14977   SDLoc dl(Op);
14978   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
14979   EVT VT = Op.getValueType();
14980   const IntrinsicData* IntrData = getIntrinsicWithoutChain(IntNo);
14981   if (IntrData) {
14982     switch(IntrData->Type) {
14983     case INTR_TYPE_1OP:
14984       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1));
14985     case INTR_TYPE_2OP:
14986       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
14987         Op.getOperand(2));
14988     case INTR_TYPE_3OP:
14989       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
14990         Op.getOperand(2), Op.getOperand(3));
14991     case INTR_TYPE_1OP_MASK_RM: {
14992       SDValue Src = Op.getOperand(1);
14993       SDValue Src0 = Op.getOperand(2);
14994       SDValue Mask = Op.getOperand(3);
14995       SDValue RoundingMode = Op.getOperand(4);
14996       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src,
14997                                               RoundingMode),
14998                                   Mask, Src0, Subtarget, DAG);
14999     }
15000     case INTR_TYPE_SCALAR_MASK_RM: {
15001       SDValue Src1 = Op.getOperand(1);
15002       SDValue Src2 = Op.getOperand(2);
15003       SDValue Src0 = Op.getOperand(3);
15004       SDValue Mask = Op.getOperand(4);
15005       // There are 2 kinds of intrinsics in this group:
15006       // (1) With supress-all-exceptions (sae) or rounding mode- 6 operands
15007       // (2) With rounding mode and sae - 7 operands.
15008       if (Op.getNumOperands() == 6) {
15009         SDValue Sae  = Op.getOperand(5);
15010         unsigned Opc = IntrData->Opc1 ? IntrData->Opc1 : IntrData->Opc0;
15011         return getScalarMaskingNode(DAG.getNode(Opc, dl, VT, Src1, Src2,
15012                                                 Sae),
15013                                     Mask, Src0, Subtarget, DAG);
15014       }
15015       assert(Op.getNumOperands() == 7 && "Unexpected intrinsic form");
15016       SDValue RoundingMode  = Op.getOperand(5);
15017       SDValue Sae  = Op.getOperand(6);
15018       return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2,
15019                                               RoundingMode, Sae),
15020                                   Mask, Src0, Subtarget, DAG);
15021     }
15022     case INTR_TYPE_2OP_MASK: {
15023       SDValue Src1 = Op.getOperand(1);
15024       SDValue Src2 = Op.getOperand(2);
15025       SDValue PassThru = Op.getOperand(3);
15026       SDValue Mask = Op.getOperand(4);
15027       // We specify 2 possible opcodes for intrinsics with rounding modes.
15028       // First, we check if the intrinsic may have non-default rounding mode,
15029       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15030       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15031       if (IntrWithRoundingModeOpcode != 0) {
15032         SDValue Rnd = Op.getOperand(5);
15033         unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
15034         if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
15035           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15036                                       dl, Op.getValueType(),
15037                                       Src1, Src2, Rnd),
15038                                       Mask, PassThru, Subtarget, DAG);
15039         }
15040       }
15041       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15042                                               Src1,Src2),
15043                                   Mask, PassThru, Subtarget, DAG);
15044     }
15045     case FMA_OP_MASK: {
15046       SDValue Src1 = Op.getOperand(1);
15047       SDValue Src2 = Op.getOperand(2);
15048       SDValue Src3 = Op.getOperand(3);
15049       SDValue Mask = Op.getOperand(4);
15050       // We specify 2 possible opcodes for intrinsics with rounding modes.
15051       // First, we check if the intrinsic may have non-default rounding mode,
15052       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15053       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15054       if (IntrWithRoundingModeOpcode != 0) {
15055         SDValue Rnd = Op.getOperand(5);
15056         if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
15057             X86::STATIC_ROUNDING::CUR_DIRECTION)
15058           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15059                                                   dl, Op.getValueType(),
15060                                                   Src1, Src2, Src3, Rnd),
15061                                       Mask, Src1, Subtarget, DAG);
15062       }
15063       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0,
15064                                               dl, Op.getValueType(),
15065                                               Src1, Src2, Src3),
15066                                   Mask, Src1, Subtarget, DAG);
15067     }
15068     case CMP_MASK:
15069     case CMP_MASK_CC: {
15070       // Comparison intrinsics with masks.
15071       // Example of transformation:
15072       // (i8 (int_x86_avx512_mask_pcmpeq_q_128
15073       //             (v2i64 %a), (v2i64 %b), (i8 %mask))) ->
15074       // (i8 (bitcast
15075       //   (v8i1 (insert_subvector undef,
15076       //           (v2i1 (and (PCMPEQM %a, %b),
15077       //                      (extract_subvector
15078       //                         (v8i1 (bitcast %mask)), 0))), 0))))
15079       EVT VT = Op.getOperand(1).getValueType();
15080       EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15081                                     VT.getVectorNumElements());
15082       SDValue Mask = Op.getOperand((IntrData->Type == CMP_MASK_CC) ? 4 : 3);
15083       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15084                                        Mask.getValueType().getSizeInBits());
15085       SDValue Cmp;
15086       if (IntrData->Type == CMP_MASK_CC) {
15087         SDValue CC = Op.getOperand(3);
15088         CC = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, CC);
15089         // We specify 2 possible opcodes for intrinsics with rounding modes.
15090         // First, we check if the intrinsic may have non-default rounding mode,
15091         // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15092         if (IntrData->Opc1 != 0) {
15093           SDValue Rnd = Op.getOperand(5);
15094           if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
15095               X86::STATIC_ROUNDING::CUR_DIRECTION)
15096             Cmp = DAG.getNode(IntrData->Opc1, dl, MaskVT, Op.getOperand(1),
15097                               Op.getOperand(2), CC, Rnd);
15098         }
15099         //default rounding mode
15100         if(!Cmp.getNode())
15101             Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
15102                               Op.getOperand(2), CC);
15103
15104       } else {
15105         assert(IntrData->Type == CMP_MASK && "Unexpected intrinsic type!");
15106         Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
15107                           Op.getOperand(2));
15108       }
15109       SDValue CmpMask = getVectorMaskingNode(Cmp, Mask,
15110                                              DAG.getTargetConstant(0, dl,
15111                                                                    MaskVT),
15112                                              Subtarget, DAG);
15113       SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, BitcastVT,
15114                                 DAG.getUNDEF(BitcastVT), CmpMask,
15115                                 DAG.getIntPtrConstant(0, dl));
15116       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
15117     }
15118     case COMI: { // Comparison intrinsics
15119       ISD::CondCode CC = (ISD::CondCode)IntrData->Opc1;
15120       SDValue LHS = Op.getOperand(1);
15121       SDValue RHS = Op.getOperand(2);
15122       unsigned X86CC = TranslateX86CC(CC, dl, true, LHS, RHS, DAG);
15123       assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
15124       SDValue Cond = DAG.getNode(IntrData->Opc0, dl, MVT::i32, LHS, RHS);
15125       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15126                                   DAG.getConstant(X86CC, dl, MVT::i8), Cond);
15127       return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15128     }
15129     case VSHIFT:
15130       return getTargetVShiftNode(IntrData->Opc0, dl, Op.getSimpleValueType(),
15131                                  Op.getOperand(1), Op.getOperand(2), DAG);
15132     case VSHIFT_MASK:
15133       return getVectorMaskingNode(getTargetVShiftNode(IntrData->Opc0, dl,
15134                                                       Op.getSimpleValueType(),
15135                                                       Op.getOperand(1),
15136                                                       Op.getOperand(2), DAG),
15137                                   Op.getOperand(4), Op.getOperand(3), Subtarget,
15138                                   DAG);
15139     case COMPRESS_EXPAND_IN_REG: {
15140       SDValue Mask = Op.getOperand(3);
15141       SDValue DataToCompress = Op.getOperand(1);
15142       SDValue PassThru = Op.getOperand(2);
15143       if (isAllOnes(Mask)) // return data as is
15144         return Op.getOperand(1);
15145       EVT VT = Op.getValueType();
15146       EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15147                                     VT.getVectorNumElements());
15148       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15149                                        Mask.getValueType().getSizeInBits());
15150       SDLoc dl(Op);
15151       SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15152                                   DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
15153                                   DAG.getIntPtrConstant(0, dl));
15154
15155       return DAG.getNode(IntrData->Opc0, dl, VT, VMask, DataToCompress,
15156                          PassThru);
15157     }
15158     case BLEND: {
15159       SDValue Mask = Op.getOperand(3);
15160       EVT VT = Op.getValueType();
15161       EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15162                                     VT.getVectorNumElements());
15163       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15164                                        Mask.getValueType().getSizeInBits());
15165       SDLoc dl(Op);
15166       SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15167                                   DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
15168                                   DAG.getIntPtrConstant(0, dl));
15169       return DAG.getNode(IntrData->Opc0, dl, VT, VMask, Op.getOperand(1),
15170                          Op.getOperand(2));
15171     }
15172     default:
15173       break;
15174     }
15175   }
15176
15177   switch (IntNo) {
15178   default: return SDValue();    // Don't custom lower most intrinsics.
15179
15180   case Intrinsic::x86_avx2_permd:
15181   case Intrinsic::x86_avx2_permps:
15182     // Operands intentionally swapped. Mask is last operand to intrinsic,
15183     // but second operand for node/instruction.
15184     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
15185                        Op.getOperand(2), Op.getOperand(1));
15186
15187   case Intrinsic::x86_avx512_mask_valign_q_512:
15188   case Intrinsic::x86_avx512_mask_valign_d_512:
15189     // Vector source operands are swapped.
15190     return getVectorMaskingNode(DAG.getNode(X86ISD::VALIGN, dl,
15191                                             Op.getValueType(), Op.getOperand(2),
15192                                             Op.getOperand(1),
15193                                             Op.getOperand(3)),
15194                                 Op.getOperand(5), Op.getOperand(4),
15195                                 Subtarget, DAG);
15196
15197   // ptest and testp intrinsics. The intrinsic these come from are designed to
15198   // return an integer value, not just an instruction so lower it to the ptest
15199   // or testp pattern and a setcc for the result.
15200   case Intrinsic::x86_sse41_ptestz:
15201   case Intrinsic::x86_sse41_ptestc:
15202   case Intrinsic::x86_sse41_ptestnzc:
15203   case Intrinsic::x86_avx_ptestz_256:
15204   case Intrinsic::x86_avx_ptestc_256:
15205   case Intrinsic::x86_avx_ptestnzc_256:
15206   case Intrinsic::x86_avx_vtestz_ps:
15207   case Intrinsic::x86_avx_vtestc_ps:
15208   case Intrinsic::x86_avx_vtestnzc_ps:
15209   case Intrinsic::x86_avx_vtestz_pd:
15210   case Intrinsic::x86_avx_vtestc_pd:
15211   case Intrinsic::x86_avx_vtestnzc_pd:
15212   case Intrinsic::x86_avx_vtestz_ps_256:
15213   case Intrinsic::x86_avx_vtestc_ps_256:
15214   case Intrinsic::x86_avx_vtestnzc_ps_256:
15215   case Intrinsic::x86_avx_vtestz_pd_256:
15216   case Intrinsic::x86_avx_vtestc_pd_256:
15217   case Intrinsic::x86_avx_vtestnzc_pd_256: {
15218     bool IsTestPacked = false;
15219     unsigned X86CC;
15220     switch (IntNo) {
15221     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
15222     case Intrinsic::x86_avx_vtestz_ps:
15223     case Intrinsic::x86_avx_vtestz_pd:
15224     case Intrinsic::x86_avx_vtestz_ps_256:
15225     case Intrinsic::x86_avx_vtestz_pd_256:
15226       IsTestPacked = true; // Fallthrough
15227     case Intrinsic::x86_sse41_ptestz:
15228     case Intrinsic::x86_avx_ptestz_256:
15229       // ZF = 1
15230       X86CC = X86::COND_E;
15231       break;
15232     case Intrinsic::x86_avx_vtestc_ps:
15233     case Intrinsic::x86_avx_vtestc_pd:
15234     case Intrinsic::x86_avx_vtestc_ps_256:
15235     case Intrinsic::x86_avx_vtestc_pd_256:
15236       IsTestPacked = true; // Fallthrough
15237     case Intrinsic::x86_sse41_ptestc:
15238     case Intrinsic::x86_avx_ptestc_256:
15239       // CF = 1
15240       X86CC = X86::COND_B;
15241       break;
15242     case Intrinsic::x86_avx_vtestnzc_ps:
15243     case Intrinsic::x86_avx_vtestnzc_pd:
15244     case Intrinsic::x86_avx_vtestnzc_ps_256:
15245     case Intrinsic::x86_avx_vtestnzc_pd_256:
15246       IsTestPacked = true; // Fallthrough
15247     case Intrinsic::x86_sse41_ptestnzc:
15248     case Intrinsic::x86_avx_ptestnzc_256:
15249       // ZF and CF = 0
15250       X86CC = X86::COND_A;
15251       break;
15252     }
15253
15254     SDValue LHS = Op.getOperand(1);
15255     SDValue RHS = Op.getOperand(2);
15256     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
15257     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
15258     SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
15259     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
15260     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15261   }
15262   case Intrinsic::x86_avx512_kortestz_w:
15263   case Intrinsic::x86_avx512_kortestc_w: {
15264     unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
15265     SDValue LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(1));
15266     SDValue RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(2));
15267     SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
15268     SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
15269     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
15270     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15271   }
15272
15273   case Intrinsic::x86_sse42_pcmpistria128:
15274   case Intrinsic::x86_sse42_pcmpestria128:
15275   case Intrinsic::x86_sse42_pcmpistric128:
15276   case Intrinsic::x86_sse42_pcmpestric128:
15277   case Intrinsic::x86_sse42_pcmpistrio128:
15278   case Intrinsic::x86_sse42_pcmpestrio128:
15279   case Intrinsic::x86_sse42_pcmpistris128:
15280   case Intrinsic::x86_sse42_pcmpestris128:
15281   case Intrinsic::x86_sse42_pcmpistriz128:
15282   case Intrinsic::x86_sse42_pcmpestriz128: {
15283     unsigned Opcode;
15284     unsigned X86CC;
15285     switch (IntNo) {
15286     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
15287     case Intrinsic::x86_sse42_pcmpistria128:
15288       Opcode = X86ISD::PCMPISTRI;
15289       X86CC = X86::COND_A;
15290       break;
15291     case Intrinsic::x86_sse42_pcmpestria128:
15292       Opcode = X86ISD::PCMPESTRI;
15293       X86CC = X86::COND_A;
15294       break;
15295     case Intrinsic::x86_sse42_pcmpistric128:
15296       Opcode = X86ISD::PCMPISTRI;
15297       X86CC = X86::COND_B;
15298       break;
15299     case Intrinsic::x86_sse42_pcmpestric128:
15300       Opcode = X86ISD::PCMPESTRI;
15301       X86CC = X86::COND_B;
15302       break;
15303     case Intrinsic::x86_sse42_pcmpistrio128:
15304       Opcode = X86ISD::PCMPISTRI;
15305       X86CC = X86::COND_O;
15306       break;
15307     case Intrinsic::x86_sse42_pcmpestrio128:
15308       Opcode = X86ISD::PCMPESTRI;
15309       X86CC = X86::COND_O;
15310       break;
15311     case Intrinsic::x86_sse42_pcmpistris128:
15312       Opcode = X86ISD::PCMPISTRI;
15313       X86CC = X86::COND_S;
15314       break;
15315     case Intrinsic::x86_sse42_pcmpestris128:
15316       Opcode = X86ISD::PCMPESTRI;
15317       X86CC = X86::COND_S;
15318       break;
15319     case Intrinsic::x86_sse42_pcmpistriz128:
15320       Opcode = X86ISD::PCMPISTRI;
15321       X86CC = X86::COND_E;
15322       break;
15323     case Intrinsic::x86_sse42_pcmpestriz128:
15324       Opcode = X86ISD::PCMPESTRI;
15325       X86CC = X86::COND_E;
15326       break;
15327     }
15328     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
15329     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
15330     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
15331     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15332                                 DAG.getConstant(X86CC, dl, MVT::i8),
15333                                 SDValue(PCMP.getNode(), 1));
15334     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15335   }
15336
15337   case Intrinsic::x86_sse42_pcmpistri128:
15338   case Intrinsic::x86_sse42_pcmpestri128: {
15339     unsigned Opcode;
15340     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
15341       Opcode = X86ISD::PCMPISTRI;
15342     else
15343       Opcode = X86ISD::PCMPESTRI;
15344
15345     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
15346     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
15347     return DAG.getNode(Opcode, dl, VTs, NewOps);
15348   }
15349
15350   case Intrinsic::x86_seh_lsda: {
15351     // Compute the symbol for the LSDA. We know it'll get emitted later.
15352     MachineFunction &MF = DAG.getMachineFunction();
15353     SDValue Op1 = Op.getOperand(1);
15354     Op1->dump();
15355     auto *Fn = cast<Function>(cast<GlobalAddressSDNode>(Op1)->getGlobal());
15356     MCSymbol *LSDASym = MF.getMMI().getContext().getOrCreateLSDASymbol(
15357         GlobalValue::getRealLinkageName(Fn->getName()));
15358     StringRef Name = LSDASym->getName();
15359     assert(Name.data()[Name.size()] == '\0' && "not null terminated");
15360
15361     // Generate a simple absolute symbol reference. This intrinsic is only
15362     // supported on 32-bit Windows, which isn't PIC.
15363     SDValue Result =
15364         DAG.getTargetExternalSymbol(Name.data(), VT, X86II::MO_NOPREFIX);
15365     return DAG.getNode(X86ISD::Wrapper, dl, VT, Result);
15366   }
15367   }
15368 }
15369
15370 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15371                               SDValue Src, SDValue Mask, SDValue Base,
15372                               SDValue Index, SDValue ScaleOp, SDValue Chain,
15373                               const X86Subtarget * Subtarget) {
15374   SDLoc dl(Op);
15375   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15376   assert(C && "Invalid scale type");
15377   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
15378   EVT MaskVT = MVT::getVectorVT(MVT::i1,
15379                              Index.getSimpleValueType().getVectorNumElements());
15380   SDValue MaskInReg;
15381   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15382   if (MaskC)
15383     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
15384   else
15385     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
15386   SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
15387   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
15388   SDValue Segment = DAG.getRegister(0, MVT::i32);
15389   if (Src.getOpcode() == ISD::UNDEF)
15390     Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
15391   SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
15392   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
15393   SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
15394   return DAG.getMergeValues(RetOps, dl);
15395 }
15396
15397 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15398                                SDValue Src, SDValue Mask, SDValue Base,
15399                                SDValue Index, SDValue ScaleOp, SDValue Chain) {
15400   SDLoc dl(Op);
15401   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15402   assert(C && "Invalid scale type");
15403   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
15404   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
15405   SDValue Segment = DAG.getRegister(0, MVT::i32);
15406   EVT MaskVT = MVT::getVectorVT(MVT::i1,
15407                              Index.getSimpleValueType().getVectorNumElements());
15408   SDValue MaskInReg;
15409   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15410   if (MaskC)
15411     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
15412   else
15413     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
15414   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
15415   SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
15416   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
15417   return SDValue(Res, 1);
15418 }
15419
15420 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15421                                SDValue Mask, SDValue Base, SDValue Index,
15422                                SDValue ScaleOp, SDValue Chain) {
15423   SDLoc dl(Op);
15424   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15425   assert(C && "Invalid scale type");
15426   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
15427   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
15428   SDValue Segment = DAG.getRegister(0, MVT::i32);
15429   EVT MaskVT =
15430     MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
15431   SDValue MaskInReg;
15432   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15433   if (MaskC)
15434     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
15435   else
15436     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
15437   //SDVTList VTs = DAG.getVTList(MVT::Other);
15438   SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
15439   SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
15440   return SDValue(Res, 0);
15441 }
15442
15443 // getReadPerformanceCounter - Handles the lowering of builtin intrinsics that
15444 // read performance monitor counters (x86_rdpmc).
15445 static void getReadPerformanceCounter(SDNode *N, SDLoc DL,
15446                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
15447                               SmallVectorImpl<SDValue> &Results) {
15448   assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
15449   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
15450   SDValue LO, HI;
15451
15452   // The ECX register is used to select the index of the performance counter
15453   // to read.
15454   SDValue Chain = DAG.getCopyToReg(N->getOperand(0), DL, X86::ECX,
15455                                    N->getOperand(2));
15456   SDValue rd = DAG.getNode(X86ISD::RDPMC_DAG, DL, Tys, Chain);
15457
15458   // Reads the content of a 64-bit performance counter and returns it in the
15459   // registers EDX:EAX.
15460   if (Subtarget->is64Bit()) {
15461     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
15462     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
15463                             LO.getValue(2));
15464   } else {
15465     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
15466     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
15467                             LO.getValue(2));
15468   }
15469   Chain = HI.getValue(1);
15470
15471   if (Subtarget->is64Bit()) {
15472     // The EAX register is loaded with the low-order 32 bits. The EDX register
15473     // is loaded with the supported high-order bits of the counter.
15474     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
15475                               DAG.getConstant(32, DL, MVT::i8));
15476     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
15477     Results.push_back(Chain);
15478     return;
15479   }
15480
15481   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
15482   SDValue Ops[] = { LO, HI };
15483   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
15484   Results.push_back(Pair);
15485   Results.push_back(Chain);
15486 }
15487
15488 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
15489 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
15490 // also used to custom lower READCYCLECOUNTER nodes.
15491 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
15492                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
15493                               SmallVectorImpl<SDValue> &Results) {
15494   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
15495   SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
15496   SDValue LO, HI;
15497
15498   // The processor's time-stamp counter (a 64-bit MSR) is stored into the
15499   // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
15500   // and the EAX register is loaded with the low-order 32 bits.
15501   if (Subtarget->is64Bit()) {
15502     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
15503     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
15504                             LO.getValue(2));
15505   } else {
15506     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
15507     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
15508                             LO.getValue(2));
15509   }
15510   SDValue Chain = HI.getValue(1);
15511
15512   if (Opcode == X86ISD::RDTSCP_DAG) {
15513     assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
15514
15515     // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
15516     // the ECX register. Add 'ecx' explicitly to the chain.
15517     SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
15518                                      HI.getValue(2));
15519     // Explicitly store the content of ECX at the location passed in input
15520     // to the 'rdtscp' intrinsic.
15521     Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
15522                          MachinePointerInfo(), false, false, 0);
15523   }
15524
15525   if (Subtarget->is64Bit()) {
15526     // The EDX register is loaded with the high-order 32 bits of the MSR, and
15527     // the EAX register is loaded with the low-order 32 bits.
15528     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
15529                               DAG.getConstant(32, DL, MVT::i8));
15530     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
15531     Results.push_back(Chain);
15532     return;
15533   }
15534
15535   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
15536   SDValue Ops[] = { LO, HI };
15537   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
15538   Results.push_back(Pair);
15539   Results.push_back(Chain);
15540 }
15541
15542 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
15543                                      SelectionDAG &DAG) {
15544   SmallVector<SDValue, 2> Results;
15545   SDLoc DL(Op);
15546   getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
15547                           Results);
15548   return DAG.getMergeValues(Results, DL);
15549 }
15550
15551
15552 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
15553                                       SelectionDAG &DAG) {
15554   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
15555
15556   const IntrinsicData* IntrData = getIntrinsicWithChain(IntNo);
15557   if (!IntrData)
15558     return SDValue();
15559
15560   SDLoc dl(Op);
15561   switch(IntrData->Type) {
15562   default:
15563     llvm_unreachable("Unknown Intrinsic Type");
15564     break;
15565   case RDSEED:
15566   case RDRAND: {
15567     // Emit the node with the right value type.
15568     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
15569     SDValue Result = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
15570
15571     // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
15572     // Otherwise return the value from Rand, which is always 0, casted to i32.
15573     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
15574                       DAG.getConstant(1, dl, Op->getValueType(1)),
15575                       DAG.getConstant(X86::COND_B, dl, MVT::i32),
15576                       SDValue(Result.getNode(), 1) };
15577     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
15578                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
15579                                   Ops);
15580
15581     // Return { result, isValid, chain }.
15582     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
15583                        SDValue(Result.getNode(), 2));
15584   }
15585   case GATHER: {
15586   //gather(v1, mask, index, base, scale);
15587     SDValue Chain = Op.getOperand(0);
15588     SDValue Src   = Op.getOperand(2);
15589     SDValue Base  = Op.getOperand(3);
15590     SDValue Index = Op.getOperand(4);
15591     SDValue Mask  = Op.getOperand(5);
15592     SDValue Scale = Op.getOperand(6);
15593     return getGatherNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index, Scale,
15594                          Chain, Subtarget);
15595   }
15596   case SCATTER: {
15597   //scatter(base, mask, index, v1, scale);
15598     SDValue Chain = Op.getOperand(0);
15599     SDValue Base  = Op.getOperand(2);
15600     SDValue Mask  = Op.getOperand(3);
15601     SDValue Index = Op.getOperand(4);
15602     SDValue Src   = Op.getOperand(5);
15603     SDValue Scale = Op.getOperand(6);
15604     return getScatterNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index,
15605                           Scale, Chain);
15606   }
15607   case PREFETCH: {
15608     SDValue Hint = Op.getOperand(6);
15609     unsigned HintVal = cast<ConstantSDNode>(Hint)->getZExtValue();
15610     assert(HintVal < 2 && "Wrong prefetch hint in intrinsic: should be 0 or 1");
15611     unsigned Opcode = (HintVal ? IntrData->Opc1 : IntrData->Opc0);
15612     SDValue Chain = Op.getOperand(0);
15613     SDValue Mask  = Op.getOperand(2);
15614     SDValue Index = Op.getOperand(3);
15615     SDValue Base  = Op.getOperand(4);
15616     SDValue Scale = Op.getOperand(5);
15617     return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
15618   }
15619   // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
15620   case RDTSC: {
15621     SmallVector<SDValue, 2> Results;
15622     getReadTimeStampCounter(Op.getNode(), dl, IntrData->Opc0, DAG, Subtarget,
15623                             Results);
15624     return DAG.getMergeValues(Results, dl);
15625   }
15626   // Read Performance Monitoring Counters.
15627   case RDPMC: {
15628     SmallVector<SDValue, 2> Results;
15629     getReadPerformanceCounter(Op.getNode(), dl, DAG, Subtarget, Results);
15630     return DAG.getMergeValues(Results, dl);
15631   }
15632   // XTEST intrinsics.
15633   case XTEST: {
15634     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
15635     SDValue InTrans = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
15636     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15637                                 DAG.getConstant(X86::COND_NE, dl, MVT::i8),
15638                                 InTrans);
15639     SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
15640     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
15641                        Ret, SDValue(InTrans.getNode(), 1));
15642   }
15643   // ADC/ADCX/SBB
15644   case ADX: {
15645     SmallVector<SDValue, 2> Results;
15646     SDVTList CFVTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
15647     SDVTList VTs = DAG.getVTList(Op.getOperand(3)->getValueType(0), MVT::Other);
15648     SDValue GenCF = DAG.getNode(X86ISD::ADD, dl, CFVTs, Op.getOperand(2),
15649                                 DAG.getConstant(-1, dl, MVT::i8));
15650     SDValue Res = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(3),
15651                               Op.getOperand(4), GenCF.getValue(1));
15652     SDValue Store = DAG.getStore(Op.getOperand(0), dl, Res.getValue(0),
15653                                  Op.getOperand(5), MachinePointerInfo(),
15654                                  false, false, 0);
15655     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15656                                 DAG.getConstant(X86::COND_B, dl, MVT::i8),
15657                                 Res.getValue(1));
15658     Results.push_back(SetCC);
15659     Results.push_back(Store);
15660     return DAG.getMergeValues(Results, dl);
15661   }
15662   case COMPRESS_TO_MEM: {
15663     SDLoc dl(Op);
15664     SDValue Mask = Op.getOperand(4);
15665     SDValue DataToCompress = Op.getOperand(3);
15666     SDValue Addr = Op.getOperand(2);
15667     SDValue Chain = Op.getOperand(0);
15668
15669     if (isAllOnes(Mask)) // return just a store
15670       return DAG.getStore(Chain, dl, DataToCompress, Addr,
15671                           MachinePointerInfo(), false, false, 0);
15672
15673     EVT VT = DataToCompress.getValueType();
15674     EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15675                                   VT.getVectorNumElements());
15676     EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15677                                      Mask.getValueType().getSizeInBits());
15678     SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15679                                 DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
15680                                 DAG.getIntPtrConstant(0, dl));
15681
15682     SDValue Compressed =  DAG.getNode(IntrData->Opc0, dl, VT, VMask,
15683                                       DataToCompress, DAG.getUNDEF(VT));
15684     return DAG.getStore(Chain, dl, Compressed, Addr,
15685                         MachinePointerInfo(), false, false, 0);
15686   }
15687   case EXPAND_FROM_MEM: {
15688     SDLoc dl(Op);
15689     SDValue Mask = Op.getOperand(4);
15690     SDValue PathThru = Op.getOperand(3);
15691     SDValue Addr = Op.getOperand(2);
15692     SDValue Chain = Op.getOperand(0);
15693     EVT VT = Op.getValueType();
15694
15695     if (isAllOnes(Mask)) // return just a load
15696       return DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(), false, false,
15697                          false, 0);
15698     EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15699                                   VT.getVectorNumElements());
15700     EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15701                                      Mask.getValueType().getSizeInBits());
15702     SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15703                                 DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
15704                                 DAG.getIntPtrConstant(0, dl));
15705
15706     SDValue DataToExpand = DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(),
15707                                    false, false, false, 0);
15708
15709     SDValue Results[] = {
15710         DAG.getNode(IntrData->Opc0, dl, VT, VMask, DataToExpand, PathThru),
15711         Chain};
15712     return DAG.getMergeValues(Results, dl);
15713   }
15714   }
15715 }
15716
15717 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
15718                                            SelectionDAG &DAG) const {
15719   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
15720   MFI->setReturnAddressIsTaken(true);
15721
15722   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
15723     return SDValue();
15724
15725   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15726   SDLoc dl(Op);
15727   EVT PtrVT = getPointerTy();
15728
15729   if (Depth > 0) {
15730     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
15731     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15732     SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), dl, PtrVT);
15733     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
15734                        DAG.getNode(ISD::ADD, dl, PtrVT,
15735                                    FrameAddr, Offset),
15736                        MachinePointerInfo(), false, false, false, 0);
15737   }
15738
15739   // Just load the return address.
15740   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
15741   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
15742                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
15743 }
15744
15745 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
15746   MachineFunction &MF = DAG.getMachineFunction();
15747   MachineFrameInfo *MFI = MF.getFrameInfo();
15748   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
15749   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15750   EVT VT = Op.getValueType();
15751
15752   MFI->setFrameAddressIsTaken(true);
15753
15754   if (MF.getTarget().getMCAsmInfo()->usesWindowsCFI()) {
15755     // Depth > 0 makes no sense on targets which use Windows unwind codes.  It
15756     // is not possible to crawl up the stack without looking at the unwind codes
15757     // simultaneously.
15758     int FrameAddrIndex = FuncInfo->getFAIndex();
15759     if (!FrameAddrIndex) {
15760       // Set up a frame object for the return address.
15761       unsigned SlotSize = RegInfo->getSlotSize();
15762       FrameAddrIndex = MF.getFrameInfo()->CreateFixedObject(
15763           SlotSize, /*Offset=*/0, /*IsImmutable=*/false);
15764       FuncInfo->setFAIndex(FrameAddrIndex);
15765     }
15766     return DAG.getFrameIndex(FrameAddrIndex, VT);
15767   }
15768
15769   unsigned FrameReg =
15770       RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
15771   SDLoc dl(Op);  // FIXME probably not meaningful
15772   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15773   assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
15774           (FrameReg == X86::EBP && VT == MVT::i32)) &&
15775          "Invalid Frame Register!");
15776   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
15777   while (Depth--)
15778     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
15779                             MachinePointerInfo(),
15780                             false, false, false, 0);
15781   return FrameAddr;
15782 }
15783
15784 // FIXME? Maybe this could be a TableGen attribute on some registers and
15785 // this table could be generated automatically from RegInfo.
15786 unsigned X86TargetLowering::getRegisterByName(const char* RegName,
15787                                               EVT VT) const {
15788   unsigned Reg = StringSwitch<unsigned>(RegName)
15789                        .Case("esp", X86::ESP)
15790                        .Case("rsp", X86::RSP)
15791                        .Default(0);
15792   if (Reg)
15793     return Reg;
15794   report_fatal_error("Invalid register name global variable");
15795 }
15796
15797 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
15798                                                      SelectionDAG &DAG) const {
15799   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15800   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize(), SDLoc(Op));
15801 }
15802
15803 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
15804   SDValue Chain     = Op.getOperand(0);
15805   SDValue Offset    = Op.getOperand(1);
15806   SDValue Handler   = Op.getOperand(2);
15807   SDLoc dl      (Op);
15808
15809   EVT PtrVT = getPointerTy();
15810   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15811   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
15812   assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
15813           (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
15814          "Invalid Frame Register!");
15815   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
15816   unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
15817
15818   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
15819                                  DAG.getIntPtrConstant(RegInfo->getSlotSize(),
15820                                                        dl));
15821   StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
15822   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
15823                        false, false, 0);
15824   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
15825
15826   return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
15827                      DAG.getRegister(StoreAddrReg, PtrVT));
15828 }
15829
15830 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
15831                                                SelectionDAG &DAG) const {
15832   SDLoc DL(Op);
15833   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
15834                      DAG.getVTList(MVT::i32, MVT::Other),
15835                      Op.getOperand(0), Op.getOperand(1));
15836 }
15837
15838 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
15839                                                 SelectionDAG &DAG) const {
15840   SDLoc DL(Op);
15841   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
15842                      Op.getOperand(0), Op.getOperand(1));
15843 }
15844
15845 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
15846   return Op.getOperand(0);
15847 }
15848
15849 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
15850                                                 SelectionDAG &DAG) const {
15851   SDValue Root = Op.getOperand(0);
15852   SDValue Trmp = Op.getOperand(1); // trampoline
15853   SDValue FPtr = Op.getOperand(2); // nested function
15854   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
15855   SDLoc dl (Op);
15856
15857   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
15858   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
15859
15860   if (Subtarget->is64Bit()) {
15861     SDValue OutChains[6];
15862
15863     // Large code-model.
15864     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
15865     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
15866
15867     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
15868     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
15869
15870     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
15871
15872     // Load the pointer to the nested function into R11.
15873     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
15874     SDValue Addr = Trmp;
15875     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
15876                                 Addr, MachinePointerInfo(TrmpAddr),
15877                                 false, false, 0);
15878
15879     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15880                        DAG.getConstant(2, dl, MVT::i64));
15881     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
15882                                 MachinePointerInfo(TrmpAddr, 2),
15883                                 false, false, 2);
15884
15885     // Load the 'nest' parameter value into R10.
15886     // R10 is specified in X86CallingConv.td
15887     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
15888     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15889                        DAG.getConstant(10, dl, MVT::i64));
15890     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
15891                                 Addr, MachinePointerInfo(TrmpAddr, 10),
15892                                 false, false, 0);
15893
15894     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15895                        DAG.getConstant(12, dl, MVT::i64));
15896     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
15897                                 MachinePointerInfo(TrmpAddr, 12),
15898                                 false, false, 2);
15899
15900     // Jump to the nested function.
15901     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
15902     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15903                        DAG.getConstant(20, dl, MVT::i64));
15904     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
15905                                 Addr, MachinePointerInfo(TrmpAddr, 20),
15906                                 false, false, 0);
15907
15908     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
15909     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15910                        DAG.getConstant(22, dl, MVT::i64));
15911     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, dl, MVT::i8),
15912                                 Addr, MachinePointerInfo(TrmpAddr, 22),
15913                                 false, false, 0);
15914
15915     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
15916   } else {
15917     const Function *Func =
15918       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
15919     CallingConv::ID CC = Func->getCallingConv();
15920     unsigned NestReg;
15921
15922     switch (CC) {
15923     default:
15924       llvm_unreachable("Unsupported calling convention");
15925     case CallingConv::C:
15926     case CallingConv::X86_StdCall: {
15927       // Pass 'nest' parameter in ECX.
15928       // Must be kept in sync with X86CallingConv.td
15929       NestReg = X86::ECX;
15930
15931       // Check that ECX wasn't needed by an 'inreg' parameter.
15932       FunctionType *FTy = Func->getFunctionType();
15933       const AttributeSet &Attrs = Func->getAttributes();
15934
15935       if (!Attrs.isEmpty() && !Func->isVarArg()) {
15936         unsigned InRegCount = 0;
15937         unsigned Idx = 1;
15938
15939         for (FunctionType::param_iterator I = FTy->param_begin(),
15940              E = FTy->param_end(); I != E; ++I, ++Idx)
15941           if (Attrs.hasAttribute(Idx, Attribute::InReg))
15942             // FIXME: should only count parameters that are lowered to integers.
15943             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
15944
15945         if (InRegCount > 2) {
15946           report_fatal_error("Nest register in use - reduce number of inreg"
15947                              " parameters!");
15948         }
15949       }
15950       break;
15951     }
15952     case CallingConv::X86_FastCall:
15953     case CallingConv::X86_ThisCall:
15954     case CallingConv::Fast:
15955       // Pass 'nest' parameter in EAX.
15956       // Must be kept in sync with X86CallingConv.td
15957       NestReg = X86::EAX;
15958       break;
15959     }
15960
15961     SDValue OutChains[4];
15962     SDValue Addr, Disp;
15963
15964     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15965                        DAG.getConstant(10, dl, MVT::i32));
15966     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
15967
15968     // This is storing the opcode for MOV32ri.
15969     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
15970     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
15971     OutChains[0] = DAG.getStore(Root, dl,
15972                                 DAG.getConstant(MOV32ri|N86Reg, dl, MVT::i8),
15973                                 Trmp, MachinePointerInfo(TrmpAddr),
15974                                 false, false, 0);
15975
15976     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15977                        DAG.getConstant(1, dl, MVT::i32));
15978     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
15979                                 MachinePointerInfo(TrmpAddr, 1),
15980                                 false, false, 1);
15981
15982     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
15983     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15984                        DAG.getConstant(5, dl, MVT::i32));
15985     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, dl, MVT::i8),
15986                                 Addr, MachinePointerInfo(TrmpAddr, 5),
15987                                 false, false, 1);
15988
15989     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15990                        DAG.getConstant(6, dl, MVT::i32));
15991     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
15992                                 MachinePointerInfo(TrmpAddr, 6),
15993                                 false, false, 1);
15994
15995     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
15996   }
15997 }
15998
15999 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
16000                                             SelectionDAG &DAG) const {
16001   /*
16002    The rounding mode is in bits 11:10 of FPSR, and has the following
16003    settings:
16004      00 Round to nearest
16005      01 Round to -inf
16006      10 Round to +inf
16007      11 Round to 0
16008
16009   FLT_ROUNDS, on the other hand, expects the following:
16010     -1 Undefined
16011      0 Round to 0
16012      1 Round to nearest
16013      2 Round to +inf
16014      3 Round to -inf
16015
16016   To perform the conversion, we do:
16017     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
16018   */
16019
16020   MachineFunction &MF = DAG.getMachineFunction();
16021   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
16022   unsigned StackAlignment = TFI.getStackAlignment();
16023   MVT VT = Op.getSimpleValueType();
16024   SDLoc DL(Op);
16025
16026   // Save FP Control Word to stack slot
16027   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
16028   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
16029
16030   MachineMemOperand *MMO =
16031    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
16032                            MachineMemOperand::MOStore, 2, 2);
16033
16034   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
16035   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
16036                                           DAG.getVTList(MVT::Other),
16037                                           Ops, MVT::i16, MMO);
16038
16039   // Load FP Control Word from stack slot
16040   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
16041                             MachinePointerInfo(), false, false, false, 0);
16042
16043   // Transform as necessary
16044   SDValue CWD1 =
16045     DAG.getNode(ISD::SRL, DL, MVT::i16,
16046                 DAG.getNode(ISD::AND, DL, MVT::i16,
16047                             CWD, DAG.getConstant(0x800, DL, MVT::i16)),
16048                 DAG.getConstant(11, DL, MVT::i8));
16049   SDValue CWD2 =
16050     DAG.getNode(ISD::SRL, DL, MVT::i16,
16051                 DAG.getNode(ISD::AND, DL, MVT::i16,
16052                             CWD, DAG.getConstant(0x400, DL, MVT::i16)),
16053                 DAG.getConstant(9, DL, MVT::i8));
16054
16055   SDValue RetVal =
16056     DAG.getNode(ISD::AND, DL, MVT::i16,
16057                 DAG.getNode(ISD::ADD, DL, MVT::i16,
16058                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
16059                             DAG.getConstant(1, DL, MVT::i16)),
16060                 DAG.getConstant(3, DL, MVT::i16));
16061
16062   return DAG.getNode((VT.getSizeInBits() < 16 ?
16063                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
16064 }
16065
16066 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
16067   MVT VT = Op.getSimpleValueType();
16068   EVT OpVT = VT;
16069   unsigned NumBits = VT.getSizeInBits();
16070   SDLoc dl(Op);
16071
16072   Op = Op.getOperand(0);
16073   if (VT == MVT::i8) {
16074     // Zero extend to i32 since there is not an i8 bsr.
16075     OpVT = MVT::i32;
16076     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
16077   }
16078
16079   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
16080   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
16081   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
16082
16083   // If src is zero (i.e. bsr sets ZF), returns NumBits.
16084   SDValue Ops[] = {
16085     Op,
16086     DAG.getConstant(NumBits + NumBits - 1, dl, OpVT),
16087     DAG.getConstant(X86::COND_E, dl, MVT::i8),
16088     Op.getValue(1)
16089   };
16090   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
16091
16092   // Finally xor with NumBits-1.
16093   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
16094                    DAG.getConstant(NumBits - 1, dl, OpVT));
16095
16096   if (VT == MVT::i8)
16097     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
16098   return Op;
16099 }
16100
16101 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
16102   MVT VT = Op.getSimpleValueType();
16103   EVT OpVT = VT;
16104   unsigned NumBits = VT.getSizeInBits();
16105   SDLoc dl(Op);
16106
16107   Op = Op.getOperand(0);
16108   if (VT == MVT::i8) {
16109     // Zero extend to i32 since there is not an i8 bsr.
16110     OpVT = MVT::i32;
16111     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
16112   }
16113
16114   // Issue a bsr (scan bits in reverse).
16115   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
16116   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
16117
16118   // And xor with NumBits-1.
16119   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
16120                    DAG.getConstant(NumBits - 1, dl, OpVT));
16121
16122   if (VT == MVT::i8)
16123     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
16124   return Op;
16125 }
16126
16127 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
16128   MVT VT = Op.getSimpleValueType();
16129   unsigned NumBits = VT.getSizeInBits();
16130   SDLoc dl(Op);
16131   Op = Op.getOperand(0);
16132
16133   // Issue a bsf (scan bits forward) which also sets EFLAGS.
16134   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
16135   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
16136
16137   // If src is zero (i.e. bsf sets ZF), returns NumBits.
16138   SDValue Ops[] = {
16139     Op,
16140     DAG.getConstant(NumBits, dl, VT),
16141     DAG.getConstant(X86::COND_E, dl, MVT::i8),
16142     Op.getValue(1)
16143   };
16144   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
16145 }
16146
16147 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
16148 // ones, and then concatenate the result back.
16149 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
16150   MVT VT = Op.getSimpleValueType();
16151
16152   assert(VT.is256BitVector() && VT.isInteger() &&
16153          "Unsupported value type for operation");
16154
16155   unsigned NumElems = VT.getVectorNumElements();
16156   SDLoc dl(Op);
16157
16158   // Extract the LHS vectors
16159   SDValue LHS = Op.getOperand(0);
16160   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
16161   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
16162
16163   // Extract the RHS vectors
16164   SDValue RHS = Op.getOperand(1);
16165   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
16166   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
16167
16168   MVT EltVT = VT.getVectorElementType();
16169   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
16170
16171   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
16172                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
16173                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
16174 }
16175
16176 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
16177   assert(Op.getSimpleValueType().is256BitVector() &&
16178          Op.getSimpleValueType().isInteger() &&
16179          "Only handle AVX 256-bit vector integer operation");
16180   return Lower256IntArith(Op, DAG);
16181 }
16182
16183 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
16184   assert(Op.getSimpleValueType().is256BitVector() &&
16185          Op.getSimpleValueType().isInteger() &&
16186          "Only handle AVX 256-bit vector integer operation");
16187   return Lower256IntArith(Op, DAG);
16188 }
16189
16190 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
16191                         SelectionDAG &DAG) {
16192   SDLoc dl(Op);
16193   MVT VT = Op.getSimpleValueType();
16194
16195   // Decompose 256-bit ops into smaller 128-bit ops.
16196   if (VT.is256BitVector() && !Subtarget->hasInt256())
16197     return Lower256IntArith(Op, DAG);
16198
16199   SDValue A = Op.getOperand(0);
16200   SDValue B = Op.getOperand(1);
16201
16202   // Lower v16i8/v32i8 mul as promotion to v8i16/v16i16 vector
16203   // pairs, multiply and truncate.
16204   if (VT == MVT::v16i8 || VT == MVT::v32i8) {
16205     if (Subtarget->hasInt256()) {
16206       if (VT == MVT::v32i8) {
16207         MVT SubVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() / 2);
16208         SDValue Lo = DAG.getIntPtrConstant(0, dl);
16209         SDValue Hi = DAG.getIntPtrConstant(VT.getVectorNumElements() / 2, dl);
16210         SDValue ALo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Lo);
16211         SDValue BLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Lo);
16212         SDValue AHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Hi);
16213         SDValue BHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Hi);
16214         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
16215                            DAG.getNode(ISD::MUL, dl, SubVT, ALo, BLo),
16216                            DAG.getNode(ISD::MUL, dl, SubVT, AHi, BHi));
16217       }
16218
16219       MVT ExVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements());
16220       return DAG.getNode(
16221           ISD::TRUNCATE, dl, VT,
16222           DAG.getNode(ISD::MUL, dl, ExVT,
16223                       DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, A),
16224                       DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, B)));
16225     }
16226
16227     assert(VT == MVT::v16i8 &&
16228            "Pre-AVX2 support only supports v16i8 multiplication");
16229     MVT ExVT = MVT::v8i16;
16230
16231     // Extract the lo parts and sign extend to i16
16232     SDValue ALo, BLo;
16233     if (Subtarget->hasSSE41()) {
16234       ALo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, A);
16235       BLo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, B);
16236     } else {
16237       const int ShufMask[] = {-1, 0, -1, 1, -1, 2, -1, 3,
16238                               -1, 4, -1, 5, -1, 6, -1, 7};
16239       ALo = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
16240       BLo = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
16241       ALo = DAG.getNode(ISD::BITCAST, dl, ExVT, ALo);
16242       BLo = DAG.getNode(ISD::BITCAST, dl, ExVT, BLo);
16243       ALo = DAG.getNode(ISD::SRA, dl, ExVT, ALo, DAG.getConstant(8, dl, ExVT));
16244       BLo = DAG.getNode(ISD::SRA, dl, ExVT, BLo, DAG.getConstant(8, dl, ExVT));
16245     }
16246
16247     // Extract the hi parts and sign extend to i16
16248     SDValue AHi, BHi;
16249     if (Subtarget->hasSSE41()) {
16250       const int ShufMask[] = {8,  9,  10, 11, 12, 13, 14, 15,
16251                               -1, -1, -1, -1, -1, -1, -1, -1};
16252       AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
16253       BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
16254       AHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, AHi);
16255       BHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, BHi);
16256     } else {
16257       const int ShufMask[] = {-1, 8,  -1, 9,  -1, 10, -1, 11,
16258                               -1, 12, -1, 13, -1, 14, -1, 15};
16259       AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
16260       BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
16261       AHi = DAG.getNode(ISD::BITCAST, dl, ExVT, AHi);
16262       BHi = DAG.getNode(ISD::BITCAST, dl, ExVT, BHi);
16263       AHi = DAG.getNode(ISD::SRA, dl, ExVT, AHi, DAG.getConstant(8, dl, ExVT));
16264       BHi = DAG.getNode(ISD::SRA, dl, ExVT, BHi, DAG.getConstant(8, dl, ExVT));
16265     }
16266
16267     // Multiply, mask the lower 8bits of the lo/hi results and pack
16268     SDValue RLo = DAG.getNode(ISD::MUL, dl, ExVT, ALo, BLo);
16269     SDValue RHi = DAG.getNode(ISD::MUL, dl, ExVT, AHi, BHi);
16270     RLo = DAG.getNode(ISD::AND, dl, ExVT, RLo, DAG.getConstant(255, dl, ExVT));
16271     RHi = DAG.getNode(ISD::AND, dl, ExVT, RHi, DAG.getConstant(255, dl, ExVT));
16272     return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
16273   }
16274
16275   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
16276   if (VT == MVT::v4i32) {
16277     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
16278            "Should not custom lower when pmuldq is available!");
16279
16280     // Extract the odd parts.
16281     static const int UnpackMask[] = { 1, -1, 3, -1 };
16282     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
16283     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
16284
16285     // Multiply the even parts.
16286     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
16287     // Now multiply odd parts.
16288     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
16289
16290     Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
16291     Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
16292
16293     // Merge the two vectors back together with a shuffle. This expands into 2
16294     // shuffles.
16295     static const int ShufMask[] = { 0, 4, 2, 6 };
16296     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
16297   }
16298
16299   assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
16300          "Only know how to lower V2I64/V4I64/V8I64 multiply");
16301
16302   //  Ahi = psrlqi(a, 32);
16303   //  Bhi = psrlqi(b, 32);
16304   //
16305   //  AloBlo = pmuludq(a, b);
16306   //  AloBhi = pmuludq(a, Bhi);
16307   //  AhiBlo = pmuludq(Ahi, b);
16308
16309   //  AloBhi = psllqi(AloBhi, 32);
16310   //  AhiBlo = psllqi(AhiBlo, 32);
16311   //  return AloBlo + AloBhi + AhiBlo;
16312
16313   SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
16314   SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
16315
16316   // Bit cast to 32-bit vectors for MULUDQ
16317   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
16318                                   (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
16319   A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
16320   B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
16321   Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
16322   Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
16323
16324   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
16325   SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
16326   SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
16327
16328   AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
16329   AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
16330
16331   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
16332   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
16333 }
16334
16335 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
16336   assert(Subtarget->isTargetWin64() && "Unexpected target");
16337   EVT VT = Op.getValueType();
16338   assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
16339          "Unexpected return type for lowering");
16340
16341   RTLIB::Libcall LC;
16342   bool isSigned;
16343   switch (Op->getOpcode()) {
16344   default: llvm_unreachable("Unexpected request for libcall!");
16345   case ISD::SDIV:      isSigned = true;  LC = RTLIB::SDIV_I128;    break;
16346   case ISD::UDIV:      isSigned = false; LC = RTLIB::UDIV_I128;    break;
16347   case ISD::SREM:      isSigned = true;  LC = RTLIB::SREM_I128;    break;
16348   case ISD::UREM:      isSigned = false; LC = RTLIB::UREM_I128;    break;
16349   case ISD::SDIVREM:   isSigned = true;  LC = RTLIB::SDIVREM_I128; break;
16350   case ISD::UDIVREM:   isSigned = false; LC = RTLIB::UDIVREM_I128; break;
16351   }
16352
16353   SDLoc dl(Op);
16354   SDValue InChain = DAG.getEntryNode();
16355
16356   TargetLowering::ArgListTy Args;
16357   TargetLowering::ArgListEntry Entry;
16358   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
16359     EVT ArgVT = Op->getOperand(i).getValueType();
16360     assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
16361            "Unexpected argument type for lowering");
16362     SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
16363     Entry.Node = StackPtr;
16364     InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
16365                            false, false, 16);
16366     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
16367     Entry.Ty = PointerType::get(ArgTy,0);
16368     Entry.isSExt = false;
16369     Entry.isZExt = false;
16370     Args.push_back(Entry);
16371   }
16372
16373   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
16374                                          getPointerTy());
16375
16376   TargetLowering::CallLoweringInfo CLI(DAG);
16377   CLI.setDebugLoc(dl).setChain(InChain)
16378     .setCallee(getLibcallCallingConv(LC),
16379                static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
16380                Callee, std::move(Args), 0)
16381     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
16382
16383   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
16384   return DAG.getNode(ISD::BITCAST, dl, VT, CallInfo.first);
16385 }
16386
16387 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
16388                              SelectionDAG &DAG) {
16389   SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
16390   EVT VT = Op0.getValueType();
16391   SDLoc dl(Op);
16392
16393   assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
16394          (VT == MVT::v8i32 && Subtarget->hasInt256()));
16395
16396   // PMULxD operations multiply each even value (starting at 0) of LHS with
16397   // the related value of RHS and produce a widen result.
16398   // E.g., PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
16399   // => <2 x i64> <ae|cg>
16400   //
16401   // In other word, to have all the results, we need to perform two PMULxD:
16402   // 1. one with the even values.
16403   // 2. one with the odd values.
16404   // To achieve #2, with need to place the odd values at an even position.
16405   //
16406   // Place the odd value at an even position (basically, shift all values 1
16407   // step to the left):
16408   const int Mask[] = {1, -1, 3, -1, 5, -1, 7, -1};
16409   // <a|b|c|d> => <b|undef|d|undef>
16410   SDValue Odd0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
16411   // <e|f|g|h> => <f|undef|h|undef>
16412   SDValue Odd1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
16413
16414   // Emit two multiplies, one for the lower 2 ints and one for the higher 2
16415   // ints.
16416   MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
16417   bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
16418   unsigned Opcode =
16419       (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
16420   // PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
16421   // => <2 x i64> <ae|cg>
16422   SDValue Mul1 = DAG.getNode(ISD::BITCAST, dl, VT,
16423                              DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
16424   // PMULUDQ <4 x i32> <b|undef|d|undef>, <4 x i32> <f|undef|h|undef>
16425   // => <2 x i64> <bf|dh>
16426   SDValue Mul2 = DAG.getNode(ISD::BITCAST, dl, VT,
16427                              DAG.getNode(Opcode, dl, MulVT, Odd0, Odd1));
16428
16429   // Shuffle it back into the right order.
16430   SDValue Highs, Lows;
16431   if (VT == MVT::v8i32) {
16432     const int HighMask[] = {1, 9, 3, 11, 5, 13, 7, 15};
16433     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
16434     const int LowMask[] = {0, 8, 2, 10, 4, 12, 6, 14};
16435     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
16436   } else {
16437     const int HighMask[] = {1, 5, 3, 7};
16438     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
16439     const int LowMask[] = {0, 4, 2, 6};
16440     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
16441   }
16442
16443   // If we have a signed multiply but no PMULDQ fix up the high parts of a
16444   // unsigned multiply.
16445   if (IsSigned && !Subtarget->hasSSE41()) {
16446     SDValue ShAmt =
16447         DAG.getConstant(31, dl,
16448                         DAG.getTargetLoweringInfo().getShiftAmountTy(VT));
16449     SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
16450                              DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
16451     SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
16452                              DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
16453
16454     SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
16455     Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
16456   }
16457
16458   // The first result of MUL_LOHI is actually the low value, followed by the
16459   // high value.
16460   SDValue Ops[] = {Lows, Highs};
16461   return DAG.getMergeValues(Ops, dl);
16462 }
16463
16464 // Return true if the requred (according to Opcode) shift-imm form is natively
16465 // supported by the Subtarget
16466 static bool SupportedVectorShiftWithImm(MVT VT, const X86Subtarget *Subtarget, 
16467                                         unsigned Opcode) {
16468   if (VT.getScalarSizeInBits() < 16)
16469     return false;
16470  
16471   if (VT.is512BitVector() &&
16472       (VT.getScalarSizeInBits() > 16 || Subtarget->hasBWI()))
16473     return true;
16474
16475   bool LShift = VT.is128BitVector() || 
16476     (VT.is256BitVector() && Subtarget->hasInt256());
16477
16478   bool AShift = LShift && (Subtarget->hasVLX() ||
16479     (VT != MVT::v2i64 && VT != MVT::v4i64));
16480   return (Opcode == ISD::SRA) ? AShift : LShift;
16481 }
16482
16483 // The shift amount is a variable, but it is the same for all vector lanes.
16484 // These instrcutions are defined together with shift-immediate.
16485 static 
16486 bool SupportedVectorShiftWithBaseAmnt(MVT VT, const X86Subtarget *Subtarget, 
16487                                       unsigned Opcode) {
16488   return SupportedVectorShiftWithImm(VT, Subtarget, Opcode);
16489 }
16490
16491 // Return true if the requred (according to Opcode) variable-shift form is
16492 // natively supported by the Subtarget
16493 static bool SupportedVectorVarShift(MVT VT, const X86Subtarget *Subtarget, 
16494                                     unsigned Opcode) {
16495
16496   if (!Subtarget->hasInt256() || VT.getScalarSizeInBits() < 16)
16497     return false;
16498
16499   // vXi16 supported only on AVX-512, BWI
16500   if (VT.getScalarSizeInBits() == 16 && !Subtarget->hasBWI())
16501     return false;
16502
16503   if (VT.is512BitVector() || Subtarget->hasVLX())
16504     return true;
16505
16506   bool LShift = VT.is128BitVector() || VT.is256BitVector();
16507   bool AShift = LShift &&  VT != MVT::v2i64 && VT != MVT::v4i64;
16508   return (Opcode == ISD::SRA) ? AShift : LShift;
16509 }
16510
16511 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
16512                                          const X86Subtarget *Subtarget) {
16513   MVT VT = Op.getSimpleValueType();
16514   SDLoc dl(Op);
16515   SDValue R = Op.getOperand(0);
16516   SDValue Amt = Op.getOperand(1);
16517
16518   unsigned X86Opc = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHLI :
16519     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRLI : X86ISD::VSRAI;
16520
16521   // Optimize shl/srl/sra with constant shift amount.
16522   if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
16523     if (auto *ShiftConst = BVAmt->getConstantSplatNode()) {
16524       uint64_t ShiftAmt = ShiftConst->getZExtValue();
16525
16526       if (SupportedVectorShiftWithImm(VT, Subtarget, Op.getOpcode()))
16527         return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
16528
16529       if (VT == MVT::v16i8 || (Subtarget->hasInt256() && VT == MVT::v32i8)) {
16530         unsigned NumElts = VT.getVectorNumElements();
16531         MVT ShiftVT = MVT::getVectorVT(MVT::i16, NumElts / 2);
16532
16533         if (Op.getOpcode() == ISD::SHL) {
16534           // Make a large shift.
16535           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, ShiftVT,
16536                                                    R, ShiftAmt, DAG);
16537           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
16538           // Zero out the rightmost bits.
16539           SmallVector<SDValue, 32> V(
16540               NumElts, DAG.getConstant(uint8_t(-1U << ShiftAmt), dl, MVT::i8));
16541           return DAG.getNode(ISD::AND, dl, VT, SHL,
16542                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
16543         }
16544         if (Op.getOpcode() == ISD::SRL) {
16545           // Make a large shift.
16546           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ShiftVT,
16547                                                    R, ShiftAmt, DAG);
16548           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
16549           // Zero out the leftmost bits.
16550           SmallVector<SDValue, 32> V(
16551               NumElts, DAG.getConstant(uint8_t(-1U) >> ShiftAmt, dl, MVT::i8));
16552           return DAG.getNode(ISD::AND, dl, VT, SRL,
16553                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
16554         }
16555         if (Op.getOpcode() == ISD::SRA) {
16556           if (ShiftAmt == 7) {
16557             // R s>> 7  ===  R s< 0
16558             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
16559             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
16560           }
16561
16562           // R s>> a === ((R u>> a) ^ m) - m
16563           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
16564           SmallVector<SDValue, 32> V(NumElts,
16565                                      DAG.getConstant(128 >> ShiftAmt, dl,
16566                                                      MVT::i8));
16567           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
16568           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
16569           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
16570           return Res;
16571         }
16572         llvm_unreachable("Unknown shift opcode.");
16573       }
16574     }
16575   }
16576
16577   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
16578   if (!Subtarget->is64Bit() &&
16579       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
16580       Amt.getOpcode() == ISD::BITCAST &&
16581       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
16582     Amt = Amt.getOperand(0);
16583     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
16584                      VT.getVectorNumElements();
16585     unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
16586     uint64_t ShiftAmt = 0;
16587     for (unsigned i = 0; i != Ratio; ++i) {
16588       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
16589       if (!C)
16590         return SDValue();
16591       // 6 == Log2(64)
16592       ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
16593     }
16594     // Check remaining shift amounts.
16595     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
16596       uint64_t ShAmt = 0;
16597       for (unsigned j = 0; j != Ratio; ++j) {
16598         ConstantSDNode *C =
16599           dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
16600         if (!C)
16601           return SDValue();
16602         // 6 == Log2(64)
16603         ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
16604       }
16605       if (ShAmt != ShiftAmt)
16606         return SDValue();
16607     }
16608     return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
16609   }
16610
16611   return SDValue();
16612 }
16613
16614 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
16615                                         const X86Subtarget* Subtarget) {
16616   MVT VT = Op.getSimpleValueType();
16617   SDLoc dl(Op);
16618   SDValue R = Op.getOperand(0);
16619   SDValue Amt = Op.getOperand(1);
16620
16621   unsigned X86OpcI = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHLI :
16622     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRLI : X86ISD::VSRAI;
16623
16624   unsigned X86OpcV = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHL :
16625     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRL : X86ISD::VSRA;
16626
16627   if (SupportedVectorShiftWithBaseAmnt(VT, Subtarget, Op.getOpcode())) {
16628     SDValue BaseShAmt;
16629     EVT EltVT = VT.getVectorElementType();
16630
16631     if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Amt)) {
16632       // Check if this build_vector node is doing a splat.
16633       // If so, then set BaseShAmt equal to the splat value.
16634       BaseShAmt = BV->getSplatValue();
16635       if (BaseShAmt && BaseShAmt.getOpcode() == ISD::UNDEF)
16636         BaseShAmt = SDValue();
16637     } else {
16638       if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
16639         Amt = Amt.getOperand(0);
16640
16641       ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(Amt);
16642       if (SVN && SVN->isSplat()) {
16643         unsigned SplatIdx = (unsigned)SVN->getSplatIndex();
16644         SDValue InVec = Amt.getOperand(0);
16645         if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
16646           assert((SplatIdx < InVec.getValueType().getVectorNumElements()) &&
16647                  "Unexpected shuffle index found!");
16648           BaseShAmt = InVec.getOperand(SplatIdx);
16649         } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
16650            if (ConstantSDNode *C =
16651                dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
16652              if (C->getZExtValue() == SplatIdx)
16653                BaseShAmt = InVec.getOperand(1);
16654            }
16655         }
16656
16657         if (!BaseShAmt)
16658           // Avoid introducing an extract element from a shuffle.
16659           BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, InVec,
16660                                   DAG.getIntPtrConstant(SplatIdx, dl));
16661       }
16662     }
16663
16664     if (BaseShAmt.getNode()) {
16665       assert(EltVT.bitsLE(MVT::i64) && "Unexpected element type!");
16666       if (EltVT != MVT::i64 && EltVT.bitsGT(MVT::i32))
16667         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, BaseShAmt);
16668       else if (EltVT.bitsLT(MVT::i32))
16669         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
16670
16671       return getTargetVShiftNode(X86OpcI, dl, VT, R, BaseShAmt, DAG);
16672     }
16673   }
16674
16675   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
16676   if (!Subtarget->is64Bit() && VT == MVT::v2i64  &&
16677       Amt.getOpcode() == ISD::BITCAST &&
16678       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
16679     Amt = Amt.getOperand(0);
16680     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
16681                      VT.getVectorNumElements();
16682     std::vector<SDValue> Vals(Ratio);
16683     for (unsigned i = 0; i != Ratio; ++i)
16684       Vals[i] = Amt.getOperand(i);
16685     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
16686       for (unsigned j = 0; j != Ratio; ++j)
16687         if (Vals[j] != Amt.getOperand(i + j))
16688           return SDValue();
16689     }
16690     return DAG.getNode(X86OpcV, dl, VT, R, Op.getOperand(1));
16691   }
16692   return SDValue();
16693 }
16694
16695 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
16696                           SelectionDAG &DAG) {
16697   MVT VT = Op.getSimpleValueType();
16698   SDLoc dl(Op);
16699   SDValue R = Op.getOperand(0);
16700   SDValue Amt = Op.getOperand(1);
16701
16702   assert(VT.isVector() && "Custom lowering only for vector shifts!");
16703   assert(Subtarget->hasSSE2() && "Only custom lower when we have SSE2!");
16704
16705   if (SDValue V = LowerScalarImmediateShift(Op, DAG, Subtarget))
16706     return V;
16707
16708   if (SDValue V = LowerScalarVariableShift(Op, DAG, Subtarget))
16709       return V;
16710
16711   if (SupportedVectorVarShift(VT, Subtarget, Op.getOpcode()))
16712     return Op;
16713
16714   // 2i64 vector logical shifts can efficiently avoid scalarization - do the
16715   // shifts per-lane and then shuffle the partial results back together.
16716   if (VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) {
16717     // Splat the shift amounts so the scalar shifts above will catch it.
16718     SDValue Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {0, 0});
16719     SDValue Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {1, 1});
16720     SDValue R0 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt0);
16721     SDValue R1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt1);
16722     return DAG.getVectorShuffle(VT, dl, R0, R1, {0, 3});
16723   }
16724
16725   // If possible, lower this packed shift into a vector multiply instead of
16726   // expanding it into a sequence of scalar shifts.
16727   // Do this only if the vector shift count is a constant build_vector.
16728   if (Op.getOpcode() == ISD::SHL &&
16729       (VT == MVT::v8i16 || VT == MVT::v4i32 ||
16730        (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
16731       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
16732     SmallVector<SDValue, 8> Elts;
16733     EVT SVT = VT.getScalarType();
16734     unsigned SVTBits = SVT.getSizeInBits();
16735     const APInt &One = APInt(SVTBits, 1);
16736     unsigned NumElems = VT.getVectorNumElements();
16737
16738     for (unsigned i=0; i !=NumElems; ++i) {
16739       SDValue Op = Amt->getOperand(i);
16740       if (Op->getOpcode() == ISD::UNDEF) {
16741         Elts.push_back(Op);
16742         continue;
16743       }
16744
16745       ConstantSDNode *ND = cast<ConstantSDNode>(Op);
16746       const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
16747       uint64_t ShAmt = C.getZExtValue();
16748       if (ShAmt >= SVTBits) {
16749         Elts.push_back(DAG.getUNDEF(SVT));
16750         continue;
16751       }
16752       Elts.push_back(DAG.getConstant(One.shl(ShAmt), dl, SVT));
16753     }
16754     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
16755     return DAG.getNode(ISD::MUL, dl, VT, R, BV);
16756   }
16757
16758   // Lower SHL with variable shift amount.
16759   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
16760     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, dl, VT));
16761
16762     Op = DAG.getNode(ISD::ADD, dl, VT, Op,
16763                      DAG.getConstant(0x3f800000U, dl, VT));
16764     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
16765     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
16766     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
16767   }
16768
16769   // If possible, lower this shift as a sequence of two shifts by
16770   // constant plus a MOVSS/MOVSD instead of scalarizing it.
16771   // Example:
16772   //   (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
16773   //
16774   // Could be rewritten as:
16775   //   (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
16776   //
16777   // The advantage is that the two shifts from the example would be
16778   // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
16779   // the vector shift into four scalar shifts plus four pairs of vector
16780   // insert/extract.
16781   if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
16782       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
16783     unsigned TargetOpcode = X86ISD::MOVSS;
16784     bool CanBeSimplified;
16785     // The splat value for the first packed shift (the 'X' from the example).
16786     SDValue Amt1 = Amt->getOperand(0);
16787     // The splat value for the second packed shift (the 'Y' from the example).
16788     SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
16789                                         Amt->getOperand(2);
16790
16791     // See if it is possible to replace this node with a sequence of
16792     // two shifts followed by a MOVSS/MOVSD
16793     if (VT == MVT::v4i32) {
16794       // Check if it is legal to use a MOVSS.
16795       CanBeSimplified = Amt2 == Amt->getOperand(2) &&
16796                         Amt2 == Amt->getOperand(3);
16797       if (!CanBeSimplified) {
16798         // Otherwise, check if we can still simplify this node using a MOVSD.
16799         CanBeSimplified = Amt1 == Amt->getOperand(1) &&
16800                           Amt->getOperand(2) == Amt->getOperand(3);
16801         TargetOpcode = X86ISD::MOVSD;
16802         Amt2 = Amt->getOperand(2);
16803       }
16804     } else {
16805       // Do similar checks for the case where the machine value type
16806       // is MVT::v8i16.
16807       CanBeSimplified = Amt1 == Amt->getOperand(1);
16808       for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
16809         CanBeSimplified = Amt2 == Amt->getOperand(i);
16810
16811       if (!CanBeSimplified) {
16812         TargetOpcode = X86ISD::MOVSD;
16813         CanBeSimplified = true;
16814         Amt2 = Amt->getOperand(4);
16815         for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
16816           CanBeSimplified = Amt1 == Amt->getOperand(i);
16817         for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
16818           CanBeSimplified = Amt2 == Amt->getOperand(j);
16819       }
16820     }
16821
16822     if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
16823         isa<ConstantSDNode>(Amt2)) {
16824       // Replace this node with two shifts followed by a MOVSS/MOVSD.
16825       EVT CastVT = MVT::v4i32;
16826       SDValue Splat1 =
16827         DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), dl, VT);
16828       SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
16829       SDValue Splat2 =
16830         DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), dl, VT);
16831       SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
16832       if (TargetOpcode == X86ISD::MOVSD)
16833         CastVT = MVT::v2i64;
16834       SDValue BitCast1 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift1);
16835       SDValue BitCast2 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift2);
16836       SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
16837                                             BitCast1, DAG);
16838       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
16839     }
16840   }
16841
16842   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
16843     // Turn 'a' into a mask suitable for VSELECT: a = a << 5;
16844     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, dl, VT));
16845
16846     SDValue VSelM = DAG.getConstant(0x80, dl, VT);
16847     SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
16848     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
16849
16850     // r = VSELECT(r, shl(r, 4), a);
16851     SDValue M = DAG.getNode(ISD::SHL, dl, VT, R, DAG.getConstant(4, dl, VT));
16852     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
16853
16854     // a += a
16855     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
16856     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
16857     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
16858
16859     // r = VSELECT(r, shl(r, 2), a);
16860     M = DAG.getNode(ISD::SHL, dl, VT, R, DAG.getConstant(2, dl, VT));
16861     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
16862
16863     // a += a
16864     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
16865     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
16866     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
16867
16868     // return VSELECT(r, r+r, a);
16869     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
16870                     DAG.getNode(ISD::ADD, dl, VT, R, R), R);
16871     return R;
16872   }
16873
16874   // It's worth extending once and using the v8i32 shifts for 16-bit types, but
16875   // the extra overheads to get from v16i8 to v8i32 make the existing SSE
16876   // solution better.
16877   if (Subtarget->hasInt256() && VT == MVT::v8i16) {
16878     MVT NewVT = VT == MVT::v8i16 ? MVT::v8i32 : MVT::v16i16;
16879     unsigned ExtOpc =
16880         Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
16881     R = DAG.getNode(ExtOpc, dl, NewVT, R);
16882     Amt = DAG.getNode(ISD::ANY_EXTEND, dl, NewVT, Amt);
16883     return DAG.getNode(ISD::TRUNCATE, dl, VT,
16884                        DAG.getNode(Op.getOpcode(), dl, NewVT, R, Amt));
16885   }
16886
16887   // Decompose 256-bit shifts into smaller 128-bit shifts.
16888   if (VT.is256BitVector()) {
16889     unsigned NumElems = VT.getVectorNumElements();
16890     MVT EltVT = VT.getVectorElementType();
16891     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
16892
16893     // Extract the two vectors
16894     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
16895     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
16896
16897     // Recreate the shift amount vectors
16898     SDValue Amt1, Amt2;
16899     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
16900       // Constant shift amount
16901       SmallVector<SDValue, 8> Ops(Amt->op_begin(), Amt->op_begin() + NumElems);
16902       ArrayRef<SDValue> Amt1Csts = makeArrayRef(Ops).slice(0, NumElems / 2);
16903       ArrayRef<SDValue> Amt2Csts = makeArrayRef(Ops).slice(NumElems / 2);
16904
16905       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
16906       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
16907     } else {
16908       // Variable shift amount
16909       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
16910       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
16911     }
16912
16913     // Issue new vector shifts for the smaller types
16914     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
16915     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
16916
16917     // Concatenate the result back
16918     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
16919   }
16920
16921   return SDValue();
16922 }
16923
16924 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
16925   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
16926   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
16927   // looks for this combo and may remove the "setcc" instruction if the "setcc"
16928   // has only one use.
16929   SDNode *N = Op.getNode();
16930   SDValue LHS = N->getOperand(0);
16931   SDValue RHS = N->getOperand(1);
16932   unsigned BaseOp = 0;
16933   unsigned Cond = 0;
16934   SDLoc DL(Op);
16935   switch (Op.getOpcode()) {
16936   default: llvm_unreachable("Unknown ovf instruction!");
16937   case ISD::SADDO:
16938     // A subtract of one will be selected as a INC. Note that INC doesn't
16939     // set CF, so we can't do this for UADDO.
16940     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
16941       if (C->isOne()) {
16942         BaseOp = X86ISD::INC;
16943         Cond = X86::COND_O;
16944         break;
16945       }
16946     BaseOp = X86ISD::ADD;
16947     Cond = X86::COND_O;
16948     break;
16949   case ISD::UADDO:
16950     BaseOp = X86ISD::ADD;
16951     Cond = X86::COND_B;
16952     break;
16953   case ISD::SSUBO:
16954     // A subtract of one will be selected as a DEC. Note that DEC doesn't
16955     // set CF, so we can't do this for USUBO.
16956     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
16957       if (C->isOne()) {
16958         BaseOp = X86ISD::DEC;
16959         Cond = X86::COND_O;
16960         break;
16961       }
16962     BaseOp = X86ISD::SUB;
16963     Cond = X86::COND_O;
16964     break;
16965   case ISD::USUBO:
16966     BaseOp = X86ISD::SUB;
16967     Cond = X86::COND_B;
16968     break;
16969   case ISD::SMULO:
16970     BaseOp = N->getValueType(0) == MVT::i8 ? X86ISD::SMUL8 : X86ISD::SMUL;
16971     Cond = X86::COND_O;
16972     break;
16973   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
16974     if (N->getValueType(0) == MVT::i8) {
16975       BaseOp = X86ISD::UMUL8;
16976       Cond = X86::COND_O;
16977       break;
16978     }
16979     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
16980                                  MVT::i32);
16981     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
16982
16983     SDValue SetCC =
16984       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
16985                   DAG.getConstant(X86::COND_O, DL, MVT::i32),
16986                   SDValue(Sum.getNode(), 2));
16987
16988     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
16989   }
16990   }
16991
16992   // Also sets EFLAGS.
16993   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
16994   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
16995
16996   SDValue SetCC =
16997     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
16998                 DAG.getConstant(Cond, DL, MVT::i32),
16999                 SDValue(Sum.getNode(), 1));
17000
17001   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
17002 }
17003
17004 /// Returns true if the operand type is exactly twice the native width, and
17005 /// the corresponding cmpxchg8b or cmpxchg16b instruction is available.
17006 /// Used to know whether to use cmpxchg8/16b when expanding atomic operations
17007 /// (otherwise we leave them alone to become __sync_fetch_and_... calls).
17008 bool X86TargetLowering::needsCmpXchgNb(const Type *MemType) const {
17009   unsigned OpWidth = MemType->getPrimitiveSizeInBits();
17010
17011   if (OpWidth == 64)
17012     return !Subtarget->is64Bit(); // FIXME this should be Subtarget.hasCmpxchg8b
17013   else if (OpWidth == 128)
17014     return Subtarget->hasCmpxchg16b();
17015   else
17016     return false;
17017 }
17018
17019 bool X86TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
17020   return needsCmpXchgNb(SI->getValueOperand()->getType());
17021 }
17022
17023 // Note: this turns large loads into lock cmpxchg8b/16b.
17024 // FIXME: On 32 bits x86, fild/movq might be faster than lock cmpxchg8b.
17025 bool X86TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
17026   auto PTy = cast<PointerType>(LI->getPointerOperand()->getType());
17027   return needsCmpXchgNb(PTy->getElementType());
17028 }
17029
17030 TargetLoweringBase::AtomicRMWExpansionKind
17031 X86TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
17032   unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
17033   const Type *MemType = AI->getType();
17034
17035   // If the operand is too big, we must see if cmpxchg8/16b is available
17036   // and default to library calls otherwise.
17037   if (MemType->getPrimitiveSizeInBits() > NativeWidth) {
17038     return needsCmpXchgNb(MemType) ? AtomicRMWExpansionKind::CmpXChg
17039                                    : AtomicRMWExpansionKind::None;
17040   }
17041
17042   AtomicRMWInst::BinOp Op = AI->getOperation();
17043   switch (Op) {
17044   default:
17045     llvm_unreachable("Unknown atomic operation");
17046   case AtomicRMWInst::Xchg:
17047   case AtomicRMWInst::Add:
17048   case AtomicRMWInst::Sub:
17049     // It's better to use xadd, xsub or xchg for these in all cases.
17050     return AtomicRMWExpansionKind::None;
17051   case AtomicRMWInst::Or:
17052   case AtomicRMWInst::And:
17053   case AtomicRMWInst::Xor:
17054     // If the atomicrmw's result isn't actually used, we can just add a "lock"
17055     // prefix to a normal instruction for these operations.
17056     return !AI->use_empty() ? AtomicRMWExpansionKind::CmpXChg
17057                             : AtomicRMWExpansionKind::None;
17058   case AtomicRMWInst::Nand:
17059   case AtomicRMWInst::Max:
17060   case AtomicRMWInst::Min:
17061   case AtomicRMWInst::UMax:
17062   case AtomicRMWInst::UMin:
17063     // These always require a non-trivial set of data operations on x86. We must
17064     // use a cmpxchg loop.
17065     return AtomicRMWExpansionKind::CmpXChg;
17066   }
17067 }
17068
17069 static bool hasMFENCE(const X86Subtarget& Subtarget) {
17070   // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
17071   // no-sse2). There isn't any reason to disable it if the target processor
17072   // supports it.
17073   return Subtarget.hasSSE2() || Subtarget.is64Bit();
17074 }
17075
17076 LoadInst *
17077 X86TargetLowering::lowerIdempotentRMWIntoFencedLoad(AtomicRMWInst *AI) const {
17078   unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
17079   const Type *MemType = AI->getType();
17080   // Accesses larger than the native width are turned into cmpxchg/libcalls, so
17081   // there is no benefit in turning such RMWs into loads, and it is actually
17082   // harmful as it introduces a mfence.
17083   if (MemType->getPrimitiveSizeInBits() > NativeWidth)
17084     return nullptr;
17085
17086   auto Builder = IRBuilder<>(AI);
17087   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
17088   auto SynchScope = AI->getSynchScope();
17089   // We must restrict the ordering to avoid generating loads with Release or
17090   // ReleaseAcquire orderings.
17091   auto Order = AtomicCmpXchgInst::getStrongestFailureOrdering(AI->getOrdering());
17092   auto Ptr = AI->getPointerOperand();
17093
17094   // Before the load we need a fence. Here is an example lifted from
17095   // http://www.hpl.hp.com/techreports/2012/HPL-2012-68.pdf showing why a fence
17096   // is required:
17097   // Thread 0:
17098   //   x.store(1, relaxed);
17099   //   r1 = y.fetch_add(0, release);
17100   // Thread 1:
17101   //   y.fetch_add(42, acquire);
17102   //   r2 = x.load(relaxed);
17103   // r1 = r2 = 0 is impossible, but becomes possible if the idempotent rmw is
17104   // lowered to just a load without a fence. A mfence flushes the store buffer,
17105   // making the optimization clearly correct.
17106   // FIXME: it is required if isAtLeastRelease(Order) but it is not clear
17107   // otherwise, we might be able to be more agressive on relaxed idempotent
17108   // rmw. In practice, they do not look useful, so we don't try to be
17109   // especially clever.
17110   if (SynchScope == SingleThread)
17111     // FIXME: we could just insert an X86ISD::MEMBARRIER here, except we are at
17112     // the IR level, so we must wrap it in an intrinsic.
17113     return nullptr;
17114
17115   if (!hasMFENCE(*Subtarget))
17116     // FIXME: it might make sense to use a locked operation here but on a
17117     // different cache-line to prevent cache-line bouncing. In practice it
17118     // is probably a small win, and x86 processors without mfence are rare
17119     // enough that we do not bother.
17120     return nullptr;
17121
17122   Function *MFence =
17123       llvm::Intrinsic::getDeclaration(M, Intrinsic::x86_sse2_mfence);
17124   Builder.CreateCall(MFence, {});
17125
17126   // Finally we can emit the atomic load.
17127   LoadInst *Loaded = Builder.CreateAlignedLoad(Ptr,
17128           AI->getType()->getPrimitiveSizeInBits());
17129   Loaded->setAtomic(Order, SynchScope);
17130   AI->replaceAllUsesWith(Loaded);
17131   AI->eraseFromParent();
17132   return Loaded;
17133 }
17134
17135 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
17136                                  SelectionDAG &DAG) {
17137   SDLoc dl(Op);
17138   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
17139     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
17140   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
17141     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
17142
17143   // The only fence that needs an instruction is a sequentially-consistent
17144   // cross-thread fence.
17145   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
17146     if (hasMFENCE(*Subtarget))
17147       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
17148
17149     SDValue Chain = Op.getOperand(0);
17150     SDValue Zero = DAG.getConstant(0, dl, MVT::i32);
17151     SDValue Ops[] = {
17152       DAG.getRegister(X86::ESP, MVT::i32),     // Base
17153       DAG.getTargetConstant(1, dl, MVT::i8),   // Scale
17154       DAG.getRegister(0, MVT::i32),            // Index
17155       DAG.getTargetConstant(0, dl, MVT::i32),  // Disp
17156       DAG.getRegister(0, MVT::i32),            // Segment.
17157       Zero,
17158       Chain
17159     };
17160     SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
17161     return SDValue(Res, 0);
17162   }
17163
17164   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
17165   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
17166 }
17167
17168 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
17169                              SelectionDAG &DAG) {
17170   MVT T = Op.getSimpleValueType();
17171   SDLoc DL(Op);
17172   unsigned Reg = 0;
17173   unsigned size = 0;
17174   switch(T.SimpleTy) {
17175   default: llvm_unreachable("Invalid value type!");
17176   case MVT::i8:  Reg = X86::AL;  size = 1; break;
17177   case MVT::i16: Reg = X86::AX;  size = 2; break;
17178   case MVT::i32: Reg = X86::EAX; size = 4; break;
17179   case MVT::i64:
17180     assert(Subtarget->is64Bit() && "Node not type legal!");
17181     Reg = X86::RAX; size = 8;
17182     break;
17183   }
17184   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
17185                                   Op.getOperand(2), SDValue());
17186   SDValue Ops[] = { cpIn.getValue(0),
17187                     Op.getOperand(1),
17188                     Op.getOperand(3),
17189                     DAG.getTargetConstant(size, DL, MVT::i8),
17190                     cpIn.getValue(1) };
17191   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
17192   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
17193   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
17194                                            Ops, T, MMO);
17195
17196   SDValue cpOut =
17197     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
17198   SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
17199                                       MVT::i32, cpOut.getValue(2));
17200   SDValue Success = DAG.getNode(X86ISD::SETCC, DL, Op->getValueType(1),
17201                                 DAG.getConstant(X86::COND_E, DL, MVT::i8),
17202                                 EFLAGS);
17203
17204   DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), cpOut);
17205   DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
17206   DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), EFLAGS.getValue(1));
17207   return SDValue();
17208 }
17209
17210 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
17211                             SelectionDAG &DAG) {
17212   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
17213   MVT DstVT = Op.getSimpleValueType();
17214
17215   if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
17216     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
17217     if (DstVT != MVT::f64)
17218       // This conversion needs to be expanded.
17219       return SDValue();
17220
17221     SDValue InVec = Op->getOperand(0);
17222     SDLoc dl(Op);
17223     unsigned NumElts = SrcVT.getVectorNumElements();
17224     EVT SVT = SrcVT.getVectorElementType();
17225
17226     // Widen the vector in input in the case of MVT::v2i32.
17227     // Example: from MVT::v2i32 to MVT::v4i32.
17228     SmallVector<SDValue, 16> Elts;
17229     for (unsigned i = 0, e = NumElts; i != e; ++i)
17230       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
17231                                  DAG.getIntPtrConstant(i, dl)));
17232
17233     // Explicitly mark the extra elements as Undef.
17234     Elts.append(NumElts, DAG.getUNDEF(SVT));
17235
17236     EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
17237     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
17238     SDValue ToV2F64 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, BV);
17239     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
17240                        DAG.getIntPtrConstant(0, dl));
17241   }
17242
17243   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
17244          Subtarget->hasMMX() && "Unexpected custom BITCAST");
17245   assert((DstVT == MVT::i64 ||
17246           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
17247          "Unexpected custom BITCAST");
17248   // i64 <=> MMX conversions are Legal.
17249   if (SrcVT==MVT::i64 && DstVT.isVector())
17250     return Op;
17251   if (DstVT==MVT::i64 && SrcVT.isVector())
17252     return Op;
17253   // MMX <=> MMX conversions are Legal.
17254   if (SrcVT.isVector() && DstVT.isVector())
17255     return Op;
17256   // All other conversions need to be expanded.
17257   return SDValue();
17258 }
17259
17260 static SDValue LowerCTPOP(SDValue Op, const X86Subtarget *Subtarget,
17261                           SelectionDAG &DAG) {
17262   SDNode *Node = Op.getNode();
17263   SDLoc dl(Node);
17264
17265   Op = Op.getOperand(0);
17266   EVT VT = Op.getValueType();
17267   assert((VT.is128BitVector() || VT.is256BitVector()) &&
17268          "CTPOP lowering only implemented for 128/256-bit wide vector types");
17269
17270   unsigned NumElts = VT.getVectorNumElements();
17271   EVT EltVT = VT.getVectorElementType();
17272   unsigned Len = EltVT.getSizeInBits();
17273
17274   // This is the vectorized version of the "best" algorithm from
17275   // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
17276   // with a minor tweak to use a series of adds + shifts instead of vector
17277   // multiplications. Implemented for the v2i64, v4i64, v4i32, v8i32 types:
17278   //
17279   //  v2i64, v4i64, v4i32 => Only profitable w/ popcnt disabled
17280   //  v8i32 => Always profitable
17281   //
17282   // FIXME: There a couple of possible improvements:
17283   //
17284   // 1) Support for i8 and i16 vectors (needs measurements if popcnt enabled).
17285   // 2) Use strategies from http://wm.ite.pl/articles/sse-popcount.html
17286   //
17287   assert(EltVT.isInteger() && (Len == 32 || Len == 64) && Len % 8 == 0 &&
17288          "CTPOP not implemented for this vector element type.");
17289
17290   // X86 canonicalize ANDs to vXi64, generate the appropriate bitcasts to avoid
17291   // extra legalization.
17292   bool NeedsBitcast = EltVT == MVT::i32;
17293   MVT BitcastVT = VT.is256BitVector() ? MVT::v4i64 : MVT::v2i64;
17294
17295   SDValue Cst55 = DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x55)), dl,
17296                                   EltVT);
17297   SDValue Cst33 = DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x33)), dl,
17298                                   EltVT);
17299   SDValue Cst0F = DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x0F)), dl,
17300                                   EltVT);
17301
17302   // v = v - ((v >> 1) & 0x55555555...)
17303   SmallVector<SDValue, 8> Ones(NumElts, DAG.getConstant(1, dl, EltVT));
17304   SDValue OnesV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ones);
17305   SDValue Srl = DAG.getNode(ISD::SRL, dl, VT, Op, OnesV);
17306   if (NeedsBitcast)
17307     Srl = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Srl);
17308
17309   SmallVector<SDValue, 8> Mask55(NumElts, Cst55);
17310   SDValue M55 = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Mask55);
17311   if (NeedsBitcast)
17312     M55 = DAG.getNode(ISD::BITCAST, dl, BitcastVT, M55);
17313
17314   SDValue And = DAG.getNode(ISD::AND, dl, Srl.getValueType(), Srl, M55);
17315   if (VT != And.getValueType())
17316     And = DAG.getNode(ISD::BITCAST, dl, VT, And);
17317   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, Op, And);
17318
17319   // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...)
17320   SmallVector<SDValue, 8> Mask33(NumElts, Cst33);
17321   SDValue M33 = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Mask33);
17322   SmallVector<SDValue, 8> Twos(NumElts, DAG.getConstant(2, dl, EltVT));
17323   SDValue TwosV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Twos);
17324
17325   Srl = DAG.getNode(ISD::SRL, dl, VT, Sub, TwosV);
17326   if (NeedsBitcast) {
17327     Srl = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Srl);
17328     M33 = DAG.getNode(ISD::BITCAST, dl, BitcastVT, M33);
17329     Sub = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Sub);
17330   }
17331
17332   SDValue AndRHS = DAG.getNode(ISD::AND, dl, M33.getValueType(), Srl, M33);
17333   SDValue AndLHS = DAG.getNode(ISD::AND, dl, M33.getValueType(), Sub, M33);
17334   if (VT != AndRHS.getValueType()) {
17335     AndRHS = DAG.getNode(ISD::BITCAST, dl, VT, AndRHS);
17336     AndLHS = DAG.getNode(ISD::BITCAST, dl, VT, AndLHS);
17337   }
17338   SDValue Add = DAG.getNode(ISD::ADD, dl, VT, AndLHS, AndRHS);
17339
17340   // v = (v + (v >> 4)) & 0x0F0F0F0F...
17341   SmallVector<SDValue, 8> Fours(NumElts, DAG.getConstant(4, dl, EltVT));
17342   SDValue FoursV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Fours);
17343   Srl = DAG.getNode(ISD::SRL, dl, VT, Add, FoursV);
17344   Add = DAG.getNode(ISD::ADD, dl, VT, Add, Srl);
17345
17346   SmallVector<SDValue, 8> Mask0F(NumElts, Cst0F);
17347   SDValue M0F = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Mask0F);
17348   if (NeedsBitcast) {
17349     Add = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Add);
17350     M0F = DAG.getNode(ISD::BITCAST, dl, BitcastVT, M0F);
17351   }
17352   And = DAG.getNode(ISD::AND, dl, M0F.getValueType(), Add, M0F);
17353   if (VT != And.getValueType())
17354     And = DAG.getNode(ISD::BITCAST, dl, VT, And);
17355
17356   // The algorithm mentioned above uses:
17357   //    v = (v * 0x01010101...) >> (Len - 8)
17358   //
17359   // Change it to use vector adds + vector shifts which yield faster results on
17360   // Haswell than using vector integer multiplication.
17361   //
17362   // For i32 elements:
17363   //    v = v + (v >> 8)
17364   //    v = v + (v >> 16)
17365   //
17366   // For i64 elements:
17367   //    v = v + (v >> 8)
17368   //    v = v + (v >> 16)
17369   //    v = v + (v >> 32)
17370   //
17371   Add = And;
17372   SmallVector<SDValue, 8> Csts;
17373   for (unsigned i = 8; i <= Len/2; i *= 2) {
17374     Csts.assign(NumElts, DAG.getConstant(i, dl, EltVT));
17375     SDValue CstsV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Csts);
17376     Srl = DAG.getNode(ISD::SRL, dl, VT, Add, CstsV);
17377     Add = DAG.getNode(ISD::ADD, dl, VT, Add, Srl);
17378     Csts.clear();
17379   }
17380
17381   // The result is on the least significant 6-bits on i32 and 7-bits on i64.
17382   SDValue Cst3F = DAG.getConstant(APInt(Len, Len == 32 ? 0x3F : 0x7F), dl,
17383                                   EltVT);
17384   SmallVector<SDValue, 8> Cst3FV(NumElts, Cst3F);
17385   SDValue M3F = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Cst3FV);
17386   if (NeedsBitcast) {
17387     Add = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Add);
17388     M3F = DAG.getNode(ISD::BITCAST, dl, BitcastVT, M3F);
17389   }
17390   And = DAG.getNode(ISD::AND, dl, M3F.getValueType(), Add, M3F);
17391   if (VT != And.getValueType())
17392     And = DAG.getNode(ISD::BITCAST, dl, VT, And);
17393
17394   return And;
17395 }
17396
17397 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
17398   SDNode *Node = Op.getNode();
17399   SDLoc dl(Node);
17400   EVT T = Node->getValueType(0);
17401   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
17402                               DAG.getConstant(0, dl, T), Node->getOperand(2));
17403   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
17404                        cast<AtomicSDNode>(Node)->getMemoryVT(),
17405                        Node->getOperand(0),
17406                        Node->getOperand(1), negOp,
17407                        cast<AtomicSDNode>(Node)->getMemOperand(),
17408                        cast<AtomicSDNode>(Node)->getOrdering(),
17409                        cast<AtomicSDNode>(Node)->getSynchScope());
17410 }
17411
17412 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
17413   SDNode *Node = Op.getNode();
17414   SDLoc dl(Node);
17415   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
17416
17417   // Convert seq_cst store -> xchg
17418   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
17419   // FIXME: On 32-bit, store -> fist or movq would be more efficient
17420   //        (The only way to get a 16-byte store is cmpxchg16b)
17421   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
17422   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
17423       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
17424     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
17425                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
17426                                  Node->getOperand(0),
17427                                  Node->getOperand(1), Node->getOperand(2),
17428                                  cast<AtomicSDNode>(Node)->getMemOperand(),
17429                                  cast<AtomicSDNode>(Node)->getOrdering(),
17430                                  cast<AtomicSDNode>(Node)->getSynchScope());
17431     return Swap.getValue(1);
17432   }
17433   // Other atomic stores have a simple pattern.
17434   return Op;
17435 }
17436
17437 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
17438   EVT VT = Op.getNode()->getSimpleValueType(0);
17439
17440   // Let legalize expand this if it isn't a legal type yet.
17441   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
17442     return SDValue();
17443
17444   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
17445
17446   unsigned Opc;
17447   bool ExtraOp = false;
17448   switch (Op.getOpcode()) {
17449   default: llvm_unreachable("Invalid code");
17450   case ISD::ADDC: Opc = X86ISD::ADD; break;
17451   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
17452   case ISD::SUBC: Opc = X86ISD::SUB; break;
17453   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
17454   }
17455
17456   if (!ExtraOp)
17457     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
17458                        Op.getOperand(1));
17459   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
17460                      Op.getOperand(1), Op.getOperand(2));
17461 }
17462
17463 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
17464                             SelectionDAG &DAG) {
17465   assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
17466
17467   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
17468   // which returns the values as { float, float } (in XMM0) or
17469   // { double, double } (which is returned in XMM0, XMM1).
17470   SDLoc dl(Op);
17471   SDValue Arg = Op.getOperand(0);
17472   EVT ArgVT = Arg.getValueType();
17473   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
17474
17475   TargetLowering::ArgListTy Args;
17476   TargetLowering::ArgListEntry Entry;
17477
17478   Entry.Node = Arg;
17479   Entry.Ty = ArgTy;
17480   Entry.isSExt = false;
17481   Entry.isZExt = false;
17482   Args.push_back(Entry);
17483
17484   bool isF64 = ArgVT == MVT::f64;
17485   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
17486   // the small struct {f32, f32} is returned in (eax, edx). For f64,
17487   // the results are returned via SRet in memory.
17488   const char *LibcallName =  isF64 ? "__sincos_stret" : "__sincosf_stret";
17489   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17490   SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy());
17491
17492   Type *RetTy = isF64
17493     ? (Type*)StructType::get(ArgTy, ArgTy, nullptr)
17494     : (Type*)VectorType::get(ArgTy, 4);
17495
17496   TargetLowering::CallLoweringInfo CLI(DAG);
17497   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
17498     .setCallee(CallingConv::C, RetTy, Callee, std::move(Args), 0);
17499
17500   std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
17501
17502   if (isF64)
17503     // Returned in xmm0 and xmm1.
17504     return CallResult.first;
17505
17506   // Returned in bits 0:31 and 32:64 xmm0.
17507   SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
17508                                CallResult.first, DAG.getIntPtrConstant(0, dl));
17509   SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
17510                                CallResult.first, DAG.getIntPtrConstant(1, dl));
17511   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
17512   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
17513 }
17514
17515 static SDValue LowerMSCATTER(SDValue Op, const X86Subtarget *Subtarget,
17516                              SelectionDAG &DAG) {
17517   assert(Subtarget->hasAVX512() &&
17518          "MGATHER/MSCATTER are supported on AVX-512 arch only");
17519
17520   MaskedScatterSDNode *N = cast<MaskedScatterSDNode>(Op.getNode());
17521   EVT VT = N->getValue().getValueType();
17522   assert(VT.getScalarSizeInBits() >= 32 && "Unsupported scatter op");
17523   SDLoc dl(Op);
17524
17525   // X86 scatter kills mask register, so its type should be added to
17526   // the list of return values
17527   if (N->getNumValues() == 1) {
17528     SDValue Index = N->getIndex();
17529     if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
17530         !Index.getValueType().is512BitVector())
17531       Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
17532
17533     SDVTList VTs = DAG.getVTList(N->getMask().getValueType(), MVT::Other);
17534     SDValue Ops[] = { N->getOperand(0), N->getOperand(1),  N->getOperand(2),
17535                       N->getOperand(3), Index };
17536
17537     SDValue NewScatter = DAG.getMaskedScatter(VTs, VT, dl, Ops, N->getMemOperand());
17538     DAG.ReplaceAllUsesWith(Op, SDValue(NewScatter.getNode(), 1));
17539     return SDValue(NewScatter.getNode(), 0);
17540   }
17541   return Op;
17542 }
17543
17544 static SDValue LowerMGATHER(SDValue Op, const X86Subtarget *Subtarget,
17545                             SelectionDAG &DAG) {
17546   assert(Subtarget->hasAVX512() &&
17547          "MGATHER/MSCATTER are supported on AVX-512 arch only");
17548
17549   MaskedGatherSDNode *N = cast<MaskedGatherSDNode>(Op.getNode());
17550   EVT VT = Op.getValueType();
17551   assert(VT.getScalarSizeInBits() >= 32 && "Unsupported gather op");
17552   SDLoc dl(Op);
17553
17554   SDValue Index = N->getIndex();
17555   if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
17556       !Index.getValueType().is512BitVector()) {
17557     Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
17558     SDValue Ops[] = { N->getOperand(0), N->getOperand(1),  N->getOperand(2),
17559                       N->getOperand(3), Index };
17560     DAG.UpdateNodeOperands(N, Ops);
17561   }
17562   return Op;
17563 }
17564
17565 SDValue X86TargetLowering::LowerGC_TRANSITION_START(SDValue Op,
17566                                                     SelectionDAG &DAG) const {
17567   // TODO: Eventually, the lowering of these nodes should be informed by or
17568   // deferred to the GC strategy for the function in which they appear. For
17569   // now, however, they must be lowered to something. Since they are logically
17570   // no-ops in the case of a null GC strategy (or a GC strategy which does not
17571   // require special handling for these nodes), lower them as literal NOOPs for
17572   // the time being.
17573   SmallVector<SDValue, 2> Ops;
17574
17575   Ops.push_back(Op.getOperand(0));
17576   if (Op->getGluedNode())
17577     Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
17578
17579   SDLoc OpDL(Op);
17580   SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
17581   SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
17582
17583   return NOOP;
17584 }
17585
17586 SDValue X86TargetLowering::LowerGC_TRANSITION_END(SDValue Op,
17587                                                   SelectionDAG &DAG) const {
17588   // TODO: Eventually, the lowering of these nodes should be informed by or
17589   // deferred to the GC strategy for the function in which they appear. For
17590   // now, however, they must be lowered to something. Since they are logically
17591   // no-ops in the case of a null GC strategy (or a GC strategy which does not
17592   // require special handling for these nodes), lower them as literal NOOPs for
17593   // the time being.
17594   SmallVector<SDValue, 2> Ops;
17595
17596   Ops.push_back(Op.getOperand(0));
17597   if (Op->getGluedNode())
17598     Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
17599
17600   SDLoc OpDL(Op);
17601   SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
17602   SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
17603
17604   return NOOP;
17605 }
17606
17607 /// LowerOperation - Provide custom lowering hooks for some operations.
17608 ///
17609 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
17610   switch (Op.getOpcode()) {
17611   default: llvm_unreachable("Should not custom lower this!");
17612   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
17613   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
17614     return LowerCMP_SWAP(Op, Subtarget, DAG);
17615   case ISD::CTPOP:              return LowerCTPOP(Op, Subtarget, DAG);
17616   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
17617   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
17618   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
17619   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, Subtarget, DAG);
17620   case ISD::VECTOR_SHUFFLE:     return lowerVectorShuffle(Op, Subtarget, DAG);
17621   case ISD::VSELECT:            return LowerVSELECT(Op, DAG);
17622   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
17623   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
17624   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
17625   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
17626   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
17627   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
17628   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
17629   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
17630   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
17631   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
17632   case ISD::SHL_PARTS:
17633   case ISD::SRA_PARTS:
17634   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
17635   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
17636   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
17637   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
17638   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, Subtarget, DAG);
17639   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, Subtarget, DAG);
17640   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, Subtarget, DAG);
17641   case ISD::SIGN_EXTEND_VECTOR_INREG:
17642     return LowerSIGN_EXTEND_VECTOR_INREG(Op, Subtarget, DAG);
17643   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
17644   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
17645   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
17646   case ISD::LOAD:               return LowerExtendedLoad(Op, Subtarget, DAG);
17647   case ISD::FABS:
17648   case ISD::FNEG:               return LowerFABSorFNEG(Op, DAG);
17649   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
17650   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
17651   case ISD::SETCC:              return LowerSETCC(Op, DAG);
17652   case ISD::SELECT:             return LowerSELECT(Op, DAG);
17653   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
17654   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
17655   case ISD::VASTART:            return LowerVASTART(Op, DAG);
17656   case ISD::VAARG:              return LowerVAARG(Op, DAG);
17657   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
17658   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, Subtarget, DAG);
17659   case ISD::INTRINSIC_VOID:
17660   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
17661   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
17662   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
17663   case ISD::FRAME_TO_ARGS_OFFSET:
17664                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
17665   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
17666   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
17667   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
17668   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
17669   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
17670   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
17671   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
17672   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
17673   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
17674   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
17675   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
17676   case ISD::UMUL_LOHI:
17677   case ISD::SMUL_LOHI:          return LowerMUL_LOHI(Op, Subtarget, DAG);
17678   case ISD::SRA:
17679   case ISD::SRL:
17680   case ISD::SHL:                return LowerShift(Op, Subtarget, DAG);
17681   case ISD::SADDO:
17682   case ISD::UADDO:
17683   case ISD::SSUBO:
17684   case ISD::USUBO:
17685   case ISD::SMULO:
17686   case ISD::UMULO:              return LowerXALUO(Op, DAG);
17687   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
17688   case ISD::BITCAST:            return LowerBITCAST(Op, Subtarget, DAG);
17689   case ISD::ADDC:
17690   case ISD::ADDE:
17691   case ISD::SUBC:
17692   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
17693   case ISD::ADD:                return LowerADD(Op, DAG);
17694   case ISD::SUB:                return LowerSUB(Op, DAG);
17695   case ISD::FSINCOS:            return LowerFSINCOS(Op, Subtarget, DAG);
17696   case ISD::MGATHER:            return LowerMGATHER(Op, Subtarget, DAG);
17697   case ISD::MSCATTER:           return LowerMSCATTER(Op, Subtarget, DAG);
17698   case ISD::GC_TRANSITION_START:
17699                                 return LowerGC_TRANSITION_START(Op, DAG);
17700   case ISD::GC_TRANSITION_END:  return LowerGC_TRANSITION_END(Op, DAG);
17701   }
17702 }
17703
17704 /// ReplaceNodeResults - Replace a node with an illegal result type
17705 /// with a new node built out of custom code.
17706 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
17707                                            SmallVectorImpl<SDValue>&Results,
17708                                            SelectionDAG &DAG) const {
17709   SDLoc dl(N);
17710   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17711   switch (N->getOpcode()) {
17712   default:
17713     llvm_unreachable("Do not know how to custom type legalize this operation!");
17714   // We might have generated v2f32 FMIN/FMAX operations. Widen them to v4f32.
17715   case X86ISD::FMINC:
17716   case X86ISD::FMIN:
17717   case X86ISD::FMAXC:
17718   case X86ISD::FMAX: {
17719     EVT VT = N->getValueType(0);
17720     if (VT != MVT::v2f32)
17721       llvm_unreachable("Unexpected type (!= v2f32) on FMIN/FMAX.");
17722     SDValue UNDEF = DAG.getUNDEF(VT);
17723     SDValue LHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
17724                               N->getOperand(0), UNDEF);
17725     SDValue RHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
17726                               N->getOperand(1), UNDEF);
17727     Results.push_back(DAG.getNode(N->getOpcode(), dl, MVT::v4f32, LHS, RHS));
17728     return;
17729   }
17730   case ISD::SIGN_EXTEND_INREG:
17731   case ISD::ADDC:
17732   case ISD::ADDE:
17733   case ISD::SUBC:
17734   case ISD::SUBE:
17735     // We don't want to expand or promote these.
17736     return;
17737   case ISD::SDIV:
17738   case ISD::UDIV:
17739   case ISD::SREM:
17740   case ISD::UREM:
17741   case ISD::SDIVREM:
17742   case ISD::UDIVREM: {
17743     SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
17744     Results.push_back(V);
17745     return;
17746   }
17747   case ISD::FP_TO_SINT:
17748     // FP_TO_INT*_IN_MEM is not legal for f16 inputs.  Do not convert
17749     // (FP_TO_SINT (load f16)) to FP_TO_INT*.
17750     if (N->getOperand(0).getValueType() == MVT::f16)
17751       break;
17752     // fallthrough
17753   case ISD::FP_TO_UINT: {
17754     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
17755
17756     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
17757       return;
17758
17759     std::pair<SDValue,SDValue> Vals =
17760         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
17761     SDValue FIST = Vals.first, StackSlot = Vals.second;
17762     if (FIST.getNode()) {
17763       EVT VT = N->getValueType(0);
17764       // Return a load from the stack slot.
17765       if (StackSlot.getNode())
17766         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
17767                                       MachinePointerInfo(),
17768                                       false, false, false, 0));
17769       else
17770         Results.push_back(FIST);
17771     }
17772     return;
17773   }
17774   case ISD::UINT_TO_FP: {
17775     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
17776     if (N->getOperand(0).getValueType() != MVT::v2i32 ||
17777         N->getValueType(0) != MVT::v2f32)
17778       return;
17779     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
17780                                  N->getOperand(0));
17781     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
17782                                      MVT::f64);
17783     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
17784     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
17785                              DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
17786     Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
17787     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
17788     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
17789     return;
17790   }
17791   case ISD::FP_ROUND: {
17792     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
17793         return;
17794     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
17795     Results.push_back(V);
17796     return;
17797   }
17798   case ISD::FP_EXTEND: {
17799     // Right now, only MVT::v2f32 has OperationAction for FP_EXTEND.
17800     // No other ValueType for FP_EXTEND should reach this point.
17801     assert(N->getValueType(0) == MVT::v2f32 &&
17802            "Do not know how to legalize this Node");
17803     return;
17804   }
17805   case ISD::INTRINSIC_W_CHAIN: {
17806     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
17807     switch (IntNo) {
17808     default : llvm_unreachable("Do not know how to custom type "
17809                                "legalize this intrinsic operation!");
17810     case Intrinsic::x86_rdtsc:
17811       return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
17812                                      Results);
17813     case Intrinsic::x86_rdtscp:
17814       return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
17815                                      Results);
17816     case Intrinsic::x86_rdpmc:
17817       return getReadPerformanceCounter(N, dl, DAG, Subtarget, Results);
17818     }
17819   }
17820   case ISD::READCYCLECOUNTER: {
17821     return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
17822                                    Results);
17823   }
17824   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
17825     EVT T = N->getValueType(0);
17826     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
17827     bool Regs64bit = T == MVT::i128;
17828     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
17829     SDValue cpInL, cpInH;
17830     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
17831                         DAG.getConstant(0, dl, HalfT));
17832     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
17833                         DAG.getConstant(1, dl, HalfT));
17834     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
17835                              Regs64bit ? X86::RAX : X86::EAX,
17836                              cpInL, SDValue());
17837     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
17838                              Regs64bit ? X86::RDX : X86::EDX,
17839                              cpInH, cpInL.getValue(1));
17840     SDValue swapInL, swapInH;
17841     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
17842                           DAG.getConstant(0, dl, HalfT));
17843     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
17844                           DAG.getConstant(1, dl, HalfT));
17845     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
17846                                Regs64bit ? X86::RBX : X86::EBX,
17847                                swapInL, cpInH.getValue(1));
17848     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
17849                                Regs64bit ? X86::RCX : X86::ECX,
17850                                swapInH, swapInL.getValue(1));
17851     SDValue Ops[] = { swapInH.getValue(0),
17852                       N->getOperand(1),
17853                       swapInH.getValue(1) };
17854     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
17855     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
17856     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
17857                                   X86ISD::LCMPXCHG8_DAG;
17858     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
17859     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
17860                                         Regs64bit ? X86::RAX : X86::EAX,
17861                                         HalfT, Result.getValue(1));
17862     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
17863                                         Regs64bit ? X86::RDX : X86::EDX,
17864                                         HalfT, cpOutL.getValue(2));
17865     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
17866
17867     SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
17868                                         MVT::i32, cpOutH.getValue(2));
17869     SDValue Success =
17870         DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
17871                     DAG.getConstant(X86::COND_E, dl, MVT::i8), EFLAGS);
17872     Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
17873
17874     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
17875     Results.push_back(Success);
17876     Results.push_back(EFLAGS.getValue(1));
17877     return;
17878   }
17879   case ISD::ATOMIC_SWAP:
17880   case ISD::ATOMIC_LOAD_ADD:
17881   case ISD::ATOMIC_LOAD_SUB:
17882   case ISD::ATOMIC_LOAD_AND:
17883   case ISD::ATOMIC_LOAD_OR:
17884   case ISD::ATOMIC_LOAD_XOR:
17885   case ISD::ATOMIC_LOAD_NAND:
17886   case ISD::ATOMIC_LOAD_MIN:
17887   case ISD::ATOMIC_LOAD_MAX:
17888   case ISD::ATOMIC_LOAD_UMIN:
17889   case ISD::ATOMIC_LOAD_UMAX:
17890   case ISD::ATOMIC_LOAD: {
17891     // Delegate to generic TypeLegalization. Situations we can really handle
17892     // should have already been dealt with by AtomicExpandPass.cpp.
17893     break;
17894   }
17895   case ISD::BITCAST: {
17896     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
17897     EVT DstVT = N->getValueType(0);
17898     EVT SrcVT = N->getOperand(0)->getValueType(0);
17899
17900     if (SrcVT != MVT::f64 ||
17901         (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
17902       return;
17903
17904     unsigned NumElts = DstVT.getVectorNumElements();
17905     EVT SVT = DstVT.getVectorElementType();
17906     EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
17907     SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
17908                                    MVT::v2f64, N->getOperand(0));
17909     SDValue ToVecInt = DAG.getNode(ISD::BITCAST, dl, WiderVT, Expanded);
17910
17911     if (ExperimentalVectorWideningLegalization) {
17912       // If we are legalizing vectors by widening, we already have the desired
17913       // legal vector type, just return it.
17914       Results.push_back(ToVecInt);
17915       return;
17916     }
17917
17918     SmallVector<SDValue, 8> Elts;
17919     for (unsigned i = 0, e = NumElts; i != e; ++i)
17920       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
17921                                    ToVecInt, DAG.getIntPtrConstant(i, dl)));
17922
17923     Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
17924   }
17925   }
17926 }
17927
17928 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
17929   switch ((X86ISD::NodeType)Opcode) {
17930   case X86ISD::FIRST_NUMBER:       break;
17931   case X86ISD::BSF:                return "X86ISD::BSF";
17932   case X86ISD::BSR:                return "X86ISD::BSR";
17933   case X86ISD::SHLD:               return "X86ISD::SHLD";
17934   case X86ISD::SHRD:               return "X86ISD::SHRD";
17935   case X86ISD::FAND:               return "X86ISD::FAND";
17936   case X86ISD::FANDN:              return "X86ISD::FANDN";
17937   case X86ISD::FOR:                return "X86ISD::FOR";
17938   case X86ISD::FXOR:               return "X86ISD::FXOR";
17939   case X86ISD::FSRL:               return "X86ISD::FSRL";
17940   case X86ISD::FILD:               return "X86ISD::FILD";
17941   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
17942   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
17943   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
17944   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
17945   case X86ISD::FLD:                return "X86ISD::FLD";
17946   case X86ISD::FST:                return "X86ISD::FST";
17947   case X86ISD::CALL:               return "X86ISD::CALL";
17948   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
17949   case X86ISD::RDTSCP_DAG:         return "X86ISD::RDTSCP_DAG";
17950   case X86ISD::RDPMC_DAG:          return "X86ISD::RDPMC_DAG";
17951   case X86ISD::BT:                 return "X86ISD::BT";
17952   case X86ISD::CMP:                return "X86ISD::CMP";
17953   case X86ISD::COMI:               return "X86ISD::COMI";
17954   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
17955   case X86ISD::CMPM:               return "X86ISD::CMPM";
17956   case X86ISD::CMPMU:              return "X86ISD::CMPMU";
17957   case X86ISD::CMPM_RND:           return "X86ISD::CMPM_RND";
17958   case X86ISD::SETCC:              return "X86ISD::SETCC";
17959   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
17960   case X86ISD::FSETCC:             return "X86ISD::FSETCC";
17961   case X86ISD::FGETSIGNx86:        return "X86ISD::FGETSIGNx86";
17962   case X86ISD::CMOV:               return "X86ISD::CMOV";
17963   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
17964   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
17965   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
17966   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
17967   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
17968   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
17969   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
17970   case X86ISD::MOVDQ2Q:            return "X86ISD::MOVDQ2Q";
17971   case X86ISD::MMX_MOVD2W:         return "X86ISD::MMX_MOVD2W";
17972   case X86ISD::MMX_MOVW2D:         return "X86ISD::MMX_MOVW2D";
17973   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
17974   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
17975   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
17976   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
17977   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
17978   case X86ISD::MMX_PINSRW:         return "X86ISD::MMX_PINSRW";
17979   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
17980   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
17981   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
17982   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
17983   case X86ISD::SHRUNKBLEND:        return "X86ISD::SHRUNKBLEND";
17984   case X86ISD::ADDUS:              return "X86ISD::ADDUS";
17985   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
17986   case X86ISD::HADD:               return "X86ISD::HADD";
17987   case X86ISD::HSUB:               return "X86ISD::HSUB";
17988   case X86ISD::FHADD:              return "X86ISD::FHADD";
17989   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
17990   case X86ISD::UMAX:               return "X86ISD::UMAX";
17991   case X86ISD::UMIN:               return "X86ISD::UMIN";
17992   case X86ISD::SMAX:               return "X86ISD::SMAX";
17993   case X86ISD::SMIN:               return "X86ISD::SMIN";
17994   case X86ISD::FMAX:               return "X86ISD::FMAX";
17995   case X86ISD::FMAX_RND:           return "X86ISD::FMAX_RND";
17996   case X86ISD::FMIN:               return "X86ISD::FMIN";
17997   case X86ISD::FMIN_RND:           return "X86ISD::FMIN_RND";
17998   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
17999   case X86ISD::FMINC:              return "X86ISD::FMINC";
18000   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
18001   case X86ISD::FRCP:               return "X86ISD::FRCP";
18002   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
18003   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
18004   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
18005   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
18006   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
18007   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
18008   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
18009   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
18010   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
18011   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
18012   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
18013   case X86ISD::LCMPXCHG16_DAG:     return "X86ISD::LCMPXCHG16_DAG";
18014   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
18015   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
18016   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
18017   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
18018   case X86ISD::VTRUNC:             return "X86ISD::VTRUNC";
18019   case X86ISD::VTRUNCM:            return "X86ISD::VTRUNCM";
18020   case X86ISD::VINSERT:            return "X86ISD::VINSERT";
18021   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
18022   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
18023   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
18024   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
18025   case X86ISD::VSHL:               return "X86ISD::VSHL";
18026   case X86ISD::VSRL:               return "X86ISD::VSRL";
18027   case X86ISD::VSRA:               return "X86ISD::VSRA";
18028   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
18029   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
18030   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
18031   case X86ISD::CMPP:               return "X86ISD::CMPP";
18032   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
18033   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
18034   case X86ISD::PCMPEQM:            return "X86ISD::PCMPEQM";
18035   case X86ISD::PCMPGTM:            return "X86ISD::PCMPGTM";
18036   case X86ISD::ADD:                return "X86ISD::ADD";
18037   case X86ISD::SUB:                return "X86ISD::SUB";
18038   case X86ISD::ADC:                return "X86ISD::ADC";
18039   case X86ISD::SBB:                return "X86ISD::SBB";
18040   case X86ISD::SMUL:               return "X86ISD::SMUL";
18041   case X86ISD::UMUL:               return "X86ISD::UMUL";
18042   case X86ISD::SMUL8:              return "X86ISD::SMUL8";
18043   case X86ISD::UMUL8:              return "X86ISD::UMUL8";
18044   case X86ISD::SDIVREM8_SEXT_HREG: return "X86ISD::SDIVREM8_SEXT_HREG";
18045   case X86ISD::UDIVREM8_ZEXT_HREG: return "X86ISD::UDIVREM8_ZEXT_HREG";
18046   case X86ISD::INC:                return "X86ISD::INC";
18047   case X86ISD::DEC:                return "X86ISD::DEC";
18048   case X86ISD::OR:                 return "X86ISD::OR";
18049   case X86ISD::XOR:                return "X86ISD::XOR";
18050   case X86ISD::AND:                return "X86ISD::AND";
18051   case X86ISD::BEXTR:              return "X86ISD::BEXTR";
18052   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
18053   case X86ISD::PTEST:              return "X86ISD::PTEST";
18054   case X86ISD::TESTP:              return "X86ISD::TESTP";
18055   case X86ISD::TESTM:              return "X86ISD::TESTM";
18056   case X86ISD::TESTNM:             return "X86ISD::TESTNM";
18057   case X86ISD::KORTEST:            return "X86ISD::KORTEST";
18058   case X86ISD::PACKSS:             return "X86ISD::PACKSS";
18059   case X86ISD::PACKUS:             return "X86ISD::PACKUS";
18060   case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
18061   case X86ISD::VALIGN:             return "X86ISD::VALIGN";
18062   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
18063   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
18064   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
18065   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
18066   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
18067   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
18068   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
18069   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
18070   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
18071   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
18072   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
18073   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
18074   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
18075   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
18076   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
18077   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
18078   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
18079   case X86ISD::SUBV_BROADCAST:     return "X86ISD::SUBV_BROADCAST";
18080   case X86ISD::VEXTRACT:           return "X86ISD::VEXTRACT";
18081   case X86ISD::VPERMILPV:          return "X86ISD::VPERMILPV";
18082   case X86ISD::VPERMILPI:          return "X86ISD::VPERMILPI";
18083   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
18084   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
18085   case X86ISD::VPERMV3:            return "X86ISD::VPERMV3";
18086   case X86ISD::VPERMIV3:           return "X86ISD::VPERMIV3";
18087   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
18088   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
18089   case X86ISD::PMULDQ:             return "X86ISD::PMULDQ";
18090   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
18091   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
18092   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
18093   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
18094   case X86ISD::MFENCE:             return "X86ISD::MFENCE";
18095   case X86ISD::SFENCE:             return "X86ISD::SFENCE";
18096   case X86ISD::LFENCE:             return "X86ISD::LFENCE";
18097   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
18098   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
18099   case X86ISD::SAHF:               return "X86ISD::SAHF";
18100   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
18101   case X86ISD::RDSEED:             return "X86ISD::RDSEED";
18102   case X86ISD::FMADD:              return "X86ISD::FMADD";
18103   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
18104   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
18105   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
18106   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
18107   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
18108   case X86ISD::FMADD_RND:          return "X86ISD::FMADD_RND";
18109   case X86ISD::FNMADD_RND:         return "X86ISD::FNMADD_RND";
18110   case X86ISD::FMSUB_RND:          return "X86ISD::FMSUB_RND";
18111   case X86ISD::FNMSUB_RND:         return "X86ISD::FNMSUB_RND";
18112   case X86ISD::FMADDSUB_RND:       return "X86ISD::FMADDSUB_RND";
18113   case X86ISD::FMSUBADD_RND:       return "X86ISD::FMSUBADD_RND";
18114   case X86ISD::RNDSCALE:           return "X86ISD::RNDSCALE";
18115   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
18116   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
18117   case X86ISD::XTEST:              return "X86ISD::XTEST";
18118   case X86ISD::COMPRESS:           return "X86ISD::COMPRESS";
18119   case X86ISD::EXPAND:             return "X86ISD::EXPAND";
18120   case X86ISD::SELECT:             return "X86ISD::SELECT";
18121   case X86ISD::ADDSUB:             return "X86ISD::ADDSUB";
18122   case X86ISD::RCP28:              return "X86ISD::RCP28";
18123   case X86ISD::EXP2:               return "X86ISD::EXP2";
18124   case X86ISD::RSQRT28:            return "X86ISD::RSQRT28";
18125   case X86ISD::FADD_RND:           return "X86ISD::FADD_RND";
18126   case X86ISD::FSUB_RND:           return "X86ISD::FSUB_RND";
18127   case X86ISD::FMUL_RND:           return "X86ISD::FMUL_RND";
18128   case X86ISD::FDIV_RND:           return "X86ISD::FDIV_RND";
18129   case X86ISD::ADDS:               return "X86ISD::ADDS";
18130   case X86ISD::SUBS:               return "X86ISD::SUBS";
18131   }
18132   return nullptr;
18133 }
18134
18135 // isLegalAddressingMode - Return true if the addressing mode represented
18136 // by AM is legal for this target, for a load/store of the specified type.
18137 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
18138                                               Type *Ty) const {
18139   // X86 supports extremely general addressing modes.
18140   CodeModel::Model M = getTargetMachine().getCodeModel();
18141   Reloc::Model R = getTargetMachine().getRelocationModel();
18142
18143   // X86 allows a sign-extended 32-bit immediate field as a displacement.
18144   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
18145     return false;
18146
18147   if (AM.BaseGV) {
18148     unsigned GVFlags =
18149       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
18150
18151     // If a reference to this global requires an extra load, we can't fold it.
18152     if (isGlobalStubReference(GVFlags))
18153       return false;
18154
18155     // If BaseGV requires a register for the PIC base, we cannot also have a
18156     // BaseReg specified.
18157     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
18158       return false;
18159
18160     // If lower 4G is not available, then we must use rip-relative addressing.
18161     if ((M != CodeModel::Small || R != Reloc::Static) &&
18162         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
18163       return false;
18164   }
18165
18166   switch (AM.Scale) {
18167   case 0:
18168   case 1:
18169   case 2:
18170   case 4:
18171   case 8:
18172     // These scales always work.
18173     break;
18174   case 3:
18175   case 5:
18176   case 9:
18177     // These scales are formed with basereg+scalereg.  Only accept if there is
18178     // no basereg yet.
18179     if (AM.HasBaseReg)
18180       return false;
18181     break;
18182   default:  // Other stuff never works.
18183     return false;
18184   }
18185
18186   return true;
18187 }
18188
18189 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
18190   unsigned Bits = Ty->getScalarSizeInBits();
18191
18192   // 8-bit shifts are always expensive, but versions with a scalar amount aren't
18193   // particularly cheaper than those without.
18194   if (Bits == 8)
18195     return false;
18196
18197   // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
18198   // variable shifts just as cheap as scalar ones.
18199   if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
18200     return false;
18201
18202   // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
18203   // fully general vector.
18204   return true;
18205 }
18206
18207 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
18208   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
18209     return false;
18210   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
18211   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
18212   return NumBits1 > NumBits2;
18213 }
18214
18215 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
18216   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
18217     return false;
18218
18219   if (!isTypeLegal(EVT::getEVT(Ty1)))
18220     return false;
18221
18222   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
18223
18224   // Assuming the caller doesn't have a zeroext or signext return parameter,
18225   // truncation all the way down to i1 is valid.
18226   return true;
18227 }
18228
18229 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
18230   return isInt<32>(Imm);
18231 }
18232
18233 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
18234   // Can also use sub to handle negated immediates.
18235   return isInt<32>(Imm);
18236 }
18237
18238 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
18239   if (!VT1.isInteger() || !VT2.isInteger())
18240     return false;
18241   unsigned NumBits1 = VT1.getSizeInBits();
18242   unsigned NumBits2 = VT2.getSizeInBits();
18243   return NumBits1 > NumBits2;
18244 }
18245
18246 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
18247   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
18248   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
18249 }
18250
18251 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
18252   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
18253   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
18254 }
18255
18256 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
18257   EVT VT1 = Val.getValueType();
18258   if (isZExtFree(VT1, VT2))
18259     return true;
18260
18261   if (Val.getOpcode() != ISD::LOAD)
18262     return false;
18263
18264   if (!VT1.isSimple() || !VT1.isInteger() ||
18265       !VT2.isSimple() || !VT2.isInteger())
18266     return false;
18267
18268   switch (VT1.getSimpleVT().SimpleTy) {
18269   default: break;
18270   case MVT::i8:
18271   case MVT::i16:
18272   case MVT::i32:
18273     // X86 has 8, 16, and 32-bit zero-extending loads.
18274     return true;
18275   }
18276
18277   return false;
18278 }
18279
18280 bool X86TargetLowering::isVectorLoadExtDesirable(SDValue) const { return true; }
18281
18282 bool
18283 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
18284   if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
18285     return false;
18286
18287   VT = VT.getScalarType();
18288
18289   if (!VT.isSimple())
18290     return false;
18291
18292   switch (VT.getSimpleVT().SimpleTy) {
18293   case MVT::f32:
18294   case MVT::f64:
18295     return true;
18296   default:
18297     break;
18298   }
18299
18300   return false;
18301 }
18302
18303 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
18304   // i16 instructions are longer (0x66 prefix) and potentially slower.
18305   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
18306 }
18307
18308 /// isShuffleMaskLegal - Targets can use this to indicate that they only
18309 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
18310 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
18311 /// are assumed to be legal.
18312 bool
18313 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
18314                                       EVT VT) const {
18315   if (!VT.isSimple())
18316     return false;
18317
18318   // Not for i1 vectors
18319   if (VT.getScalarType() == MVT::i1)
18320     return false;
18321
18322   // Very little shuffling can be done for 64-bit vectors right now.
18323   if (VT.getSizeInBits() == 64)
18324     return false;
18325
18326   // We only care that the types being shuffled are legal. The lowering can
18327   // handle any possible shuffle mask that results.
18328   return isTypeLegal(VT.getSimpleVT());
18329 }
18330
18331 bool
18332 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
18333                                           EVT VT) const {
18334   // Just delegate to the generic legality, clear masks aren't special.
18335   return isShuffleMaskLegal(Mask, VT);
18336 }
18337
18338 //===----------------------------------------------------------------------===//
18339 //                           X86 Scheduler Hooks
18340 //===----------------------------------------------------------------------===//
18341
18342 /// Utility function to emit xbegin specifying the start of an RTM region.
18343 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
18344                                      const TargetInstrInfo *TII) {
18345   DebugLoc DL = MI->getDebugLoc();
18346
18347   const BasicBlock *BB = MBB->getBasicBlock();
18348   MachineFunction::iterator I = MBB;
18349   ++I;
18350
18351   // For the v = xbegin(), we generate
18352   //
18353   // thisMBB:
18354   //  xbegin sinkMBB
18355   //
18356   // mainMBB:
18357   //  eax = -1
18358   //
18359   // sinkMBB:
18360   //  v = eax
18361
18362   MachineBasicBlock *thisMBB = MBB;
18363   MachineFunction *MF = MBB->getParent();
18364   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
18365   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
18366   MF->insert(I, mainMBB);
18367   MF->insert(I, sinkMBB);
18368
18369   // Transfer the remainder of BB and its successor edges to sinkMBB.
18370   sinkMBB->splice(sinkMBB->begin(), MBB,
18371                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
18372   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
18373
18374   // thisMBB:
18375   //  xbegin sinkMBB
18376   //  # fallthrough to mainMBB
18377   //  # abortion to sinkMBB
18378   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
18379   thisMBB->addSuccessor(mainMBB);
18380   thisMBB->addSuccessor(sinkMBB);
18381
18382   // mainMBB:
18383   //  EAX = -1
18384   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
18385   mainMBB->addSuccessor(sinkMBB);
18386
18387   // sinkMBB:
18388   // EAX is live into the sinkMBB
18389   sinkMBB->addLiveIn(X86::EAX);
18390   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
18391           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
18392     .addReg(X86::EAX);
18393
18394   MI->eraseFromParent();
18395   return sinkMBB;
18396 }
18397
18398 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
18399 // or XMM0_V32I8 in AVX all of this code can be replaced with that
18400 // in the .td file.
18401 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
18402                                        const TargetInstrInfo *TII) {
18403   unsigned Opc;
18404   switch (MI->getOpcode()) {
18405   default: llvm_unreachable("illegal opcode!");
18406   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
18407   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
18408   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
18409   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
18410   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
18411   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
18412   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
18413   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
18414   }
18415
18416   DebugLoc dl = MI->getDebugLoc();
18417   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
18418
18419   unsigned NumArgs = MI->getNumOperands();
18420   for (unsigned i = 1; i < NumArgs; ++i) {
18421     MachineOperand &Op = MI->getOperand(i);
18422     if (!(Op.isReg() && Op.isImplicit()))
18423       MIB.addOperand(Op);
18424   }
18425   if (MI->hasOneMemOperand())
18426     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
18427
18428   BuildMI(*BB, MI, dl,
18429     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
18430     .addReg(X86::XMM0);
18431
18432   MI->eraseFromParent();
18433   return BB;
18434 }
18435
18436 // FIXME: Custom handling because TableGen doesn't support multiple implicit
18437 // defs in an instruction pattern
18438 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
18439                                        const TargetInstrInfo *TII) {
18440   unsigned Opc;
18441   switch (MI->getOpcode()) {
18442   default: llvm_unreachable("illegal opcode!");
18443   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
18444   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
18445   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
18446   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
18447   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
18448   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
18449   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
18450   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
18451   }
18452
18453   DebugLoc dl = MI->getDebugLoc();
18454   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
18455
18456   unsigned NumArgs = MI->getNumOperands(); // remove the results
18457   for (unsigned i = 1; i < NumArgs; ++i) {
18458     MachineOperand &Op = MI->getOperand(i);
18459     if (!(Op.isReg() && Op.isImplicit()))
18460       MIB.addOperand(Op);
18461   }
18462   if (MI->hasOneMemOperand())
18463     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
18464
18465   BuildMI(*BB, MI, dl,
18466     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
18467     .addReg(X86::ECX);
18468
18469   MI->eraseFromParent();
18470   return BB;
18471 }
18472
18473 static MachineBasicBlock *EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
18474                                       const X86Subtarget *Subtarget) {
18475   DebugLoc dl = MI->getDebugLoc();
18476   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18477   // Address into RAX/EAX, other two args into ECX, EDX.
18478   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
18479   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
18480   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
18481   for (int i = 0; i < X86::AddrNumOperands; ++i)
18482     MIB.addOperand(MI->getOperand(i));
18483
18484   unsigned ValOps = X86::AddrNumOperands;
18485   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
18486     .addReg(MI->getOperand(ValOps).getReg());
18487   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
18488     .addReg(MI->getOperand(ValOps+1).getReg());
18489
18490   // The instruction doesn't actually take any operands though.
18491   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
18492
18493   MI->eraseFromParent(); // The pseudo is gone now.
18494   return BB;
18495 }
18496
18497 MachineBasicBlock *
18498 X86TargetLowering::EmitVAARG64WithCustomInserter(MachineInstr *MI,
18499                                                  MachineBasicBlock *MBB) const {
18500   // Emit va_arg instruction on X86-64.
18501
18502   // Operands to this pseudo-instruction:
18503   // 0  ) Output        : destination address (reg)
18504   // 1-5) Input         : va_list address (addr, i64mem)
18505   // 6  ) ArgSize       : Size (in bytes) of vararg type
18506   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
18507   // 8  ) Align         : Alignment of type
18508   // 9  ) EFLAGS (implicit-def)
18509
18510   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
18511   static_assert(X86::AddrNumOperands == 5,
18512                 "VAARG_64 assumes 5 address operands");
18513
18514   unsigned DestReg = MI->getOperand(0).getReg();
18515   MachineOperand &Base = MI->getOperand(1);
18516   MachineOperand &Scale = MI->getOperand(2);
18517   MachineOperand &Index = MI->getOperand(3);
18518   MachineOperand &Disp = MI->getOperand(4);
18519   MachineOperand &Segment = MI->getOperand(5);
18520   unsigned ArgSize = MI->getOperand(6).getImm();
18521   unsigned ArgMode = MI->getOperand(7).getImm();
18522   unsigned Align = MI->getOperand(8).getImm();
18523
18524   // Memory Reference
18525   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
18526   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
18527   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
18528
18529   // Machine Information
18530   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18531   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
18532   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
18533   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
18534   DebugLoc DL = MI->getDebugLoc();
18535
18536   // struct va_list {
18537   //   i32   gp_offset
18538   //   i32   fp_offset
18539   //   i64   overflow_area (address)
18540   //   i64   reg_save_area (address)
18541   // }
18542   // sizeof(va_list) = 24
18543   // alignment(va_list) = 8
18544
18545   unsigned TotalNumIntRegs = 6;
18546   unsigned TotalNumXMMRegs = 8;
18547   bool UseGPOffset = (ArgMode == 1);
18548   bool UseFPOffset = (ArgMode == 2);
18549   unsigned MaxOffset = TotalNumIntRegs * 8 +
18550                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
18551
18552   /* Align ArgSize to a multiple of 8 */
18553   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
18554   bool NeedsAlign = (Align > 8);
18555
18556   MachineBasicBlock *thisMBB = MBB;
18557   MachineBasicBlock *overflowMBB;
18558   MachineBasicBlock *offsetMBB;
18559   MachineBasicBlock *endMBB;
18560
18561   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
18562   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
18563   unsigned OffsetReg = 0;
18564
18565   if (!UseGPOffset && !UseFPOffset) {
18566     // If we only pull from the overflow region, we don't create a branch.
18567     // We don't need to alter control flow.
18568     OffsetDestReg = 0; // unused
18569     OverflowDestReg = DestReg;
18570
18571     offsetMBB = nullptr;
18572     overflowMBB = thisMBB;
18573     endMBB = thisMBB;
18574   } else {
18575     // First emit code to check if gp_offset (or fp_offset) is below the bound.
18576     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
18577     // If not, pull from overflow_area. (branch to overflowMBB)
18578     //
18579     //       thisMBB
18580     //         |     .
18581     //         |        .
18582     //     offsetMBB   overflowMBB
18583     //         |        .
18584     //         |     .
18585     //        endMBB
18586
18587     // Registers for the PHI in endMBB
18588     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
18589     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
18590
18591     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
18592     MachineFunction *MF = MBB->getParent();
18593     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18594     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18595     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18596
18597     MachineFunction::iterator MBBIter = MBB;
18598     ++MBBIter;
18599
18600     // Insert the new basic blocks
18601     MF->insert(MBBIter, offsetMBB);
18602     MF->insert(MBBIter, overflowMBB);
18603     MF->insert(MBBIter, endMBB);
18604
18605     // Transfer the remainder of MBB and its successor edges to endMBB.
18606     endMBB->splice(endMBB->begin(), thisMBB,
18607                    std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
18608     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
18609
18610     // Make offsetMBB and overflowMBB successors of thisMBB
18611     thisMBB->addSuccessor(offsetMBB);
18612     thisMBB->addSuccessor(overflowMBB);
18613
18614     // endMBB is a successor of both offsetMBB and overflowMBB
18615     offsetMBB->addSuccessor(endMBB);
18616     overflowMBB->addSuccessor(endMBB);
18617
18618     // Load the offset value into a register
18619     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
18620     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
18621       .addOperand(Base)
18622       .addOperand(Scale)
18623       .addOperand(Index)
18624       .addDisp(Disp, UseFPOffset ? 4 : 0)
18625       .addOperand(Segment)
18626       .setMemRefs(MMOBegin, MMOEnd);
18627
18628     // Check if there is enough room left to pull this argument.
18629     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
18630       .addReg(OffsetReg)
18631       .addImm(MaxOffset + 8 - ArgSizeA8);
18632
18633     // Branch to "overflowMBB" if offset >= max
18634     // Fall through to "offsetMBB" otherwise
18635     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
18636       .addMBB(overflowMBB);
18637   }
18638
18639   // In offsetMBB, emit code to use the reg_save_area.
18640   if (offsetMBB) {
18641     assert(OffsetReg != 0);
18642
18643     // Read the reg_save_area address.
18644     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
18645     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
18646       .addOperand(Base)
18647       .addOperand(Scale)
18648       .addOperand(Index)
18649       .addDisp(Disp, 16)
18650       .addOperand(Segment)
18651       .setMemRefs(MMOBegin, MMOEnd);
18652
18653     // Zero-extend the offset
18654     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
18655       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
18656         .addImm(0)
18657         .addReg(OffsetReg)
18658         .addImm(X86::sub_32bit);
18659
18660     // Add the offset to the reg_save_area to get the final address.
18661     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
18662       .addReg(OffsetReg64)
18663       .addReg(RegSaveReg);
18664
18665     // Compute the offset for the next argument
18666     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
18667     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
18668       .addReg(OffsetReg)
18669       .addImm(UseFPOffset ? 16 : 8);
18670
18671     // Store it back into the va_list.
18672     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
18673       .addOperand(Base)
18674       .addOperand(Scale)
18675       .addOperand(Index)
18676       .addDisp(Disp, UseFPOffset ? 4 : 0)
18677       .addOperand(Segment)
18678       .addReg(NextOffsetReg)
18679       .setMemRefs(MMOBegin, MMOEnd);
18680
18681     // Jump to endMBB
18682     BuildMI(offsetMBB, DL, TII->get(X86::JMP_1))
18683       .addMBB(endMBB);
18684   }
18685
18686   //
18687   // Emit code to use overflow area
18688   //
18689
18690   // Load the overflow_area address into a register.
18691   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
18692   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
18693     .addOperand(Base)
18694     .addOperand(Scale)
18695     .addOperand(Index)
18696     .addDisp(Disp, 8)
18697     .addOperand(Segment)
18698     .setMemRefs(MMOBegin, MMOEnd);
18699
18700   // If we need to align it, do so. Otherwise, just copy the address
18701   // to OverflowDestReg.
18702   if (NeedsAlign) {
18703     // Align the overflow address
18704     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
18705     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
18706
18707     // aligned_addr = (addr + (align-1)) & ~(align-1)
18708     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
18709       .addReg(OverflowAddrReg)
18710       .addImm(Align-1);
18711
18712     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
18713       .addReg(TmpReg)
18714       .addImm(~(uint64_t)(Align-1));
18715   } else {
18716     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
18717       .addReg(OverflowAddrReg);
18718   }
18719
18720   // Compute the next overflow address after this argument.
18721   // (the overflow address should be kept 8-byte aligned)
18722   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
18723   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
18724     .addReg(OverflowDestReg)
18725     .addImm(ArgSizeA8);
18726
18727   // Store the new overflow address.
18728   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
18729     .addOperand(Base)
18730     .addOperand(Scale)
18731     .addOperand(Index)
18732     .addDisp(Disp, 8)
18733     .addOperand(Segment)
18734     .addReg(NextAddrReg)
18735     .setMemRefs(MMOBegin, MMOEnd);
18736
18737   // If we branched, emit the PHI to the front of endMBB.
18738   if (offsetMBB) {
18739     BuildMI(*endMBB, endMBB->begin(), DL,
18740             TII->get(X86::PHI), DestReg)
18741       .addReg(OffsetDestReg).addMBB(offsetMBB)
18742       .addReg(OverflowDestReg).addMBB(overflowMBB);
18743   }
18744
18745   // Erase the pseudo instruction
18746   MI->eraseFromParent();
18747
18748   return endMBB;
18749 }
18750
18751 MachineBasicBlock *
18752 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
18753                                                  MachineInstr *MI,
18754                                                  MachineBasicBlock *MBB) const {
18755   // Emit code to save XMM registers to the stack. The ABI says that the
18756   // number of registers to save is given in %al, so it's theoretically
18757   // possible to do an indirect jump trick to avoid saving all of them,
18758   // however this code takes a simpler approach and just executes all
18759   // of the stores if %al is non-zero. It's less code, and it's probably
18760   // easier on the hardware branch predictor, and stores aren't all that
18761   // expensive anyway.
18762
18763   // Create the new basic blocks. One block contains all the XMM stores,
18764   // and one block is the final destination regardless of whether any
18765   // stores were performed.
18766   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
18767   MachineFunction *F = MBB->getParent();
18768   MachineFunction::iterator MBBIter = MBB;
18769   ++MBBIter;
18770   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
18771   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
18772   F->insert(MBBIter, XMMSaveMBB);
18773   F->insert(MBBIter, EndMBB);
18774
18775   // Transfer the remainder of MBB and its successor edges to EndMBB.
18776   EndMBB->splice(EndMBB->begin(), MBB,
18777                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
18778   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
18779
18780   // The original block will now fall through to the XMM save block.
18781   MBB->addSuccessor(XMMSaveMBB);
18782   // The XMMSaveMBB will fall through to the end block.
18783   XMMSaveMBB->addSuccessor(EndMBB);
18784
18785   // Now add the instructions.
18786   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18787   DebugLoc DL = MI->getDebugLoc();
18788
18789   unsigned CountReg = MI->getOperand(0).getReg();
18790   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
18791   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
18792
18793   if (!Subtarget->isTargetWin64()) {
18794     // If %al is 0, branch around the XMM save block.
18795     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
18796     BuildMI(MBB, DL, TII->get(X86::JE_1)).addMBB(EndMBB);
18797     MBB->addSuccessor(EndMBB);
18798   }
18799
18800   // Make sure the last operand is EFLAGS, which gets clobbered by the branch
18801   // that was just emitted, but clearly shouldn't be "saved".
18802   assert((MI->getNumOperands() <= 3 ||
18803           !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
18804           MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
18805          && "Expected last argument to be EFLAGS");
18806   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
18807   // In the XMM save block, save all the XMM argument registers.
18808   for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
18809     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
18810     MachineMemOperand *MMO =
18811       F->getMachineMemOperand(
18812           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
18813         MachineMemOperand::MOStore,
18814         /*Size=*/16, /*Align=*/16);
18815     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
18816       .addFrameIndex(RegSaveFrameIndex)
18817       .addImm(/*Scale=*/1)
18818       .addReg(/*IndexReg=*/0)
18819       .addImm(/*Disp=*/Offset)
18820       .addReg(/*Segment=*/0)
18821       .addReg(MI->getOperand(i).getReg())
18822       .addMemOperand(MMO);
18823   }
18824
18825   MI->eraseFromParent();   // The pseudo instruction is gone now.
18826
18827   return EndMBB;
18828 }
18829
18830 // The EFLAGS operand of SelectItr might be missing a kill marker
18831 // because there were multiple uses of EFLAGS, and ISel didn't know
18832 // which to mark. Figure out whether SelectItr should have had a
18833 // kill marker, and set it if it should. Returns the correct kill
18834 // marker value.
18835 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
18836                                      MachineBasicBlock* BB,
18837                                      const TargetRegisterInfo* TRI) {
18838   // Scan forward through BB for a use/def of EFLAGS.
18839   MachineBasicBlock::iterator miI(std::next(SelectItr));
18840   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
18841     const MachineInstr& mi = *miI;
18842     if (mi.readsRegister(X86::EFLAGS))
18843       return false;
18844     if (mi.definesRegister(X86::EFLAGS))
18845       break; // Should have kill-flag - update below.
18846   }
18847
18848   // If we hit the end of the block, check whether EFLAGS is live into a
18849   // successor.
18850   if (miI == BB->end()) {
18851     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
18852                                           sEnd = BB->succ_end();
18853          sItr != sEnd; ++sItr) {
18854       MachineBasicBlock* succ = *sItr;
18855       if (succ->isLiveIn(X86::EFLAGS))
18856         return false;
18857     }
18858   }
18859
18860   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
18861   // out. SelectMI should have a kill flag on EFLAGS.
18862   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
18863   return true;
18864 }
18865
18866 MachineBasicBlock *
18867 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
18868                                      MachineBasicBlock *BB) const {
18869   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18870   DebugLoc DL = MI->getDebugLoc();
18871
18872   // To "insert" a SELECT_CC instruction, we actually have to insert the
18873   // diamond control-flow pattern.  The incoming instruction knows the
18874   // destination vreg to set, the condition code register to branch on, the
18875   // true/false values to select between, and a branch opcode to use.
18876   const BasicBlock *LLVM_BB = BB->getBasicBlock();
18877   MachineFunction::iterator It = BB;
18878   ++It;
18879
18880   //  thisMBB:
18881   //  ...
18882   //   TrueVal = ...
18883   //   cmpTY ccX, r1, r2
18884   //   bCC copy1MBB
18885   //   fallthrough --> copy0MBB
18886   MachineBasicBlock *thisMBB = BB;
18887   MachineFunction *F = BB->getParent();
18888
18889   // We also lower double CMOVs:
18890   //   (CMOV (CMOV F, T, cc1), T, cc2)
18891   // to two successives branches.  For that, we look for another CMOV as the
18892   // following instruction.
18893   //
18894   // Without this, we would add a PHI between the two jumps, which ends up
18895   // creating a few copies all around. For instance, for
18896   //
18897   //    (sitofp (zext (fcmp une)))
18898   //
18899   // we would generate:
18900   //
18901   //         ucomiss %xmm1, %xmm0
18902   //         movss  <1.0f>, %xmm0
18903   //         movaps  %xmm0, %xmm1
18904   //         jne     .LBB5_2
18905   //         xorps   %xmm1, %xmm1
18906   // .LBB5_2:
18907   //         jp      .LBB5_4
18908   //         movaps  %xmm1, %xmm0
18909   // .LBB5_4:
18910   //         retq
18911   //
18912   // because this custom-inserter would have generated:
18913   //
18914   //   A
18915   //   | \
18916   //   |  B
18917   //   | /
18918   //   C
18919   //   | \
18920   //   |  D
18921   //   | /
18922   //   E
18923   //
18924   // A: X = ...; Y = ...
18925   // B: empty
18926   // C: Z = PHI [X, A], [Y, B]
18927   // D: empty
18928   // E: PHI [X, C], [Z, D]
18929   //
18930   // If we lower both CMOVs in a single step, we can instead generate:
18931   //
18932   //   A
18933   //   | \
18934   //   |  C
18935   //   | /|
18936   //   |/ |
18937   //   |  |
18938   //   |  D
18939   //   | /
18940   //   E
18941   //
18942   // A: X = ...; Y = ...
18943   // D: empty
18944   // E: PHI [X, A], [X, C], [Y, D]
18945   //
18946   // Which, in our sitofp/fcmp example, gives us something like:
18947   //
18948   //         ucomiss %xmm1, %xmm0
18949   //         movss  <1.0f>, %xmm0
18950   //         jne     .LBB5_4
18951   //         jp      .LBB5_4
18952   //         xorps   %xmm0, %xmm0
18953   // .LBB5_4:
18954   //         retq
18955   //
18956   MachineInstr *NextCMOV = nullptr;
18957   MachineBasicBlock::iterator NextMIIt =
18958       std::next(MachineBasicBlock::iterator(MI));
18959   if (NextMIIt != BB->end() && NextMIIt->getOpcode() == MI->getOpcode() &&
18960       NextMIIt->getOperand(2).getReg() == MI->getOperand(2).getReg() &&
18961       NextMIIt->getOperand(1).getReg() == MI->getOperand(0).getReg())
18962     NextCMOV = &*NextMIIt;
18963
18964   MachineBasicBlock *jcc1MBB = nullptr;
18965
18966   // If we have a double CMOV, we lower it to two successive branches to
18967   // the same block.  EFLAGS is used by both, so mark it as live in the second.
18968   if (NextCMOV) {
18969     jcc1MBB = F->CreateMachineBasicBlock(LLVM_BB);
18970     F->insert(It, jcc1MBB);
18971     jcc1MBB->addLiveIn(X86::EFLAGS);
18972   }
18973
18974   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
18975   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
18976   F->insert(It, copy0MBB);
18977   F->insert(It, sinkMBB);
18978
18979   // If the EFLAGS register isn't dead in the terminator, then claim that it's
18980   // live into the sink and copy blocks.
18981   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
18982
18983   MachineInstr *LastEFLAGSUser = NextCMOV ? NextCMOV : MI;
18984   if (!LastEFLAGSUser->killsRegister(X86::EFLAGS) &&
18985       !checkAndUpdateEFLAGSKill(LastEFLAGSUser, BB, TRI)) {
18986     copy0MBB->addLiveIn(X86::EFLAGS);
18987     sinkMBB->addLiveIn(X86::EFLAGS);
18988   }
18989
18990   // Transfer the remainder of BB and its successor edges to sinkMBB.
18991   sinkMBB->splice(sinkMBB->begin(), BB,
18992                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
18993   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
18994
18995   // Add the true and fallthrough blocks as its successors.
18996   if (NextCMOV) {
18997     // The fallthrough block may be jcc1MBB, if we have a double CMOV.
18998     BB->addSuccessor(jcc1MBB);
18999
19000     // In that case, jcc1MBB will itself fallthrough the copy0MBB, and
19001     // jump to the sinkMBB.
19002     jcc1MBB->addSuccessor(copy0MBB);
19003     jcc1MBB->addSuccessor(sinkMBB);
19004   } else {
19005     BB->addSuccessor(copy0MBB);
19006   }
19007
19008   // The true block target of the first (or only) branch is always sinkMBB.
19009   BB->addSuccessor(sinkMBB);
19010
19011   // Create the conditional branch instruction.
19012   unsigned Opc =
19013     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
19014   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
19015
19016   if (NextCMOV) {
19017     unsigned Opc2 = X86::GetCondBranchFromCond(
19018         (X86::CondCode)NextCMOV->getOperand(3).getImm());
19019     BuildMI(jcc1MBB, DL, TII->get(Opc2)).addMBB(sinkMBB);
19020   }
19021
19022   //  copy0MBB:
19023   //   %FalseValue = ...
19024   //   # fallthrough to sinkMBB
19025   copy0MBB->addSuccessor(sinkMBB);
19026
19027   //  sinkMBB:
19028   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
19029   //  ...
19030   MachineInstrBuilder MIB =
19031       BuildMI(*sinkMBB, sinkMBB->begin(), DL, TII->get(X86::PHI),
19032               MI->getOperand(0).getReg())
19033           .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
19034           .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
19035
19036   // If we have a double CMOV, the second Jcc provides the same incoming
19037   // value as the first Jcc (the True operand of the SELECT_CC/CMOV nodes).
19038   if (NextCMOV) {
19039     MIB.addReg(MI->getOperand(2).getReg()).addMBB(jcc1MBB);
19040     // Copy the PHI result to the register defined by the second CMOV.
19041     BuildMI(*sinkMBB, std::next(MachineBasicBlock::iterator(MIB.getInstr())),
19042             DL, TII->get(TargetOpcode::COPY), NextCMOV->getOperand(0).getReg())
19043         .addReg(MI->getOperand(0).getReg());
19044     NextCMOV->eraseFromParent();
19045   }
19046
19047   MI->eraseFromParent();   // The pseudo instruction is gone now.
19048   return sinkMBB;
19049 }
19050
19051 MachineBasicBlock *
19052 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI,
19053                                         MachineBasicBlock *BB) const {
19054   MachineFunction *MF = BB->getParent();
19055   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19056   DebugLoc DL = MI->getDebugLoc();
19057   const BasicBlock *LLVM_BB = BB->getBasicBlock();
19058
19059   assert(MF->shouldSplitStack());
19060
19061   const bool Is64Bit = Subtarget->is64Bit();
19062   const bool IsLP64 = Subtarget->isTarget64BitLP64();
19063
19064   const unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
19065   const unsigned TlsOffset = IsLP64 ? 0x70 : Is64Bit ? 0x40 : 0x30;
19066
19067   // BB:
19068   //  ... [Till the alloca]
19069   // If stacklet is not large enough, jump to mallocMBB
19070   //
19071   // bumpMBB:
19072   //  Allocate by subtracting from RSP
19073   //  Jump to continueMBB
19074   //
19075   // mallocMBB:
19076   //  Allocate by call to runtime
19077   //
19078   // continueMBB:
19079   //  ...
19080   //  [rest of original BB]
19081   //
19082
19083   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
19084   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
19085   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
19086
19087   MachineRegisterInfo &MRI = MF->getRegInfo();
19088   const TargetRegisterClass *AddrRegClass =
19089     getRegClassFor(getPointerTy());
19090
19091   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
19092     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
19093     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
19094     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
19095     sizeVReg = MI->getOperand(1).getReg(),
19096     physSPReg = IsLP64 || Subtarget->isTargetNaCl64() ? X86::RSP : X86::ESP;
19097
19098   MachineFunction::iterator MBBIter = BB;
19099   ++MBBIter;
19100
19101   MF->insert(MBBIter, bumpMBB);
19102   MF->insert(MBBIter, mallocMBB);
19103   MF->insert(MBBIter, continueMBB);
19104
19105   continueMBB->splice(continueMBB->begin(), BB,
19106                       std::next(MachineBasicBlock::iterator(MI)), BB->end());
19107   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
19108
19109   // Add code to the main basic block to check if the stack limit has been hit,
19110   // and if so, jump to mallocMBB otherwise to bumpMBB.
19111   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
19112   BuildMI(BB, DL, TII->get(IsLP64 ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
19113     .addReg(tmpSPVReg).addReg(sizeVReg);
19114   BuildMI(BB, DL, TII->get(IsLP64 ? X86::CMP64mr:X86::CMP32mr))
19115     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
19116     .addReg(SPLimitVReg);
19117   BuildMI(BB, DL, TII->get(X86::JG_1)).addMBB(mallocMBB);
19118
19119   // bumpMBB simply decreases the stack pointer, since we know the current
19120   // stacklet has enough space.
19121   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
19122     .addReg(SPLimitVReg);
19123   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
19124     .addReg(SPLimitVReg);
19125   BuildMI(bumpMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
19126
19127   // Calls into a routine in libgcc to allocate more space from the heap.
19128   const uint32_t *RegMask =
19129       Subtarget->getRegisterInfo()->getCallPreservedMask(*MF, CallingConv::C);
19130   if (IsLP64) {
19131     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
19132       .addReg(sizeVReg);
19133     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
19134       .addExternalSymbol("__morestack_allocate_stack_space")
19135       .addRegMask(RegMask)
19136       .addReg(X86::RDI, RegState::Implicit)
19137       .addReg(X86::RAX, RegState::ImplicitDefine);
19138   } else if (Is64Bit) {
19139     BuildMI(mallocMBB, DL, TII->get(X86::MOV32rr), X86::EDI)
19140       .addReg(sizeVReg);
19141     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
19142       .addExternalSymbol("__morestack_allocate_stack_space")
19143       .addRegMask(RegMask)
19144       .addReg(X86::EDI, RegState::Implicit)
19145       .addReg(X86::EAX, RegState::ImplicitDefine);
19146   } else {
19147     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
19148       .addImm(12);
19149     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
19150     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
19151       .addExternalSymbol("__morestack_allocate_stack_space")
19152       .addRegMask(RegMask)
19153       .addReg(X86::EAX, RegState::ImplicitDefine);
19154   }
19155
19156   if (!Is64Bit)
19157     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
19158       .addImm(16);
19159
19160   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
19161     .addReg(IsLP64 ? X86::RAX : X86::EAX);
19162   BuildMI(mallocMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
19163
19164   // Set up the CFG correctly.
19165   BB->addSuccessor(bumpMBB);
19166   BB->addSuccessor(mallocMBB);
19167   mallocMBB->addSuccessor(continueMBB);
19168   bumpMBB->addSuccessor(continueMBB);
19169
19170   // Take care of the PHI nodes.
19171   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
19172           MI->getOperand(0).getReg())
19173     .addReg(mallocPtrVReg).addMBB(mallocMBB)
19174     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
19175
19176   // Delete the original pseudo instruction.
19177   MI->eraseFromParent();
19178
19179   // And we're done.
19180   return continueMBB;
19181 }
19182
19183 MachineBasicBlock *
19184 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
19185                                         MachineBasicBlock *BB) const {
19186   DebugLoc DL = MI->getDebugLoc();
19187
19188   assert(!Subtarget->isTargetMachO());
19189
19190   X86FrameLowering::emitStackProbeCall(*BB->getParent(), *BB, MI, DL);
19191
19192   MI->eraseFromParent();   // The pseudo instruction is gone now.
19193   return BB;
19194 }
19195
19196 MachineBasicBlock *
19197 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
19198                                       MachineBasicBlock *BB) const {
19199   // This is pretty easy.  We're taking the value that we received from
19200   // our load from the relocation, sticking it in either RDI (x86-64)
19201   // or EAX and doing an indirect call.  The return value will then
19202   // be in the normal return register.
19203   MachineFunction *F = BB->getParent();
19204   const X86InstrInfo *TII = Subtarget->getInstrInfo();
19205   DebugLoc DL = MI->getDebugLoc();
19206
19207   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
19208   assert(MI->getOperand(3).isGlobal() && "This should be a global");
19209
19210   // Get a register mask for the lowered call.
19211   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
19212   // proper register mask.
19213   const uint32_t *RegMask =
19214       Subtarget->getRegisterInfo()->getCallPreservedMask(*F, CallingConv::C);
19215   if (Subtarget->is64Bit()) {
19216     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
19217                                       TII->get(X86::MOV64rm), X86::RDI)
19218     .addReg(X86::RIP)
19219     .addImm(0).addReg(0)
19220     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
19221                       MI->getOperand(3).getTargetFlags())
19222     .addReg(0);
19223     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
19224     addDirectMem(MIB, X86::RDI);
19225     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
19226   } else if (F->getTarget().getRelocationModel() != Reloc::PIC_) {
19227     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
19228                                       TII->get(X86::MOV32rm), X86::EAX)
19229     .addReg(0)
19230     .addImm(0).addReg(0)
19231     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
19232                       MI->getOperand(3).getTargetFlags())
19233     .addReg(0);
19234     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
19235     addDirectMem(MIB, X86::EAX);
19236     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
19237   } else {
19238     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
19239                                       TII->get(X86::MOV32rm), X86::EAX)
19240     .addReg(TII->getGlobalBaseReg(F))
19241     .addImm(0).addReg(0)
19242     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
19243                       MI->getOperand(3).getTargetFlags())
19244     .addReg(0);
19245     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
19246     addDirectMem(MIB, X86::EAX);
19247     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
19248   }
19249
19250   MI->eraseFromParent(); // The pseudo instruction is gone now.
19251   return BB;
19252 }
19253
19254 MachineBasicBlock *
19255 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
19256                                     MachineBasicBlock *MBB) const {
19257   DebugLoc DL = MI->getDebugLoc();
19258   MachineFunction *MF = MBB->getParent();
19259   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19260   MachineRegisterInfo &MRI = MF->getRegInfo();
19261
19262   const BasicBlock *BB = MBB->getBasicBlock();
19263   MachineFunction::iterator I = MBB;
19264   ++I;
19265
19266   // Memory Reference
19267   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
19268   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
19269
19270   unsigned DstReg;
19271   unsigned MemOpndSlot = 0;
19272
19273   unsigned CurOp = 0;
19274
19275   DstReg = MI->getOperand(CurOp++).getReg();
19276   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
19277   assert(RC->hasType(MVT::i32) && "Invalid destination!");
19278   unsigned mainDstReg = MRI.createVirtualRegister(RC);
19279   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
19280
19281   MemOpndSlot = CurOp;
19282
19283   MVT PVT = getPointerTy();
19284   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
19285          "Invalid Pointer Size!");
19286
19287   // For v = setjmp(buf), we generate
19288   //
19289   // thisMBB:
19290   //  buf[LabelOffset] = restoreMBB
19291   //  SjLjSetup restoreMBB
19292   //
19293   // mainMBB:
19294   //  v_main = 0
19295   //
19296   // sinkMBB:
19297   //  v = phi(main, restore)
19298   //
19299   // restoreMBB:
19300   //  if base pointer being used, load it from frame
19301   //  v_restore = 1
19302
19303   MachineBasicBlock *thisMBB = MBB;
19304   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
19305   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
19306   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
19307   MF->insert(I, mainMBB);
19308   MF->insert(I, sinkMBB);
19309   MF->push_back(restoreMBB);
19310
19311   MachineInstrBuilder MIB;
19312
19313   // Transfer the remainder of BB and its successor edges to sinkMBB.
19314   sinkMBB->splice(sinkMBB->begin(), MBB,
19315                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
19316   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
19317
19318   // thisMBB:
19319   unsigned PtrStoreOpc = 0;
19320   unsigned LabelReg = 0;
19321   const int64_t LabelOffset = 1 * PVT.getStoreSize();
19322   Reloc::Model RM = MF->getTarget().getRelocationModel();
19323   bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
19324                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
19325
19326   // Prepare IP either in reg or imm.
19327   if (!UseImmLabel) {
19328     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
19329     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
19330     LabelReg = MRI.createVirtualRegister(PtrRC);
19331     if (Subtarget->is64Bit()) {
19332       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
19333               .addReg(X86::RIP)
19334               .addImm(0)
19335               .addReg(0)
19336               .addMBB(restoreMBB)
19337               .addReg(0);
19338     } else {
19339       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
19340       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
19341               .addReg(XII->getGlobalBaseReg(MF))
19342               .addImm(0)
19343               .addReg(0)
19344               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
19345               .addReg(0);
19346     }
19347   } else
19348     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
19349   // Store IP
19350   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
19351   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
19352     if (i == X86::AddrDisp)
19353       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
19354     else
19355       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
19356   }
19357   if (!UseImmLabel)
19358     MIB.addReg(LabelReg);
19359   else
19360     MIB.addMBB(restoreMBB);
19361   MIB.setMemRefs(MMOBegin, MMOEnd);
19362   // Setup
19363   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
19364           .addMBB(restoreMBB);
19365
19366   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
19367   MIB.addRegMask(RegInfo->getNoPreservedMask());
19368   thisMBB->addSuccessor(mainMBB);
19369   thisMBB->addSuccessor(restoreMBB);
19370
19371   // mainMBB:
19372   //  EAX = 0
19373   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
19374   mainMBB->addSuccessor(sinkMBB);
19375
19376   // sinkMBB:
19377   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
19378           TII->get(X86::PHI), DstReg)
19379     .addReg(mainDstReg).addMBB(mainMBB)
19380     .addReg(restoreDstReg).addMBB(restoreMBB);
19381
19382   // restoreMBB:
19383   if (RegInfo->hasBasePointer(*MF)) {
19384     const bool Uses64BitFramePtr =
19385         Subtarget->isTarget64BitLP64() || Subtarget->isTargetNaCl64();
19386     X86MachineFunctionInfo *X86FI = MF->getInfo<X86MachineFunctionInfo>();
19387     X86FI->setRestoreBasePointer(MF);
19388     unsigned FramePtr = RegInfo->getFrameRegister(*MF);
19389     unsigned BasePtr = RegInfo->getBaseRegister();
19390     unsigned Opm = Uses64BitFramePtr ? X86::MOV64rm : X86::MOV32rm;
19391     addRegOffset(BuildMI(restoreMBB, DL, TII->get(Opm), BasePtr),
19392                  FramePtr, true, X86FI->getRestoreBasePointerOffset())
19393       .setMIFlag(MachineInstr::FrameSetup);
19394   }
19395   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
19396   BuildMI(restoreMBB, DL, TII->get(X86::JMP_1)).addMBB(sinkMBB);
19397   restoreMBB->addSuccessor(sinkMBB);
19398
19399   MI->eraseFromParent();
19400   return sinkMBB;
19401 }
19402
19403 MachineBasicBlock *
19404 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
19405                                      MachineBasicBlock *MBB) const {
19406   DebugLoc DL = MI->getDebugLoc();
19407   MachineFunction *MF = MBB->getParent();
19408   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19409   MachineRegisterInfo &MRI = MF->getRegInfo();
19410
19411   // Memory Reference
19412   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
19413   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
19414
19415   MVT PVT = getPointerTy();
19416   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
19417          "Invalid Pointer Size!");
19418
19419   const TargetRegisterClass *RC =
19420     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
19421   unsigned Tmp = MRI.createVirtualRegister(RC);
19422   // Since FP is only updated here but NOT referenced, it's treated as GPR.
19423   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
19424   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
19425   unsigned SP = RegInfo->getStackRegister();
19426
19427   MachineInstrBuilder MIB;
19428
19429   const int64_t LabelOffset = 1 * PVT.getStoreSize();
19430   const int64_t SPOffset = 2 * PVT.getStoreSize();
19431
19432   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
19433   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
19434
19435   // Reload FP
19436   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
19437   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
19438     MIB.addOperand(MI->getOperand(i));
19439   MIB.setMemRefs(MMOBegin, MMOEnd);
19440   // Reload IP
19441   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
19442   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
19443     if (i == X86::AddrDisp)
19444       MIB.addDisp(MI->getOperand(i), LabelOffset);
19445     else
19446       MIB.addOperand(MI->getOperand(i));
19447   }
19448   MIB.setMemRefs(MMOBegin, MMOEnd);
19449   // Reload SP
19450   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
19451   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
19452     if (i == X86::AddrDisp)
19453       MIB.addDisp(MI->getOperand(i), SPOffset);
19454     else
19455       MIB.addOperand(MI->getOperand(i));
19456   }
19457   MIB.setMemRefs(MMOBegin, MMOEnd);
19458   // Jump
19459   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
19460
19461   MI->eraseFromParent();
19462   return MBB;
19463 }
19464
19465 // Replace 213-type (isel default) FMA3 instructions with 231-type for
19466 // accumulator loops. Writing back to the accumulator allows the coalescer
19467 // to remove extra copies in the loop.
19468 MachineBasicBlock *
19469 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
19470                                  MachineBasicBlock *MBB) const {
19471   MachineOperand &AddendOp = MI->getOperand(3);
19472
19473   // Bail out early if the addend isn't a register - we can't switch these.
19474   if (!AddendOp.isReg())
19475     return MBB;
19476
19477   MachineFunction &MF = *MBB->getParent();
19478   MachineRegisterInfo &MRI = MF.getRegInfo();
19479
19480   // Check whether the addend is defined by a PHI:
19481   assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
19482   MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
19483   if (!AddendDef.isPHI())
19484     return MBB;
19485
19486   // Look for the following pattern:
19487   // loop:
19488   //   %addend = phi [%entry, 0], [%loop, %result]
19489   //   ...
19490   //   %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
19491
19492   // Replace with:
19493   //   loop:
19494   //   %addend = phi [%entry, 0], [%loop, %result]
19495   //   ...
19496   //   %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
19497
19498   for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
19499     assert(AddendDef.getOperand(i).isReg());
19500     MachineOperand PHISrcOp = AddendDef.getOperand(i);
19501     MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
19502     if (&PHISrcInst == MI) {
19503       // Found a matching instruction.
19504       unsigned NewFMAOpc = 0;
19505       switch (MI->getOpcode()) {
19506         case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
19507         case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
19508         case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
19509         case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
19510         case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
19511         case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
19512         case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
19513         case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
19514         case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
19515         case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
19516         case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
19517         case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
19518         case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
19519         case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
19520         case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
19521         case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
19522         case X86::VFMADDSUBPDr213r: NewFMAOpc = X86::VFMADDSUBPDr231r; break;
19523         case X86::VFMADDSUBPSr213r: NewFMAOpc = X86::VFMADDSUBPSr231r; break;
19524         case X86::VFMSUBADDPDr213r: NewFMAOpc = X86::VFMSUBADDPDr231r; break;
19525         case X86::VFMSUBADDPSr213r: NewFMAOpc = X86::VFMSUBADDPSr231r; break;
19526
19527         case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
19528         case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
19529         case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
19530         case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
19531         case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
19532         case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
19533         case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
19534         case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
19535         case X86::VFMADDSUBPDr213rY: NewFMAOpc = X86::VFMADDSUBPDr231rY; break;
19536         case X86::VFMADDSUBPSr213rY: NewFMAOpc = X86::VFMADDSUBPSr231rY; break;
19537         case X86::VFMSUBADDPDr213rY: NewFMAOpc = X86::VFMSUBADDPDr231rY; break;
19538         case X86::VFMSUBADDPSr213rY: NewFMAOpc = X86::VFMSUBADDPSr231rY; break;
19539         default: llvm_unreachable("Unrecognized FMA variant.");
19540       }
19541
19542       const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
19543       MachineInstrBuilder MIB =
19544         BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
19545         .addOperand(MI->getOperand(0))
19546         .addOperand(MI->getOperand(3))
19547         .addOperand(MI->getOperand(2))
19548         .addOperand(MI->getOperand(1));
19549       MBB->insert(MachineBasicBlock::iterator(MI), MIB);
19550       MI->eraseFromParent();
19551     }
19552   }
19553
19554   return MBB;
19555 }
19556
19557 MachineBasicBlock *
19558 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
19559                                                MachineBasicBlock *BB) const {
19560   switch (MI->getOpcode()) {
19561   default: llvm_unreachable("Unexpected instr type to insert");
19562   case X86::TAILJMPd64:
19563   case X86::TAILJMPr64:
19564   case X86::TAILJMPm64:
19565   case X86::TAILJMPd64_REX:
19566   case X86::TAILJMPr64_REX:
19567   case X86::TAILJMPm64_REX:
19568     llvm_unreachable("TAILJMP64 would not be touched here.");
19569   case X86::TCRETURNdi64:
19570   case X86::TCRETURNri64:
19571   case X86::TCRETURNmi64:
19572     return BB;
19573   case X86::WIN_ALLOCA:
19574     return EmitLoweredWinAlloca(MI, BB);
19575   case X86::SEG_ALLOCA_32:
19576   case X86::SEG_ALLOCA_64:
19577     return EmitLoweredSegAlloca(MI, BB);
19578   case X86::TLSCall_32:
19579   case X86::TLSCall_64:
19580     return EmitLoweredTLSCall(MI, BB);
19581   case X86::CMOV_GR8:
19582   case X86::CMOV_FR32:
19583   case X86::CMOV_FR64:
19584   case X86::CMOV_V4F32:
19585   case X86::CMOV_V2F64:
19586   case X86::CMOV_V2I64:
19587   case X86::CMOV_V8F32:
19588   case X86::CMOV_V4F64:
19589   case X86::CMOV_V4I64:
19590   case X86::CMOV_V16F32:
19591   case X86::CMOV_V8F64:
19592   case X86::CMOV_V8I64:
19593   case X86::CMOV_GR16:
19594   case X86::CMOV_GR32:
19595   case X86::CMOV_RFP32:
19596   case X86::CMOV_RFP64:
19597   case X86::CMOV_RFP80:
19598   case X86::CMOV_V8I1:
19599   case X86::CMOV_V16I1:
19600   case X86::CMOV_V32I1:
19601   case X86::CMOV_V64I1:
19602     return EmitLoweredSelect(MI, BB);
19603
19604   case X86::FP32_TO_INT16_IN_MEM:
19605   case X86::FP32_TO_INT32_IN_MEM:
19606   case X86::FP32_TO_INT64_IN_MEM:
19607   case X86::FP64_TO_INT16_IN_MEM:
19608   case X86::FP64_TO_INT32_IN_MEM:
19609   case X86::FP64_TO_INT64_IN_MEM:
19610   case X86::FP80_TO_INT16_IN_MEM:
19611   case X86::FP80_TO_INT32_IN_MEM:
19612   case X86::FP80_TO_INT64_IN_MEM: {
19613     MachineFunction *F = BB->getParent();
19614     const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19615     DebugLoc DL = MI->getDebugLoc();
19616
19617     // Change the floating point control register to use "round towards zero"
19618     // mode when truncating to an integer value.
19619     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
19620     addFrameReference(BuildMI(*BB, MI, DL,
19621                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
19622
19623     // Load the old value of the high byte of the control word...
19624     unsigned OldCW =
19625       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
19626     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
19627                       CWFrameIdx);
19628
19629     // Set the high part to be round to zero...
19630     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
19631       .addImm(0xC7F);
19632
19633     // Reload the modified control word now...
19634     addFrameReference(BuildMI(*BB, MI, DL,
19635                               TII->get(X86::FLDCW16m)), CWFrameIdx);
19636
19637     // Restore the memory image of control word to original value
19638     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
19639       .addReg(OldCW);
19640
19641     // Get the X86 opcode to use.
19642     unsigned Opc;
19643     switch (MI->getOpcode()) {
19644     default: llvm_unreachable("illegal opcode!");
19645     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
19646     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
19647     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
19648     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
19649     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
19650     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
19651     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
19652     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
19653     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
19654     }
19655
19656     X86AddressMode AM;
19657     MachineOperand &Op = MI->getOperand(0);
19658     if (Op.isReg()) {
19659       AM.BaseType = X86AddressMode::RegBase;
19660       AM.Base.Reg = Op.getReg();
19661     } else {
19662       AM.BaseType = X86AddressMode::FrameIndexBase;
19663       AM.Base.FrameIndex = Op.getIndex();
19664     }
19665     Op = MI->getOperand(1);
19666     if (Op.isImm())
19667       AM.Scale = Op.getImm();
19668     Op = MI->getOperand(2);
19669     if (Op.isImm())
19670       AM.IndexReg = Op.getImm();
19671     Op = MI->getOperand(3);
19672     if (Op.isGlobal()) {
19673       AM.GV = Op.getGlobal();
19674     } else {
19675       AM.Disp = Op.getImm();
19676     }
19677     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
19678                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
19679
19680     // Reload the original control word now.
19681     addFrameReference(BuildMI(*BB, MI, DL,
19682                               TII->get(X86::FLDCW16m)), CWFrameIdx);
19683
19684     MI->eraseFromParent();   // The pseudo instruction is gone now.
19685     return BB;
19686   }
19687     // String/text processing lowering.
19688   case X86::PCMPISTRM128REG:
19689   case X86::VPCMPISTRM128REG:
19690   case X86::PCMPISTRM128MEM:
19691   case X86::VPCMPISTRM128MEM:
19692   case X86::PCMPESTRM128REG:
19693   case X86::VPCMPESTRM128REG:
19694   case X86::PCMPESTRM128MEM:
19695   case X86::VPCMPESTRM128MEM:
19696     assert(Subtarget->hasSSE42() &&
19697            "Target must have SSE4.2 or AVX features enabled");
19698     return EmitPCMPSTRM(MI, BB, Subtarget->getInstrInfo());
19699
19700   // String/text processing lowering.
19701   case X86::PCMPISTRIREG:
19702   case X86::VPCMPISTRIREG:
19703   case X86::PCMPISTRIMEM:
19704   case X86::VPCMPISTRIMEM:
19705   case X86::PCMPESTRIREG:
19706   case X86::VPCMPESTRIREG:
19707   case X86::PCMPESTRIMEM:
19708   case X86::VPCMPESTRIMEM:
19709     assert(Subtarget->hasSSE42() &&
19710            "Target must have SSE4.2 or AVX features enabled");
19711     return EmitPCMPSTRI(MI, BB, Subtarget->getInstrInfo());
19712
19713   // Thread synchronization.
19714   case X86::MONITOR:
19715     return EmitMonitor(MI, BB, Subtarget);
19716
19717   // xbegin
19718   case X86::XBEGIN:
19719     return EmitXBegin(MI, BB, Subtarget->getInstrInfo());
19720
19721   case X86::VASTART_SAVE_XMM_REGS:
19722     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
19723
19724   case X86::VAARG_64:
19725     return EmitVAARG64WithCustomInserter(MI, BB);
19726
19727   case X86::EH_SjLj_SetJmp32:
19728   case X86::EH_SjLj_SetJmp64:
19729     return emitEHSjLjSetJmp(MI, BB);
19730
19731   case X86::EH_SjLj_LongJmp32:
19732   case X86::EH_SjLj_LongJmp64:
19733     return emitEHSjLjLongJmp(MI, BB);
19734
19735   case TargetOpcode::STATEPOINT:
19736     // As an implementation detail, STATEPOINT shares the STACKMAP format at
19737     // this point in the process.  We diverge later.
19738     return emitPatchPoint(MI, BB);
19739
19740   case TargetOpcode::STACKMAP:
19741   case TargetOpcode::PATCHPOINT:
19742     return emitPatchPoint(MI, BB);
19743
19744   case X86::VFMADDPDr213r:
19745   case X86::VFMADDPSr213r:
19746   case X86::VFMADDSDr213r:
19747   case X86::VFMADDSSr213r:
19748   case X86::VFMSUBPDr213r:
19749   case X86::VFMSUBPSr213r:
19750   case X86::VFMSUBSDr213r:
19751   case X86::VFMSUBSSr213r:
19752   case X86::VFNMADDPDr213r:
19753   case X86::VFNMADDPSr213r:
19754   case X86::VFNMADDSDr213r:
19755   case X86::VFNMADDSSr213r:
19756   case X86::VFNMSUBPDr213r:
19757   case X86::VFNMSUBPSr213r:
19758   case X86::VFNMSUBSDr213r:
19759   case X86::VFNMSUBSSr213r:
19760   case X86::VFMADDSUBPDr213r:
19761   case X86::VFMADDSUBPSr213r:
19762   case X86::VFMSUBADDPDr213r:
19763   case X86::VFMSUBADDPSr213r:
19764   case X86::VFMADDPDr213rY:
19765   case X86::VFMADDPSr213rY:
19766   case X86::VFMSUBPDr213rY:
19767   case X86::VFMSUBPSr213rY:
19768   case X86::VFNMADDPDr213rY:
19769   case X86::VFNMADDPSr213rY:
19770   case X86::VFNMSUBPDr213rY:
19771   case X86::VFNMSUBPSr213rY:
19772   case X86::VFMADDSUBPDr213rY:
19773   case X86::VFMADDSUBPSr213rY:
19774   case X86::VFMSUBADDPDr213rY:
19775   case X86::VFMSUBADDPSr213rY:
19776     return emitFMA3Instr(MI, BB);
19777   }
19778 }
19779
19780 //===----------------------------------------------------------------------===//
19781 //                           X86 Optimization Hooks
19782 //===----------------------------------------------------------------------===//
19783
19784 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
19785                                                       APInt &KnownZero,
19786                                                       APInt &KnownOne,
19787                                                       const SelectionDAG &DAG,
19788                                                       unsigned Depth) const {
19789   unsigned BitWidth = KnownZero.getBitWidth();
19790   unsigned Opc = Op.getOpcode();
19791   assert((Opc >= ISD::BUILTIN_OP_END ||
19792           Opc == ISD::INTRINSIC_WO_CHAIN ||
19793           Opc == ISD::INTRINSIC_W_CHAIN ||
19794           Opc == ISD::INTRINSIC_VOID) &&
19795          "Should use MaskedValueIsZero if you don't know whether Op"
19796          " is a target node!");
19797
19798   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
19799   switch (Opc) {
19800   default: break;
19801   case X86ISD::ADD:
19802   case X86ISD::SUB:
19803   case X86ISD::ADC:
19804   case X86ISD::SBB:
19805   case X86ISD::SMUL:
19806   case X86ISD::UMUL:
19807   case X86ISD::INC:
19808   case X86ISD::DEC:
19809   case X86ISD::OR:
19810   case X86ISD::XOR:
19811   case X86ISD::AND:
19812     // These nodes' second result is a boolean.
19813     if (Op.getResNo() == 0)
19814       break;
19815     // Fallthrough
19816   case X86ISD::SETCC:
19817     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
19818     break;
19819   case ISD::INTRINSIC_WO_CHAIN: {
19820     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
19821     unsigned NumLoBits = 0;
19822     switch (IntId) {
19823     default: break;
19824     case Intrinsic::x86_sse_movmsk_ps:
19825     case Intrinsic::x86_avx_movmsk_ps_256:
19826     case Intrinsic::x86_sse2_movmsk_pd:
19827     case Intrinsic::x86_avx_movmsk_pd_256:
19828     case Intrinsic::x86_mmx_pmovmskb:
19829     case Intrinsic::x86_sse2_pmovmskb_128:
19830     case Intrinsic::x86_avx2_pmovmskb: {
19831       // High bits of movmskp{s|d}, pmovmskb are known zero.
19832       switch (IntId) {
19833         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
19834         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
19835         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
19836         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
19837         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
19838         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
19839         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
19840         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
19841       }
19842       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
19843       break;
19844     }
19845     }
19846     break;
19847   }
19848   }
19849 }
19850
19851 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
19852   SDValue Op,
19853   const SelectionDAG &,
19854   unsigned Depth) const {
19855   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
19856   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
19857     return Op.getValueType().getScalarType().getSizeInBits();
19858
19859   // Fallback case.
19860   return 1;
19861 }
19862
19863 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
19864 /// node is a GlobalAddress + offset.
19865 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
19866                                        const GlobalValue* &GA,
19867                                        int64_t &Offset) const {
19868   if (N->getOpcode() == X86ISD::Wrapper) {
19869     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
19870       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
19871       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
19872       return true;
19873     }
19874   }
19875   return TargetLowering::isGAPlusOffset(N, GA, Offset);
19876 }
19877
19878 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
19879 /// same as extracting the high 128-bit part of 256-bit vector and then
19880 /// inserting the result into the low part of a new 256-bit vector
19881 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
19882   EVT VT = SVOp->getValueType(0);
19883   unsigned NumElems = VT.getVectorNumElements();
19884
19885   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
19886   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
19887     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
19888         SVOp->getMaskElt(j) >= 0)
19889       return false;
19890
19891   return true;
19892 }
19893
19894 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
19895 /// same as extracting the low 128-bit part of 256-bit vector and then
19896 /// inserting the result into the high part of a new 256-bit vector
19897 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
19898   EVT VT = SVOp->getValueType(0);
19899   unsigned NumElems = VT.getVectorNumElements();
19900
19901   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
19902   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
19903     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
19904         SVOp->getMaskElt(j) >= 0)
19905       return false;
19906
19907   return true;
19908 }
19909
19910 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
19911 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
19912                                         TargetLowering::DAGCombinerInfo &DCI,
19913                                         const X86Subtarget* Subtarget) {
19914   SDLoc dl(N);
19915   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
19916   SDValue V1 = SVOp->getOperand(0);
19917   SDValue V2 = SVOp->getOperand(1);
19918   EVT VT = SVOp->getValueType(0);
19919   unsigned NumElems = VT.getVectorNumElements();
19920
19921   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
19922       V2.getOpcode() == ISD::CONCAT_VECTORS) {
19923     //
19924     //                   0,0,0,...
19925     //                      |
19926     //    V      UNDEF    BUILD_VECTOR    UNDEF
19927     //     \      /           \           /
19928     //  CONCAT_VECTOR         CONCAT_VECTOR
19929     //         \                  /
19930     //          \                /
19931     //          RESULT: V + zero extended
19932     //
19933     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
19934         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
19935         V1.getOperand(1).getOpcode() != ISD::UNDEF)
19936       return SDValue();
19937
19938     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
19939       return SDValue();
19940
19941     // To match the shuffle mask, the first half of the mask should
19942     // be exactly the first vector, and all the rest a splat with the
19943     // first element of the second one.
19944     for (unsigned i = 0; i != NumElems/2; ++i)
19945       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
19946           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
19947         return SDValue();
19948
19949     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
19950     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
19951       if (Ld->hasNUsesOfValue(1, 0)) {
19952         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
19953         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
19954         SDValue ResNode =
19955           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
19956                                   Ld->getMemoryVT(),
19957                                   Ld->getPointerInfo(),
19958                                   Ld->getAlignment(),
19959                                   false/*isVolatile*/, true/*ReadMem*/,
19960                                   false/*WriteMem*/);
19961
19962         // Make sure the newly-created LOAD is in the same position as Ld in
19963         // terms of dependency. We create a TokenFactor for Ld and ResNode,
19964         // and update uses of Ld's output chain to use the TokenFactor.
19965         if (Ld->hasAnyUseOfValue(1)) {
19966           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
19967                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
19968           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
19969           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
19970                                  SDValue(ResNode.getNode(), 1));
19971         }
19972
19973         return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
19974       }
19975     }
19976
19977     // Emit a zeroed vector and insert the desired subvector on its
19978     // first half.
19979     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
19980     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
19981     return DCI.CombineTo(N, InsV);
19982   }
19983
19984   //===--------------------------------------------------------------------===//
19985   // Combine some shuffles into subvector extracts and inserts:
19986   //
19987
19988   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
19989   if (isShuffleHigh128VectorInsertLow(SVOp)) {
19990     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
19991     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
19992     return DCI.CombineTo(N, InsV);
19993   }
19994
19995   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
19996   if (isShuffleLow128VectorInsertHigh(SVOp)) {
19997     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
19998     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
19999     return DCI.CombineTo(N, InsV);
20000   }
20001
20002   return SDValue();
20003 }
20004
20005 /// \brief Combine an arbitrary chain of shuffles into a single instruction if
20006 /// possible.
20007 ///
20008 /// This is the leaf of the recursive combinine below. When we have found some
20009 /// chain of single-use x86 shuffle instructions and accumulated the combined
20010 /// shuffle mask represented by them, this will try to pattern match that mask
20011 /// into either a single instruction if there is a special purpose instruction
20012 /// for this operation, or into a PSHUFB instruction which is a fully general
20013 /// instruction but should only be used to replace chains over a certain depth.
20014 static bool combineX86ShuffleChain(SDValue Op, SDValue Root, ArrayRef<int> Mask,
20015                                    int Depth, bool HasPSHUFB, SelectionDAG &DAG,
20016                                    TargetLowering::DAGCombinerInfo &DCI,
20017                                    const X86Subtarget *Subtarget) {
20018   assert(!Mask.empty() && "Cannot combine an empty shuffle mask!");
20019
20020   // Find the operand that enters the chain. Note that multiple uses are OK
20021   // here, we're not going to remove the operand we find.
20022   SDValue Input = Op.getOperand(0);
20023   while (Input.getOpcode() == ISD::BITCAST)
20024     Input = Input.getOperand(0);
20025
20026   MVT VT = Input.getSimpleValueType();
20027   MVT RootVT = Root.getSimpleValueType();
20028   SDLoc DL(Root);
20029
20030   // Just remove no-op shuffle masks.
20031   if (Mask.size() == 1) {
20032     DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Input),
20033                   /*AddTo*/ true);
20034     return true;
20035   }
20036
20037   // Use the float domain if the operand type is a floating point type.
20038   bool FloatDomain = VT.isFloatingPoint();
20039
20040   // For floating point shuffles, we don't have free copies in the shuffle
20041   // instructions or the ability to load as part of the instruction, so
20042   // canonicalize their shuffles to UNPCK or MOV variants.
20043   //
20044   // Note that even with AVX we prefer the PSHUFD form of shuffle for integer
20045   // vectors because it can have a load folded into it that UNPCK cannot. This
20046   // doesn't preclude something switching to the shorter encoding post-RA.
20047   //
20048   // FIXME: Should teach these routines about AVX vector widths.
20049   if (FloatDomain && VT.getSizeInBits() == 128) {
20050     if (Mask.equals({0, 0}) || Mask.equals({1, 1})) {
20051       bool Lo = Mask.equals({0, 0});
20052       unsigned Shuffle;
20053       MVT ShuffleVT;
20054       // Check if we have SSE3 which will let us use MOVDDUP. That instruction
20055       // is no slower than UNPCKLPD but has the option to fold the input operand
20056       // into even an unaligned memory load.
20057       if (Lo && Subtarget->hasSSE3()) {
20058         Shuffle = X86ISD::MOVDDUP;
20059         ShuffleVT = MVT::v2f64;
20060       } else {
20061         // We have MOVLHPS and MOVHLPS throughout SSE and they encode smaller
20062         // than the UNPCK variants.
20063         Shuffle = Lo ? X86ISD::MOVLHPS : X86ISD::MOVHLPS;
20064         ShuffleVT = MVT::v4f32;
20065       }
20066       if (Depth == 1 && Root->getOpcode() == Shuffle)
20067         return false; // Nothing to do!
20068       Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
20069       DCI.AddToWorklist(Op.getNode());
20070       if (Shuffle == X86ISD::MOVDDUP)
20071         Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
20072       else
20073         Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
20074       DCI.AddToWorklist(Op.getNode());
20075       DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
20076                     /*AddTo*/ true);
20077       return true;
20078     }
20079     if (Subtarget->hasSSE3() &&
20080         (Mask.equals({0, 0, 2, 2}) || Mask.equals({1, 1, 3, 3}))) {
20081       bool Lo = Mask.equals({0, 0, 2, 2});
20082       unsigned Shuffle = Lo ? X86ISD::MOVSLDUP : X86ISD::MOVSHDUP;
20083       MVT ShuffleVT = MVT::v4f32;
20084       if (Depth == 1 && Root->getOpcode() == Shuffle)
20085         return false; // Nothing to do!
20086       Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
20087       DCI.AddToWorklist(Op.getNode());
20088       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
20089       DCI.AddToWorklist(Op.getNode());
20090       DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
20091                     /*AddTo*/ true);
20092       return true;
20093     }
20094     if (Mask.equals({0, 0, 1, 1}) || Mask.equals({2, 2, 3, 3})) {
20095       bool Lo = Mask.equals({0, 0, 1, 1});
20096       unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
20097       MVT ShuffleVT = MVT::v4f32;
20098       if (Depth == 1 && Root->getOpcode() == Shuffle)
20099         return false; // Nothing to do!
20100       Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
20101       DCI.AddToWorklist(Op.getNode());
20102       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
20103       DCI.AddToWorklist(Op.getNode());
20104       DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
20105                     /*AddTo*/ true);
20106       return true;
20107     }
20108   }
20109
20110   // We always canonicalize the 8 x i16 and 16 x i8 shuffles into their UNPCK
20111   // variants as none of these have single-instruction variants that are
20112   // superior to the UNPCK formulation.
20113   if (!FloatDomain && VT.getSizeInBits() == 128 &&
20114       (Mask.equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
20115        Mask.equals({4, 4, 5, 5, 6, 6, 7, 7}) ||
20116        Mask.equals({0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7}) ||
20117        Mask.equals(
20118            {8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15, 15}))) {
20119     bool Lo = Mask[0] == 0;
20120     unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
20121     if (Depth == 1 && Root->getOpcode() == Shuffle)
20122       return false; // Nothing to do!
20123     MVT ShuffleVT;
20124     switch (Mask.size()) {
20125     case 8:
20126       ShuffleVT = MVT::v8i16;
20127       break;
20128     case 16:
20129       ShuffleVT = MVT::v16i8;
20130       break;
20131     default:
20132       llvm_unreachable("Impossible mask size!");
20133     };
20134     Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
20135     DCI.AddToWorklist(Op.getNode());
20136     Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
20137     DCI.AddToWorklist(Op.getNode());
20138     DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
20139                   /*AddTo*/ true);
20140     return true;
20141   }
20142
20143   // Don't try to re-form single instruction chains under any circumstances now
20144   // that we've done encoding canonicalization for them.
20145   if (Depth < 2)
20146     return false;
20147
20148   // If we have 3 or more shuffle instructions or a chain involving PSHUFB, we
20149   // can replace them with a single PSHUFB instruction profitably. Intel's
20150   // manuals suggest only using PSHUFB if doing so replacing 5 instructions, but
20151   // in practice PSHUFB tends to be *very* fast so we're more aggressive.
20152   if ((Depth >= 3 || HasPSHUFB) && Subtarget->hasSSSE3()) {
20153     SmallVector<SDValue, 16> PSHUFBMask;
20154     int NumBytes = VT.getSizeInBits() / 8;
20155     int Ratio = NumBytes / Mask.size();
20156     for (int i = 0; i < NumBytes; ++i) {
20157       if (Mask[i / Ratio] == SM_SentinelUndef) {
20158         PSHUFBMask.push_back(DAG.getUNDEF(MVT::i8));
20159         continue;
20160       }
20161       int M = Mask[i / Ratio] != SM_SentinelZero
20162                   ? Ratio * Mask[i / Ratio] + i % Ratio
20163                   : 255;
20164       PSHUFBMask.push_back(DAG.getConstant(M, DL, MVT::i8));
20165     }
20166     MVT ByteVT = MVT::getVectorVT(MVT::i8, NumBytes);
20167     Op = DAG.getNode(ISD::BITCAST, DL, ByteVT, Input);
20168     DCI.AddToWorklist(Op.getNode());
20169     SDValue PSHUFBMaskOp =
20170         DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVT, PSHUFBMask);
20171     DCI.AddToWorklist(PSHUFBMaskOp.getNode());
20172     Op = DAG.getNode(X86ISD::PSHUFB, DL, ByteVT, Op, PSHUFBMaskOp);
20173     DCI.AddToWorklist(Op.getNode());
20174     DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
20175                   /*AddTo*/ true);
20176     return true;
20177   }
20178
20179   // Failed to find any combines.
20180   return false;
20181 }
20182
20183 /// \brief Fully generic combining of x86 shuffle instructions.
20184 ///
20185 /// This should be the last combine run over the x86 shuffle instructions. Once
20186 /// they have been fully optimized, this will recursively consider all chains
20187 /// of single-use shuffle instructions, build a generic model of the cumulative
20188 /// shuffle operation, and check for simpler instructions which implement this
20189 /// operation. We use this primarily for two purposes:
20190 ///
20191 /// 1) Collapse generic shuffles to specialized single instructions when
20192 ///    equivalent. In most cases, this is just an encoding size win, but
20193 ///    sometimes we will collapse multiple generic shuffles into a single
20194 ///    special-purpose shuffle.
20195 /// 2) Look for sequences of shuffle instructions with 3 or more total
20196 ///    instructions, and replace them with the slightly more expensive SSSE3
20197 ///    PSHUFB instruction if available. We do this as the last combining step
20198 ///    to ensure we avoid using PSHUFB if we can implement the shuffle with
20199 ///    a suitable short sequence of other instructions. The PHUFB will either
20200 ///    use a register or have to read from memory and so is slightly (but only
20201 ///    slightly) more expensive than the other shuffle instructions.
20202 ///
20203 /// Because this is inherently a quadratic operation (for each shuffle in
20204 /// a chain, we recurse up the chain), the depth is limited to 8 instructions.
20205 /// This should never be an issue in practice as the shuffle lowering doesn't
20206 /// produce sequences of more than 8 instructions.
20207 ///
20208 /// FIXME: We will currently miss some cases where the redundant shuffling
20209 /// would simplify under the threshold for PSHUFB formation because of
20210 /// combine-ordering. To fix this, we should do the redundant instruction
20211 /// combining in this recursive walk.
20212 static bool combineX86ShufflesRecursively(SDValue Op, SDValue Root,
20213                                           ArrayRef<int> RootMask,
20214                                           int Depth, bool HasPSHUFB,
20215                                           SelectionDAG &DAG,
20216                                           TargetLowering::DAGCombinerInfo &DCI,
20217                                           const X86Subtarget *Subtarget) {
20218   // Bound the depth of our recursive combine because this is ultimately
20219   // quadratic in nature.
20220   if (Depth > 8)
20221     return false;
20222
20223   // Directly rip through bitcasts to find the underlying operand.
20224   while (Op.getOpcode() == ISD::BITCAST && Op.getOperand(0).hasOneUse())
20225     Op = Op.getOperand(0);
20226
20227   MVT VT = Op.getSimpleValueType();
20228   if (!VT.isVector())
20229     return false; // Bail if we hit a non-vector.
20230
20231   assert(Root.getSimpleValueType().isVector() &&
20232          "Shuffles operate on vector types!");
20233   assert(VT.getSizeInBits() == Root.getSimpleValueType().getSizeInBits() &&
20234          "Can only combine shuffles of the same vector register size.");
20235
20236   if (!isTargetShuffle(Op.getOpcode()))
20237     return false;
20238   SmallVector<int, 16> OpMask;
20239   bool IsUnary;
20240   bool HaveMask = getTargetShuffleMask(Op.getNode(), VT, OpMask, IsUnary);
20241   // We only can combine unary shuffles which we can decode the mask for.
20242   if (!HaveMask || !IsUnary)
20243     return false;
20244
20245   assert(VT.getVectorNumElements() == OpMask.size() &&
20246          "Different mask size from vector size!");
20247   assert(((RootMask.size() > OpMask.size() &&
20248            RootMask.size() % OpMask.size() == 0) ||
20249           (OpMask.size() > RootMask.size() &&
20250            OpMask.size() % RootMask.size() == 0) ||
20251           OpMask.size() == RootMask.size()) &&
20252          "The smaller number of elements must divide the larger.");
20253   int RootRatio = std::max<int>(1, OpMask.size() / RootMask.size());
20254   int OpRatio = std::max<int>(1, RootMask.size() / OpMask.size());
20255   assert(((RootRatio == 1 && OpRatio == 1) ||
20256           (RootRatio == 1) != (OpRatio == 1)) &&
20257          "Must not have a ratio for both incoming and op masks!");
20258
20259   SmallVector<int, 16> Mask;
20260   Mask.reserve(std::max(OpMask.size(), RootMask.size()));
20261
20262   // Merge this shuffle operation's mask into our accumulated mask. Note that
20263   // this shuffle's mask will be the first applied to the input, followed by the
20264   // root mask to get us all the way to the root value arrangement. The reason
20265   // for this order is that we are recursing up the operation chain.
20266   for (int i = 0, e = std::max(OpMask.size(), RootMask.size()); i < e; ++i) {
20267     int RootIdx = i / RootRatio;
20268     if (RootMask[RootIdx] < 0) {
20269       // This is a zero or undef lane, we're done.
20270       Mask.push_back(RootMask[RootIdx]);
20271       continue;
20272     }
20273
20274     int RootMaskedIdx = RootMask[RootIdx] * RootRatio + i % RootRatio;
20275     int OpIdx = RootMaskedIdx / OpRatio;
20276     if (OpMask[OpIdx] < 0) {
20277       // The incoming lanes are zero or undef, it doesn't matter which ones we
20278       // are using.
20279       Mask.push_back(OpMask[OpIdx]);
20280       continue;
20281     }
20282
20283     // Ok, we have non-zero lanes, map them through.
20284     Mask.push_back(OpMask[OpIdx] * OpRatio +
20285                    RootMaskedIdx % OpRatio);
20286   }
20287
20288   // See if we can recurse into the operand to combine more things.
20289   switch (Op.getOpcode()) {
20290     case X86ISD::PSHUFB:
20291       HasPSHUFB = true;
20292     case X86ISD::PSHUFD:
20293     case X86ISD::PSHUFHW:
20294     case X86ISD::PSHUFLW:
20295       if (Op.getOperand(0).hasOneUse() &&
20296           combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
20297                                         HasPSHUFB, DAG, DCI, Subtarget))
20298         return true;
20299       break;
20300
20301     case X86ISD::UNPCKL:
20302     case X86ISD::UNPCKH:
20303       assert(Op.getOperand(0) == Op.getOperand(1) && "We only combine unary shuffles!");
20304       // We can't check for single use, we have to check that this shuffle is the only user.
20305       if (Op->isOnlyUserOf(Op.getOperand(0).getNode()) &&
20306           combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
20307                                         HasPSHUFB, DAG, DCI, Subtarget))
20308           return true;
20309       break;
20310   }
20311
20312   // Minor canonicalization of the accumulated shuffle mask to make it easier
20313   // to match below. All this does is detect masks with squential pairs of
20314   // elements, and shrink them to the half-width mask. It does this in a loop
20315   // so it will reduce the size of the mask to the minimal width mask which
20316   // performs an equivalent shuffle.
20317   SmallVector<int, 16> WidenedMask;
20318   while (Mask.size() > 1 && canWidenShuffleElements(Mask, WidenedMask)) {
20319     Mask = std::move(WidenedMask);
20320     WidenedMask.clear();
20321   }
20322
20323   return combineX86ShuffleChain(Op, Root, Mask, Depth, HasPSHUFB, DAG, DCI,
20324                                 Subtarget);
20325 }
20326
20327 /// \brief Get the PSHUF-style mask from PSHUF node.
20328 ///
20329 /// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
20330 /// PSHUF-style masks that can be reused with such instructions.
20331 static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
20332   MVT VT = N.getSimpleValueType();
20333   SmallVector<int, 4> Mask;
20334   bool IsUnary;
20335   bool HaveMask = getTargetShuffleMask(N.getNode(), VT, Mask, IsUnary);
20336   (void)HaveMask;
20337   assert(HaveMask);
20338
20339   // If we have more than 128-bits, only the low 128-bits of shuffle mask
20340   // matter. Check that the upper masks are repeats and remove them.
20341   if (VT.getSizeInBits() > 128) {
20342     int LaneElts = 128 / VT.getScalarSizeInBits();
20343 #ifndef NDEBUG
20344     for (int i = 1, NumLanes = VT.getSizeInBits() / 128; i < NumLanes; ++i)
20345       for (int j = 0; j < LaneElts; ++j)
20346         assert(Mask[j] == Mask[i * LaneElts + j] - LaneElts &&
20347                "Mask doesn't repeat in high 128-bit lanes!");
20348 #endif
20349     Mask.resize(LaneElts);
20350   }
20351
20352   switch (N.getOpcode()) {
20353   case X86ISD::PSHUFD:
20354     return Mask;
20355   case X86ISD::PSHUFLW:
20356     Mask.resize(4);
20357     return Mask;
20358   case X86ISD::PSHUFHW:
20359     Mask.erase(Mask.begin(), Mask.begin() + 4);
20360     for (int &M : Mask)
20361       M -= 4;
20362     return Mask;
20363   default:
20364     llvm_unreachable("No valid shuffle instruction found!");
20365   }
20366 }
20367
20368 /// \brief Search for a combinable shuffle across a chain ending in pshufd.
20369 ///
20370 /// We walk up the chain and look for a combinable shuffle, skipping over
20371 /// shuffles that we could hoist this shuffle's transformation past without
20372 /// altering anything.
20373 static SDValue
20374 combineRedundantDWordShuffle(SDValue N, MutableArrayRef<int> Mask,
20375                              SelectionDAG &DAG,
20376                              TargetLowering::DAGCombinerInfo &DCI) {
20377   assert(N.getOpcode() == X86ISD::PSHUFD &&
20378          "Called with something other than an x86 128-bit half shuffle!");
20379   SDLoc DL(N);
20380
20381   // Walk up a single-use chain looking for a combinable shuffle. Keep a stack
20382   // of the shuffles in the chain so that we can form a fresh chain to replace
20383   // this one.
20384   SmallVector<SDValue, 8> Chain;
20385   SDValue V = N.getOperand(0);
20386   for (; V.hasOneUse(); V = V.getOperand(0)) {
20387     switch (V.getOpcode()) {
20388     default:
20389       return SDValue(); // Nothing combined!
20390
20391     case ISD::BITCAST:
20392       // Skip bitcasts as we always know the type for the target specific
20393       // instructions.
20394       continue;
20395
20396     case X86ISD::PSHUFD:
20397       // Found another dword shuffle.
20398       break;
20399
20400     case X86ISD::PSHUFLW:
20401       // Check that the low words (being shuffled) are the identity in the
20402       // dword shuffle, and the high words are self-contained.
20403       if (Mask[0] != 0 || Mask[1] != 1 ||
20404           !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
20405         return SDValue();
20406
20407       Chain.push_back(V);
20408       continue;
20409
20410     case X86ISD::PSHUFHW:
20411       // Check that the high words (being shuffled) are the identity in the
20412       // dword shuffle, and the low words are self-contained.
20413       if (Mask[2] != 2 || Mask[3] != 3 ||
20414           !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
20415         return SDValue();
20416
20417       Chain.push_back(V);
20418       continue;
20419
20420     case X86ISD::UNPCKL:
20421     case X86ISD::UNPCKH:
20422       // For either i8 -> i16 or i16 -> i32 unpacks, we can combine a dword
20423       // shuffle into a preceding word shuffle.
20424       if (V.getSimpleValueType().getScalarType() != MVT::i8 &&
20425           V.getSimpleValueType().getScalarType() != MVT::i16)
20426         return SDValue();
20427
20428       // Search for a half-shuffle which we can combine with.
20429       unsigned CombineOp =
20430           V.getOpcode() == X86ISD::UNPCKL ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
20431       if (V.getOperand(0) != V.getOperand(1) ||
20432           !V->isOnlyUserOf(V.getOperand(0).getNode()))
20433         return SDValue();
20434       Chain.push_back(V);
20435       V = V.getOperand(0);
20436       do {
20437         switch (V.getOpcode()) {
20438         default:
20439           return SDValue(); // Nothing to combine.
20440
20441         case X86ISD::PSHUFLW:
20442         case X86ISD::PSHUFHW:
20443           if (V.getOpcode() == CombineOp)
20444             break;
20445
20446           Chain.push_back(V);
20447
20448           // Fallthrough!
20449         case ISD::BITCAST:
20450           V = V.getOperand(0);
20451           continue;
20452         }
20453         break;
20454       } while (V.hasOneUse());
20455       break;
20456     }
20457     // Break out of the loop if we break out of the switch.
20458     break;
20459   }
20460
20461   if (!V.hasOneUse())
20462     // We fell out of the loop without finding a viable combining instruction.
20463     return SDValue();
20464
20465   // Merge this node's mask and our incoming mask.
20466   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
20467   for (int &M : Mask)
20468     M = VMask[M];
20469   V = DAG.getNode(V.getOpcode(), DL, V.getValueType(), V.getOperand(0),
20470                   getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
20471
20472   // Rebuild the chain around this new shuffle.
20473   while (!Chain.empty()) {
20474     SDValue W = Chain.pop_back_val();
20475
20476     if (V.getValueType() != W.getOperand(0).getValueType())
20477       V = DAG.getNode(ISD::BITCAST, DL, W.getOperand(0).getValueType(), V);
20478
20479     switch (W.getOpcode()) {
20480     default:
20481       llvm_unreachable("Only PSHUF and UNPCK instructions get here!");
20482
20483     case X86ISD::UNPCKL:
20484     case X86ISD::UNPCKH:
20485       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, V);
20486       break;
20487
20488     case X86ISD::PSHUFD:
20489     case X86ISD::PSHUFLW:
20490     case X86ISD::PSHUFHW:
20491       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, W.getOperand(1));
20492       break;
20493     }
20494   }
20495   if (V.getValueType() != N.getValueType())
20496     V = DAG.getNode(ISD::BITCAST, DL, N.getValueType(), V);
20497
20498   // Return the new chain to replace N.
20499   return V;
20500 }
20501
20502 /// \brief Search for a combinable shuffle across a chain ending in pshuflw or pshufhw.
20503 ///
20504 /// We walk up the chain, skipping shuffles of the other half and looking
20505 /// through shuffles which switch halves trying to find a shuffle of the same
20506 /// pair of dwords.
20507 static bool combineRedundantHalfShuffle(SDValue N, MutableArrayRef<int> Mask,
20508                                         SelectionDAG &DAG,
20509                                         TargetLowering::DAGCombinerInfo &DCI) {
20510   assert(
20511       (N.getOpcode() == X86ISD::PSHUFLW || N.getOpcode() == X86ISD::PSHUFHW) &&
20512       "Called with something other than an x86 128-bit half shuffle!");
20513   SDLoc DL(N);
20514   unsigned CombineOpcode = N.getOpcode();
20515
20516   // Walk up a single-use chain looking for a combinable shuffle.
20517   SDValue V = N.getOperand(0);
20518   for (; V.hasOneUse(); V = V.getOperand(0)) {
20519     switch (V.getOpcode()) {
20520     default:
20521       return false; // Nothing combined!
20522
20523     case ISD::BITCAST:
20524       // Skip bitcasts as we always know the type for the target specific
20525       // instructions.
20526       continue;
20527
20528     case X86ISD::PSHUFLW:
20529     case X86ISD::PSHUFHW:
20530       if (V.getOpcode() == CombineOpcode)
20531         break;
20532
20533       // Other-half shuffles are no-ops.
20534       continue;
20535     }
20536     // Break out of the loop if we break out of the switch.
20537     break;
20538   }
20539
20540   if (!V.hasOneUse())
20541     // We fell out of the loop without finding a viable combining instruction.
20542     return false;
20543
20544   // Combine away the bottom node as its shuffle will be accumulated into
20545   // a preceding shuffle.
20546   DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
20547
20548   // Record the old value.
20549   SDValue Old = V;
20550
20551   // Merge this node's mask and our incoming mask (adjusted to account for all
20552   // the pshufd instructions encountered).
20553   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
20554   for (int &M : Mask)
20555     M = VMask[M];
20556   V = DAG.getNode(V.getOpcode(), DL, MVT::v8i16, V.getOperand(0),
20557                   getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
20558
20559   // Check that the shuffles didn't cancel each other out. If not, we need to
20560   // combine to the new one.
20561   if (Old != V)
20562     // Replace the combinable shuffle with the combined one, updating all users
20563     // so that we re-evaluate the chain here.
20564     DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
20565
20566   return true;
20567 }
20568
20569 /// \brief Try to combine x86 target specific shuffles.
20570 static SDValue PerformTargetShuffleCombine(SDValue N, SelectionDAG &DAG,
20571                                            TargetLowering::DAGCombinerInfo &DCI,
20572                                            const X86Subtarget *Subtarget) {
20573   SDLoc DL(N);
20574   MVT VT = N.getSimpleValueType();
20575   SmallVector<int, 4> Mask;
20576
20577   switch (N.getOpcode()) {
20578   case X86ISD::PSHUFD:
20579   case X86ISD::PSHUFLW:
20580   case X86ISD::PSHUFHW:
20581     Mask = getPSHUFShuffleMask(N);
20582     assert(Mask.size() == 4);
20583     break;
20584   default:
20585     return SDValue();
20586   }
20587
20588   // Nuke no-op shuffles that show up after combining.
20589   if (isNoopShuffleMask(Mask))
20590     return DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
20591
20592   // Look for simplifications involving one or two shuffle instructions.
20593   SDValue V = N.getOperand(0);
20594   switch (N.getOpcode()) {
20595   default:
20596     break;
20597   case X86ISD::PSHUFLW:
20598   case X86ISD::PSHUFHW:
20599     assert(VT.getScalarType() == MVT::i16 && "Bad word shuffle type!");
20600
20601     if (combineRedundantHalfShuffle(N, Mask, DAG, DCI))
20602       return SDValue(); // We combined away this shuffle, so we're done.
20603
20604     // See if this reduces to a PSHUFD which is no more expensive and can
20605     // combine with more operations. Note that it has to at least flip the
20606     // dwords as otherwise it would have been removed as a no-op.
20607     if (makeArrayRef(Mask).equals({2, 3, 0, 1})) {
20608       int DMask[] = {0, 1, 2, 3};
20609       int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
20610       DMask[DOffset + 0] = DOffset + 1;
20611       DMask[DOffset + 1] = DOffset + 0;
20612       MVT DVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
20613       V = DAG.getNode(ISD::BITCAST, DL, DVT, V);
20614       DCI.AddToWorklist(V.getNode());
20615       V = DAG.getNode(X86ISD::PSHUFD, DL, DVT, V,
20616                       getV4X86ShuffleImm8ForMask(DMask, DL, DAG));
20617       DCI.AddToWorklist(V.getNode());
20618       return DAG.getNode(ISD::BITCAST, DL, VT, V);
20619     }
20620
20621     // Look for shuffle patterns which can be implemented as a single unpack.
20622     // FIXME: This doesn't handle the location of the PSHUFD generically, and
20623     // only works when we have a PSHUFD followed by two half-shuffles.
20624     if (Mask[0] == Mask[1] && Mask[2] == Mask[3] &&
20625         (V.getOpcode() == X86ISD::PSHUFLW ||
20626          V.getOpcode() == X86ISD::PSHUFHW) &&
20627         V.getOpcode() != N.getOpcode() &&
20628         V.hasOneUse()) {
20629       SDValue D = V.getOperand(0);
20630       while (D.getOpcode() == ISD::BITCAST && D.hasOneUse())
20631         D = D.getOperand(0);
20632       if (D.getOpcode() == X86ISD::PSHUFD && D.hasOneUse()) {
20633         SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
20634         SmallVector<int, 4> DMask = getPSHUFShuffleMask(D);
20635         int NOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
20636         int VOffset = V.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
20637         int WordMask[8];
20638         for (int i = 0; i < 4; ++i) {
20639           WordMask[i + NOffset] = Mask[i] + NOffset;
20640           WordMask[i + VOffset] = VMask[i] + VOffset;
20641         }
20642         // Map the word mask through the DWord mask.
20643         int MappedMask[8];
20644         for (int i = 0; i < 8; ++i)
20645           MappedMask[i] = 2 * DMask[WordMask[i] / 2] + WordMask[i] % 2;
20646         if (makeArrayRef(MappedMask).equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
20647             makeArrayRef(MappedMask).equals({4, 4, 5, 5, 6, 6, 7, 7})) {
20648           // We can replace all three shuffles with an unpack.
20649           V = DAG.getNode(ISD::BITCAST, DL, VT, D.getOperand(0));
20650           DCI.AddToWorklist(V.getNode());
20651           return DAG.getNode(MappedMask[0] == 0 ? X86ISD::UNPCKL
20652                                                 : X86ISD::UNPCKH,
20653                              DL, VT, V, V);
20654         }
20655       }
20656     }
20657
20658     break;
20659
20660   case X86ISD::PSHUFD:
20661     if (SDValue NewN = combineRedundantDWordShuffle(N, Mask, DAG, DCI))
20662       return NewN;
20663
20664     break;
20665   }
20666
20667   return SDValue();
20668 }
20669
20670 /// \brief Try to combine a shuffle into a target-specific add-sub node.
20671 ///
20672 /// We combine this directly on the abstract vector shuffle nodes so it is
20673 /// easier to generically match. We also insert dummy vector shuffle nodes for
20674 /// the operands which explicitly discard the lanes which are unused by this
20675 /// operation to try to flow through the rest of the combiner the fact that
20676 /// they're unused.
20677 static SDValue combineShuffleToAddSub(SDNode *N, SelectionDAG &DAG) {
20678   SDLoc DL(N);
20679   EVT VT = N->getValueType(0);
20680
20681   // We only handle target-independent shuffles.
20682   // FIXME: It would be easy and harmless to use the target shuffle mask
20683   // extraction tool to support more.
20684   if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
20685     return SDValue();
20686
20687   auto *SVN = cast<ShuffleVectorSDNode>(N);
20688   ArrayRef<int> Mask = SVN->getMask();
20689   SDValue V1 = N->getOperand(0);
20690   SDValue V2 = N->getOperand(1);
20691
20692   // We require the first shuffle operand to be the SUB node, and the second to
20693   // be the ADD node.
20694   // FIXME: We should support the commuted patterns.
20695   if (V1->getOpcode() != ISD::FSUB || V2->getOpcode() != ISD::FADD)
20696     return SDValue();
20697
20698   // If there are other uses of these operations we can't fold them.
20699   if (!V1->hasOneUse() || !V2->hasOneUse())
20700     return SDValue();
20701
20702   // Ensure that both operations have the same operands. Note that we can
20703   // commute the FADD operands.
20704   SDValue LHS = V1->getOperand(0), RHS = V1->getOperand(1);
20705   if ((V2->getOperand(0) != LHS || V2->getOperand(1) != RHS) &&
20706       (V2->getOperand(0) != RHS || V2->getOperand(1) != LHS))
20707     return SDValue();
20708
20709   // We're looking for blends between FADD and FSUB nodes. We insist on these
20710   // nodes being lined up in a specific expected pattern.
20711   if (!(isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
20712         isShuffleEquivalent(V1, V2, Mask, {0, 5, 2, 7}) ||
20713         isShuffleEquivalent(V1, V2, Mask, {0, 9, 2, 11, 4, 13, 6, 15})))
20714     return SDValue();
20715
20716   // Only specific types are legal at this point, assert so we notice if and
20717   // when these change.
20718   assert((VT == MVT::v4f32 || VT == MVT::v2f64 || VT == MVT::v8f32 ||
20719           VT == MVT::v4f64) &&
20720          "Unknown vector type encountered!");
20721
20722   return DAG.getNode(X86ISD::ADDSUB, DL, VT, LHS, RHS);
20723 }
20724
20725 /// PerformShuffleCombine - Performs several different shuffle combines.
20726 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
20727                                      TargetLowering::DAGCombinerInfo &DCI,
20728                                      const X86Subtarget *Subtarget) {
20729   SDLoc dl(N);
20730   SDValue N0 = N->getOperand(0);
20731   SDValue N1 = N->getOperand(1);
20732   EVT VT = N->getValueType(0);
20733
20734   // Don't create instructions with illegal types after legalize types has run.
20735   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20736   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
20737     return SDValue();
20738
20739   // If we have legalized the vector types, look for blends of FADD and FSUB
20740   // nodes that we can fuse into an ADDSUB node.
20741   if (TLI.isTypeLegal(VT) && Subtarget->hasSSE3())
20742     if (SDValue AddSub = combineShuffleToAddSub(N, DAG))
20743       return AddSub;
20744
20745   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
20746   if (Subtarget->hasFp256() && VT.is256BitVector() &&
20747       N->getOpcode() == ISD::VECTOR_SHUFFLE)
20748     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
20749
20750   // During Type Legalization, when promoting illegal vector types,
20751   // the backend might introduce new shuffle dag nodes and bitcasts.
20752   //
20753   // This code performs the following transformation:
20754   // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
20755   //       (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
20756   //
20757   // We do this only if both the bitcast and the BINOP dag nodes have
20758   // one use. Also, perform this transformation only if the new binary
20759   // operation is legal. This is to avoid introducing dag nodes that
20760   // potentially need to be further expanded (or custom lowered) into a
20761   // less optimal sequence of dag nodes.
20762   if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
20763       N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
20764       N0.getOpcode() == ISD::BITCAST) {
20765     SDValue BC0 = N0.getOperand(0);
20766     EVT SVT = BC0.getValueType();
20767     unsigned Opcode = BC0.getOpcode();
20768     unsigned NumElts = VT.getVectorNumElements();
20769
20770     if (BC0.hasOneUse() && SVT.isVector() &&
20771         SVT.getVectorNumElements() * 2 == NumElts &&
20772         TLI.isOperationLegal(Opcode, VT)) {
20773       bool CanFold = false;
20774       switch (Opcode) {
20775       default : break;
20776       case ISD::ADD :
20777       case ISD::FADD :
20778       case ISD::SUB :
20779       case ISD::FSUB :
20780       case ISD::MUL :
20781       case ISD::FMUL :
20782         CanFold = true;
20783       }
20784
20785       unsigned SVTNumElts = SVT.getVectorNumElements();
20786       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
20787       for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
20788         CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
20789       for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
20790         CanFold = SVOp->getMaskElt(i) < 0;
20791
20792       if (CanFold) {
20793         SDValue BC00 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(0));
20794         SDValue BC01 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(1));
20795         SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
20796         return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
20797       }
20798     }
20799   }
20800
20801   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
20802   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
20803   // consecutive, non-overlapping, and in the right order.
20804   SmallVector<SDValue, 16> Elts;
20805   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
20806     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
20807
20808   SDValue LD = EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true);
20809   if (LD.getNode())
20810     return LD;
20811
20812   if (isTargetShuffle(N->getOpcode())) {
20813     SDValue Shuffle =
20814         PerformTargetShuffleCombine(SDValue(N, 0), DAG, DCI, Subtarget);
20815     if (Shuffle.getNode())
20816       return Shuffle;
20817
20818     // Try recursively combining arbitrary sequences of x86 shuffle
20819     // instructions into higher-order shuffles. We do this after combining
20820     // specific PSHUF instruction sequences into their minimal form so that we
20821     // can evaluate how many specialized shuffle instructions are involved in
20822     // a particular chain.
20823     SmallVector<int, 1> NonceMask; // Just a placeholder.
20824     NonceMask.push_back(0);
20825     if (combineX86ShufflesRecursively(SDValue(N, 0), SDValue(N, 0), NonceMask,
20826                                       /*Depth*/ 1, /*HasPSHUFB*/ false, DAG,
20827                                       DCI, Subtarget))
20828       return SDValue(); // This routine will use CombineTo to replace N.
20829   }
20830
20831   return SDValue();
20832 }
20833
20834 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
20835 /// specific shuffle of a load can be folded into a single element load.
20836 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
20837 /// shuffles have been custom lowered so we need to handle those here.
20838 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
20839                                          TargetLowering::DAGCombinerInfo &DCI) {
20840   if (DCI.isBeforeLegalizeOps())
20841     return SDValue();
20842
20843   SDValue InVec = N->getOperand(0);
20844   SDValue EltNo = N->getOperand(1);
20845
20846   if (!isa<ConstantSDNode>(EltNo))
20847     return SDValue();
20848
20849   EVT OriginalVT = InVec.getValueType();
20850
20851   if (InVec.getOpcode() == ISD::BITCAST) {
20852     // Don't duplicate a load with other uses.
20853     if (!InVec.hasOneUse())
20854       return SDValue();
20855     EVT BCVT = InVec.getOperand(0).getValueType();
20856     if (!BCVT.isVector() || 
20857         BCVT.getVectorNumElements() != OriginalVT.getVectorNumElements())
20858       return SDValue();
20859     InVec = InVec.getOperand(0);
20860   }
20861
20862   EVT CurrentVT = InVec.getValueType();
20863
20864   if (!isTargetShuffle(InVec.getOpcode()))
20865     return SDValue();
20866
20867   // Don't duplicate a load with other uses.
20868   if (!InVec.hasOneUse())
20869     return SDValue();
20870
20871   SmallVector<int, 16> ShuffleMask;
20872   bool UnaryShuffle;
20873   if (!getTargetShuffleMask(InVec.getNode(), CurrentVT.getSimpleVT(),
20874                             ShuffleMask, UnaryShuffle))
20875     return SDValue();
20876
20877   // Select the input vector, guarding against out of range extract vector.
20878   unsigned NumElems = CurrentVT.getVectorNumElements();
20879   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
20880   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
20881   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
20882                                          : InVec.getOperand(1);
20883
20884   // If inputs to shuffle are the same for both ops, then allow 2 uses
20885   unsigned AllowedUses = InVec.getNumOperands() > 1 &&
20886                          InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
20887
20888   if (LdNode.getOpcode() == ISD::BITCAST) {
20889     // Don't duplicate a load with other uses.
20890     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
20891       return SDValue();
20892
20893     AllowedUses = 1; // only allow 1 load use if we have a bitcast
20894     LdNode = LdNode.getOperand(0);
20895   }
20896
20897   if (!ISD::isNormalLoad(LdNode.getNode()))
20898     return SDValue();
20899
20900   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
20901
20902   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
20903     return SDValue();
20904
20905   EVT EltVT = N->getValueType(0);
20906   // If there's a bitcast before the shuffle, check if the load type and
20907   // alignment is valid.
20908   unsigned Align = LN0->getAlignment();
20909   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20910   unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment(
20911       EltVT.getTypeForEVT(*DAG.getContext()));
20912
20913   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, EltVT))
20914     return SDValue();
20915
20916   // All checks match so transform back to vector_shuffle so that DAG combiner
20917   // can finish the job
20918   SDLoc dl(N);
20919
20920   // Create shuffle node taking into account the case that its a unary shuffle
20921   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(CurrentVT)
20922                                    : InVec.getOperand(1);
20923   Shuffle = DAG.getVectorShuffle(CurrentVT, dl,
20924                                  InVec.getOperand(0), Shuffle,
20925                                  &ShuffleMask[0]);
20926   Shuffle = DAG.getNode(ISD::BITCAST, dl, OriginalVT, Shuffle);
20927   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
20928                      EltNo);
20929 }
20930
20931 /// \brief Detect bitcasts between i32 to x86mmx low word. Since MMX types are
20932 /// special and don't usually play with other vector types, it's better to
20933 /// handle them early to be sure we emit efficient code by avoiding
20934 /// store-load conversions.
20935 static SDValue PerformBITCASTCombine(SDNode *N, SelectionDAG &DAG) {
20936   if (N->getValueType(0) != MVT::x86mmx ||
20937       N->getOperand(0)->getOpcode() != ISD::BUILD_VECTOR ||
20938       N->getOperand(0)->getValueType(0) != MVT::v2i32)
20939     return SDValue();
20940
20941   SDValue V = N->getOperand(0);
20942   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V.getOperand(1));
20943   if (C && C->getZExtValue() == 0 && V.getOperand(0).getValueType() == MVT::i32)
20944     return DAG.getNode(X86ISD::MMX_MOVW2D, SDLoc(V.getOperand(0)),
20945                        N->getValueType(0), V.getOperand(0));
20946
20947   return SDValue();
20948 }
20949
20950 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
20951 /// generation and convert it from being a bunch of shuffles and extracts
20952 /// into a somewhat faster sequence. For i686, the best sequence is apparently
20953 /// storing the value and loading scalars back, while for x64 we should
20954 /// use 64-bit extracts and shifts.
20955 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
20956                                          TargetLowering::DAGCombinerInfo &DCI) {
20957   SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
20958   if (NewOp.getNode())
20959     return NewOp;
20960
20961   SDValue InputVector = N->getOperand(0);
20962   SDLoc dl(InputVector);
20963   // Detect mmx to i32 conversion through a v2i32 elt extract.
20964   if (InputVector.getOpcode() == ISD::BITCAST && InputVector.hasOneUse() &&
20965       N->getValueType(0) == MVT::i32 &&
20966       InputVector.getValueType() == MVT::v2i32) {
20967
20968     // The bitcast source is a direct mmx result.
20969     SDValue MMXSrc = InputVector.getNode()->getOperand(0);
20970     if (MMXSrc.getValueType() == MVT::x86mmx)
20971       return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
20972                          N->getValueType(0),
20973                          InputVector.getNode()->getOperand(0));
20974
20975     // The mmx is indirect: (i64 extract_elt (v1i64 bitcast (x86mmx ...))).
20976     SDValue MMXSrcOp = MMXSrc.getOperand(0);
20977     if (MMXSrc.getOpcode() == ISD::EXTRACT_VECTOR_ELT && MMXSrc.hasOneUse() &&
20978         MMXSrc.getValueType() == MVT::i64 && MMXSrcOp.hasOneUse() &&
20979         MMXSrcOp.getOpcode() == ISD::BITCAST &&
20980         MMXSrcOp.getValueType() == MVT::v1i64 &&
20981         MMXSrcOp.getOperand(0).getValueType() == MVT::x86mmx)
20982       return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
20983                          N->getValueType(0),
20984                          MMXSrcOp.getOperand(0));
20985   }
20986
20987   EVT VT = N->getValueType(0);
20988   
20989   if (VT == MVT::i1 && dyn_cast<ConstantSDNode>(N->getOperand(1)) &&
20990       InputVector.getOpcode() == ISD::BITCAST &&
20991       dyn_cast<ConstantSDNode>(InputVector.getOperand(0))) {
20992     uint64_t ExtractedElt =
20993           cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
20994     uint64_t InputValue =
20995           cast<ConstantSDNode>(InputVector.getOperand(0))->getZExtValue();
20996     uint64_t Res = (InputValue >> ExtractedElt) & 1;
20997     return DAG.getConstant(Res, dl, MVT::i1);
20998   }
20999   // Only operate on vectors of 4 elements, where the alternative shuffling
21000   // gets to be more expensive.
21001   if (InputVector.getValueType() != MVT::v4i32)
21002     return SDValue();
21003
21004   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
21005   // single use which is a sign-extend or zero-extend, and all elements are
21006   // used.
21007   SmallVector<SDNode *, 4> Uses;
21008   unsigned ExtractedElements = 0;
21009   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
21010        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
21011     if (UI.getUse().getResNo() != InputVector.getResNo())
21012       return SDValue();
21013
21014     SDNode *Extract = *UI;
21015     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
21016       return SDValue();
21017
21018     if (Extract->getValueType(0) != MVT::i32)
21019       return SDValue();
21020     if (!Extract->hasOneUse())
21021       return SDValue();
21022     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
21023         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
21024       return SDValue();
21025     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
21026       return SDValue();
21027
21028     // Record which element was extracted.
21029     ExtractedElements |=
21030       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
21031
21032     Uses.push_back(Extract);
21033   }
21034
21035   // If not all the elements were used, this may not be worthwhile.
21036   if (ExtractedElements != 15)
21037     return SDValue();
21038
21039   // Ok, we've now decided to do the transformation.
21040   // If 64-bit shifts are legal, use the extract-shift sequence,
21041   // otherwise bounce the vector off the cache.
21042   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21043   SDValue Vals[4];
21044
21045   if (TLI.isOperationLegal(ISD::SRA, MVT::i64)) {
21046     SDValue Cst = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, InputVector);
21047     EVT VecIdxTy = DAG.getTargetLoweringInfo().getVectorIdxTy();
21048     SDValue BottomHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
21049       DAG.getConstant(0, dl, VecIdxTy));
21050     SDValue TopHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
21051       DAG.getConstant(1, dl, VecIdxTy));
21052
21053     SDValue ShAmt = DAG.getConstant(32, dl,
21054       DAG.getTargetLoweringInfo().getShiftAmountTy(MVT::i64));
21055     Vals[0] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BottomHalf);
21056     Vals[1] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
21057       DAG.getNode(ISD::SRA, dl, MVT::i64, BottomHalf, ShAmt));
21058     Vals[2] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, TopHalf);
21059     Vals[3] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
21060       DAG.getNode(ISD::SRA, dl, MVT::i64, TopHalf, ShAmt));
21061   } else {
21062     // Store the value to a temporary stack slot.
21063     SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
21064     SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
21065       MachinePointerInfo(), false, false, 0);
21066
21067     EVT ElementType = InputVector.getValueType().getVectorElementType();
21068     unsigned EltSize = ElementType.getSizeInBits() / 8;
21069
21070     // Replace each use (extract) with a load of the appropriate element.
21071     for (unsigned i = 0; i < 4; ++i) {
21072       uint64_t Offset = EltSize * i;
21073       SDValue OffsetVal = DAG.getConstant(Offset, dl, TLI.getPointerTy());
21074
21075       SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
21076                                        StackPtr, OffsetVal);
21077
21078       // Load the scalar.
21079       Vals[i] = DAG.getLoad(ElementType, dl, Ch,
21080                             ScalarAddr, MachinePointerInfo(),
21081                             false, false, false, 0);
21082
21083     }
21084   }
21085
21086   // Replace the extracts
21087   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
21088     UE = Uses.end(); UI != UE; ++UI) {
21089     SDNode *Extract = *UI;
21090
21091     SDValue Idx = Extract->getOperand(1);
21092     uint64_t IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
21093     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), Vals[IdxVal]);
21094   }
21095
21096   // The replacement was made in place; don't return anything.
21097   return SDValue();
21098 }
21099
21100 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
21101 static std::pair<unsigned, bool>
21102 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
21103                    SelectionDAG &DAG, const X86Subtarget *Subtarget) {
21104   if (!VT.isVector())
21105     return std::make_pair(0, false);
21106
21107   bool NeedSplit = false;
21108   switch (VT.getSimpleVT().SimpleTy) {
21109   default: return std::make_pair(0, false);
21110   case MVT::v4i64:
21111   case MVT::v2i64:
21112     if (!Subtarget->hasVLX())
21113       return std::make_pair(0, false);
21114     break;
21115   case MVT::v64i8:
21116   case MVT::v32i16:
21117     if (!Subtarget->hasBWI())
21118       return std::make_pair(0, false);
21119     break;
21120   case MVT::v16i32:
21121   case MVT::v8i64:
21122     if (!Subtarget->hasAVX512())
21123       return std::make_pair(0, false);
21124     break;
21125   case MVT::v32i8:
21126   case MVT::v16i16:
21127   case MVT::v8i32:
21128     if (!Subtarget->hasAVX2())
21129       NeedSplit = true;
21130     if (!Subtarget->hasAVX())
21131       return std::make_pair(0, false);
21132     break;
21133   case MVT::v16i8:
21134   case MVT::v8i16:
21135   case MVT::v4i32:
21136     if (!Subtarget->hasSSE2())
21137       return std::make_pair(0, false);
21138   }
21139
21140   // SSE2 has only a small subset of the operations.
21141   bool hasUnsigned = Subtarget->hasSSE41() ||
21142                      (Subtarget->hasSSE2() && VT == MVT::v16i8);
21143   bool hasSigned = Subtarget->hasSSE41() ||
21144                    (Subtarget->hasSSE2() && VT == MVT::v8i16);
21145
21146   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
21147
21148   unsigned Opc = 0;
21149   // Check for x CC y ? x : y.
21150   if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
21151       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
21152     switch (CC) {
21153     default: break;
21154     case ISD::SETULT:
21155     case ISD::SETULE:
21156       Opc = hasUnsigned ? X86ISD::UMIN : 0u; break;
21157     case ISD::SETUGT:
21158     case ISD::SETUGE:
21159       Opc = hasUnsigned ? X86ISD::UMAX : 0u; break;
21160     case ISD::SETLT:
21161     case ISD::SETLE:
21162       Opc = hasSigned ? X86ISD::SMIN : 0u; break;
21163     case ISD::SETGT:
21164     case ISD::SETGE:
21165       Opc = hasSigned ? X86ISD::SMAX : 0u; break;
21166     }
21167   // Check for x CC y ? y : x -- a min/max with reversed arms.
21168   } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
21169              DAG.isEqualTo(RHS, Cond.getOperand(0))) {
21170     switch (CC) {
21171     default: break;
21172     case ISD::SETULT:
21173     case ISD::SETULE:
21174       Opc = hasUnsigned ? X86ISD::UMAX : 0u; break;
21175     case ISD::SETUGT:
21176     case ISD::SETUGE:
21177       Opc = hasUnsigned ? X86ISD::UMIN : 0u; break;
21178     case ISD::SETLT:
21179     case ISD::SETLE:
21180       Opc = hasSigned ? X86ISD::SMAX : 0u; break;
21181     case ISD::SETGT:
21182     case ISD::SETGE:
21183       Opc = hasSigned ? X86ISD::SMIN : 0u; break;
21184     }
21185   }
21186
21187   return std::make_pair(Opc, NeedSplit);
21188 }
21189
21190 static SDValue
21191 transformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
21192                                       const X86Subtarget *Subtarget) {
21193   SDLoc dl(N);
21194   SDValue Cond = N->getOperand(0);
21195   SDValue LHS = N->getOperand(1);
21196   SDValue RHS = N->getOperand(2);
21197
21198   if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
21199     SDValue CondSrc = Cond->getOperand(0);
21200     if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
21201       Cond = CondSrc->getOperand(0);
21202   }
21203
21204   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
21205     return SDValue();
21206
21207   // A vselect where all conditions and data are constants can be optimized into
21208   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
21209   if (ISD::isBuildVectorOfConstantSDNodes(LHS.getNode()) &&
21210       ISD::isBuildVectorOfConstantSDNodes(RHS.getNode()))
21211     return SDValue();
21212
21213   unsigned MaskValue = 0;
21214   if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
21215     return SDValue();
21216
21217   MVT VT = N->getSimpleValueType(0);
21218   unsigned NumElems = VT.getVectorNumElements();
21219   SmallVector<int, 8> ShuffleMask(NumElems, -1);
21220   for (unsigned i = 0; i < NumElems; ++i) {
21221     // Be sure we emit undef where we can.
21222     if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
21223       ShuffleMask[i] = -1;
21224     else
21225       ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
21226   }
21227
21228   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21229   if (!TLI.isShuffleMaskLegal(ShuffleMask, VT))
21230     return SDValue();
21231   return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
21232 }
21233
21234 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
21235 /// nodes.
21236 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
21237                                     TargetLowering::DAGCombinerInfo &DCI,
21238                                     const X86Subtarget *Subtarget) {
21239   SDLoc DL(N);
21240   SDValue Cond = N->getOperand(0);
21241   // Get the LHS/RHS of the select.
21242   SDValue LHS = N->getOperand(1);
21243   SDValue RHS = N->getOperand(2);
21244   EVT VT = LHS.getValueType();
21245   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21246
21247   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
21248   // instructions match the semantics of the common C idiom x<y?x:y but not
21249   // x<=y?x:y, because of how they handle negative zero (which can be
21250   // ignored in unsafe-math mode).
21251   // We also try to create v2f32 min/max nodes, which we later widen to v4f32.
21252   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
21253       VT != MVT::f80 && (TLI.isTypeLegal(VT) || VT == MVT::v2f32) &&
21254       (Subtarget->hasSSE2() ||
21255        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
21256     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
21257
21258     unsigned Opcode = 0;
21259     // Check for x CC y ? x : y.
21260     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
21261         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
21262       switch (CC) {
21263       default: break;
21264       case ISD::SETULT:
21265         // Converting this to a min would handle NaNs incorrectly, and swapping
21266         // the operands would cause it to handle comparisons between positive
21267         // and negative zero incorrectly.
21268         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
21269           if (!DAG.getTarget().Options.UnsafeFPMath &&
21270               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
21271             break;
21272           std::swap(LHS, RHS);
21273         }
21274         Opcode = X86ISD::FMIN;
21275         break;
21276       case ISD::SETOLE:
21277         // Converting this to a min would handle comparisons between positive
21278         // and negative zero incorrectly.
21279         if (!DAG.getTarget().Options.UnsafeFPMath &&
21280             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
21281           break;
21282         Opcode = X86ISD::FMIN;
21283         break;
21284       case ISD::SETULE:
21285         // Converting this to a min would handle both negative zeros and NaNs
21286         // incorrectly, but we can swap the operands to fix both.
21287         std::swap(LHS, RHS);
21288       case ISD::SETOLT:
21289       case ISD::SETLT:
21290       case ISD::SETLE:
21291         Opcode = X86ISD::FMIN;
21292         break;
21293
21294       case ISD::SETOGE:
21295         // Converting this to a max would handle comparisons between positive
21296         // and negative zero incorrectly.
21297         if (!DAG.getTarget().Options.UnsafeFPMath &&
21298             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
21299           break;
21300         Opcode = X86ISD::FMAX;
21301         break;
21302       case ISD::SETUGT:
21303         // Converting this to a max would handle NaNs incorrectly, and swapping
21304         // the operands would cause it to handle comparisons between positive
21305         // and negative zero incorrectly.
21306         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
21307           if (!DAG.getTarget().Options.UnsafeFPMath &&
21308               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
21309             break;
21310           std::swap(LHS, RHS);
21311         }
21312         Opcode = X86ISD::FMAX;
21313         break;
21314       case ISD::SETUGE:
21315         // Converting this to a max would handle both negative zeros and NaNs
21316         // incorrectly, but we can swap the operands to fix both.
21317         std::swap(LHS, RHS);
21318       case ISD::SETOGT:
21319       case ISD::SETGT:
21320       case ISD::SETGE:
21321         Opcode = X86ISD::FMAX;
21322         break;
21323       }
21324     // Check for x CC y ? y : x -- a min/max with reversed arms.
21325     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
21326                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
21327       switch (CC) {
21328       default: break;
21329       case ISD::SETOGE:
21330         // Converting this to a min would handle comparisons between positive
21331         // and negative zero incorrectly, and swapping the operands would
21332         // cause it to handle NaNs incorrectly.
21333         if (!DAG.getTarget().Options.UnsafeFPMath &&
21334             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
21335           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
21336             break;
21337           std::swap(LHS, RHS);
21338         }
21339         Opcode = X86ISD::FMIN;
21340         break;
21341       case ISD::SETUGT:
21342         // Converting this to a min would handle NaNs incorrectly.
21343         if (!DAG.getTarget().Options.UnsafeFPMath &&
21344             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
21345           break;
21346         Opcode = X86ISD::FMIN;
21347         break;
21348       case ISD::SETUGE:
21349         // Converting this to a min would handle both negative zeros and NaNs
21350         // incorrectly, but we can swap the operands to fix both.
21351         std::swap(LHS, RHS);
21352       case ISD::SETOGT:
21353       case ISD::SETGT:
21354       case ISD::SETGE:
21355         Opcode = X86ISD::FMIN;
21356         break;
21357
21358       case ISD::SETULT:
21359         // Converting this to a max would handle NaNs incorrectly.
21360         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
21361           break;
21362         Opcode = X86ISD::FMAX;
21363         break;
21364       case ISD::SETOLE:
21365         // Converting this to a max would handle comparisons between positive
21366         // and negative zero incorrectly, and swapping the operands would
21367         // cause it to handle NaNs incorrectly.
21368         if (!DAG.getTarget().Options.UnsafeFPMath &&
21369             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
21370           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
21371             break;
21372           std::swap(LHS, RHS);
21373         }
21374         Opcode = X86ISD::FMAX;
21375         break;
21376       case ISD::SETULE:
21377         // Converting this to a max would handle both negative zeros and NaNs
21378         // incorrectly, but we can swap the operands to fix both.
21379         std::swap(LHS, RHS);
21380       case ISD::SETOLT:
21381       case ISD::SETLT:
21382       case ISD::SETLE:
21383         Opcode = X86ISD::FMAX;
21384         break;
21385       }
21386     }
21387
21388     if (Opcode)
21389       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
21390   }
21391
21392   EVT CondVT = Cond.getValueType();
21393   if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
21394       CondVT.getVectorElementType() == MVT::i1) {
21395     // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
21396     // lowering on KNL. In this case we convert it to
21397     // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
21398     // The same situation for all 128 and 256-bit vectors of i8 and i16.
21399     // Since SKX these selects have a proper lowering.
21400     EVT OpVT = LHS.getValueType();
21401     if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
21402         (OpVT.getVectorElementType() == MVT::i8 ||
21403          OpVT.getVectorElementType() == MVT::i16) &&
21404         !(Subtarget->hasBWI() && Subtarget->hasVLX())) {
21405       Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
21406       DCI.AddToWorklist(Cond.getNode());
21407       return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
21408     }
21409   }
21410   // If this is a select between two integer constants, try to do some
21411   // optimizations.
21412   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
21413     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
21414       // Don't do this for crazy integer types.
21415       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
21416         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
21417         // so that TrueC (the true value) is larger than FalseC.
21418         bool NeedsCondInvert = false;
21419
21420         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
21421             // Efficiently invertible.
21422             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
21423              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
21424               isa<ConstantSDNode>(Cond.getOperand(1))))) {
21425           NeedsCondInvert = true;
21426           std::swap(TrueC, FalseC);
21427         }
21428
21429         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
21430         if (FalseC->getAPIntValue() == 0 &&
21431             TrueC->getAPIntValue().isPowerOf2()) {
21432           if (NeedsCondInvert) // Invert the condition if needed.
21433             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
21434                                DAG.getConstant(1, DL, Cond.getValueType()));
21435
21436           // Zero extend the condition if needed.
21437           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
21438
21439           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
21440           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
21441                              DAG.getConstant(ShAmt, DL, MVT::i8));
21442         }
21443
21444         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
21445         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
21446           if (NeedsCondInvert) // Invert the condition if needed.
21447             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
21448                                DAG.getConstant(1, DL, Cond.getValueType()));
21449
21450           // Zero extend the condition if needed.
21451           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
21452                              FalseC->getValueType(0), Cond);
21453           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
21454                              SDValue(FalseC, 0));
21455         }
21456
21457         // Optimize cases that will turn into an LEA instruction.  This requires
21458         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
21459         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
21460           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
21461           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
21462
21463           bool isFastMultiplier = false;
21464           if (Diff < 10) {
21465             switch ((unsigned char)Diff) {
21466               default: break;
21467               case 1:  // result = add base, cond
21468               case 2:  // result = lea base(    , cond*2)
21469               case 3:  // result = lea base(cond, cond*2)
21470               case 4:  // result = lea base(    , cond*4)
21471               case 5:  // result = lea base(cond, cond*4)
21472               case 8:  // result = lea base(    , cond*8)
21473               case 9:  // result = lea base(cond, cond*8)
21474                 isFastMultiplier = true;
21475                 break;
21476             }
21477           }
21478
21479           if (isFastMultiplier) {
21480             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
21481             if (NeedsCondInvert) // Invert the condition if needed.
21482               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
21483                                  DAG.getConstant(1, DL, Cond.getValueType()));
21484
21485             // Zero extend the condition if needed.
21486             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
21487                                Cond);
21488             // Scale the condition by the difference.
21489             if (Diff != 1)
21490               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
21491                                  DAG.getConstant(Diff, DL,
21492                                                  Cond.getValueType()));
21493
21494             // Add the base if non-zero.
21495             if (FalseC->getAPIntValue() != 0)
21496               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
21497                                  SDValue(FalseC, 0));
21498             return Cond;
21499           }
21500         }
21501       }
21502   }
21503
21504   // Canonicalize max and min:
21505   // (x > y) ? x : y -> (x >= y) ? x : y
21506   // (x < y) ? x : y -> (x <= y) ? x : y
21507   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
21508   // the need for an extra compare
21509   // against zero. e.g.
21510   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
21511   // subl   %esi, %edi
21512   // testl  %edi, %edi
21513   // movl   $0, %eax
21514   // cmovgl %edi, %eax
21515   // =>
21516   // xorl   %eax, %eax
21517   // subl   %esi, $edi
21518   // cmovsl %eax, %edi
21519   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
21520       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
21521       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
21522     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
21523     switch (CC) {
21524     default: break;
21525     case ISD::SETLT:
21526     case ISD::SETGT: {
21527       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
21528       Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
21529                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
21530       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
21531     }
21532     }
21533   }
21534
21535   // Early exit check
21536   if (!TLI.isTypeLegal(VT))
21537     return SDValue();
21538
21539   // Match VSELECTs into subs with unsigned saturation.
21540   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
21541       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
21542       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
21543        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
21544     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
21545
21546     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
21547     // left side invert the predicate to simplify logic below.
21548     SDValue Other;
21549     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
21550       Other = RHS;
21551       CC = ISD::getSetCCInverse(CC, true);
21552     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
21553       Other = LHS;
21554     }
21555
21556     if (Other.getNode() && Other->getNumOperands() == 2 &&
21557         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
21558       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
21559       SDValue CondRHS = Cond->getOperand(1);
21560
21561       // Look for a general sub with unsigned saturation first.
21562       // x >= y ? x-y : 0 --> subus x, y
21563       // x >  y ? x-y : 0 --> subus x, y
21564       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
21565           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
21566         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
21567
21568       if (auto *OpRHSBV = dyn_cast<BuildVectorSDNode>(OpRHS))
21569         if (auto *OpRHSConst = OpRHSBV->getConstantSplatNode()) {
21570           if (auto *CondRHSBV = dyn_cast<BuildVectorSDNode>(CondRHS))
21571             if (auto *CondRHSConst = CondRHSBV->getConstantSplatNode())
21572               // If the RHS is a constant we have to reverse the const
21573               // canonicalization.
21574               // x > C-1 ? x+-C : 0 --> subus x, C
21575               if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
21576                   CondRHSConst->getAPIntValue() ==
21577                       (-OpRHSConst->getAPIntValue() - 1))
21578                 return DAG.getNode(
21579                     X86ISD::SUBUS, DL, VT, OpLHS,
21580                     DAG.getConstant(-OpRHSConst->getAPIntValue(), DL, VT));
21581
21582           // Another special case: If C was a sign bit, the sub has been
21583           // canonicalized into a xor.
21584           // FIXME: Would it be better to use computeKnownBits to determine
21585           //        whether it's safe to decanonicalize the xor?
21586           // x s< 0 ? x^C : 0 --> subus x, C
21587           if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
21588               ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
21589               OpRHSConst->getAPIntValue().isSignBit())
21590             // Note that we have to rebuild the RHS constant here to ensure we
21591             // don't rely on particular values of undef lanes.
21592             return DAG.getNode(
21593                 X86ISD::SUBUS, DL, VT, OpLHS,
21594                 DAG.getConstant(OpRHSConst->getAPIntValue(), DL, VT));
21595         }
21596     }
21597   }
21598
21599   // Try to match a min/max vector operation.
21600   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
21601     std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
21602     unsigned Opc = ret.first;
21603     bool NeedSplit = ret.second;
21604
21605     if (Opc && NeedSplit) {
21606       unsigned NumElems = VT.getVectorNumElements();
21607       // Extract the LHS vectors
21608       SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
21609       SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
21610
21611       // Extract the RHS vectors
21612       SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
21613       SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
21614
21615       // Create min/max for each subvector
21616       LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
21617       RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
21618
21619       // Merge the result
21620       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
21621     } else if (Opc)
21622       return DAG.getNode(Opc, DL, VT, LHS, RHS);
21623   }
21624
21625   // Simplify vector selection if condition value type matches vselect
21626   // operand type
21627   if (N->getOpcode() == ISD::VSELECT && CondVT == VT) {
21628     assert(Cond.getValueType().isVector() &&
21629            "vector select expects a vector selector!");
21630
21631     bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
21632     bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
21633
21634     // Try invert the condition if true value is not all 1s and false value
21635     // is not all 0s.
21636     if (!TValIsAllOnes && !FValIsAllZeros &&
21637         // Check if the selector will be produced by CMPP*/PCMP*
21638         Cond.getOpcode() == ISD::SETCC &&
21639         // Check if SETCC has already been promoted
21640         TLI.getSetCCResultType(*DAG.getContext(), VT) == CondVT) {
21641       bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
21642       bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
21643
21644       if (TValIsAllZeros || FValIsAllOnes) {
21645         SDValue CC = Cond.getOperand(2);
21646         ISD::CondCode NewCC =
21647           ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
21648                                Cond.getOperand(0).getValueType().isInteger());
21649         Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
21650         std::swap(LHS, RHS);
21651         TValIsAllOnes = FValIsAllOnes;
21652         FValIsAllZeros = TValIsAllZeros;
21653       }
21654     }
21655
21656     if (TValIsAllOnes || FValIsAllZeros) {
21657       SDValue Ret;
21658
21659       if (TValIsAllOnes && FValIsAllZeros)
21660         Ret = Cond;
21661       else if (TValIsAllOnes)
21662         Ret = DAG.getNode(ISD::OR, DL, CondVT, Cond,
21663                           DAG.getNode(ISD::BITCAST, DL, CondVT, RHS));
21664       else if (FValIsAllZeros)
21665         Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
21666                           DAG.getNode(ISD::BITCAST, DL, CondVT, LHS));
21667
21668       return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
21669     }
21670   }
21671
21672   // We should generate an X86ISD::BLENDI from a vselect if its argument
21673   // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
21674   // constants. This specific pattern gets generated when we split a
21675   // selector for a 512 bit vector in a machine without AVX512 (but with
21676   // 256-bit vectors), during legalization:
21677   //
21678   // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
21679   //
21680   // Iff we find this pattern and the build_vectors are built from
21681   // constants, we translate the vselect into a shuffle_vector that we
21682   // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
21683   if ((N->getOpcode() == ISD::VSELECT ||
21684        N->getOpcode() == X86ISD::SHRUNKBLEND) &&
21685       !DCI.isBeforeLegalize()) {
21686     SDValue Shuffle = transformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
21687     if (Shuffle.getNode())
21688       return Shuffle;
21689   }
21690
21691   // If this is a *dynamic* select (non-constant condition) and we can match
21692   // this node with one of the variable blend instructions, restructure the
21693   // condition so that the blends can use the high bit of each element and use
21694   // SimplifyDemandedBits to simplify the condition operand.
21695   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
21696       !DCI.isBeforeLegalize() &&
21697       !ISD::isBuildVectorOfConstantSDNodes(Cond.getNode())) {
21698     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
21699
21700     // Don't optimize vector selects that map to mask-registers.
21701     if (BitWidth == 1)
21702       return SDValue();
21703
21704     // We can only handle the cases where VSELECT is directly legal on the
21705     // subtarget. We custom lower VSELECT nodes with constant conditions and
21706     // this makes it hard to see whether a dynamic VSELECT will correctly
21707     // lower, so we both check the operation's status and explicitly handle the
21708     // cases where a *dynamic* blend will fail even though a constant-condition
21709     // blend could be custom lowered.
21710     // FIXME: We should find a better way to handle this class of problems.
21711     // Potentially, we should combine constant-condition vselect nodes
21712     // pre-legalization into shuffles and not mark as many types as custom
21713     // lowered.
21714     if (!TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
21715       return SDValue();
21716     // FIXME: We don't support i16-element blends currently. We could and
21717     // should support them by making *all* the bits in the condition be set
21718     // rather than just the high bit and using an i8-element blend.
21719     if (VT.getScalarType() == MVT::i16)
21720       return SDValue();
21721     // Dynamic blending was only available from SSE4.1 onward.
21722     if (VT.getSizeInBits() == 128 && !Subtarget->hasSSE41())
21723       return SDValue();
21724     // Byte blends are only available in AVX2
21725     if (VT.getSizeInBits() == 256 && VT.getScalarType() == MVT::i8 &&
21726         !Subtarget->hasAVX2())
21727       return SDValue();
21728
21729     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
21730     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
21731
21732     APInt KnownZero, KnownOne;
21733     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
21734                                           DCI.isBeforeLegalizeOps());
21735     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
21736         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne,
21737                                  TLO)) {
21738       // If we changed the computation somewhere in the DAG, this change
21739       // will affect all users of Cond.
21740       // Make sure it is fine and update all the nodes so that we do not
21741       // use the generic VSELECT anymore. Otherwise, we may perform
21742       // wrong optimizations as we messed up with the actual expectation
21743       // for the vector boolean values.
21744       if (Cond != TLO.Old) {
21745         // Check all uses of that condition operand to check whether it will be
21746         // consumed by non-BLEND instructions, which may depend on all bits are
21747         // set properly.
21748         for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
21749              I != E; ++I)
21750           if (I->getOpcode() != ISD::VSELECT)
21751             // TODO: Add other opcodes eventually lowered into BLEND.
21752             return SDValue();
21753
21754         // Update all the users of the condition, before committing the change,
21755         // so that the VSELECT optimizations that expect the correct vector
21756         // boolean value will not be triggered.
21757         for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
21758              I != E; ++I)
21759           DAG.ReplaceAllUsesOfValueWith(
21760               SDValue(*I, 0),
21761               DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(*I), I->getValueType(0),
21762                           Cond, I->getOperand(1), I->getOperand(2)));
21763         DCI.CommitTargetLoweringOpt(TLO);
21764         return SDValue();
21765       }
21766       // At this point, only Cond is changed. Change the condition
21767       // just for N to keep the opportunity to optimize all other
21768       // users their own way.
21769       DAG.ReplaceAllUsesOfValueWith(
21770           SDValue(N, 0),
21771           DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(N), N->getValueType(0),
21772                       TLO.New, N->getOperand(1), N->getOperand(2)));
21773       return SDValue();
21774     }
21775   }
21776
21777   return SDValue();
21778 }
21779
21780 // Check whether a boolean test is testing a boolean value generated by
21781 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
21782 // code.
21783 //
21784 // Simplify the following patterns:
21785 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
21786 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
21787 // to (Op EFLAGS Cond)
21788 //
21789 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
21790 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
21791 // to (Op EFLAGS !Cond)
21792 //
21793 // where Op could be BRCOND or CMOV.
21794 //
21795 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
21796   // Quit if not CMP and SUB with its value result used.
21797   if (Cmp.getOpcode() != X86ISD::CMP &&
21798       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
21799       return SDValue();
21800
21801   // Quit if not used as a boolean value.
21802   if (CC != X86::COND_E && CC != X86::COND_NE)
21803     return SDValue();
21804
21805   // Check CMP operands. One of them should be 0 or 1 and the other should be
21806   // an SetCC or extended from it.
21807   SDValue Op1 = Cmp.getOperand(0);
21808   SDValue Op2 = Cmp.getOperand(1);
21809
21810   SDValue SetCC;
21811   const ConstantSDNode* C = nullptr;
21812   bool needOppositeCond = (CC == X86::COND_E);
21813   bool checkAgainstTrue = false; // Is it a comparison against 1?
21814
21815   if ((C = dyn_cast<ConstantSDNode>(Op1)))
21816     SetCC = Op2;
21817   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
21818     SetCC = Op1;
21819   else // Quit if all operands are not constants.
21820     return SDValue();
21821
21822   if (C->getZExtValue() == 1) {
21823     needOppositeCond = !needOppositeCond;
21824     checkAgainstTrue = true;
21825   } else if (C->getZExtValue() != 0)
21826     // Quit if the constant is neither 0 or 1.
21827     return SDValue();
21828
21829   bool truncatedToBoolWithAnd = false;
21830   // Skip (zext $x), (trunc $x), or (and $x, 1) node.
21831   while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
21832          SetCC.getOpcode() == ISD::TRUNCATE ||
21833          SetCC.getOpcode() == ISD::AND) {
21834     if (SetCC.getOpcode() == ISD::AND) {
21835       int OpIdx = -1;
21836       ConstantSDNode *CS;
21837       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
21838           CS->getZExtValue() == 1)
21839         OpIdx = 1;
21840       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
21841           CS->getZExtValue() == 1)
21842         OpIdx = 0;
21843       if (OpIdx == -1)
21844         break;
21845       SetCC = SetCC.getOperand(OpIdx);
21846       truncatedToBoolWithAnd = true;
21847     } else
21848       SetCC = SetCC.getOperand(0);
21849   }
21850
21851   switch (SetCC.getOpcode()) {
21852   case X86ISD::SETCC_CARRY:
21853     // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
21854     // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
21855     // i.e. it's a comparison against true but the result of SETCC_CARRY is not
21856     // truncated to i1 using 'and'.
21857     if (checkAgainstTrue && !truncatedToBoolWithAnd)
21858       break;
21859     assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
21860            "Invalid use of SETCC_CARRY!");
21861     // FALL THROUGH
21862   case X86ISD::SETCC:
21863     // Set the condition code or opposite one if necessary.
21864     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
21865     if (needOppositeCond)
21866       CC = X86::GetOppositeBranchCondition(CC);
21867     return SetCC.getOperand(1);
21868   case X86ISD::CMOV: {
21869     // Check whether false/true value has canonical one, i.e. 0 or 1.
21870     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
21871     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
21872     // Quit if true value is not a constant.
21873     if (!TVal)
21874       return SDValue();
21875     // Quit if false value is not a constant.
21876     if (!FVal) {
21877       SDValue Op = SetCC.getOperand(0);
21878       // Skip 'zext' or 'trunc' node.
21879       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
21880           Op.getOpcode() == ISD::TRUNCATE)
21881         Op = Op.getOperand(0);
21882       // A special case for rdrand/rdseed, where 0 is set if false cond is
21883       // found.
21884       if ((Op.getOpcode() != X86ISD::RDRAND &&
21885            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
21886         return SDValue();
21887     }
21888     // Quit if false value is not the constant 0 or 1.
21889     bool FValIsFalse = true;
21890     if (FVal && FVal->getZExtValue() != 0) {
21891       if (FVal->getZExtValue() != 1)
21892         return SDValue();
21893       // If FVal is 1, opposite cond is needed.
21894       needOppositeCond = !needOppositeCond;
21895       FValIsFalse = false;
21896     }
21897     // Quit if TVal is not the constant opposite of FVal.
21898     if (FValIsFalse && TVal->getZExtValue() != 1)
21899       return SDValue();
21900     if (!FValIsFalse && TVal->getZExtValue() != 0)
21901       return SDValue();
21902     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
21903     if (needOppositeCond)
21904       CC = X86::GetOppositeBranchCondition(CC);
21905     return SetCC.getOperand(3);
21906   }
21907   }
21908
21909   return SDValue();
21910 }
21911
21912 /// Check whether Cond is an AND/OR of SETCCs off of the same EFLAGS.
21913 /// Match:
21914 ///   (X86or (X86setcc) (X86setcc))
21915 ///   (X86cmp (and (X86setcc) (X86setcc)), 0)
21916 static bool checkBoolTestAndOrSetCCCombine(SDValue Cond, X86::CondCode &CC0,
21917                                            X86::CondCode &CC1, SDValue &Flags,
21918                                            bool &isAnd) {
21919   if (Cond->getOpcode() == X86ISD::CMP) {
21920     ConstantSDNode *CondOp1C = dyn_cast<ConstantSDNode>(Cond->getOperand(1));
21921     if (!CondOp1C || !CondOp1C->isNullValue())
21922       return false;
21923
21924     Cond = Cond->getOperand(0);
21925   }
21926
21927   isAnd = false;
21928
21929   SDValue SetCC0, SetCC1;
21930   switch (Cond->getOpcode()) {
21931   default: return false;
21932   case ISD::AND:
21933   case X86ISD::AND:
21934     isAnd = true;
21935     // fallthru
21936   case ISD::OR:
21937   case X86ISD::OR:
21938     SetCC0 = Cond->getOperand(0);
21939     SetCC1 = Cond->getOperand(1);
21940     break;
21941   };
21942
21943   // Make sure we have SETCC nodes, using the same flags value.
21944   if (SetCC0.getOpcode() != X86ISD::SETCC ||
21945       SetCC1.getOpcode() != X86ISD::SETCC ||
21946       SetCC0->getOperand(1) != SetCC1->getOperand(1))
21947     return false;
21948
21949   CC0 = (X86::CondCode)SetCC0->getConstantOperandVal(0);
21950   CC1 = (X86::CondCode)SetCC1->getConstantOperandVal(0);
21951   Flags = SetCC0->getOperand(1);
21952   return true;
21953 }
21954
21955 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
21956 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
21957                                   TargetLowering::DAGCombinerInfo &DCI,
21958                                   const X86Subtarget *Subtarget) {
21959   SDLoc DL(N);
21960
21961   // If the flag operand isn't dead, don't touch this CMOV.
21962   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
21963     return SDValue();
21964
21965   SDValue FalseOp = N->getOperand(0);
21966   SDValue TrueOp = N->getOperand(1);
21967   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
21968   SDValue Cond = N->getOperand(3);
21969
21970   if (CC == X86::COND_E || CC == X86::COND_NE) {
21971     switch (Cond.getOpcode()) {
21972     default: break;
21973     case X86ISD::BSR:
21974     case X86ISD::BSF:
21975       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
21976       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
21977         return (CC == X86::COND_E) ? FalseOp : TrueOp;
21978     }
21979   }
21980
21981   SDValue Flags;
21982
21983   Flags = checkBoolTestSetCCCombine(Cond, CC);
21984   if (Flags.getNode() &&
21985       // Extra check as FCMOV only supports a subset of X86 cond.
21986       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
21987     SDValue Ops[] = { FalseOp, TrueOp,
21988                       DAG.getConstant(CC, DL, MVT::i8), Flags };
21989     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
21990   }
21991
21992   // If this is a select between two integer constants, try to do some
21993   // optimizations.  Note that the operands are ordered the opposite of SELECT
21994   // operands.
21995   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
21996     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
21997       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
21998       // larger than FalseC (the false value).
21999       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
22000         CC = X86::GetOppositeBranchCondition(CC);
22001         std::swap(TrueC, FalseC);
22002         std::swap(TrueOp, FalseOp);
22003       }
22004
22005       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
22006       // This is efficient for any integer data type (including i8/i16) and
22007       // shift amount.
22008       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
22009         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
22010                            DAG.getConstant(CC, DL, MVT::i8), Cond);
22011
22012         // Zero extend the condition if needed.
22013         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
22014
22015         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
22016         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
22017                            DAG.getConstant(ShAmt, DL, MVT::i8));
22018         if (N->getNumValues() == 2)  // Dead flag value?
22019           return DCI.CombineTo(N, Cond, SDValue());
22020         return Cond;
22021       }
22022
22023       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
22024       // for any integer data type, including i8/i16.
22025       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
22026         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
22027                            DAG.getConstant(CC, DL, MVT::i8), Cond);
22028
22029         // Zero extend the condition if needed.
22030         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
22031                            FalseC->getValueType(0), Cond);
22032         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
22033                            SDValue(FalseC, 0));
22034
22035         if (N->getNumValues() == 2)  // Dead flag value?
22036           return DCI.CombineTo(N, Cond, SDValue());
22037         return Cond;
22038       }
22039
22040       // Optimize cases that will turn into an LEA instruction.  This requires
22041       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
22042       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
22043         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
22044         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
22045
22046         bool isFastMultiplier = false;
22047         if (Diff < 10) {
22048           switch ((unsigned char)Diff) {
22049           default: break;
22050           case 1:  // result = add base, cond
22051           case 2:  // result = lea base(    , cond*2)
22052           case 3:  // result = lea base(cond, cond*2)
22053           case 4:  // result = lea base(    , cond*4)
22054           case 5:  // result = lea base(cond, cond*4)
22055           case 8:  // result = lea base(    , cond*8)
22056           case 9:  // result = lea base(cond, cond*8)
22057             isFastMultiplier = true;
22058             break;
22059           }
22060         }
22061
22062         if (isFastMultiplier) {
22063           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
22064           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
22065                              DAG.getConstant(CC, DL, MVT::i8), Cond);
22066           // Zero extend the condition if needed.
22067           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
22068                              Cond);
22069           // Scale the condition by the difference.
22070           if (Diff != 1)
22071             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
22072                                DAG.getConstant(Diff, DL, Cond.getValueType()));
22073
22074           // Add the base if non-zero.
22075           if (FalseC->getAPIntValue() != 0)
22076             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
22077                                SDValue(FalseC, 0));
22078           if (N->getNumValues() == 2)  // Dead flag value?
22079             return DCI.CombineTo(N, Cond, SDValue());
22080           return Cond;
22081         }
22082       }
22083     }
22084   }
22085
22086   // Handle these cases:
22087   //   (select (x != c), e, c) -> select (x != c), e, x),
22088   //   (select (x == c), c, e) -> select (x == c), x, e)
22089   // where the c is an integer constant, and the "select" is the combination
22090   // of CMOV and CMP.
22091   //
22092   // The rationale for this change is that the conditional-move from a constant
22093   // needs two instructions, however, conditional-move from a register needs
22094   // only one instruction.
22095   //
22096   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
22097   //  some instruction-combining opportunities. This opt needs to be
22098   //  postponed as late as possible.
22099   //
22100   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
22101     // the DCI.xxxx conditions are provided to postpone the optimization as
22102     // late as possible.
22103
22104     ConstantSDNode *CmpAgainst = nullptr;
22105     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
22106         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
22107         !isa<ConstantSDNode>(Cond.getOperand(0))) {
22108
22109       if (CC == X86::COND_NE &&
22110           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
22111         CC = X86::GetOppositeBranchCondition(CC);
22112         std::swap(TrueOp, FalseOp);
22113       }
22114
22115       if (CC == X86::COND_E &&
22116           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
22117         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
22118                           DAG.getConstant(CC, DL, MVT::i8), Cond };
22119         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
22120       }
22121     }
22122   }
22123
22124   // Fold and/or of setcc's to double CMOV:
22125   //   (CMOV F, T, ((cc1 | cc2) != 0)) -> (CMOV (CMOV F, T, cc1), T, cc2)
22126   //   (CMOV F, T, ((cc1 & cc2) != 0)) -> (CMOV (CMOV T, F, !cc1), F, !cc2)
22127   //
22128   // This combine lets us generate:
22129   //   cmovcc1 (jcc1 if we don't have CMOV)
22130   //   cmovcc2 (same)
22131   // instead of:
22132   //   setcc1
22133   //   setcc2
22134   //   and/or
22135   //   cmovne (jne if we don't have CMOV)
22136   // When we can't use the CMOV instruction, it might increase branch
22137   // mispredicts.
22138   // When we can use CMOV, or when there is no mispredict, this improves
22139   // throughput and reduces register pressure.
22140   //
22141   if (CC == X86::COND_NE) {
22142     SDValue Flags;
22143     X86::CondCode CC0, CC1;
22144     bool isAndSetCC;
22145     if (checkBoolTestAndOrSetCCCombine(Cond, CC0, CC1, Flags, isAndSetCC)) {
22146       if (isAndSetCC) {
22147         std::swap(FalseOp, TrueOp);
22148         CC0 = X86::GetOppositeBranchCondition(CC0);
22149         CC1 = X86::GetOppositeBranchCondition(CC1);
22150       }
22151
22152       SDValue LOps[] = {FalseOp, TrueOp, DAG.getConstant(CC0, DL, MVT::i8),
22153         Flags};
22154       SDValue LCMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), LOps);
22155       SDValue Ops[] = {LCMOV, TrueOp, DAG.getConstant(CC1, DL, MVT::i8), Flags};
22156       SDValue CMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
22157       DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SDValue(CMOV.getNode(), 1));
22158       return CMOV;
22159     }
22160   }
22161
22162   return SDValue();
22163 }
22164
22165 static SDValue PerformINTRINSIC_WO_CHAINCombine(SDNode *N, SelectionDAG &DAG,
22166                                                 const X86Subtarget *Subtarget) {
22167   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
22168   switch (IntNo) {
22169   default: return SDValue();
22170   // SSE/AVX/AVX2 blend intrinsics.
22171   case Intrinsic::x86_avx2_pblendvb:
22172     // Don't try to simplify this intrinsic if we don't have AVX2.
22173     if (!Subtarget->hasAVX2())
22174       return SDValue();
22175     // FALL-THROUGH
22176   case Intrinsic::x86_avx_blendv_pd_256:
22177   case Intrinsic::x86_avx_blendv_ps_256:
22178     // Don't try to simplify this intrinsic if we don't have AVX.
22179     if (!Subtarget->hasAVX())
22180       return SDValue();
22181     // FALL-THROUGH
22182   case Intrinsic::x86_sse41_blendvps:
22183   case Intrinsic::x86_sse41_blendvpd:
22184   case Intrinsic::x86_sse41_pblendvb: {
22185     SDValue Op0 = N->getOperand(1);
22186     SDValue Op1 = N->getOperand(2);
22187     SDValue Mask = N->getOperand(3);
22188
22189     // Don't try to simplify this intrinsic if we don't have SSE4.1.
22190     if (!Subtarget->hasSSE41())
22191       return SDValue();
22192
22193     // fold (blend A, A, Mask) -> A
22194     if (Op0 == Op1)
22195       return Op0;
22196     // fold (blend A, B, allZeros) -> A
22197     if (ISD::isBuildVectorAllZeros(Mask.getNode()))
22198       return Op0;
22199     // fold (blend A, B, allOnes) -> B
22200     if (ISD::isBuildVectorAllOnes(Mask.getNode()))
22201       return Op1;
22202
22203     // Simplify the case where the mask is a constant i32 value.
22204     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Mask)) {
22205       if (C->isNullValue())
22206         return Op0;
22207       if (C->isAllOnesValue())
22208         return Op1;
22209     }
22210
22211     return SDValue();
22212   }
22213
22214   // Packed SSE2/AVX2 arithmetic shift immediate intrinsics.
22215   case Intrinsic::x86_sse2_psrai_w:
22216   case Intrinsic::x86_sse2_psrai_d:
22217   case Intrinsic::x86_avx2_psrai_w:
22218   case Intrinsic::x86_avx2_psrai_d:
22219   case Intrinsic::x86_sse2_psra_w:
22220   case Intrinsic::x86_sse2_psra_d:
22221   case Intrinsic::x86_avx2_psra_w:
22222   case Intrinsic::x86_avx2_psra_d: {
22223     SDValue Op0 = N->getOperand(1);
22224     SDValue Op1 = N->getOperand(2);
22225     EVT VT = Op0.getValueType();
22226     assert(VT.isVector() && "Expected a vector type!");
22227
22228     if (isa<BuildVectorSDNode>(Op1))
22229       Op1 = Op1.getOperand(0);
22230
22231     if (!isa<ConstantSDNode>(Op1))
22232       return SDValue();
22233
22234     EVT SVT = VT.getVectorElementType();
22235     unsigned SVTBits = SVT.getSizeInBits();
22236
22237     ConstantSDNode *CND = cast<ConstantSDNode>(Op1);
22238     const APInt &C = APInt(SVTBits, CND->getAPIntValue().getZExtValue());
22239     uint64_t ShAmt = C.getZExtValue();
22240
22241     // Don't try to convert this shift into a ISD::SRA if the shift
22242     // count is bigger than or equal to the element size.
22243     if (ShAmt >= SVTBits)
22244       return SDValue();
22245
22246     // Trivial case: if the shift count is zero, then fold this
22247     // into the first operand.
22248     if (ShAmt == 0)
22249       return Op0;
22250
22251     // Replace this packed shift intrinsic with a target independent
22252     // shift dag node.
22253     SDLoc DL(N);
22254     SDValue Splat = DAG.getConstant(C, DL, VT);
22255     return DAG.getNode(ISD::SRA, DL, VT, Op0, Splat);
22256   }
22257   }
22258 }
22259
22260 /// PerformMulCombine - Optimize a single multiply with constant into two
22261 /// in order to implement it with two cheaper instructions, e.g.
22262 /// LEA + SHL, LEA + LEA.
22263 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
22264                                  TargetLowering::DAGCombinerInfo &DCI) {
22265   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
22266     return SDValue();
22267
22268   EVT VT = N->getValueType(0);
22269   if (VT != MVT::i64 && VT != MVT::i32)
22270     return SDValue();
22271
22272   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
22273   if (!C)
22274     return SDValue();
22275   uint64_t MulAmt = C->getZExtValue();
22276   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
22277     return SDValue();
22278
22279   uint64_t MulAmt1 = 0;
22280   uint64_t MulAmt2 = 0;
22281   if ((MulAmt % 9) == 0) {
22282     MulAmt1 = 9;
22283     MulAmt2 = MulAmt / 9;
22284   } else if ((MulAmt % 5) == 0) {
22285     MulAmt1 = 5;
22286     MulAmt2 = MulAmt / 5;
22287   } else if ((MulAmt % 3) == 0) {
22288     MulAmt1 = 3;
22289     MulAmt2 = MulAmt / 3;
22290   }
22291   if (MulAmt2 &&
22292       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
22293     SDLoc DL(N);
22294
22295     if (isPowerOf2_64(MulAmt2) &&
22296         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
22297       // If second multiplifer is pow2, issue it first. We want the multiply by
22298       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
22299       // is an add.
22300       std::swap(MulAmt1, MulAmt2);
22301
22302     SDValue NewMul;
22303     if (isPowerOf2_64(MulAmt1))
22304       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
22305                            DAG.getConstant(Log2_64(MulAmt1), DL, MVT::i8));
22306     else
22307       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
22308                            DAG.getConstant(MulAmt1, DL, VT));
22309
22310     if (isPowerOf2_64(MulAmt2))
22311       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
22312                            DAG.getConstant(Log2_64(MulAmt2), DL, MVT::i8));
22313     else
22314       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
22315                            DAG.getConstant(MulAmt2, DL, VT));
22316
22317     // Do not add new nodes to DAG combiner worklist.
22318     DCI.CombineTo(N, NewMul, false);
22319   }
22320   return SDValue();
22321 }
22322
22323 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
22324   SDValue N0 = N->getOperand(0);
22325   SDValue N1 = N->getOperand(1);
22326   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
22327   EVT VT = N0.getValueType();
22328
22329   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
22330   // since the result of setcc_c is all zero's or all ones.
22331   if (VT.isInteger() && !VT.isVector() &&
22332       N1C && N0.getOpcode() == ISD::AND &&
22333       N0.getOperand(1).getOpcode() == ISD::Constant) {
22334     SDValue N00 = N0.getOperand(0);
22335     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
22336         ((N00.getOpcode() == ISD::ANY_EXTEND ||
22337           N00.getOpcode() == ISD::ZERO_EXTEND) &&
22338          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
22339       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
22340       APInt ShAmt = N1C->getAPIntValue();
22341       Mask = Mask.shl(ShAmt);
22342       if (Mask != 0) {
22343         SDLoc DL(N);
22344         return DAG.getNode(ISD::AND, DL, VT,
22345                            N00, DAG.getConstant(Mask, DL, VT));
22346       }
22347     }
22348   }
22349
22350   // Hardware support for vector shifts is sparse which makes us scalarize the
22351   // vector operations in many cases. Also, on sandybridge ADD is faster than
22352   // shl.
22353   // (shl V, 1) -> add V,V
22354   if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
22355     if (auto *N1SplatC = N1BV->getConstantSplatNode()) {
22356       assert(N0.getValueType().isVector() && "Invalid vector shift type");
22357       // We shift all of the values by one. In many cases we do not have
22358       // hardware support for this operation. This is better expressed as an ADD
22359       // of two values.
22360       if (N1SplatC->getZExtValue() == 1)
22361         return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
22362     }
22363
22364   return SDValue();
22365 }
22366
22367 /// \brief Returns a vector of 0s if the node in input is a vector logical
22368 /// shift by a constant amount which is known to be bigger than or equal
22369 /// to the vector element size in bits.
22370 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
22371                                       const X86Subtarget *Subtarget) {
22372   EVT VT = N->getValueType(0);
22373
22374   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
22375       (!Subtarget->hasInt256() ||
22376        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
22377     return SDValue();
22378
22379   SDValue Amt = N->getOperand(1);
22380   SDLoc DL(N);
22381   if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Amt))
22382     if (auto *AmtSplat = AmtBV->getConstantSplatNode()) {
22383       APInt ShiftAmt = AmtSplat->getAPIntValue();
22384       unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
22385
22386       // SSE2/AVX2 logical shifts always return a vector of 0s
22387       // if the shift amount is bigger than or equal to
22388       // the element size. The constant shift amount will be
22389       // encoded as a 8-bit immediate.
22390       if (ShiftAmt.trunc(8).uge(MaxAmount))
22391         return getZeroVector(VT, Subtarget, DAG, DL);
22392     }
22393
22394   return SDValue();
22395 }
22396
22397 /// PerformShiftCombine - Combine shifts.
22398 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
22399                                    TargetLowering::DAGCombinerInfo &DCI,
22400                                    const X86Subtarget *Subtarget) {
22401   if (N->getOpcode() == ISD::SHL) {
22402     SDValue V = PerformSHLCombine(N, DAG);
22403     if (V.getNode()) return V;
22404   }
22405
22406   if (N->getOpcode() != ISD::SRA) {
22407     // Try to fold this logical shift into a zero vector.
22408     SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
22409     if (V.getNode()) return V;
22410   }
22411
22412   return SDValue();
22413 }
22414
22415 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
22416 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
22417 // and friends.  Likewise for OR -> CMPNEQSS.
22418 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
22419                             TargetLowering::DAGCombinerInfo &DCI,
22420                             const X86Subtarget *Subtarget) {
22421   unsigned opcode;
22422
22423   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
22424   // we're requiring SSE2 for both.
22425   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
22426     SDValue N0 = N->getOperand(0);
22427     SDValue N1 = N->getOperand(1);
22428     SDValue CMP0 = N0->getOperand(1);
22429     SDValue CMP1 = N1->getOperand(1);
22430     SDLoc DL(N);
22431
22432     // The SETCCs should both refer to the same CMP.
22433     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
22434       return SDValue();
22435
22436     SDValue CMP00 = CMP0->getOperand(0);
22437     SDValue CMP01 = CMP0->getOperand(1);
22438     EVT     VT    = CMP00.getValueType();
22439
22440     if (VT == MVT::f32 || VT == MVT::f64) {
22441       bool ExpectingFlags = false;
22442       // Check for any users that want flags:
22443       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
22444            !ExpectingFlags && UI != UE; ++UI)
22445         switch (UI->getOpcode()) {
22446         default:
22447         case ISD::BR_CC:
22448         case ISD::BRCOND:
22449         case ISD::SELECT:
22450           ExpectingFlags = true;
22451           break;
22452         case ISD::CopyToReg:
22453         case ISD::SIGN_EXTEND:
22454         case ISD::ZERO_EXTEND:
22455         case ISD::ANY_EXTEND:
22456           break;
22457         }
22458
22459       if (!ExpectingFlags) {
22460         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
22461         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
22462
22463         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
22464           X86::CondCode tmp = cc0;
22465           cc0 = cc1;
22466           cc1 = tmp;
22467         }
22468
22469         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
22470             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
22471           // FIXME: need symbolic constants for these magic numbers.
22472           // See X86ATTInstPrinter.cpp:printSSECC().
22473           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
22474           if (Subtarget->hasAVX512()) {
22475             SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
22476                                          CMP01,
22477                                          DAG.getConstant(x86cc, DL, MVT::i8));
22478             if (N->getValueType(0) != MVT::i1)
22479               return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
22480                                  FSetCC);
22481             return FSetCC;
22482           }
22483           SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
22484                                               CMP00.getValueType(), CMP00, CMP01,
22485                                               DAG.getConstant(x86cc, DL,
22486                                                               MVT::i8));
22487
22488           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
22489           MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
22490
22491           if (is64BitFP && !Subtarget->is64Bit()) {
22492             // On a 32-bit target, we cannot bitcast the 64-bit float to a
22493             // 64-bit integer, since that's not a legal type. Since
22494             // OnesOrZeroesF is all ones of all zeroes, we don't need all the
22495             // bits, but can do this little dance to extract the lowest 32 bits
22496             // and work with those going forward.
22497             SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
22498                                            OnesOrZeroesF);
22499             SDValue Vector32 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f32,
22500                                            Vector64);
22501             OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
22502                                         Vector32, DAG.getIntPtrConstant(0, DL));
22503             IntVT = MVT::i32;
22504           }
22505
22506           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, IntVT,
22507                                               OnesOrZeroesF);
22508           SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
22509                                       DAG.getConstant(1, DL, IntVT));
22510           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8,
22511                                               ANDed);
22512           return OneBitOfTruth;
22513         }
22514       }
22515     }
22516   }
22517   return SDValue();
22518 }
22519
22520 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
22521 /// so it can be folded inside ANDNP.
22522 static bool CanFoldXORWithAllOnes(const SDNode *N) {
22523   EVT VT = N->getValueType(0);
22524
22525   // Match direct AllOnes for 128 and 256-bit vectors
22526   if (ISD::isBuildVectorAllOnes(N))
22527     return true;
22528
22529   // Look through a bit convert.
22530   if (N->getOpcode() == ISD::BITCAST)
22531     N = N->getOperand(0).getNode();
22532
22533   // Sometimes the operand may come from a insert_subvector building a 256-bit
22534   // allones vector
22535   if (VT.is256BitVector() &&
22536       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
22537     SDValue V1 = N->getOperand(0);
22538     SDValue V2 = N->getOperand(1);
22539
22540     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
22541         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
22542         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
22543         ISD::isBuildVectorAllOnes(V2.getNode()))
22544       return true;
22545   }
22546
22547   return false;
22548 }
22549
22550 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
22551 // register. In most cases we actually compare or select YMM-sized registers
22552 // and mixing the two types creates horrible code. This method optimizes
22553 // some of the transition sequences.
22554 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
22555                                  TargetLowering::DAGCombinerInfo &DCI,
22556                                  const X86Subtarget *Subtarget) {
22557   EVT VT = N->getValueType(0);
22558   if (!VT.is256BitVector())
22559     return SDValue();
22560
22561   assert((N->getOpcode() == ISD::ANY_EXTEND ||
22562           N->getOpcode() == ISD::ZERO_EXTEND ||
22563           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
22564
22565   SDValue Narrow = N->getOperand(0);
22566   EVT NarrowVT = Narrow->getValueType(0);
22567   if (!NarrowVT.is128BitVector())
22568     return SDValue();
22569
22570   if (Narrow->getOpcode() != ISD::XOR &&
22571       Narrow->getOpcode() != ISD::AND &&
22572       Narrow->getOpcode() != ISD::OR)
22573     return SDValue();
22574
22575   SDValue N0  = Narrow->getOperand(0);
22576   SDValue N1  = Narrow->getOperand(1);
22577   SDLoc DL(Narrow);
22578
22579   // The Left side has to be a trunc.
22580   if (N0.getOpcode() != ISD::TRUNCATE)
22581     return SDValue();
22582
22583   // The type of the truncated inputs.
22584   EVT WideVT = N0->getOperand(0)->getValueType(0);
22585   if (WideVT != VT)
22586     return SDValue();
22587
22588   // The right side has to be a 'trunc' or a constant vector.
22589   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
22590   ConstantSDNode *RHSConstSplat = nullptr;
22591   if (auto *RHSBV = dyn_cast<BuildVectorSDNode>(N1))
22592     RHSConstSplat = RHSBV->getConstantSplatNode();
22593   if (!RHSTrunc && !RHSConstSplat)
22594     return SDValue();
22595
22596   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22597
22598   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
22599     return SDValue();
22600
22601   // Set N0 and N1 to hold the inputs to the new wide operation.
22602   N0 = N0->getOperand(0);
22603   if (RHSConstSplat) {
22604     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
22605                      SDValue(RHSConstSplat, 0));
22606     SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
22607     N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
22608   } else if (RHSTrunc) {
22609     N1 = N1->getOperand(0);
22610   }
22611
22612   // Generate the wide operation.
22613   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
22614   unsigned Opcode = N->getOpcode();
22615   switch (Opcode) {
22616   case ISD::ANY_EXTEND:
22617     return Op;
22618   case ISD::ZERO_EXTEND: {
22619     unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
22620     APInt Mask = APInt::getAllOnesValue(InBits);
22621     Mask = Mask.zext(VT.getScalarType().getSizeInBits());
22622     return DAG.getNode(ISD::AND, DL, VT,
22623                        Op, DAG.getConstant(Mask, DL, VT));
22624   }
22625   case ISD::SIGN_EXTEND:
22626     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
22627                        Op, DAG.getValueType(NarrowVT));
22628   default:
22629     llvm_unreachable("Unexpected opcode");
22630   }
22631 }
22632
22633 static SDValue VectorZextCombine(SDNode *N, SelectionDAG &DAG,
22634                                  TargetLowering::DAGCombinerInfo &DCI,
22635                                  const X86Subtarget *Subtarget) {
22636   SDValue N0 = N->getOperand(0);
22637   SDValue N1 = N->getOperand(1);
22638   SDLoc DL(N);
22639
22640   // A vector zext_in_reg may be represented as a shuffle,
22641   // feeding into a bitcast (this represents anyext) feeding into
22642   // an and with a mask.
22643   // We'd like to try to combine that into a shuffle with zero
22644   // plus a bitcast, removing the and.
22645   if (N0.getOpcode() != ISD::BITCAST ||
22646       N0.getOperand(0).getOpcode() != ISD::VECTOR_SHUFFLE)
22647     return SDValue();
22648
22649   // The other side of the AND should be a splat of 2^C, where C
22650   // is the number of bits in the source type.
22651   if (N1.getOpcode() == ISD::BITCAST)
22652     N1 = N1.getOperand(0);
22653   if (N1.getOpcode() != ISD::BUILD_VECTOR)
22654     return SDValue();
22655   BuildVectorSDNode *Vector = cast<BuildVectorSDNode>(N1);
22656
22657   ShuffleVectorSDNode *Shuffle = cast<ShuffleVectorSDNode>(N0.getOperand(0));
22658   EVT SrcType = Shuffle->getValueType(0);
22659
22660   // We expect a single-source shuffle
22661   if (Shuffle->getOperand(1)->getOpcode() != ISD::UNDEF)
22662     return SDValue();
22663
22664   unsigned SrcSize = SrcType.getScalarSizeInBits();
22665
22666   APInt SplatValue, SplatUndef;
22667   unsigned SplatBitSize;
22668   bool HasAnyUndefs;
22669   if (!Vector->isConstantSplat(SplatValue, SplatUndef,
22670                                 SplatBitSize, HasAnyUndefs))
22671     return SDValue();
22672
22673   unsigned ResSize = N1.getValueType().getScalarSizeInBits();
22674   // Make sure the splat matches the mask we expect
22675   if (SplatBitSize > ResSize ||
22676       (SplatValue + 1).exactLogBase2() != (int)SrcSize)
22677     return SDValue();
22678
22679   // Make sure the input and output size make sense
22680   if (SrcSize >= ResSize || ResSize % SrcSize)
22681     return SDValue();
22682
22683   // We expect a shuffle of the form <0, u, u, u, 1, u, u, u...>
22684   // The number of u's between each two values depends on the ratio between
22685   // the source and dest type.
22686   unsigned ZextRatio = ResSize / SrcSize;
22687   bool IsZext = true;
22688   for (unsigned i = 0; i < SrcType.getVectorNumElements(); ++i) {
22689     if (i % ZextRatio) {
22690       if (Shuffle->getMaskElt(i) > 0) {
22691         // Expected undef
22692         IsZext = false;
22693         break;
22694       }
22695     } else {
22696       if (Shuffle->getMaskElt(i) != (int)(i / ZextRatio)) {
22697         // Expected element number
22698         IsZext = false;
22699         break;
22700       }
22701     }
22702   }
22703
22704   if (!IsZext)
22705     return SDValue();
22706
22707   // Ok, perform the transformation - replace the shuffle with
22708   // a shuffle of the form <0, k, k, k, 1, k, k, k> with zero
22709   // (instead of undef) where the k elements come from the zero vector.
22710   SmallVector<int, 8> Mask;
22711   unsigned NumElems = SrcType.getVectorNumElements();
22712   for (unsigned i = 0; i < NumElems; ++i)
22713     if (i % ZextRatio)
22714       Mask.push_back(NumElems);
22715     else
22716       Mask.push_back(i / ZextRatio);
22717
22718   SDValue NewShuffle = DAG.getVectorShuffle(Shuffle->getValueType(0), DL,
22719     Shuffle->getOperand(0), DAG.getConstant(0, DL, SrcType), Mask);
22720   return DAG.getNode(ISD::BITCAST, DL, N0.getValueType(), NewShuffle);
22721 }
22722
22723 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
22724                                  TargetLowering::DAGCombinerInfo &DCI,
22725                                  const X86Subtarget *Subtarget) {
22726   if (DCI.isBeforeLegalizeOps())
22727     return SDValue();
22728
22729   if (SDValue Zext = VectorZextCombine(N, DAG, DCI, Subtarget))
22730     return Zext;
22731
22732   if (SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget))
22733     return R;
22734
22735   EVT VT = N->getValueType(0);
22736   SDValue N0 = N->getOperand(0);
22737   SDValue N1 = N->getOperand(1);
22738   SDLoc DL(N);
22739
22740   // Create BEXTR instructions
22741   // BEXTR is ((X >> imm) & (2**size-1))
22742   if (VT == MVT::i32 || VT == MVT::i64) {
22743     // Check for BEXTR.
22744     if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
22745         (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
22746       ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
22747       ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
22748       if (MaskNode && ShiftNode) {
22749         uint64_t Mask = MaskNode->getZExtValue();
22750         uint64_t Shift = ShiftNode->getZExtValue();
22751         if (isMask_64(Mask)) {
22752           uint64_t MaskSize = countPopulation(Mask);
22753           if (Shift + MaskSize <= VT.getSizeInBits())
22754             return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
22755                                DAG.getConstant(Shift | (MaskSize << 8), DL,
22756                                                VT));
22757         }
22758       }
22759     } // BEXTR
22760
22761     return SDValue();
22762   }
22763
22764   // Want to form ANDNP nodes:
22765   // 1) In the hopes of then easily combining them with OR and AND nodes
22766   //    to form PBLEND/PSIGN.
22767   // 2) To match ANDN packed intrinsics
22768   if (VT != MVT::v2i64 && VT != MVT::v4i64)
22769     return SDValue();
22770
22771   // Check LHS for vnot
22772   if (N0.getOpcode() == ISD::XOR &&
22773       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
22774       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
22775     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
22776
22777   // Check RHS for vnot
22778   if (N1.getOpcode() == ISD::XOR &&
22779       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
22780       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
22781     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
22782
22783   return SDValue();
22784 }
22785
22786 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
22787                                 TargetLowering::DAGCombinerInfo &DCI,
22788                                 const X86Subtarget *Subtarget) {
22789   if (DCI.isBeforeLegalizeOps())
22790     return SDValue();
22791
22792   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
22793   if (R.getNode())
22794     return R;
22795
22796   SDValue N0 = N->getOperand(0);
22797   SDValue N1 = N->getOperand(1);
22798   EVT VT = N->getValueType(0);
22799
22800   // look for psign/blend
22801   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
22802     if (!Subtarget->hasSSSE3() ||
22803         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
22804       return SDValue();
22805
22806     // Canonicalize pandn to RHS
22807     if (N0.getOpcode() == X86ISD::ANDNP)
22808       std::swap(N0, N1);
22809     // or (and (m, y), (pandn m, x))
22810     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
22811       SDValue Mask = N1.getOperand(0);
22812       SDValue X    = N1.getOperand(1);
22813       SDValue Y;
22814       if (N0.getOperand(0) == Mask)
22815         Y = N0.getOperand(1);
22816       if (N0.getOperand(1) == Mask)
22817         Y = N0.getOperand(0);
22818
22819       // Check to see if the mask appeared in both the AND and ANDNP and
22820       if (!Y.getNode())
22821         return SDValue();
22822
22823       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
22824       // Look through mask bitcast.
22825       if (Mask.getOpcode() == ISD::BITCAST)
22826         Mask = Mask.getOperand(0);
22827       if (X.getOpcode() == ISD::BITCAST)
22828         X = X.getOperand(0);
22829       if (Y.getOpcode() == ISD::BITCAST)
22830         Y = Y.getOperand(0);
22831
22832       EVT MaskVT = Mask.getValueType();
22833
22834       // Validate that the Mask operand is a vector sra node.
22835       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
22836       // there is no psrai.b
22837       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
22838       unsigned SraAmt = ~0;
22839       if (Mask.getOpcode() == ISD::SRA) {
22840         if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Mask.getOperand(1)))
22841           if (auto *AmtConst = AmtBV->getConstantSplatNode())
22842             SraAmt = AmtConst->getZExtValue();
22843       } else if (Mask.getOpcode() == X86ISD::VSRAI) {
22844         SDValue SraC = Mask.getOperand(1);
22845         SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
22846       }
22847       if ((SraAmt + 1) != EltBits)
22848         return SDValue();
22849
22850       SDLoc DL(N);
22851
22852       // Now we know we at least have a plendvb with the mask val.  See if
22853       // we can form a psignb/w/d.
22854       // psign = x.type == y.type == mask.type && y = sub(0, x);
22855       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
22856           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
22857           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
22858         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
22859                "Unsupported VT for PSIGN");
22860         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
22861         return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
22862       }
22863       // PBLENDVB only available on SSE 4.1
22864       if (!Subtarget->hasSSE41())
22865         return SDValue();
22866
22867       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
22868
22869       X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
22870       Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
22871       Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
22872       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
22873       return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
22874     }
22875   }
22876
22877   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
22878     return SDValue();
22879
22880   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
22881   MachineFunction &MF = DAG.getMachineFunction();
22882   bool OptForSize =
22883       MF.getFunction()->hasFnAttribute(Attribute::OptimizeForSize);
22884
22885   // SHLD/SHRD instructions have lower register pressure, but on some
22886   // platforms they have higher latency than the equivalent
22887   // series of shifts/or that would otherwise be generated.
22888   // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
22889   // have higher latencies and we are not optimizing for size.
22890   if (!OptForSize && Subtarget->isSHLDSlow())
22891     return SDValue();
22892
22893   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
22894     std::swap(N0, N1);
22895   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
22896     return SDValue();
22897   if (!N0.hasOneUse() || !N1.hasOneUse())
22898     return SDValue();
22899
22900   SDValue ShAmt0 = N0.getOperand(1);
22901   if (ShAmt0.getValueType() != MVT::i8)
22902     return SDValue();
22903   SDValue ShAmt1 = N1.getOperand(1);
22904   if (ShAmt1.getValueType() != MVT::i8)
22905     return SDValue();
22906   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
22907     ShAmt0 = ShAmt0.getOperand(0);
22908   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
22909     ShAmt1 = ShAmt1.getOperand(0);
22910
22911   SDLoc DL(N);
22912   unsigned Opc = X86ISD::SHLD;
22913   SDValue Op0 = N0.getOperand(0);
22914   SDValue Op1 = N1.getOperand(0);
22915   if (ShAmt0.getOpcode() == ISD::SUB) {
22916     Opc = X86ISD::SHRD;
22917     std::swap(Op0, Op1);
22918     std::swap(ShAmt0, ShAmt1);
22919   }
22920
22921   unsigned Bits = VT.getSizeInBits();
22922   if (ShAmt1.getOpcode() == ISD::SUB) {
22923     SDValue Sum = ShAmt1.getOperand(0);
22924     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
22925       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
22926       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
22927         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
22928       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
22929         return DAG.getNode(Opc, DL, VT,
22930                            Op0, Op1,
22931                            DAG.getNode(ISD::TRUNCATE, DL,
22932                                        MVT::i8, ShAmt0));
22933     }
22934   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
22935     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
22936     if (ShAmt0C &&
22937         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
22938       return DAG.getNode(Opc, DL, VT,
22939                          N0.getOperand(0), N1.getOperand(0),
22940                          DAG.getNode(ISD::TRUNCATE, DL,
22941                                        MVT::i8, ShAmt0));
22942   }
22943
22944   return SDValue();
22945 }
22946
22947 // Generate NEG and CMOV for integer abs.
22948 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
22949   EVT VT = N->getValueType(0);
22950
22951   // Since X86 does not have CMOV for 8-bit integer, we don't convert
22952   // 8-bit integer abs to NEG and CMOV.
22953   if (VT.isInteger() && VT.getSizeInBits() == 8)
22954     return SDValue();
22955
22956   SDValue N0 = N->getOperand(0);
22957   SDValue N1 = N->getOperand(1);
22958   SDLoc DL(N);
22959
22960   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
22961   // and change it to SUB and CMOV.
22962   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
22963       N0.getOpcode() == ISD::ADD &&
22964       N0.getOperand(1) == N1 &&
22965       N1.getOpcode() == ISD::SRA &&
22966       N1.getOperand(0) == N0.getOperand(0))
22967     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
22968       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
22969         // Generate SUB & CMOV.
22970         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
22971                                   DAG.getConstant(0, DL, VT), N0.getOperand(0));
22972
22973         SDValue Ops[] = { N0.getOperand(0), Neg,
22974                           DAG.getConstant(X86::COND_GE, DL, MVT::i8),
22975                           SDValue(Neg.getNode(), 1) };
22976         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
22977       }
22978   return SDValue();
22979 }
22980
22981 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
22982 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
22983                                  TargetLowering::DAGCombinerInfo &DCI,
22984                                  const X86Subtarget *Subtarget) {
22985   if (DCI.isBeforeLegalizeOps())
22986     return SDValue();
22987
22988   if (Subtarget->hasCMov()) {
22989     SDValue RV = performIntegerAbsCombine(N, DAG);
22990     if (RV.getNode())
22991       return RV;
22992   }
22993
22994   return SDValue();
22995 }
22996
22997 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
22998 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
22999                                   TargetLowering::DAGCombinerInfo &DCI,
23000                                   const X86Subtarget *Subtarget) {
23001   LoadSDNode *Ld = cast<LoadSDNode>(N);
23002   EVT RegVT = Ld->getValueType(0);
23003   EVT MemVT = Ld->getMemoryVT();
23004   SDLoc dl(Ld);
23005   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23006
23007   // For chips with slow 32-byte unaligned loads, break the 32-byte operation
23008   // into two 16-byte operations.
23009   ISD::LoadExtType Ext = Ld->getExtensionType();
23010   unsigned Alignment = Ld->getAlignment();
23011   bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
23012   if (RegVT.is256BitVector() && Subtarget->isUnalignedMem32Slow() &&
23013       !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
23014     unsigned NumElems = RegVT.getVectorNumElements();
23015     if (NumElems < 2)
23016       return SDValue();
23017
23018     SDValue Ptr = Ld->getBasePtr();
23019     SDValue Increment = DAG.getConstant(16, dl, TLI.getPointerTy());
23020
23021     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
23022                                   NumElems/2);
23023     SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
23024                                 Ld->getPointerInfo(), Ld->isVolatile(),
23025                                 Ld->isNonTemporal(), Ld->isInvariant(),
23026                                 Alignment);
23027     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
23028     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
23029                                 Ld->getPointerInfo(), Ld->isVolatile(),
23030                                 Ld->isNonTemporal(), Ld->isInvariant(),
23031                                 std::min(16U, Alignment));
23032     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
23033                              Load1.getValue(1),
23034                              Load2.getValue(1));
23035
23036     SDValue NewVec = DAG.getUNDEF(RegVT);
23037     NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
23038     NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
23039     return DCI.CombineTo(N, NewVec, TF, true);
23040   }
23041
23042   return SDValue();
23043 }
23044
23045 /// PerformMLOADCombine - Resolve extending loads
23046 static SDValue PerformMLOADCombine(SDNode *N, SelectionDAG &DAG,
23047                                    TargetLowering::DAGCombinerInfo &DCI,
23048                                    const X86Subtarget *Subtarget) {
23049   MaskedLoadSDNode *Mld = cast<MaskedLoadSDNode>(N);
23050   if (Mld->getExtensionType() != ISD::SEXTLOAD)
23051     return SDValue();
23052
23053   EVT VT = Mld->getValueType(0);
23054   unsigned NumElems = VT.getVectorNumElements();
23055   EVT LdVT = Mld->getMemoryVT();
23056   SDLoc dl(Mld);
23057
23058   assert(LdVT != VT && "Cannot extend to the same type");
23059   unsigned ToSz = VT.getVectorElementType().getSizeInBits();
23060   unsigned FromSz = LdVT.getVectorElementType().getSizeInBits();
23061   // From, To sizes and ElemCount must be pow of two
23062   assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
23063     "Unexpected size for extending masked load");
23064
23065   unsigned SizeRatio  = ToSz / FromSz;
23066   assert(SizeRatio * NumElems * FromSz == VT.getSizeInBits());
23067
23068   // Create a type on which we perform the shuffle
23069   EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
23070           LdVT.getScalarType(), NumElems*SizeRatio);
23071   assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
23072
23073   // Convert Src0 value
23074   SDValue WideSrc0 = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Mld->getSrc0());
23075   if (Mld->getSrc0().getOpcode() != ISD::UNDEF) {
23076     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
23077     for (unsigned i = 0; i != NumElems; ++i)
23078       ShuffleVec[i] = i * SizeRatio;
23079
23080     // Can't shuffle using an illegal type.
23081     assert (DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT)
23082             && "WideVecVT should be legal");
23083     WideSrc0 = DAG.getVectorShuffle(WideVecVT, dl, WideSrc0,
23084                                     DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
23085   }
23086   // Prepare the new mask
23087   SDValue NewMask;
23088   SDValue Mask = Mld->getMask();
23089   if (Mask.getValueType() == VT) {
23090     // Mask and original value have the same type
23091     NewMask = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Mask);
23092     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
23093     for (unsigned i = 0; i != NumElems; ++i)
23094       ShuffleVec[i] = i * SizeRatio;
23095     for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
23096       ShuffleVec[i] = NumElems*SizeRatio;
23097     NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
23098                                    DAG.getConstant(0, dl, WideVecVT),
23099                                    &ShuffleVec[0]);
23100   }
23101   else {
23102     assert(Mask.getValueType().getVectorElementType() == MVT::i1);
23103     unsigned WidenNumElts = NumElems*SizeRatio;
23104     unsigned MaskNumElts = VT.getVectorNumElements();
23105     EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(),  MVT::i1,
23106                                      WidenNumElts);
23107
23108     unsigned NumConcat = WidenNumElts / MaskNumElts;
23109     SmallVector<SDValue, 16> Ops(NumConcat);
23110     SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
23111     Ops[0] = Mask;
23112     for (unsigned i = 1; i != NumConcat; ++i)
23113       Ops[i] = ZeroVal;
23114
23115     NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
23116   }
23117
23118   SDValue WideLd = DAG.getMaskedLoad(WideVecVT, dl, Mld->getChain(),
23119                                      Mld->getBasePtr(), NewMask, WideSrc0,
23120                                      Mld->getMemoryVT(), Mld->getMemOperand(),
23121                                      ISD::NON_EXTLOAD);
23122   SDValue NewVec = DAG.getNode(X86ISD::VSEXT, dl, VT, WideLd);
23123   return DCI.CombineTo(N, NewVec, WideLd.getValue(1), true);
23124
23125 }
23126 /// PerformMSTORECombine - Resolve truncating stores
23127 static SDValue PerformMSTORECombine(SDNode *N, SelectionDAG &DAG,
23128                                     const X86Subtarget *Subtarget) {
23129   MaskedStoreSDNode *Mst = cast<MaskedStoreSDNode>(N);
23130   if (!Mst->isTruncatingStore())
23131     return SDValue();
23132
23133   EVT VT = Mst->getValue().getValueType();
23134   unsigned NumElems = VT.getVectorNumElements();
23135   EVT StVT = Mst->getMemoryVT();
23136   SDLoc dl(Mst);
23137
23138   assert(StVT != VT && "Cannot truncate to the same type");
23139   unsigned FromSz = VT.getVectorElementType().getSizeInBits();
23140   unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
23141
23142   // From, To sizes and ElemCount must be pow of two
23143   assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
23144     "Unexpected size for truncating masked store");
23145   // We are going to use the original vector elt for storing.
23146   // Accumulated smaller vector elements must be a multiple of the store size.
23147   assert (((NumElems * FromSz) % ToSz) == 0 &&
23148           "Unexpected ratio for truncating masked store");
23149
23150   unsigned SizeRatio  = FromSz / ToSz;
23151   assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
23152
23153   // Create a type on which we perform the shuffle
23154   EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
23155           StVT.getScalarType(), NumElems*SizeRatio);
23156
23157   assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
23158
23159   SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Mst->getValue());
23160   SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
23161   for (unsigned i = 0; i != NumElems; ++i)
23162     ShuffleVec[i] = i * SizeRatio;
23163
23164   // Can't shuffle using an illegal type.
23165   assert (DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT)
23166           && "WideVecVT should be legal");
23167
23168   SDValue TruncatedVal = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
23169                                         DAG.getUNDEF(WideVecVT),
23170                                         &ShuffleVec[0]);
23171
23172   SDValue NewMask;
23173   SDValue Mask = Mst->getMask();
23174   if (Mask.getValueType() == VT) {
23175     // Mask and original value have the same type
23176     NewMask = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Mask);
23177     for (unsigned i = 0; i != NumElems; ++i)
23178       ShuffleVec[i] = i * SizeRatio;
23179     for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
23180       ShuffleVec[i] = NumElems*SizeRatio;
23181     NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
23182                                    DAG.getConstant(0, dl, WideVecVT),
23183                                    &ShuffleVec[0]);
23184   }
23185   else {
23186     assert(Mask.getValueType().getVectorElementType() == MVT::i1);
23187     unsigned WidenNumElts = NumElems*SizeRatio;
23188     unsigned MaskNumElts = VT.getVectorNumElements();
23189     EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(),  MVT::i1,
23190                                      WidenNumElts);
23191
23192     unsigned NumConcat = WidenNumElts / MaskNumElts;
23193     SmallVector<SDValue, 16> Ops(NumConcat);
23194     SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
23195     Ops[0] = Mask;
23196     for (unsigned i = 1; i != NumConcat; ++i)
23197       Ops[i] = ZeroVal;
23198
23199     NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
23200   }
23201
23202   return DAG.getMaskedStore(Mst->getChain(), dl, TruncatedVal, Mst->getBasePtr(),
23203                             NewMask, StVT, Mst->getMemOperand(), false);
23204 }
23205 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
23206 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
23207                                    const X86Subtarget *Subtarget) {
23208   StoreSDNode *St = cast<StoreSDNode>(N);
23209   EVT VT = St->getValue().getValueType();
23210   EVT StVT = St->getMemoryVT();
23211   SDLoc dl(St);
23212   SDValue StoredVal = St->getOperand(1);
23213   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23214
23215   // If we are saving a concatenation of two XMM registers and 32-byte stores
23216   // are slow, such as on Sandy Bridge, perform two 16-byte stores.
23217   unsigned Alignment = St->getAlignment();
23218   bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
23219   if (VT.is256BitVector() && Subtarget->isUnalignedMem32Slow() &&
23220       StVT == VT && !IsAligned) {
23221     unsigned NumElems = VT.getVectorNumElements();
23222     if (NumElems < 2)
23223       return SDValue();
23224
23225     SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
23226     SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
23227
23228     SDValue Stride = DAG.getConstant(16, dl, TLI.getPointerTy());
23229     SDValue Ptr0 = St->getBasePtr();
23230     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
23231
23232     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
23233                                 St->getPointerInfo(), St->isVolatile(),
23234                                 St->isNonTemporal(), Alignment);
23235     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
23236                                 St->getPointerInfo(), St->isVolatile(),
23237                                 St->isNonTemporal(),
23238                                 std::min(16U, Alignment));
23239     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
23240   }
23241
23242   // Optimize trunc store (of multiple scalars) to shuffle and store.
23243   // First, pack all of the elements in one place. Next, store to memory
23244   // in fewer chunks.
23245   if (St->isTruncatingStore() && VT.isVector()) {
23246     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23247     unsigned NumElems = VT.getVectorNumElements();
23248     assert(StVT != VT && "Cannot truncate to the same type");
23249     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
23250     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
23251
23252     // From, To sizes and ElemCount must be pow of two
23253     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
23254     // We are going to use the original vector elt for storing.
23255     // Accumulated smaller vector elements must be a multiple of the store size.
23256     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
23257
23258     unsigned SizeRatio  = FromSz / ToSz;
23259
23260     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
23261
23262     // Create a type on which we perform the shuffle
23263     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
23264             StVT.getScalarType(), NumElems*SizeRatio);
23265
23266     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
23267
23268     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
23269     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
23270     for (unsigned i = 0; i != NumElems; ++i)
23271       ShuffleVec[i] = i * SizeRatio;
23272
23273     // Can't shuffle using an illegal type.
23274     if (!TLI.isTypeLegal(WideVecVT))
23275       return SDValue();
23276
23277     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
23278                                          DAG.getUNDEF(WideVecVT),
23279                                          &ShuffleVec[0]);
23280     // At this point all of the data is stored at the bottom of the
23281     // register. We now need to save it to mem.
23282
23283     // Find the largest store unit
23284     MVT StoreType = MVT::i8;
23285     for (MVT Tp : MVT::integer_valuetypes()) {
23286       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
23287         StoreType = Tp;
23288     }
23289
23290     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
23291     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
23292         (64 <= NumElems * ToSz))
23293       StoreType = MVT::f64;
23294
23295     // Bitcast the original vector into a vector of store-size units
23296     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
23297             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
23298     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
23299     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
23300     SmallVector<SDValue, 8> Chains;
23301     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8, dl,
23302                                         TLI.getPointerTy());
23303     SDValue Ptr = St->getBasePtr();
23304
23305     // Perform one or more big stores into memory.
23306     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
23307       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
23308                                    StoreType, ShuffWide,
23309                                    DAG.getIntPtrConstant(i, dl));
23310       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
23311                                 St->getPointerInfo(), St->isVolatile(),
23312                                 St->isNonTemporal(), St->getAlignment());
23313       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
23314       Chains.push_back(Ch);
23315     }
23316
23317     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
23318   }
23319
23320   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
23321   // the FP state in cases where an emms may be missing.
23322   // A preferable solution to the general problem is to figure out the right
23323   // places to insert EMMS.  This qualifies as a quick hack.
23324
23325   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
23326   if (VT.getSizeInBits() != 64)
23327     return SDValue();
23328
23329   const Function *F = DAG.getMachineFunction().getFunction();
23330   bool NoImplicitFloatOps = F->hasFnAttribute(Attribute::NoImplicitFloat);
23331   bool F64IsLegal =
23332       !Subtarget->useSoftFloat() && !NoImplicitFloatOps && Subtarget->hasSSE2();
23333   if ((VT.isVector() ||
23334        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
23335       isa<LoadSDNode>(St->getValue()) &&
23336       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
23337       St->getChain().hasOneUse() && !St->isVolatile()) {
23338     SDNode* LdVal = St->getValue().getNode();
23339     LoadSDNode *Ld = nullptr;
23340     int TokenFactorIndex = -1;
23341     SmallVector<SDValue, 8> Ops;
23342     SDNode* ChainVal = St->getChain().getNode();
23343     // Must be a store of a load.  We currently handle two cases:  the load
23344     // is a direct child, and it's under an intervening TokenFactor.  It is
23345     // possible to dig deeper under nested TokenFactors.
23346     if (ChainVal == LdVal)
23347       Ld = cast<LoadSDNode>(St->getChain());
23348     else if (St->getValue().hasOneUse() &&
23349              ChainVal->getOpcode() == ISD::TokenFactor) {
23350       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
23351         if (ChainVal->getOperand(i).getNode() == LdVal) {
23352           TokenFactorIndex = i;
23353           Ld = cast<LoadSDNode>(St->getValue());
23354         } else
23355           Ops.push_back(ChainVal->getOperand(i));
23356       }
23357     }
23358
23359     if (!Ld || !ISD::isNormalLoad(Ld))
23360       return SDValue();
23361
23362     // If this is not the MMX case, i.e. we are just turning i64 load/store
23363     // into f64 load/store, avoid the transformation if there are multiple
23364     // uses of the loaded value.
23365     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
23366       return SDValue();
23367
23368     SDLoc LdDL(Ld);
23369     SDLoc StDL(N);
23370     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
23371     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
23372     // pair instead.
23373     if (Subtarget->is64Bit() || F64IsLegal) {
23374       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
23375       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
23376                                   Ld->getPointerInfo(), Ld->isVolatile(),
23377                                   Ld->isNonTemporal(), Ld->isInvariant(),
23378                                   Ld->getAlignment());
23379       SDValue NewChain = NewLd.getValue(1);
23380       if (TokenFactorIndex != -1) {
23381         Ops.push_back(NewChain);
23382         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
23383       }
23384       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
23385                           St->getPointerInfo(),
23386                           St->isVolatile(), St->isNonTemporal(),
23387                           St->getAlignment());
23388     }
23389
23390     // Otherwise, lower to two pairs of 32-bit loads / stores.
23391     SDValue LoAddr = Ld->getBasePtr();
23392     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
23393                                  DAG.getConstant(4, LdDL, MVT::i32));
23394
23395     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
23396                                Ld->getPointerInfo(),
23397                                Ld->isVolatile(), Ld->isNonTemporal(),
23398                                Ld->isInvariant(), Ld->getAlignment());
23399     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
23400                                Ld->getPointerInfo().getWithOffset(4),
23401                                Ld->isVolatile(), Ld->isNonTemporal(),
23402                                Ld->isInvariant(),
23403                                MinAlign(Ld->getAlignment(), 4));
23404
23405     SDValue NewChain = LoLd.getValue(1);
23406     if (TokenFactorIndex != -1) {
23407       Ops.push_back(LoLd);
23408       Ops.push_back(HiLd);
23409       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
23410     }
23411
23412     LoAddr = St->getBasePtr();
23413     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
23414                          DAG.getConstant(4, StDL, MVT::i32));
23415
23416     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
23417                                 St->getPointerInfo(),
23418                                 St->isVolatile(), St->isNonTemporal(),
23419                                 St->getAlignment());
23420     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
23421                                 St->getPointerInfo().getWithOffset(4),
23422                                 St->isVolatile(),
23423                                 St->isNonTemporal(),
23424                                 MinAlign(St->getAlignment(), 4));
23425     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
23426   }
23427
23428   // This is similar to the above case, but here we handle a scalar 64-bit
23429   // integer store that is extracted from a vector on a 32-bit target.
23430   // If we have SSE2, then we can treat it like a floating-point double
23431   // to get past legalization. The execution dependencies fixup pass will
23432   // choose the optimal machine instruction for the store if this really is
23433   // an integer or v2f32 rather than an f64.
23434   if (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit() &&
23435       St->getOperand(1).getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
23436     SDValue OldExtract = St->getOperand(1);
23437     SDValue ExtOp0 = OldExtract.getOperand(0);
23438     unsigned VecSize = ExtOp0.getValueSizeInBits();
23439     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, VecSize / 64);
23440     SDValue BitCast = DAG.getNode(ISD::BITCAST, dl, VecVT, ExtOp0);
23441     SDValue NewExtract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
23442                                      BitCast, OldExtract.getOperand(1));
23443     return DAG.getStore(St->getChain(), dl, NewExtract, St->getBasePtr(),
23444                         St->getPointerInfo(), St->isVolatile(),
23445                         St->isNonTemporal(), St->getAlignment());
23446   }
23447
23448   return SDValue();
23449 }
23450
23451 /// Return 'true' if this vector operation is "horizontal"
23452 /// and return the operands for the horizontal operation in LHS and RHS.  A
23453 /// horizontal operation performs the binary operation on successive elements
23454 /// of its first operand, then on successive elements of its second operand,
23455 /// returning the resulting values in a vector.  For example, if
23456 ///   A = < float a0, float a1, float a2, float a3 >
23457 /// and
23458 ///   B = < float b0, float b1, float b2, float b3 >
23459 /// then the result of doing a horizontal operation on A and B is
23460 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
23461 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
23462 /// A horizontal-op B, for some already available A and B, and if so then LHS is
23463 /// set to A, RHS to B, and the routine returns 'true'.
23464 /// Note that the binary operation should have the property that if one of the
23465 /// operands is UNDEF then the result is UNDEF.
23466 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
23467   // Look for the following pattern: if
23468   //   A = < float a0, float a1, float a2, float a3 >
23469   //   B = < float b0, float b1, float b2, float b3 >
23470   // and
23471   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
23472   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
23473   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
23474   // which is A horizontal-op B.
23475
23476   // At least one of the operands should be a vector shuffle.
23477   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
23478       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
23479     return false;
23480
23481   MVT VT = LHS.getSimpleValueType();
23482
23483   assert((VT.is128BitVector() || VT.is256BitVector()) &&
23484          "Unsupported vector type for horizontal add/sub");
23485
23486   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
23487   // operate independently on 128-bit lanes.
23488   unsigned NumElts = VT.getVectorNumElements();
23489   unsigned NumLanes = VT.getSizeInBits()/128;
23490   unsigned NumLaneElts = NumElts / NumLanes;
23491   assert((NumLaneElts % 2 == 0) &&
23492          "Vector type should have an even number of elements in each lane");
23493   unsigned HalfLaneElts = NumLaneElts/2;
23494
23495   // View LHS in the form
23496   //   LHS = VECTOR_SHUFFLE A, B, LMask
23497   // If LHS is not a shuffle then pretend it is the shuffle
23498   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
23499   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
23500   // type VT.
23501   SDValue A, B;
23502   SmallVector<int, 16> LMask(NumElts);
23503   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
23504     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
23505       A = LHS.getOperand(0);
23506     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
23507       B = LHS.getOperand(1);
23508     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
23509     std::copy(Mask.begin(), Mask.end(), LMask.begin());
23510   } else {
23511     if (LHS.getOpcode() != ISD::UNDEF)
23512       A = LHS;
23513     for (unsigned i = 0; i != NumElts; ++i)
23514       LMask[i] = i;
23515   }
23516
23517   // Likewise, view RHS in the form
23518   //   RHS = VECTOR_SHUFFLE C, D, RMask
23519   SDValue C, D;
23520   SmallVector<int, 16> RMask(NumElts);
23521   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
23522     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
23523       C = RHS.getOperand(0);
23524     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
23525       D = RHS.getOperand(1);
23526     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
23527     std::copy(Mask.begin(), Mask.end(), RMask.begin());
23528   } else {
23529     if (RHS.getOpcode() != ISD::UNDEF)
23530       C = RHS;
23531     for (unsigned i = 0; i != NumElts; ++i)
23532       RMask[i] = i;
23533   }
23534
23535   // Check that the shuffles are both shuffling the same vectors.
23536   if (!(A == C && B == D) && !(A == D && B == C))
23537     return false;
23538
23539   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
23540   if (!A.getNode() && !B.getNode())
23541     return false;
23542
23543   // If A and B occur in reverse order in RHS, then "swap" them (which means
23544   // rewriting the mask).
23545   if (A != C)
23546     ShuffleVectorSDNode::commuteMask(RMask);
23547
23548   // At this point LHS and RHS are equivalent to
23549   //   LHS = VECTOR_SHUFFLE A, B, LMask
23550   //   RHS = VECTOR_SHUFFLE A, B, RMask
23551   // Check that the masks correspond to performing a horizontal operation.
23552   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
23553     for (unsigned i = 0; i != NumLaneElts; ++i) {
23554       int LIdx = LMask[i+l], RIdx = RMask[i+l];
23555
23556       // Ignore any UNDEF components.
23557       if (LIdx < 0 || RIdx < 0 ||
23558           (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
23559           (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
23560         continue;
23561
23562       // Check that successive elements are being operated on.  If not, this is
23563       // not a horizontal operation.
23564       unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
23565       int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
23566       if (!(LIdx == Index && RIdx == Index + 1) &&
23567           !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
23568         return false;
23569     }
23570   }
23571
23572   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
23573   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
23574   return true;
23575 }
23576
23577 /// Do target-specific dag combines on floating point adds.
23578 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
23579                                   const X86Subtarget *Subtarget) {
23580   EVT VT = N->getValueType(0);
23581   SDValue LHS = N->getOperand(0);
23582   SDValue RHS = N->getOperand(1);
23583
23584   // Try to synthesize horizontal adds from adds of shuffles.
23585   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
23586        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
23587       isHorizontalBinOp(LHS, RHS, true))
23588     return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
23589   return SDValue();
23590 }
23591
23592 /// Do target-specific dag combines on floating point subs.
23593 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
23594                                   const X86Subtarget *Subtarget) {
23595   EVT VT = N->getValueType(0);
23596   SDValue LHS = N->getOperand(0);
23597   SDValue RHS = N->getOperand(1);
23598
23599   // Try to synthesize horizontal subs from subs of shuffles.
23600   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
23601        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
23602       isHorizontalBinOp(LHS, RHS, false))
23603     return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
23604   return SDValue();
23605 }
23606
23607 /// Do target-specific dag combines on X86ISD::FOR and X86ISD::FXOR nodes.
23608 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
23609   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
23610
23611   // F[X]OR(0.0, x) -> x
23612   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
23613     if (C->getValueAPF().isPosZero())
23614       return N->getOperand(1);
23615
23616   // F[X]OR(x, 0.0) -> x
23617   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
23618     if (C->getValueAPF().isPosZero())
23619       return N->getOperand(0);
23620   return SDValue();
23621 }
23622
23623 /// Do target-specific dag combines on X86ISD::FMIN and X86ISD::FMAX nodes.
23624 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
23625   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
23626
23627   // Only perform optimizations if UnsafeMath is used.
23628   if (!DAG.getTarget().Options.UnsafeFPMath)
23629     return SDValue();
23630
23631   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
23632   // into FMINC and FMAXC, which are Commutative operations.
23633   unsigned NewOp = 0;
23634   switch (N->getOpcode()) {
23635     default: llvm_unreachable("unknown opcode");
23636     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
23637     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
23638   }
23639
23640   return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
23641                      N->getOperand(0), N->getOperand(1));
23642 }
23643
23644 /// Do target-specific dag combines on X86ISD::FAND nodes.
23645 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
23646   // FAND(0.0, x) -> 0.0
23647   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
23648     if (C->getValueAPF().isPosZero())
23649       return N->getOperand(0);
23650
23651   // FAND(x, 0.0) -> 0.0
23652   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
23653     if (C->getValueAPF().isPosZero())
23654       return N->getOperand(1);
23655
23656   return SDValue();
23657 }
23658
23659 /// Do target-specific dag combines on X86ISD::FANDN nodes
23660 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
23661   // FANDN(0.0, x) -> x
23662   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
23663     if (C->getValueAPF().isPosZero())
23664       return N->getOperand(1);
23665
23666   // FANDN(x, 0.0) -> 0.0
23667   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
23668     if (C->getValueAPF().isPosZero())
23669       return N->getOperand(1);
23670
23671   return SDValue();
23672 }
23673
23674 static SDValue PerformBTCombine(SDNode *N,
23675                                 SelectionDAG &DAG,
23676                                 TargetLowering::DAGCombinerInfo &DCI) {
23677   // BT ignores high bits in the bit index operand.
23678   SDValue Op1 = N->getOperand(1);
23679   if (Op1.hasOneUse()) {
23680     unsigned BitWidth = Op1.getValueSizeInBits();
23681     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
23682     APInt KnownZero, KnownOne;
23683     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
23684                                           !DCI.isBeforeLegalizeOps());
23685     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23686     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
23687         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
23688       DCI.CommitTargetLoweringOpt(TLO);
23689   }
23690   return SDValue();
23691 }
23692
23693 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
23694   SDValue Op = N->getOperand(0);
23695   if (Op.getOpcode() == ISD::BITCAST)
23696     Op = Op.getOperand(0);
23697   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
23698   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
23699       VT.getVectorElementType().getSizeInBits() ==
23700       OpVT.getVectorElementType().getSizeInBits()) {
23701     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
23702   }
23703   return SDValue();
23704 }
23705
23706 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
23707                                                const X86Subtarget *Subtarget) {
23708   EVT VT = N->getValueType(0);
23709   if (!VT.isVector())
23710     return SDValue();
23711
23712   SDValue N0 = N->getOperand(0);
23713   SDValue N1 = N->getOperand(1);
23714   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
23715   SDLoc dl(N);
23716
23717   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
23718   // both SSE and AVX2 since there is no sign-extended shift right
23719   // operation on a vector with 64-bit elements.
23720   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
23721   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
23722   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
23723       N0.getOpcode() == ISD::SIGN_EXTEND)) {
23724     SDValue N00 = N0.getOperand(0);
23725
23726     // EXTLOAD has a better solution on AVX2,
23727     // it may be replaced with X86ISD::VSEXT node.
23728     if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
23729       if (!ISD::isNormalLoad(N00.getNode()))
23730         return SDValue();
23731
23732     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
23733         SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
23734                                   N00, N1);
23735       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
23736     }
23737   }
23738   return SDValue();
23739 }
23740
23741 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
23742                                   TargetLowering::DAGCombinerInfo &DCI,
23743                                   const X86Subtarget *Subtarget) {
23744   SDValue N0 = N->getOperand(0);
23745   EVT VT = N->getValueType(0);
23746   EVT SVT = VT.getScalarType();
23747   EVT InVT = N0->getValueType(0);
23748   EVT InSVT = InVT.getScalarType();
23749   SDLoc DL(N);
23750
23751   // (i8,i32 sext (sdivrem (i8 x, i8 y)) ->
23752   // (i8,i32 (sdivrem_sext_hreg (i8 x, i8 y)
23753   // This exposes the sext to the sdivrem lowering, so that it directly extends
23754   // from AH (which we otherwise need to do contortions to access).
23755   if (N0.getOpcode() == ISD::SDIVREM && N0.getResNo() == 1 &&
23756       InVT == MVT::i8 && VT == MVT::i32) {
23757     SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
23758     SDValue R = DAG.getNode(X86ISD::SDIVREM8_SEXT_HREG, DL, NodeTys,
23759                             N0.getOperand(0), N0.getOperand(1));
23760     DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
23761     return R.getValue(1);
23762   }
23763
23764   if (!DCI.isBeforeLegalizeOps()) {
23765     if (N0.getValueType() == MVT::i1) {
23766       SDValue Zero = DAG.getConstant(0, DL, VT);
23767       SDValue AllOnes =
23768         DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), DL, VT);
23769       return DAG.getNode(ISD::SELECT, DL, VT, N0, AllOnes, Zero);
23770     }
23771     return SDValue();
23772   }
23773
23774   if (VT.isVector()) {
23775     auto ExtendToVec128 = [&DAG](SDLoc DL, SDValue N) {
23776       EVT InVT = N->getValueType(0);
23777       EVT OutVT = EVT::getVectorVT(*DAG.getContext(), InVT.getScalarType(),
23778                                    128 / InVT.getScalarSizeInBits());
23779       SmallVector<SDValue, 8> Opnds(128 / InVT.getSizeInBits(),
23780                                     DAG.getUNDEF(InVT));
23781       Opnds[0] = N;
23782       return DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, Opnds);
23783     };
23784
23785     // If target-size is 128-bits, then convert to ISD::SIGN_EXTEND_VECTOR_INREG
23786     // which ensures lowering to X86ISD::VSEXT (pmovsx*).
23787     if (VT.getSizeInBits() == 128 &&
23788         (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
23789         (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
23790       SDValue ExOp = ExtendToVec128(DL, N0);
23791       return DAG.getSignExtendVectorInReg(ExOp, DL, VT);
23792     }
23793
23794     // On pre-AVX2 targets, split into 128-bit nodes of
23795     // ISD::SIGN_EXTEND_VECTOR_INREG.
23796     if (!Subtarget->hasInt256() && !(VT.getSizeInBits() % 128) &&
23797         (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
23798         (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
23799       unsigned NumVecs = VT.getSizeInBits() / 128;
23800       unsigned NumSubElts = 128 / SVT.getSizeInBits();
23801       EVT SubVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumSubElts);
23802       EVT InSubVT = EVT::getVectorVT(*DAG.getContext(), InSVT, NumSubElts);
23803
23804       SmallVector<SDValue, 8> Opnds;
23805       for (unsigned i = 0, Offset = 0; i != NumVecs;
23806            ++i, Offset += NumSubElts) {
23807         SDValue SrcVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InSubVT, N0,
23808                                      DAG.getIntPtrConstant(Offset, DL));
23809         SrcVec = ExtendToVec128(DL, SrcVec);
23810         SrcVec = DAG.getSignExtendVectorInReg(SrcVec, DL, SubVT);
23811         Opnds.push_back(SrcVec);
23812       }
23813       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Opnds);
23814     }
23815   }
23816
23817   if (!Subtarget->hasFp256())
23818     return SDValue();
23819
23820   if (VT.isVector() && VT.getSizeInBits() == 256) {
23821     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
23822     if (R.getNode())
23823       return R;
23824   }
23825
23826   return SDValue();
23827 }
23828
23829 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
23830                                  const X86Subtarget* Subtarget) {
23831   SDLoc dl(N);
23832   EVT VT = N->getValueType(0);
23833
23834   // Let legalize expand this if it isn't a legal type yet.
23835   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
23836     return SDValue();
23837
23838   EVT ScalarVT = VT.getScalarType();
23839   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
23840       (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
23841     return SDValue();
23842
23843   SDValue A = N->getOperand(0);
23844   SDValue B = N->getOperand(1);
23845   SDValue C = N->getOperand(2);
23846
23847   bool NegA = (A.getOpcode() == ISD::FNEG);
23848   bool NegB = (B.getOpcode() == ISD::FNEG);
23849   bool NegC = (C.getOpcode() == ISD::FNEG);
23850
23851   // Negative multiplication when NegA xor NegB
23852   bool NegMul = (NegA != NegB);
23853   if (NegA)
23854     A = A.getOperand(0);
23855   if (NegB)
23856     B = B.getOperand(0);
23857   if (NegC)
23858     C = C.getOperand(0);
23859
23860   unsigned Opcode;
23861   if (!NegMul)
23862     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
23863   else
23864     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
23865
23866   return DAG.getNode(Opcode, dl, VT, A, B, C);
23867 }
23868
23869 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
23870                                   TargetLowering::DAGCombinerInfo &DCI,
23871                                   const X86Subtarget *Subtarget) {
23872   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
23873   //           (and (i32 x86isd::setcc_carry), 1)
23874   // This eliminates the zext. This transformation is necessary because
23875   // ISD::SETCC is always legalized to i8.
23876   SDLoc dl(N);
23877   SDValue N0 = N->getOperand(0);
23878   EVT VT = N->getValueType(0);
23879
23880   if (N0.getOpcode() == ISD::AND &&
23881       N0.hasOneUse() &&
23882       N0.getOperand(0).hasOneUse()) {
23883     SDValue N00 = N0.getOperand(0);
23884     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
23885       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
23886       if (!C || C->getZExtValue() != 1)
23887         return SDValue();
23888       return DAG.getNode(ISD::AND, dl, VT,
23889                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
23890                                      N00.getOperand(0), N00.getOperand(1)),
23891                          DAG.getConstant(1, dl, VT));
23892     }
23893   }
23894
23895   if (N0.getOpcode() == ISD::TRUNCATE &&
23896       N0.hasOneUse() &&
23897       N0.getOperand(0).hasOneUse()) {
23898     SDValue N00 = N0.getOperand(0);
23899     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
23900       return DAG.getNode(ISD::AND, dl, VT,
23901                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
23902                                      N00.getOperand(0), N00.getOperand(1)),
23903                          DAG.getConstant(1, dl, VT));
23904     }
23905   }
23906   if (VT.is256BitVector()) {
23907     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
23908     if (R.getNode())
23909       return R;
23910   }
23911
23912   // (i8,i32 zext (udivrem (i8 x, i8 y)) ->
23913   // (i8,i32 (udivrem_zext_hreg (i8 x, i8 y)
23914   // This exposes the zext to the udivrem lowering, so that it directly extends
23915   // from AH (which we otherwise need to do contortions to access).
23916   if (N0.getOpcode() == ISD::UDIVREM &&
23917       N0.getResNo() == 1 && N0.getValueType() == MVT::i8 &&
23918       (VT == MVT::i32 || VT == MVT::i64)) {
23919     SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
23920     SDValue R = DAG.getNode(X86ISD::UDIVREM8_ZEXT_HREG, dl, NodeTys,
23921                             N0.getOperand(0), N0.getOperand(1));
23922     DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
23923     return R.getValue(1);
23924   }
23925
23926   return SDValue();
23927 }
23928
23929 // Optimize x == -y --> x+y == 0
23930 //          x != -y --> x+y != 0
23931 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
23932                                       const X86Subtarget* Subtarget) {
23933   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
23934   SDValue LHS = N->getOperand(0);
23935   SDValue RHS = N->getOperand(1);
23936   EVT VT = N->getValueType(0);
23937   SDLoc DL(N);
23938
23939   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
23940     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
23941       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
23942         SDValue addV = DAG.getNode(ISD::ADD, DL, LHS.getValueType(), RHS,
23943                                    LHS.getOperand(1));
23944         return DAG.getSetCC(DL, N->getValueType(0), addV,
23945                             DAG.getConstant(0, DL, addV.getValueType()), CC);
23946       }
23947   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
23948     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
23949       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
23950         SDValue addV = DAG.getNode(ISD::ADD, DL, RHS.getValueType(), LHS,
23951                                    RHS.getOperand(1));
23952         return DAG.getSetCC(DL, N->getValueType(0), addV,
23953                             DAG.getConstant(0, DL, addV.getValueType()), CC);
23954       }
23955
23956   if (VT.getScalarType() == MVT::i1 &&
23957       (CC == ISD::SETNE || CC == ISD::SETEQ || ISD::isSignedIntSetCC(CC))) {
23958     bool IsSEXT0 =
23959         (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
23960         (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
23961     bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
23962
23963     if (!IsSEXT0 || !IsVZero1) {
23964       // Swap the operands and update the condition code.
23965       std::swap(LHS, RHS);
23966       CC = ISD::getSetCCSwappedOperands(CC);
23967
23968       IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
23969                 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
23970       IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
23971     }
23972
23973     if (IsSEXT0 && IsVZero1) {
23974       assert(VT == LHS.getOperand(0).getValueType() &&
23975              "Uexpected operand type");
23976       if (CC == ISD::SETGT)
23977         return DAG.getConstant(0, DL, VT);
23978       if (CC == ISD::SETLE)
23979         return DAG.getConstant(1, DL, VT);
23980       if (CC == ISD::SETEQ || CC == ISD::SETGE)
23981         return DAG.getNOT(DL, LHS.getOperand(0), VT);
23982
23983       assert((CC == ISD::SETNE || CC == ISD::SETLT) &&
23984              "Unexpected condition code!");
23985       return LHS.getOperand(0);
23986     }
23987   }
23988
23989   return SDValue();
23990 }
23991
23992 static SDValue NarrowVectorLoadToElement(LoadSDNode *Load, unsigned Index,
23993                                          SelectionDAG &DAG) {
23994   SDLoc dl(Load);
23995   MVT VT = Load->getSimpleValueType(0);
23996   MVT EVT = VT.getVectorElementType();
23997   SDValue Addr = Load->getOperand(1);
23998   SDValue NewAddr = DAG.getNode(
23999       ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
24000       DAG.getConstant(Index * EVT.getStoreSize(), dl,
24001                       Addr.getSimpleValueType()));
24002
24003   SDValue NewLoad =
24004       DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
24005                   DAG.getMachineFunction().getMachineMemOperand(
24006                       Load->getMemOperand(), 0, EVT.getStoreSize()));
24007   return NewLoad;
24008 }
24009
24010 static SDValue PerformINSERTPSCombine(SDNode *N, SelectionDAG &DAG,
24011                                       const X86Subtarget *Subtarget) {
24012   SDLoc dl(N);
24013   MVT VT = N->getOperand(1)->getSimpleValueType(0);
24014   assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
24015          "X86insertps is only defined for v4x32");
24016
24017   SDValue Ld = N->getOperand(1);
24018   if (MayFoldLoad(Ld)) {
24019     // Extract the countS bits from the immediate so we can get the proper
24020     // address when narrowing the vector load to a specific element.
24021     // When the second source op is a memory address, insertps doesn't use
24022     // countS and just gets an f32 from that address.
24023     unsigned DestIndex =
24024         cast<ConstantSDNode>(N->getOperand(2))->getZExtValue() >> 6;
24025
24026     Ld = NarrowVectorLoadToElement(cast<LoadSDNode>(Ld), DestIndex, DAG);
24027
24028     // Create this as a scalar to vector to match the instruction pattern.
24029     SDValue LoadScalarToVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Ld);
24030     // countS bits are ignored when loading from memory on insertps, which
24031     // means we don't need to explicitly set them to 0.
24032     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N->getOperand(0),
24033                        LoadScalarToVector, N->getOperand(2));
24034   }
24035   return SDValue();
24036 }
24037
24038 static SDValue PerformBLENDICombine(SDNode *N, SelectionDAG &DAG) {
24039   SDValue V0 = N->getOperand(0);
24040   SDValue V1 = N->getOperand(1);
24041   SDLoc DL(N);
24042   EVT VT = N->getValueType(0);
24043
24044   // Canonicalize a v2f64 blend with a mask of 2 by swapping the vector
24045   // operands and changing the mask to 1. This saves us a bunch of
24046   // pattern-matching possibilities related to scalar math ops in SSE/AVX.
24047   // x86InstrInfo knows how to commute this back after instruction selection
24048   // if it would help register allocation.
24049
24050   // TODO: If optimizing for size or a processor that doesn't suffer from
24051   // partial register update stalls, this should be transformed into a MOVSD
24052   // instruction because a MOVSD is 1-2 bytes smaller than a BLENDPD.
24053
24054   if (VT == MVT::v2f64)
24055     if (auto *Mask = dyn_cast<ConstantSDNode>(N->getOperand(2)))
24056       if (Mask->getZExtValue() == 2 && !isShuffleFoldableLoad(V0)) {
24057         SDValue NewMask = DAG.getConstant(1, DL, MVT::i8);
24058         return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V0, NewMask);
24059       }
24060
24061   return SDValue();
24062 }
24063
24064 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
24065 // as "sbb reg,reg", since it can be extended without zext and produces
24066 // an all-ones bit which is more useful than 0/1 in some cases.
24067 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
24068                                MVT VT) {
24069   if (VT == MVT::i8)
24070     return DAG.getNode(ISD::AND, DL, VT,
24071                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
24072                                    DAG.getConstant(X86::COND_B, DL, MVT::i8),
24073                                    EFLAGS),
24074                        DAG.getConstant(1, DL, VT));
24075   assert (VT == MVT::i1 && "Unexpected type for SECCC node");
24076   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
24077                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
24078                                  DAG.getConstant(X86::COND_B, DL, MVT::i8),
24079                                  EFLAGS));
24080 }
24081
24082 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
24083 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
24084                                    TargetLowering::DAGCombinerInfo &DCI,
24085                                    const X86Subtarget *Subtarget) {
24086   SDLoc DL(N);
24087   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
24088   SDValue EFLAGS = N->getOperand(1);
24089
24090   if (CC == X86::COND_A) {
24091     // Try to convert COND_A into COND_B in an attempt to facilitate
24092     // materializing "setb reg".
24093     //
24094     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
24095     // cannot take an immediate as its first operand.
24096     //
24097     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
24098         EFLAGS.getValueType().isInteger() &&
24099         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
24100       SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
24101                                    EFLAGS.getNode()->getVTList(),
24102                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
24103       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
24104       return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
24105     }
24106   }
24107
24108   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
24109   // a zext and produces an all-ones bit which is more useful than 0/1 in some
24110   // cases.
24111   if (CC == X86::COND_B)
24112     return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
24113
24114   SDValue Flags;
24115
24116   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
24117   if (Flags.getNode()) {
24118     SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
24119     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
24120   }
24121
24122   return SDValue();
24123 }
24124
24125 // Optimize branch condition evaluation.
24126 //
24127 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
24128                                     TargetLowering::DAGCombinerInfo &DCI,
24129                                     const X86Subtarget *Subtarget) {
24130   SDLoc DL(N);
24131   SDValue Chain = N->getOperand(0);
24132   SDValue Dest = N->getOperand(1);
24133   SDValue EFLAGS = N->getOperand(3);
24134   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
24135
24136   SDValue Flags;
24137
24138   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
24139   if (Flags.getNode()) {
24140     SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
24141     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
24142                        Flags);
24143   }
24144
24145   return SDValue();
24146 }
24147
24148 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
24149                                                          SelectionDAG &DAG) {
24150   // Take advantage of vector comparisons producing 0 or -1 in each lane to
24151   // optimize away operation when it's from a constant.
24152   //
24153   // The general transformation is:
24154   //    UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
24155   //       AND(VECTOR_CMP(x,y), constant2)
24156   //    constant2 = UNARYOP(constant)
24157
24158   // Early exit if this isn't a vector operation, the operand of the
24159   // unary operation isn't a bitwise AND, or if the sizes of the operations
24160   // aren't the same.
24161   EVT VT = N->getValueType(0);
24162   if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
24163       N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
24164       VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
24165     return SDValue();
24166
24167   // Now check that the other operand of the AND is a constant. We could
24168   // make the transformation for non-constant splats as well, but it's unclear
24169   // that would be a benefit as it would not eliminate any operations, just
24170   // perform one more step in scalar code before moving to the vector unit.
24171   if (BuildVectorSDNode *BV =
24172           dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
24173     // Bail out if the vector isn't a constant.
24174     if (!BV->isConstant())
24175       return SDValue();
24176
24177     // Everything checks out. Build up the new and improved node.
24178     SDLoc DL(N);
24179     EVT IntVT = BV->getValueType(0);
24180     // Create a new constant of the appropriate type for the transformed
24181     // DAG.
24182     SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
24183     // The AND node needs bitcasts to/from an integer vector type around it.
24184     SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
24185     SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
24186                                  N->getOperand(0)->getOperand(0), MaskConst);
24187     SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
24188     return Res;
24189   }
24190
24191   return SDValue();
24192 }
24193
24194 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
24195                                         const X86Subtarget *Subtarget) {
24196   // First try to optimize away the conversion entirely when it's
24197   // conditionally from a constant. Vectors only.
24198   SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG);
24199   if (Res != SDValue())
24200     return Res;
24201
24202   // Now move on to more general possibilities.
24203   SDValue Op0 = N->getOperand(0);
24204   EVT InVT = Op0->getValueType(0);
24205
24206   // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
24207   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
24208     SDLoc dl(N);
24209     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
24210     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
24211     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
24212   }
24213
24214   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
24215   // a 32-bit target where SSE doesn't support i64->FP operations.
24216   if (Op0.getOpcode() == ISD::LOAD) {
24217     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
24218     EVT VT = Ld->getValueType(0);
24219
24220     // This transformation is not supported if the result type is f16
24221     if (N->getValueType(0) == MVT::f16)
24222       return SDValue();
24223
24224     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
24225         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
24226         !Subtarget->is64Bit() && VT == MVT::i64) {
24227       SDValue FILDChain = Subtarget->getTargetLowering()->BuildFILD(
24228           SDValue(N, 0), Ld->getValueType(0), Ld->getChain(), Op0, DAG);
24229       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
24230       return FILDChain;
24231     }
24232   }
24233   return SDValue();
24234 }
24235
24236 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
24237 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
24238                                  X86TargetLowering::DAGCombinerInfo &DCI) {
24239   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
24240   // the result is either zero or one (depending on the input carry bit).
24241   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
24242   if (X86::isZeroNode(N->getOperand(0)) &&
24243       X86::isZeroNode(N->getOperand(1)) &&
24244       // We don't have a good way to replace an EFLAGS use, so only do this when
24245       // dead right now.
24246       SDValue(N, 1).use_empty()) {
24247     SDLoc DL(N);
24248     EVT VT = N->getValueType(0);
24249     SDValue CarryOut = DAG.getConstant(0, DL, N->getValueType(1));
24250     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
24251                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
24252                                            DAG.getConstant(X86::COND_B, DL,
24253                                                            MVT::i8),
24254                                            N->getOperand(2)),
24255                                DAG.getConstant(1, DL, VT));
24256     return DCI.CombineTo(N, Res1, CarryOut);
24257   }
24258
24259   return SDValue();
24260 }
24261
24262 // fold (add Y, (sete  X, 0)) -> adc  0, Y
24263 //      (add Y, (setne X, 0)) -> sbb -1, Y
24264 //      (sub (sete  X, 0), Y) -> sbb  0, Y
24265 //      (sub (setne X, 0), Y) -> adc -1, Y
24266 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
24267   SDLoc DL(N);
24268
24269   // Look through ZExts.
24270   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
24271   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
24272     return SDValue();
24273
24274   SDValue SetCC = Ext.getOperand(0);
24275   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
24276     return SDValue();
24277
24278   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
24279   if (CC != X86::COND_E && CC != X86::COND_NE)
24280     return SDValue();
24281
24282   SDValue Cmp = SetCC.getOperand(1);
24283   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
24284       !X86::isZeroNode(Cmp.getOperand(1)) ||
24285       !Cmp.getOperand(0).getValueType().isInteger())
24286     return SDValue();
24287
24288   SDValue CmpOp0 = Cmp.getOperand(0);
24289   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
24290                                DAG.getConstant(1, DL, CmpOp0.getValueType()));
24291
24292   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
24293   if (CC == X86::COND_NE)
24294     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
24295                        DL, OtherVal.getValueType(), OtherVal,
24296                        DAG.getConstant(-1ULL, DL, OtherVal.getValueType()),
24297                        NewCmp);
24298   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
24299                      DL, OtherVal.getValueType(), OtherVal,
24300                      DAG.getConstant(0, DL, OtherVal.getValueType()), NewCmp);
24301 }
24302
24303 /// PerformADDCombine - Do target-specific dag combines on integer adds.
24304 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
24305                                  const X86Subtarget *Subtarget) {
24306   EVT VT = N->getValueType(0);
24307   SDValue Op0 = N->getOperand(0);
24308   SDValue Op1 = N->getOperand(1);
24309
24310   // Try to synthesize horizontal adds from adds of shuffles.
24311   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
24312        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
24313       isHorizontalBinOp(Op0, Op1, true))
24314     return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
24315
24316   return OptimizeConditionalInDecrement(N, DAG);
24317 }
24318
24319 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
24320                                  const X86Subtarget *Subtarget) {
24321   SDValue Op0 = N->getOperand(0);
24322   SDValue Op1 = N->getOperand(1);
24323
24324   // X86 can't encode an immediate LHS of a sub. See if we can push the
24325   // negation into a preceding instruction.
24326   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
24327     // If the RHS of the sub is a XOR with one use and a constant, invert the
24328     // immediate. Then add one to the LHS of the sub so we can turn
24329     // X-Y -> X+~Y+1, saving one register.
24330     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
24331         isa<ConstantSDNode>(Op1.getOperand(1))) {
24332       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
24333       EVT VT = Op0.getValueType();
24334       SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
24335                                    Op1.getOperand(0),
24336                                    DAG.getConstant(~XorC, SDLoc(Op1), VT));
24337       return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
24338                          DAG.getConstant(C->getAPIntValue() + 1, SDLoc(N), VT));
24339     }
24340   }
24341
24342   // Try to synthesize horizontal adds from adds of shuffles.
24343   EVT VT = N->getValueType(0);
24344   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
24345        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
24346       isHorizontalBinOp(Op0, Op1, true))
24347     return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
24348
24349   return OptimizeConditionalInDecrement(N, DAG);
24350 }
24351
24352 /// performVZEXTCombine - Performs build vector combines
24353 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
24354                                    TargetLowering::DAGCombinerInfo &DCI,
24355                                    const X86Subtarget *Subtarget) {
24356   SDLoc DL(N);
24357   MVT VT = N->getSimpleValueType(0);
24358   SDValue Op = N->getOperand(0);
24359   MVT OpVT = Op.getSimpleValueType();
24360   MVT OpEltVT = OpVT.getVectorElementType();
24361   unsigned InputBits = OpEltVT.getSizeInBits() * VT.getVectorNumElements();
24362
24363   // (vzext (bitcast (vzext (x)) -> (vzext x)
24364   SDValue V = Op;
24365   while (V.getOpcode() == ISD::BITCAST)
24366     V = V.getOperand(0);
24367
24368   if (V != Op && V.getOpcode() == X86ISD::VZEXT) {
24369     MVT InnerVT = V.getSimpleValueType();
24370     MVT InnerEltVT = InnerVT.getVectorElementType();
24371
24372     // If the element sizes match exactly, we can just do one larger vzext. This
24373     // is always an exact type match as vzext operates on integer types.
24374     if (OpEltVT == InnerEltVT) {
24375       assert(OpVT == InnerVT && "Types must match for vzext!");
24376       return DAG.getNode(X86ISD::VZEXT, DL, VT, V.getOperand(0));
24377     }
24378
24379     // The only other way we can combine them is if only a single element of the
24380     // inner vzext is used in the input to the outer vzext.
24381     if (InnerEltVT.getSizeInBits() < InputBits)
24382       return SDValue();
24383
24384     // In this case, the inner vzext is completely dead because we're going to
24385     // only look at bits inside of the low element. Just do the outer vzext on
24386     // a bitcast of the input to the inner.
24387     return DAG.getNode(X86ISD::VZEXT, DL, VT,
24388                        DAG.getNode(ISD::BITCAST, DL, OpVT, V));
24389   }
24390
24391   // Check if we can bypass extracting and re-inserting an element of an input
24392   // vector. Essentialy:
24393   // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
24394   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR &&
24395       V.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
24396       V.getOperand(0).getSimpleValueType().getSizeInBits() == InputBits) {
24397     SDValue ExtractedV = V.getOperand(0);
24398     SDValue OrigV = ExtractedV.getOperand(0);
24399     if (auto *ExtractIdx = dyn_cast<ConstantSDNode>(ExtractedV.getOperand(1)))
24400       if (ExtractIdx->getZExtValue() == 0) {
24401         MVT OrigVT = OrigV.getSimpleValueType();
24402         // Extract a subvector if necessary...
24403         if (OrigVT.getSizeInBits() > OpVT.getSizeInBits()) {
24404           int Ratio = OrigVT.getSizeInBits() / OpVT.getSizeInBits();
24405           OrigVT = MVT::getVectorVT(OrigVT.getVectorElementType(),
24406                                     OrigVT.getVectorNumElements() / Ratio);
24407           OrigV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigVT, OrigV,
24408                               DAG.getIntPtrConstant(0, DL));
24409         }
24410         Op = DAG.getNode(ISD::BITCAST, DL, OpVT, OrigV);
24411         return DAG.getNode(X86ISD::VZEXT, DL, VT, Op);
24412       }
24413   }
24414
24415   return SDValue();
24416 }
24417
24418 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
24419                                              DAGCombinerInfo &DCI) const {
24420   SelectionDAG &DAG = DCI.DAG;
24421   switch (N->getOpcode()) {
24422   default: break;
24423   case ISD::EXTRACT_VECTOR_ELT:
24424     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
24425   case ISD::VSELECT:
24426   case ISD::SELECT:
24427   case X86ISD::SHRUNKBLEND:
24428     return PerformSELECTCombine(N, DAG, DCI, Subtarget);
24429   case ISD::BITCAST:        return PerformBITCASTCombine(N, DAG);
24430   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
24431   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
24432   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
24433   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
24434   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
24435   case ISD::SHL:
24436   case ISD::SRA:
24437   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
24438   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
24439   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
24440   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
24441   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
24442   case ISD::MLOAD:          return PerformMLOADCombine(N, DAG, DCI, Subtarget);
24443   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
24444   case ISD::MSTORE:         return PerformMSTORECombine(N, DAG, Subtarget);
24445   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, Subtarget);
24446   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
24447   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
24448   case X86ISD::FXOR:
24449   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
24450   case X86ISD::FMIN:
24451   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
24452   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
24453   case X86ISD::FANDN:       return PerformFANDNCombine(N, DAG);
24454   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
24455   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
24456   case ISD::ANY_EXTEND:
24457   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
24458   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
24459   case ISD::SIGN_EXTEND_INREG:
24460     return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
24461   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG, Subtarget);
24462   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
24463   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
24464   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
24465   case X86ISD::SHUFP:       // Handle all target specific shuffles
24466   case X86ISD::PALIGNR:
24467   case X86ISD::UNPCKH:
24468   case X86ISD::UNPCKL:
24469   case X86ISD::MOVHLPS:
24470   case X86ISD::MOVLHPS:
24471   case X86ISD::PSHUFB:
24472   case X86ISD::PSHUFD:
24473   case X86ISD::PSHUFHW:
24474   case X86ISD::PSHUFLW:
24475   case X86ISD::MOVSS:
24476   case X86ISD::MOVSD:
24477   case X86ISD::VPERMILPI:
24478   case X86ISD::VPERM2X128:
24479   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
24480   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
24481   case ISD::INTRINSIC_WO_CHAIN:
24482     return PerformINTRINSIC_WO_CHAINCombine(N, DAG, Subtarget);
24483   case X86ISD::INSERTPS: {
24484     if (getTargetMachine().getOptLevel() > CodeGenOpt::None)
24485       return PerformINSERTPSCombine(N, DAG, Subtarget);
24486     break;
24487   }
24488   case X86ISD::BLENDI:    return PerformBLENDICombine(N, DAG);
24489   }
24490
24491   return SDValue();
24492 }
24493
24494 /// isTypeDesirableForOp - Return true if the target has native support for
24495 /// the specified value type and it is 'desirable' to use the type for the
24496 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
24497 /// instruction encodings are longer and some i16 instructions are slow.
24498 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
24499   if (!isTypeLegal(VT))
24500     return false;
24501   if (VT != MVT::i16)
24502     return true;
24503
24504   switch (Opc) {
24505   default:
24506     return true;
24507   case ISD::LOAD:
24508   case ISD::SIGN_EXTEND:
24509   case ISD::ZERO_EXTEND:
24510   case ISD::ANY_EXTEND:
24511   case ISD::SHL:
24512   case ISD::SRL:
24513   case ISD::SUB:
24514   case ISD::ADD:
24515   case ISD::MUL:
24516   case ISD::AND:
24517   case ISD::OR:
24518   case ISD::XOR:
24519     return false;
24520   }
24521 }
24522
24523 /// IsDesirableToPromoteOp - This method query the target whether it is
24524 /// beneficial for dag combiner to promote the specified node. If true, it
24525 /// should return the desired promotion type by reference.
24526 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
24527   EVT VT = Op.getValueType();
24528   if (VT != MVT::i16)
24529     return false;
24530
24531   bool Promote = false;
24532   bool Commute = false;
24533   switch (Op.getOpcode()) {
24534   default: break;
24535   case ISD::LOAD: {
24536     LoadSDNode *LD = cast<LoadSDNode>(Op);
24537     // If the non-extending load has a single use and it's not live out, then it
24538     // might be folded.
24539     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
24540                                                      Op.hasOneUse()*/) {
24541       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
24542              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
24543         // The only case where we'd want to promote LOAD (rather then it being
24544         // promoted as an operand is when it's only use is liveout.
24545         if (UI->getOpcode() != ISD::CopyToReg)
24546           return false;
24547       }
24548     }
24549     Promote = true;
24550     break;
24551   }
24552   case ISD::SIGN_EXTEND:
24553   case ISD::ZERO_EXTEND:
24554   case ISD::ANY_EXTEND:
24555     Promote = true;
24556     break;
24557   case ISD::SHL:
24558   case ISD::SRL: {
24559     SDValue N0 = Op.getOperand(0);
24560     // Look out for (store (shl (load), x)).
24561     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
24562       return false;
24563     Promote = true;
24564     break;
24565   }
24566   case ISD::ADD:
24567   case ISD::MUL:
24568   case ISD::AND:
24569   case ISD::OR:
24570   case ISD::XOR:
24571     Commute = true;
24572     // fallthrough
24573   case ISD::SUB: {
24574     SDValue N0 = Op.getOperand(0);
24575     SDValue N1 = Op.getOperand(1);
24576     if (!Commute && MayFoldLoad(N1))
24577       return false;
24578     // Avoid disabling potential load folding opportunities.
24579     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
24580       return false;
24581     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
24582       return false;
24583     Promote = true;
24584   }
24585   }
24586
24587   PVT = MVT::i32;
24588   return Promote;
24589 }
24590
24591 //===----------------------------------------------------------------------===//
24592 //                           X86 Inline Assembly Support
24593 //===----------------------------------------------------------------------===//
24594
24595 // Helper to match a string separated by whitespace.
24596 static bool matchAsm(StringRef S, ArrayRef<const char *> Pieces) {
24597   S = S.substr(S.find_first_not_of(" \t")); // Skip leading whitespace.
24598
24599   for (StringRef Piece : Pieces) {
24600     if (!S.startswith(Piece)) // Check if the piece matches.
24601       return false;
24602
24603     S = S.substr(Piece.size());
24604     StringRef::size_type Pos = S.find_first_not_of(" \t");
24605     if (Pos == 0) // We matched a prefix.
24606       return false;
24607
24608     S = S.substr(Pos);
24609   }
24610
24611   return S.empty();
24612 }
24613
24614 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
24615
24616   if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
24617     if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
24618         std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
24619         std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
24620
24621       if (AsmPieces.size() == 3)
24622         return true;
24623       else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
24624         return true;
24625     }
24626   }
24627   return false;
24628 }
24629
24630 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
24631   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
24632
24633   std::string AsmStr = IA->getAsmString();
24634
24635   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
24636   if (!Ty || Ty->getBitWidth() % 16 != 0)
24637     return false;
24638
24639   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
24640   SmallVector<StringRef, 4> AsmPieces;
24641   SplitString(AsmStr, AsmPieces, ";\n");
24642
24643   switch (AsmPieces.size()) {
24644   default: return false;
24645   case 1:
24646     // FIXME: this should verify that we are targeting a 486 or better.  If not,
24647     // we will turn this bswap into something that will be lowered to logical
24648     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
24649     // lower so don't worry about this.
24650     // bswap $0
24651     if (matchAsm(AsmPieces[0], {"bswap", "$0"}) ||
24652         matchAsm(AsmPieces[0], {"bswapl", "$0"}) ||
24653         matchAsm(AsmPieces[0], {"bswapq", "$0"}) ||
24654         matchAsm(AsmPieces[0], {"bswap", "${0:q}"}) ||
24655         matchAsm(AsmPieces[0], {"bswapl", "${0:q}"}) ||
24656         matchAsm(AsmPieces[0], {"bswapq", "${0:q}"})) {
24657       // No need to check constraints, nothing other than the equivalent of
24658       // "=r,0" would be valid here.
24659       return IntrinsicLowering::LowerToByteSwap(CI);
24660     }
24661
24662     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
24663     if (CI->getType()->isIntegerTy(16) &&
24664         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
24665         (matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) ||
24666          matchAsm(AsmPieces[0], {"rolw", "$$8,", "${0:w}"}))) {
24667       AsmPieces.clear();
24668       const std::string &ConstraintsStr = IA->getConstraintString();
24669       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
24670       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
24671       if (clobbersFlagRegisters(AsmPieces))
24672         return IntrinsicLowering::LowerToByteSwap(CI);
24673     }
24674     break;
24675   case 3:
24676     if (CI->getType()->isIntegerTy(32) &&
24677         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
24678         matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) &&
24679         matchAsm(AsmPieces[1], {"rorl", "$$16,", "$0"}) &&
24680         matchAsm(AsmPieces[2], {"rorw", "$$8,", "${0:w}"})) {
24681       AsmPieces.clear();
24682       const std::string &ConstraintsStr = IA->getConstraintString();
24683       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
24684       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
24685       if (clobbersFlagRegisters(AsmPieces))
24686         return IntrinsicLowering::LowerToByteSwap(CI);
24687     }
24688
24689     if (CI->getType()->isIntegerTy(64)) {
24690       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
24691       if (Constraints.size() >= 2 &&
24692           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
24693           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
24694         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
24695         if (matchAsm(AsmPieces[0], {"bswap", "%eax"}) &&
24696             matchAsm(AsmPieces[1], {"bswap", "%edx"}) &&
24697             matchAsm(AsmPieces[2], {"xchgl", "%eax,", "%edx"}))
24698           return IntrinsicLowering::LowerToByteSwap(CI);
24699       }
24700     }
24701     break;
24702   }
24703   return false;
24704 }
24705
24706 /// getConstraintType - Given a constraint letter, return the type of
24707 /// constraint it is for this target.
24708 X86TargetLowering::ConstraintType
24709 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
24710   if (Constraint.size() == 1) {
24711     switch (Constraint[0]) {
24712     case 'R':
24713     case 'q':
24714     case 'Q':
24715     case 'f':
24716     case 't':
24717     case 'u':
24718     case 'y':
24719     case 'x':
24720     case 'Y':
24721     case 'l':
24722       return C_RegisterClass;
24723     case 'a':
24724     case 'b':
24725     case 'c':
24726     case 'd':
24727     case 'S':
24728     case 'D':
24729     case 'A':
24730       return C_Register;
24731     case 'I':
24732     case 'J':
24733     case 'K':
24734     case 'L':
24735     case 'M':
24736     case 'N':
24737     case 'G':
24738     case 'C':
24739     case 'e':
24740     case 'Z':
24741       return C_Other;
24742     default:
24743       break;
24744     }
24745   }
24746   return TargetLowering::getConstraintType(Constraint);
24747 }
24748
24749 /// Examine constraint type and operand type and determine a weight value.
24750 /// This object must already have been set up with the operand type
24751 /// and the current alternative constraint selected.
24752 TargetLowering::ConstraintWeight
24753   X86TargetLowering::getSingleConstraintMatchWeight(
24754     AsmOperandInfo &info, const char *constraint) const {
24755   ConstraintWeight weight = CW_Invalid;
24756   Value *CallOperandVal = info.CallOperandVal;
24757     // If we don't have a value, we can't do a match,
24758     // but allow it at the lowest weight.
24759   if (!CallOperandVal)
24760     return CW_Default;
24761   Type *type = CallOperandVal->getType();
24762   // Look at the constraint type.
24763   switch (*constraint) {
24764   default:
24765     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
24766   case 'R':
24767   case 'q':
24768   case 'Q':
24769   case 'a':
24770   case 'b':
24771   case 'c':
24772   case 'd':
24773   case 'S':
24774   case 'D':
24775   case 'A':
24776     if (CallOperandVal->getType()->isIntegerTy())
24777       weight = CW_SpecificReg;
24778     break;
24779   case 'f':
24780   case 't':
24781   case 'u':
24782     if (type->isFloatingPointTy())
24783       weight = CW_SpecificReg;
24784     break;
24785   case 'y':
24786     if (type->isX86_MMXTy() && Subtarget->hasMMX())
24787       weight = CW_SpecificReg;
24788     break;
24789   case 'x':
24790   case 'Y':
24791     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
24792         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
24793       weight = CW_Register;
24794     break;
24795   case 'I':
24796     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
24797       if (C->getZExtValue() <= 31)
24798         weight = CW_Constant;
24799     }
24800     break;
24801   case 'J':
24802     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24803       if (C->getZExtValue() <= 63)
24804         weight = CW_Constant;
24805     }
24806     break;
24807   case 'K':
24808     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24809       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
24810         weight = CW_Constant;
24811     }
24812     break;
24813   case 'L':
24814     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24815       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
24816         weight = CW_Constant;
24817     }
24818     break;
24819   case 'M':
24820     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24821       if (C->getZExtValue() <= 3)
24822         weight = CW_Constant;
24823     }
24824     break;
24825   case 'N':
24826     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24827       if (C->getZExtValue() <= 0xff)
24828         weight = CW_Constant;
24829     }
24830     break;
24831   case 'G':
24832   case 'C':
24833     if (isa<ConstantFP>(CallOperandVal)) {
24834       weight = CW_Constant;
24835     }
24836     break;
24837   case 'e':
24838     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24839       if ((C->getSExtValue() >= -0x80000000LL) &&
24840           (C->getSExtValue() <= 0x7fffffffLL))
24841         weight = CW_Constant;
24842     }
24843     break;
24844   case 'Z':
24845     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24846       if (C->getZExtValue() <= 0xffffffff)
24847         weight = CW_Constant;
24848     }
24849     break;
24850   }
24851   return weight;
24852 }
24853
24854 /// LowerXConstraint - try to replace an X constraint, which matches anything,
24855 /// with another that has more specific requirements based on the type of the
24856 /// corresponding operand.
24857 const char *X86TargetLowering::
24858 LowerXConstraint(EVT ConstraintVT) const {
24859   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
24860   // 'f' like normal targets.
24861   if (ConstraintVT.isFloatingPoint()) {
24862     if (Subtarget->hasSSE2())
24863       return "Y";
24864     if (Subtarget->hasSSE1())
24865       return "x";
24866   }
24867
24868   return TargetLowering::LowerXConstraint(ConstraintVT);
24869 }
24870
24871 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
24872 /// vector.  If it is invalid, don't add anything to Ops.
24873 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
24874                                                      std::string &Constraint,
24875                                                      std::vector<SDValue>&Ops,
24876                                                      SelectionDAG &DAG) const {
24877   SDValue Result;
24878
24879   // Only support length 1 constraints for now.
24880   if (Constraint.length() > 1) return;
24881
24882   char ConstraintLetter = Constraint[0];
24883   switch (ConstraintLetter) {
24884   default: break;
24885   case 'I':
24886     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24887       if (C->getZExtValue() <= 31) {
24888         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
24889                                        Op.getValueType());
24890         break;
24891       }
24892     }
24893     return;
24894   case 'J':
24895     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24896       if (C->getZExtValue() <= 63) {
24897         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
24898                                        Op.getValueType());
24899         break;
24900       }
24901     }
24902     return;
24903   case 'K':
24904     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24905       if (isInt<8>(C->getSExtValue())) {
24906         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
24907                                        Op.getValueType());
24908         break;
24909       }
24910     }
24911     return;
24912   case 'L':
24913     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24914       if (C->getZExtValue() == 0xff || C->getZExtValue() == 0xffff ||
24915           (Subtarget->is64Bit() && C->getZExtValue() == 0xffffffff)) {
24916         Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op),
24917                                        Op.getValueType());
24918         break;
24919       }
24920     }
24921     return;
24922   case 'M':
24923     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24924       if (C->getZExtValue() <= 3) {
24925         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
24926                                        Op.getValueType());
24927         break;
24928       }
24929     }
24930     return;
24931   case 'N':
24932     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24933       if (C->getZExtValue() <= 255) {
24934         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
24935                                        Op.getValueType());
24936         break;
24937       }
24938     }
24939     return;
24940   case 'O':
24941     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24942       if (C->getZExtValue() <= 127) {
24943         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
24944                                        Op.getValueType());
24945         break;
24946       }
24947     }
24948     return;
24949   case 'e': {
24950     // 32-bit signed value
24951     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24952       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
24953                                            C->getSExtValue())) {
24954         // Widen to 64 bits here to get it sign extended.
24955         Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op), MVT::i64);
24956         break;
24957       }
24958     // FIXME gcc accepts some relocatable values here too, but only in certain
24959     // memory models; it's complicated.
24960     }
24961     return;
24962   }
24963   case 'Z': {
24964     // 32-bit unsigned value
24965     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24966       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
24967                                            C->getZExtValue())) {
24968         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
24969                                        Op.getValueType());
24970         break;
24971       }
24972     }
24973     // FIXME gcc accepts some relocatable values here too, but only in certain
24974     // memory models; it's complicated.
24975     return;
24976   }
24977   case 'i': {
24978     // Literal immediates are always ok.
24979     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
24980       // Widen to 64 bits here to get it sign extended.
24981       Result = DAG.getTargetConstant(CST->getSExtValue(), SDLoc(Op), MVT::i64);
24982       break;
24983     }
24984
24985     // In any sort of PIC mode addresses need to be computed at runtime by
24986     // adding in a register or some sort of table lookup.  These can't
24987     // be used as immediates.
24988     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
24989       return;
24990
24991     // If we are in non-pic codegen mode, we allow the address of a global (with
24992     // an optional displacement) to be used with 'i'.
24993     GlobalAddressSDNode *GA = nullptr;
24994     int64_t Offset = 0;
24995
24996     // Match either (GA), (GA+C), (GA+C1+C2), etc.
24997     while (1) {
24998       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
24999         Offset += GA->getOffset();
25000         break;
25001       } else if (Op.getOpcode() == ISD::ADD) {
25002         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
25003           Offset += C->getZExtValue();
25004           Op = Op.getOperand(0);
25005           continue;
25006         }
25007       } else if (Op.getOpcode() == ISD::SUB) {
25008         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
25009           Offset += -C->getZExtValue();
25010           Op = Op.getOperand(0);
25011           continue;
25012         }
25013       }
25014
25015       // Otherwise, this isn't something we can handle, reject it.
25016       return;
25017     }
25018
25019     const GlobalValue *GV = GA->getGlobal();
25020     // If we require an extra load to get this address, as in PIC mode, we
25021     // can't accept it.
25022     if (isGlobalStubReference(
25023             Subtarget->ClassifyGlobalReference(GV, DAG.getTarget())))
25024       return;
25025
25026     Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
25027                                         GA->getValueType(0), Offset);
25028     break;
25029   }
25030   }
25031
25032   if (Result.getNode()) {
25033     Ops.push_back(Result);
25034     return;
25035   }
25036   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
25037 }
25038
25039 std::pair<unsigned, const TargetRegisterClass *>
25040 X86TargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
25041                                                 const std::string &Constraint,
25042                                                 MVT VT) const {
25043   // First, see if this is a constraint that directly corresponds to an LLVM
25044   // register class.
25045   if (Constraint.size() == 1) {
25046     // GCC Constraint Letters
25047     switch (Constraint[0]) {
25048     default: break;
25049       // TODO: Slight differences here in allocation order and leaving
25050       // RIP in the class. Do they matter any more here than they do
25051       // in the normal allocation?
25052     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
25053       if (Subtarget->is64Bit()) {
25054         if (VT == MVT::i32 || VT == MVT::f32)
25055           return std::make_pair(0U, &X86::GR32RegClass);
25056         if (VT == MVT::i16)
25057           return std::make_pair(0U, &X86::GR16RegClass);
25058         if (VT == MVT::i8 || VT == MVT::i1)
25059           return std::make_pair(0U, &X86::GR8RegClass);
25060         if (VT == MVT::i64 || VT == MVT::f64)
25061           return std::make_pair(0U, &X86::GR64RegClass);
25062         break;
25063       }
25064       // 32-bit fallthrough
25065     case 'Q':   // Q_REGS
25066       if (VT == MVT::i32 || VT == MVT::f32)
25067         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
25068       if (VT == MVT::i16)
25069         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
25070       if (VT == MVT::i8 || VT == MVT::i1)
25071         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
25072       if (VT == MVT::i64)
25073         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
25074       break;
25075     case 'r':   // GENERAL_REGS
25076     case 'l':   // INDEX_REGS
25077       if (VT == MVT::i8 || VT == MVT::i1)
25078         return std::make_pair(0U, &X86::GR8RegClass);
25079       if (VT == MVT::i16)
25080         return std::make_pair(0U, &X86::GR16RegClass);
25081       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
25082         return std::make_pair(0U, &X86::GR32RegClass);
25083       return std::make_pair(0U, &X86::GR64RegClass);
25084     case 'R':   // LEGACY_REGS
25085       if (VT == MVT::i8 || VT == MVT::i1)
25086         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
25087       if (VT == MVT::i16)
25088         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
25089       if (VT == MVT::i32 || !Subtarget->is64Bit())
25090         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
25091       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
25092     case 'f':  // FP Stack registers.
25093       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
25094       // value to the correct fpstack register class.
25095       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
25096         return std::make_pair(0U, &X86::RFP32RegClass);
25097       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
25098         return std::make_pair(0U, &X86::RFP64RegClass);
25099       return std::make_pair(0U, &X86::RFP80RegClass);
25100     case 'y':   // MMX_REGS if MMX allowed.
25101       if (!Subtarget->hasMMX()) break;
25102       return std::make_pair(0U, &X86::VR64RegClass);
25103     case 'Y':   // SSE_REGS if SSE2 allowed
25104       if (!Subtarget->hasSSE2()) break;
25105       // FALL THROUGH.
25106     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
25107       if (!Subtarget->hasSSE1()) break;
25108
25109       switch (VT.SimpleTy) {
25110       default: break;
25111       // Scalar SSE types.
25112       case MVT::f32:
25113       case MVT::i32:
25114         return std::make_pair(0U, &X86::FR32RegClass);
25115       case MVT::f64:
25116       case MVT::i64:
25117         return std::make_pair(0U, &X86::FR64RegClass);
25118       // Vector types.
25119       case MVT::v16i8:
25120       case MVT::v8i16:
25121       case MVT::v4i32:
25122       case MVT::v2i64:
25123       case MVT::v4f32:
25124       case MVT::v2f64:
25125         return std::make_pair(0U, &X86::VR128RegClass);
25126       // AVX types.
25127       case MVT::v32i8:
25128       case MVT::v16i16:
25129       case MVT::v8i32:
25130       case MVT::v4i64:
25131       case MVT::v8f32:
25132       case MVT::v4f64:
25133         return std::make_pair(0U, &X86::VR256RegClass);
25134       case MVT::v8f64:
25135       case MVT::v16f32:
25136       case MVT::v16i32:
25137       case MVT::v8i64:
25138         return std::make_pair(0U, &X86::VR512RegClass);
25139       }
25140       break;
25141     }
25142   }
25143
25144   // Use the default implementation in TargetLowering to convert the register
25145   // constraint into a member of a register class.
25146   std::pair<unsigned, const TargetRegisterClass*> Res;
25147   Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
25148
25149   // Not found as a standard register?
25150   if (!Res.second) {
25151     // Map st(0) -> st(7) -> ST0
25152     if (Constraint.size() == 7 && Constraint[0] == '{' &&
25153         tolower(Constraint[1]) == 's' &&
25154         tolower(Constraint[2]) == 't' &&
25155         Constraint[3] == '(' &&
25156         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
25157         Constraint[5] == ')' &&
25158         Constraint[6] == '}') {
25159
25160       Res.first = X86::FP0+Constraint[4]-'0';
25161       Res.second = &X86::RFP80RegClass;
25162       return Res;
25163     }
25164
25165     // GCC allows "st(0)" to be called just plain "st".
25166     if (StringRef("{st}").equals_lower(Constraint)) {
25167       Res.first = X86::FP0;
25168       Res.second = &X86::RFP80RegClass;
25169       return Res;
25170     }
25171
25172     // flags -> EFLAGS
25173     if (StringRef("{flags}").equals_lower(Constraint)) {
25174       Res.first = X86::EFLAGS;
25175       Res.second = &X86::CCRRegClass;
25176       return Res;
25177     }
25178
25179     // 'A' means EAX + EDX.
25180     if (Constraint == "A") {
25181       Res.first = X86::EAX;
25182       Res.second = &X86::GR32_ADRegClass;
25183       return Res;
25184     }
25185     return Res;
25186   }
25187
25188   // Otherwise, check to see if this is a register class of the wrong value
25189   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
25190   // turn into {ax},{dx}.
25191   if (Res.second->hasType(VT))
25192     return Res;   // Correct type already, nothing to do.
25193
25194   // All of the single-register GCC register classes map their values onto
25195   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
25196   // really want an 8-bit or 32-bit register, map to the appropriate register
25197   // class and return the appropriate register.
25198   if (Res.second == &X86::GR16RegClass) {
25199     if (VT == MVT::i8 || VT == MVT::i1) {
25200       unsigned DestReg = 0;
25201       switch (Res.first) {
25202       default: break;
25203       case X86::AX: DestReg = X86::AL; break;
25204       case X86::DX: DestReg = X86::DL; break;
25205       case X86::CX: DestReg = X86::CL; break;
25206       case X86::BX: DestReg = X86::BL; break;
25207       }
25208       if (DestReg) {
25209         Res.first = DestReg;
25210         Res.second = &X86::GR8RegClass;
25211       }
25212     } else if (VT == MVT::i32 || VT == MVT::f32) {
25213       unsigned DestReg = 0;
25214       switch (Res.first) {
25215       default: break;
25216       case X86::AX: DestReg = X86::EAX; break;
25217       case X86::DX: DestReg = X86::EDX; break;
25218       case X86::CX: DestReg = X86::ECX; break;
25219       case X86::BX: DestReg = X86::EBX; break;
25220       case X86::SI: DestReg = X86::ESI; break;
25221       case X86::DI: DestReg = X86::EDI; break;
25222       case X86::BP: DestReg = X86::EBP; break;
25223       case X86::SP: DestReg = X86::ESP; break;
25224       }
25225       if (DestReg) {
25226         Res.first = DestReg;
25227         Res.second = &X86::GR32RegClass;
25228       }
25229     } else if (VT == MVT::i64 || VT == MVT::f64) {
25230       unsigned DestReg = 0;
25231       switch (Res.first) {
25232       default: break;
25233       case X86::AX: DestReg = X86::RAX; break;
25234       case X86::DX: DestReg = X86::RDX; break;
25235       case X86::CX: DestReg = X86::RCX; break;
25236       case X86::BX: DestReg = X86::RBX; break;
25237       case X86::SI: DestReg = X86::RSI; break;
25238       case X86::DI: DestReg = X86::RDI; break;
25239       case X86::BP: DestReg = X86::RBP; break;
25240       case X86::SP: DestReg = X86::RSP; break;
25241       }
25242       if (DestReg) {
25243         Res.first = DestReg;
25244         Res.second = &X86::GR64RegClass;
25245       }
25246     }
25247   } else if (Res.second == &X86::FR32RegClass ||
25248              Res.second == &X86::FR64RegClass ||
25249              Res.second == &X86::VR128RegClass ||
25250              Res.second == &X86::VR256RegClass ||
25251              Res.second == &X86::FR32XRegClass ||
25252              Res.second == &X86::FR64XRegClass ||
25253              Res.second == &X86::VR128XRegClass ||
25254              Res.second == &X86::VR256XRegClass ||
25255              Res.second == &X86::VR512RegClass) {
25256     // Handle references to XMM physical registers that got mapped into the
25257     // wrong class.  This can happen with constraints like {xmm0} where the
25258     // target independent register mapper will just pick the first match it can
25259     // find, ignoring the required type.
25260
25261     if (VT == MVT::f32 || VT == MVT::i32)
25262       Res.second = &X86::FR32RegClass;
25263     else if (VT == MVT::f64 || VT == MVT::i64)
25264       Res.second = &X86::FR64RegClass;
25265     else if (X86::VR128RegClass.hasType(VT))
25266       Res.second = &X86::VR128RegClass;
25267     else if (X86::VR256RegClass.hasType(VT))
25268       Res.second = &X86::VR256RegClass;
25269     else if (X86::VR512RegClass.hasType(VT))
25270       Res.second = &X86::VR512RegClass;
25271   }
25272
25273   return Res;
25274 }
25275
25276 int X86TargetLowering::getScalingFactorCost(const AddrMode &AM,
25277                                             Type *Ty) const {
25278   // Scaling factors are not free at all.
25279   // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
25280   // will take 2 allocations in the out of order engine instead of 1
25281   // for plain addressing mode, i.e. inst (reg1).
25282   // E.g.,
25283   // vaddps (%rsi,%drx), %ymm0, %ymm1
25284   // Requires two allocations (one for the load, one for the computation)
25285   // whereas:
25286   // vaddps (%rsi), %ymm0, %ymm1
25287   // Requires just 1 allocation, i.e., freeing allocations for other operations
25288   // and having less micro operations to execute.
25289   //
25290   // For some X86 architectures, this is even worse because for instance for
25291   // stores, the complex addressing mode forces the instruction to use the
25292   // "load" ports instead of the dedicated "store" port.
25293   // E.g., on Haswell:
25294   // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
25295   // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.
25296   if (isLegalAddressingMode(AM, Ty))
25297     // Scale represents reg2 * scale, thus account for 1
25298     // as soon as we use a second register.
25299     return AM.Scale != 0;
25300   return -1;
25301 }
25302
25303 bool X86TargetLowering::isTargetFTOL() const {
25304   return Subtarget->isTargetKnownWindowsMSVC() && !Subtarget->is64Bit();
25305 }