[X86] DAGCombine should not assume arbitrary vector types are simple
[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 static cl::opt<int> ReciprocalEstimateRefinementSteps(
71     "x86-recip-refinement-steps", cl::init(1),
72     cl::desc("Specify the number of Newton-Raphson iterations applied to the "
73              "result of the hardware reciprocal estimate instruction."),
74     cl::NotHidden);
75
76 // Forward declarations.
77 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
78                        SDValue V2);
79
80 X86TargetLowering::X86TargetLowering(const X86TargetMachine &TM,
81                                      const X86Subtarget &STI)
82     : TargetLowering(TM), Subtarget(&STI) {
83   X86ScalarSSEf64 = Subtarget->hasSSE2();
84   X86ScalarSSEf32 = Subtarget->hasSSE1();
85   TD = getDataLayout();
86
87   // Set up the TargetLowering object.
88   static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
89
90   // X86 is weird. It always uses i8 for shift amounts and setcc results.
91   setBooleanContents(ZeroOrOneBooleanContent);
92   // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
93   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
94
95   // For 64-bit, since we have so many registers, use the ILP scheduler.
96   // For 32-bit, use the register pressure specific scheduling.
97   // For Atom, always use ILP scheduling.
98   if (Subtarget->isAtom())
99     setSchedulingPreference(Sched::ILP);
100   else if (Subtarget->is64Bit())
101     setSchedulingPreference(Sched::ILP);
102   else
103     setSchedulingPreference(Sched::RegPressure);
104   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
105   setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
106
107   // Bypass expensive divides on Atom when compiling with O2.
108   if (TM.getOptLevel() >= CodeGenOpt::Default) {
109     if (Subtarget->hasSlowDivide32())
110       addBypassSlowDiv(32, 8);
111     if (Subtarget->hasSlowDivide64() && Subtarget->is64Bit())
112       addBypassSlowDiv(64, 16);
113   }
114
115   if (Subtarget->isTargetKnownWindowsMSVC()) {
116     // Setup Windows compiler runtime calls.
117     setLibcallName(RTLIB::SDIV_I64, "_alldiv");
118     setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
119     setLibcallName(RTLIB::SREM_I64, "_allrem");
120     setLibcallName(RTLIB::UREM_I64, "_aullrem");
121     setLibcallName(RTLIB::MUL_I64, "_allmul");
122     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
123     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
124     setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
125     setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
126     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
127
128     // The _ftol2 runtime function has an unusual calling conv, which
129     // is modeled by a special pseudo-instruction.
130     setLibcallName(RTLIB::FPTOUINT_F64_I64, nullptr);
131     setLibcallName(RTLIB::FPTOUINT_F32_I64, nullptr);
132     setLibcallName(RTLIB::FPTOUINT_F64_I32, nullptr);
133     setLibcallName(RTLIB::FPTOUINT_F32_I32, nullptr);
134   }
135
136   if (Subtarget->isTargetDarwin()) {
137     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
138     setUseUnderscoreSetJmp(false);
139     setUseUnderscoreLongJmp(false);
140   } else if (Subtarget->isTargetWindowsGNU()) {
141     // MS runtime is weird: it exports _setjmp, but longjmp!
142     setUseUnderscoreSetJmp(true);
143     setUseUnderscoreLongJmp(false);
144   } else {
145     setUseUnderscoreSetJmp(true);
146     setUseUnderscoreLongJmp(true);
147   }
148
149   // Set up the register classes.
150   addRegisterClass(MVT::i8, &X86::GR8RegClass);
151   addRegisterClass(MVT::i16, &X86::GR16RegClass);
152   addRegisterClass(MVT::i32, &X86::GR32RegClass);
153   if (Subtarget->is64Bit())
154     addRegisterClass(MVT::i64, &X86::GR64RegClass);
155
156   for (MVT VT : MVT::integer_valuetypes())
157     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
158
159   // We don't accept any truncstore of integer registers.
160   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
161   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
162   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
163   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
164   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
165   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
166
167   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
168
169   // SETOEQ and SETUNE require checking two conditions.
170   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
171   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
172   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
173   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
174   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
175   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
176
177   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
178   // operation.
179   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
180   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
181   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
182
183   if (Subtarget->is64Bit()) {
184     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
185     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
186   } else if (!Subtarget->useSoftFloat()) {
187     // We have an algorithm for SSE2->double, and we turn this into a
188     // 64-bit FILD followed by conditional FADD for other targets.
189     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
190     // We have an algorithm for SSE2, and we turn this into a 64-bit
191     // FILD for other targets.
192     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
193   }
194
195   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
196   // this operation.
197   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
198   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
199
200   if (!Subtarget->useSoftFloat()) {
201     // SSE has no i16 to fp conversion, only i32
202     if (X86ScalarSSEf32) {
203       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
204       // f32 and f64 cases are Legal, f80 case is not
205       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
206     } else {
207       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
208       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
209     }
210   } else {
211     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
212     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
213   }
214
215   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
216   // are Legal, f80 is custom lowered.
217   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
218   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
219
220   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
221   // this operation.
222   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
223   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
224
225   if (X86ScalarSSEf32) {
226     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
227     // f32 and f64 cases are Legal, f80 case is not
228     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
229   } else {
230     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
231     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
232   }
233
234   // Handle FP_TO_UINT by promoting the destination to a larger signed
235   // conversion.
236   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
237   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
238   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
239
240   if (Subtarget->is64Bit()) {
241     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
242     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
243   } else if (!Subtarget->useSoftFloat()) {
244     // Since AVX is a superset of SSE3, only check for SSE here.
245     if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
246       // Expand FP_TO_UINT into a select.
247       // FIXME: We would like to use a Custom expander here eventually to do
248       // the optimal thing for SSE vs. the default expansion in the legalizer.
249       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
250     else
251       // With SSE3 we can use fisttpll to convert to a signed i64; without
252       // SSE, we're stuck with a fistpll.
253       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
254   }
255
256   if (isTargetFTOL()) {
257     // Use the _ftol2 runtime function, which has a pseudo-instruction
258     // to handle its weird calling convention.
259     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Custom);
260   }
261
262   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
263   if (!X86ScalarSSEf64) {
264     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
265     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
266     if (Subtarget->is64Bit()) {
267       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
268       // Without SSE, i64->f64 goes through memory.
269       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
270     }
271   }
272
273   // Scalar integer divide and remainder are lowered to use operations that
274   // produce two results, to match the available instructions. This exposes
275   // the two-result form to trivial CSE, which is able to combine x/y and x%y
276   // into a single instruction.
277   //
278   // Scalar integer multiply-high is also lowered to use two-result
279   // operations, to match the available instructions. However, plain multiply
280   // (low) operations are left as Legal, as there are single-result
281   // instructions for this in x86. Using the two-result multiply instructions
282   // when both high and low results are needed must be arranged by dagcombine.
283   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
284     MVT VT = IntVTs[i];
285     setOperationAction(ISD::MULHS, VT, Expand);
286     setOperationAction(ISD::MULHU, VT, Expand);
287     setOperationAction(ISD::SDIV, VT, Expand);
288     setOperationAction(ISD::UDIV, VT, Expand);
289     setOperationAction(ISD::SREM, VT, Expand);
290     setOperationAction(ISD::UREM, VT, Expand);
291
292     // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
293     setOperationAction(ISD::ADDC, VT, Custom);
294     setOperationAction(ISD::ADDE, VT, Custom);
295     setOperationAction(ISD::SUBC, VT, Custom);
296     setOperationAction(ISD::SUBE, VT, Custom);
297   }
298
299   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
300   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
301   setOperationAction(ISD::BR_CC            , MVT::f32,   Expand);
302   setOperationAction(ISD::BR_CC            , MVT::f64,   Expand);
303   setOperationAction(ISD::BR_CC            , MVT::f80,   Expand);
304   setOperationAction(ISD::BR_CC            , MVT::i8,    Expand);
305   setOperationAction(ISD::BR_CC            , MVT::i16,   Expand);
306   setOperationAction(ISD::BR_CC            , MVT::i32,   Expand);
307   setOperationAction(ISD::BR_CC            , MVT::i64,   Expand);
308   setOperationAction(ISD::SELECT_CC        , MVT::f32,   Expand);
309   setOperationAction(ISD::SELECT_CC        , MVT::f64,   Expand);
310   setOperationAction(ISD::SELECT_CC        , MVT::f80,   Expand);
311   setOperationAction(ISD::SELECT_CC        , MVT::i8,    Expand);
312   setOperationAction(ISD::SELECT_CC        , MVT::i16,   Expand);
313   setOperationAction(ISD::SELECT_CC        , MVT::i32,   Expand);
314   setOperationAction(ISD::SELECT_CC        , MVT::i64,   Expand);
315   if (Subtarget->is64Bit())
316     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
317   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
318   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
319   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
320   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
321   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
322   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
323   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
324   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
325
326   // Promote the i8 variants and force them on up to i32 which has a shorter
327   // encoding.
328   setOperationAction(ISD::CTTZ             , MVT::i8   , Promote);
329   AddPromotedToType (ISD::CTTZ             , MVT::i8   , MVT::i32);
330   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , Promote);
331   AddPromotedToType (ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , MVT::i32);
332   if (Subtarget->hasBMI()) {
333     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16  , Expand);
334     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32  , Expand);
335     if (Subtarget->is64Bit())
336       setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
337   } else {
338     setOperationAction(ISD::CTTZ           , MVT::i16  , Custom);
339     setOperationAction(ISD::CTTZ           , MVT::i32  , Custom);
340     if (Subtarget->is64Bit())
341       setOperationAction(ISD::CTTZ         , MVT::i64  , Custom);
342   }
343
344   if (Subtarget->hasLZCNT()) {
345     // When promoting the i8 variants, force them to i32 for a shorter
346     // encoding.
347     setOperationAction(ISD::CTLZ           , MVT::i8   , Promote);
348     AddPromotedToType (ISD::CTLZ           , MVT::i8   , MVT::i32);
349     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Promote);
350     AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8   , MVT::i32);
351     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Expand);
352     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Expand);
353     if (Subtarget->is64Bit())
354       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
355   } else {
356     setOperationAction(ISD::CTLZ           , MVT::i8   , Custom);
357     setOperationAction(ISD::CTLZ           , MVT::i16  , Custom);
358     setOperationAction(ISD::CTLZ           , MVT::i32  , Custom);
359     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Custom);
360     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Custom);
361     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Custom);
362     if (Subtarget->is64Bit()) {
363       setOperationAction(ISD::CTLZ         , MVT::i64  , Custom);
364       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
365     }
366   }
367
368   // Special handling for half-precision floating point conversions.
369   // If we don't have F16C support, then lower half float conversions
370   // into library calls.
371   if (Subtarget->useSoftFloat() || !Subtarget->hasF16C()) {
372     setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
373     setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
374   }
375
376   // There's never any support for operations beyond MVT::f32.
377   setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
378   setOperationAction(ISD::FP16_TO_FP, MVT::f80, Expand);
379   setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
380   setOperationAction(ISD::FP_TO_FP16, MVT::f80, Expand);
381
382   setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
383   setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
384   setLoadExtAction(ISD::EXTLOAD, MVT::f80, MVT::f16, Expand);
385   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
386   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
387   setTruncStoreAction(MVT::f80, MVT::f16, Expand);
388
389   if (Subtarget->hasPOPCNT()) {
390     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
391   } else {
392     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
393     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
394     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
395     if (Subtarget->is64Bit())
396       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
397   }
398
399   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
400
401   if (!Subtarget->hasMOVBE())
402     setOperationAction(ISD::BSWAP          , MVT::i16  , Expand);
403
404   // These should be promoted to a larger select which is supported.
405   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
406   // X86 wants to expand cmov itself.
407   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
408   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
409   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
410   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
411   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
412   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
413   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
414   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
415   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
416   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
417   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
418   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
419   if (Subtarget->is64Bit()) {
420     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
421     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
422   }
423   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
424   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
425   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
426   // support continuation, user-level threading, and etc.. As a result, no
427   // other SjLj exception interfaces are implemented and please don't build
428   // your own exception handling based on them.
429   // LLVM/Clang supports zero-cost DWARF exception handling.
430   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
431   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
432
433   // Darwin ABI issue.
434   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
435   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
436   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
437   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
438   if (Subtarget->is64Bit())
439     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
440   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
441   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
442   if (Subtarget->is64Bit()) {
443     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
444     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
445     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
446     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
447     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
448   }
449   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
450   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
451   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
452   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
453   if (Subtarget->is64Bit()) {
454     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
455     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
456     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
457   }
458
459   if (Subtarget->hasSSE1())
460     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
461
462   setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
463
464   // Expand certain atomics
465   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
466     MVT VT = IntVTs[i];
467     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, VT, Custom);
468     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
469     setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
470   }
471
472   if (Subtarget->hasCmpxchg16b()) {
473     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i128, Custom);
474   }
475
476   // FIXME - use subtarget debug flags
477   if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetELF() &&
478       !Subtarget->isTargetCygMing() && !Subtarget->isTargetWin64()) {
479     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
480   }
481
482   if (Subtarget->is64Bit()) {
483     setExceptionPointerRegister(X86::RAX);
484     setExceptionSelectorRegister(X86::RDX);
485   } else {
486     setExceptionPointerRegister(X86::EAX);
487     setExceptionSelectorRegister(X86::EDX);
488   }
489   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
490   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
491
492   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
493   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
494
495   setOperationAction(ISD::TRAP, MVT::Other, Legal);
496   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
497
498   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
499   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
500   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
501   if (Subtarget->is64Bit() && !Subtarget->isTargetWin64()) {
502     // TargetInfo::X86_64ABIBuiltinVaList
503     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
504     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
505   } else {
506     // TargetInfo::CharPtrBuiltinVaList
507     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
508     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
509   }
510
511   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
512   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
513
514   setOperationAction(ISD::DYNAMIC_STACKALLOC, getPointerTy(), Custom);
515
516   // GC_TRANSITION_START and GC_TRANSITION_END need custom lowering.
517   setOperationAction(ISD::GC_TRANSITION_START, MVT::Other, Custom);
518   setOperationAction(ISD::GC_TRANSITION_END, MVT::Other, Custom);
519
520   if (!Subtarget->useSoftFloat() && X86ScalarSSEf64) {
521     // f32 and f64 use SSE.
522     // Set up the FP register classes.
523     addRegisterClass(MVT::f32, &X86::FR32RegClass);
524     addRegisterClass(MVT::f64, &X86::FR64RegClass);
525
526     // Use ANDPD to simulate FABS.
527     setOperationAction(ISD::FABS , MVT::f64, Custom);
528     setOperationAction(ISD::FABS , MVT::f32, Custom);
529
530     // Use XORP to simulate FNEG.
531     setOperationAction(ISD::FNEG , MVT::f64, Custom);
532     setOperationAction(ISD::FNEG , MVT::f32, Custom);
533
534     // Use ANDPD and ORPD to simulate FCOPYSIGN.
535     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
536     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
537
538     // Lower this to FGETSIGNx86 plus an AND.
539     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
540     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
541
542     // We don't support sin/cos/fmod
543     setOperationAction(ISD::FSIN   , MVT::f64, Expand);
544     setOperationAction(ISD::FCOS   , MVT::f64, Expand);
545     setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
546     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
547     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
548     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
549
550     // Expand FP immediates into loads from the stack, except for the special
551     // cases we handle.
552     addLegalFPImmediate(APFloat(+0.0)); // xorpd
553     addLegalFPImmediate(APFloat(+0.0f)); // xorps
554   } else if (!Subtarget->useSoftFloat() && X86ScalarSSEf32) {
555     // Use SSE for f32, x87 for f64.
556     // Set up the FP register classes.
557     addRegisterClass(MVT::f32, &X86::FR32RegClass);
558     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
559
560     // Use ANDPS to simulate FABS.
561     setOperationAction(ISD::FABS , MVT::f32, Custom);
562
563     // Use XORP to simulate FNEG.
564     setOperationAction(ISD::FNEG , MVT::f32, Custom);
565
566     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
567
568     // Use ANDPS and ORPS to simulate FCOPYSIGN.
569     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
570     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
571
572     // We don't support sin/cos/fmod
573     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
574     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
575     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
576
577     // Special cases we handle for FP constants.
578     addLegalFPImmediate(APFloat(+0.0f)); // xorps
579     addLegalFPImmediate(APFloat(+0.0)); // FLD0
580     addLegalFPImmediate(APFloat(+1.0)); // FLD1
581     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
582     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
583
584     if (!TM.Options.UnsafeFPMath) {
585       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
586       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
587       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
588     }
589   } else if (!Subtarget->useSoftFloat()) {
590     // f32 and f64 in x87.
591     // Set up the FP register classes.
592     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
593     addRegisterClass(MVT::f32, &X86::RFP32RegClass);
594
595     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
596     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
597     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
598     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
599
600     if (!TM.Options.UnsafeFPMath) {
601       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
602       setOperationAction(ISD::FSIN   , MVT::f32, Expand);
603       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
604       setOperationAction(ISD::FCOS   , MVT::f32, Expand);
605       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
606       setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
607     }
608     addLegalFPImmediate(APFloat(+0.0)); // FLD0
609     addLegalFPImmediate(APFloat(+1.0)); // FLD1
610     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
611     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
612     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
613     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
614     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
615     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
616   }
617
618   // We don't support FMA.
619   setOperationAction(ISD::FMA, MVT::f64, Expand);
620   setOperationAction(ISD::FMA, MVT::f32, Expand);
621
622   // Long double always uses X87.
623   if (!Subtarget->useSoftFloat()) {
624     addRegisterClass(MVT::f80, &X86::RFP80RegClass);
625     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
626     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
627     {
628       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
629       addLegalFPImmediate(TmpFlt);  // FLD0
630       TmpFlt.changeSign();
631       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
632
633       bool ignored;
634       APFloat TmpFlt2(+1.0);
635       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
636                       &ignored);
637       addLegalFPImmediate(TmpFlt2);  // FLD1
638       TmpFlt2.changeSign();
639       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
640     }
641
642     if (!TM.Options.UnsafeFPMath) {
643       setOperationAction(ISD::FSIN   , MVT::f80, Expand);
644       setOperationAction(ISD::FCOS   , MVT::f80, Expand);
645       setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
646     }
647
648     setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
649     setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
650     setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
651     setOperationAction(ISD::FRINT,  MVT::f80, Expand);
652     setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
653     setOperationAction(ISD::FMA, MVT::f80, Expand);
654   }
655
656   // Always use a library call for pow.
657   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
658   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
659   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
660
661   setOperationAction(ISD::FLOG, MVT::f80, Expand);
662   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
663   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
664   setOperationAction(ISD::FEXP, MVT::f80, Expand);
665   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
666   setOperationAction(ISD::FMINNUM, MVT::f80, Expand);
667   setOperationAction(ISD::FMAXNUM, MVT::f80, Expand);
668
669   // First set operation action for all vector types to either promote
670   // (for widening) or expand (for scalarization). Then we will selectively
671   // turn on ones that can be effectively codegen'd.
672   for (MVT VT : MVT::vector_valuetypes()) {
673     setOperationAction(ISD::ADD , VT, Expand);
674     setOperationAction(ISD::SUB , VT, Expand);
675     setOperationAction(ISD::FADD, VT, Expand);
676     setOperationAction(ISD::FNEG, VT, Expand);
677     setOperationAction(ISD::FSUB, VT, Expand);
678     setOperationAction(ISD::MUL , VT, Expand);
679     setOperationAction(ISD::FMUL, VT, Expand);
680     setOperationAction(ISD::SDIV, VT, Expand);
681     setOperationAction(ISD::UDIV, VT, Expand);
682     setOperationAction(ISD::FDIV, VT, Expand);
683     setOperationAction(ISD::SREM, VT, Expand);
684     setOperationAction(ISD::UREM, VT, Expand);
685     setOperationAction(ISD::LOAD, VT, Expand);
686     setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
687     setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
688     setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
689     setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
690     setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
691     setOperationAction(ISD::FABS, VT, Expand);
692     setOperationAction(ISD::FSIN, VT, Expand);
693     setOperationAction(ISD::FSINCOS, VT, Expand);
694     setOperationAction(ISD::FCOS, VT, Expand);
695     setOperationAction(ISD::FSINCOS, VT, Expand);
696     setOperationAction(ISD::FREM, VT, Expand);
697     setOperationAction(ISD::FMA,  VT, Expand);
698     setOperationAction(ISD::FPOWI, VT, Expand);
699     setOperationAction(ISD::FSQRT, VT, Expand);
700     setOperationAction(ISD::FCOPYSIGN, VT, Expand);
701     setOperationAction(ISD::FFLOOR, VT, Expand);
702     setOperationAction(ISD::FCEIL, VT, Expand);
703     setOperationAction(ISD::FTRUNC, VT, Expand);
704     setOperationAction(ISD::FRINT, VT, Expand);
705     setOperationAction(ISD::FNEARBYINT, VT, Expand);
706     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
707     setOperationAction(ISD::MULHS, VT, Expand);
708     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
709     setOperationAction(ISD::MULHU, VT, Expand);
710     setOperationAction(ISD::SDIVREM, VT, Expand);
711     setOperationAction(ISD::UDIVREM, VT, Expand);
712     setOperationAction(ISD::FPOW, VT, Expand);
713     setOperationAction(ISD::CTPOP, VT, Expand);
714     setOperationAction(ISD::CTTZ, VT, Expand);
715     setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
716     setOperationAction(ISD::CTLZ, VT, Expand);
717     setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
718     setOperationAction(ISD::SHL, VT, Expand);
719     setOperationAction(ISD::SRA, VT, Expand);
720     setOperationAction(ISD::SRL, VT, Expand);
721     setOperationAction(ISD::ROTL, VT, Expand);
722     setOperationAction(ISD::ROTR, VT, Expand);
723     setOperationAction(ISD::BSWAP, VT, Expand);
724     setOperationAction(ISD::SETCC, VT, Expand);
725     setOperationAction(ISD::FLOG, VT, Expand);
726     setOperationAction(ISD::FLOG2, VT, Expand);
727     setOperationAction(ISD::FLOG10, VT, Expand);
728     setOperationAction(ISD::FEXP, VT, Expand);
729     setOperationAction(ISD::FEXP2, VT, Expand);
730     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
731     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
732     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
733     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
734     setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
735     setOperationAction(ISD::TRUNCATE, VT, Expand);
736     setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
737     setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
738     setOperationAction(ISD::ANY_EXTEND, VT, Expand);
739     setOperationAction(ISD::VSELECT, VT, Expand);
740     setOperationAction(ISD::SELECT_CC, VT, Expand);
741     for (MVT InnerVT : MVT::vector_valuetypes()) {
742       setTruncStoreAction(InnerVT, VT, Expand);
743
744       setLoadExtAction(ISD::SEXTLOAD, InnerVT, VT, Expand);
745       setLoadExtAction(ISD::ZEXTLOAD, InnerVT, VT, Expand);
746
747       // N.b. ISD::EXTLOAD legality is basically ignored except for i1-like
748       // types, we have to deal with them whether we ask for Expansion or not.
749       // Setting Expand causes its own optimisation problems though, so leave
750       // them legal.
751       if (VT.getVectorElementType() == MVT::i1)
752         setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
753
754       // EXTLOAD for MVT::f16 vectors is not legal because f16 vectors are
755       // split/scalarized right now.
756       if (VT.getVectorElementType() == MVT::f16)
757         setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
758     }
759   }
760
761   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
762   // with -msoft-float, disable use of MMX as well.
763   if (!Subtarget->useSoftFloat() && Subtarget->hasMMX()) {
764     addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
765     // No operations on x86mmx supported, everything uses intrinsics.
766   }
767
768   // MMX-sized vectors (other than x86mmx) are expected to be expanded
769   // into smaller operations.
770   for (MVT MMXTy : {MVT::v8i8, MVT::v4i16, MVT::v2i32, MVT::v1i64}) {
771     setOperationAction(ISD::MULHS,              MMXTy,      Expand);
772     setOperationAction(ISD::AND,                MMXTy,      Expand);
773     setOperationAction(ISD::OR,                 MMXTy,      Expand);
774     setOperationAction(ISD::XOR,                MMXTy,      Expand);
775     setOperationAction(ISD::SCALAR_TO_VECTOR,   MMXTy,      Expand);
776     setOperationAction(ISD::SELECT,             MMXTy,      Expand);
777     setOperationAction(ISD::BITCAST,            MMXTy,      Expand);
778   }
779   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
780
781   if (!Subtarget->useSoftFloat() && Subtarget->hasSSE1()) {
782     addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
783
784     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
785     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
786     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
787     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
788     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
789     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
790     setOperationAction(ISD::FABS,               MVT::v4f32, Custom);
791     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
792     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
793     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
794     setOperationAction(ISD::VSELECT,            MVT::v4f32, Custom);
795     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
796     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
797     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Custom);
798   }
799
800   if (!Subtarget->useSoftFloat() && Subtarget->hasSSE2()) {
801     addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
802
803     // FIXME: Unfortunately, -soft-float and -no-implicit-float mean XMM
804     // registers cannot be used even for integer operations.
805     addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
806     addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
807     addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
808     addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
809
810     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
811     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
812     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
813     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
814     setOperationAction(ISD::MUL,                MVT::v16i8, Custom);
815     setOperationAction(ISD::MUL,                MVT::v4i32, Custom);
816     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
817     setOperationAction(ISD::UMUL_LOHI,          MVT::v4i32, Custom);
818     setOperationAction(ISD::SMUL_LOHI,          MVT::v4i32, Custom);
819     setOperationAction(ISD::MULHU,              MVT::v8i16, Legal);
820     setOperationAction(ISD::MULHS,              MVT::v8i16, Legal);
821     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
822     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
823     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
824     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
825     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
826     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
827     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
828     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
829     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
830     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
831     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
832     setOperationAction(ISD::FABS,               MVT::v2f64, Custom);
833
834     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
835     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
836     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
837     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
838
839     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
840     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
841     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
842     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
843     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
844
845     // Only provide customized ctpop vector bit twiddling for vector types we
846     // know to perform better than using the popcnt instructions on each vector
847     // element. If popcnt isn't supported, always provide the custom version.
848     if (!Subtarget->hasPOPCNT()) {
849       setOperationAction(ISD::CTPOP,            MVT::v4i32, Custom);
850       setOperationAction(ISD::CTPOP,            MVT::v2i64, Custom);
851     }
852
853     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
854     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
855       MVT VT = (MVT::SimpleValueType)i;
856       // Do not attempt to custom lower non-power-of-2 vectors
857       if (!isPowerOf2_32(VT.getVectorNumElements()))
858         continue;
859       // Do not attempt to custom lower non-128-bit vectors
860       if (!VT.is128BitVector())
861         continue;
862       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
863       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
864       setOperationAction(ISD::VSELECT,            VT, Custom);
865       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
866     }
867
868     // We support custom legalizing of sext and anyext loads for specific
869     // memory vector types which we can load as a scalar (or sequence of
870     // scalars) and extend in-register to a legal 128-bit vector type. For sext
871     // loads these must work with a single scalar load.
872     for (MVT VT : MVT::integer_vector_valuetypes()) {
873       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i8, Custom);
874       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i16, Custom);
875       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v8i8, Custom);
876       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i8, Custom);
877       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i16, Custom);
878       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i32, Custom);
879       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i8, Custom);
880       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i16, Custom);
881       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8i8, Custom);
882     }
883
884     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
885     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
886     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
887     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
888     setOperationAction(ISD::VSELECT,            MVT::v2f64, Custom);
889     setOperationAction(ISD::VSELECT,            MVT::v2i64, Custom);
890     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
891     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
892
893     if (Subtarget->is64Bit()) {
894       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
895       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
896     }
897
898     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
899     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
900       MVT VT = (MVT::SimpleValueType)i;
901
902       // Do not attempt to promote non-128-bit vectors
903       if (!VT.is128BitVector())
904         continue;
905
906       setOperationAction(ISD::AND,    VT, Promote);
907       AddPromotedToType (ISD::AND,    VT, MVT::v2i64);
908       setOperationAction(ISD::OR,     VT, Promote);
909       AddPromotedToType (ISD::OR,     VT, MVT::v2i64);
910       setOperationAction(ISD::XOR,    VT, Promote);
911       AddPromotedToType (ISD::XOR,    VT, MVT::v2i64);
912       setOperationAction(ISD::LOAD,   VT, Promote);
913       AddPromotedToType (ISD::LOAD,   VT, MVT::v2i64);
914       setOperationAction(ISD::SELECT, VT, Promote);
915       AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
916     }
917
918     // Custom lower v2i64 and v2f64 selects.
919     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
920     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
921     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
922     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
923
924     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
925     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
926
927     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i8,  Custom);
928     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i16, Custom);
929     // As there is no 64-bit GPR available, we need build a special custom
930     // sequence to convert from v2i32 to v2f32.
931     if (!Subtarget->is64Bit())
932       setOperationAction(ISD::UINT_TO_FP,       MVT::v2f32, Custom);
933
934     setOperationAction(ISD::FP_EXTEND,          MVT::v2f32, Custom);
935     setOperationAction(ISD::FP_ROUND,           MVT::v2f32, Custom);
936
937     for (MVT VT : MVT::fp_vector_valuetypes())
938       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2f32, Legal);
939
940     setOperationAction(ISD::BITCAST,            MVT::v2i32, Custom);
941     setOperationAction(ISD::BITCAST,            MVT::v4i16, Custom);
942     setOperationAction(ISD::BITCAST,            MVT::v8i8,  Custom);
943   }
944
945   if (!Subtarget->useSoftFloat() && Subtarget->hasSSE41()) {
946     for (MVT RoundedTy : {MVT::f32, MVT::f64, MVT::v4f32, MVT::v2f64}) {
947       setOperationAction(ISD::FFLOOR,           RoundedTy,  Legal);
948       setOperationAction(ISD::FCEIL,            RoundedTy,  Legal);
949       setOperationAction(ISD::FTRUNC,           RoundedTy,  Legal);
950       setOperationAction(ISD::FRINT,            RoundedTy,  Legal);
951       setOperationAction(ISD::FNEARBYINT,       RoundedTy,  Legal);
952     }
953
954     // FIXME: Do we need to handle scalar-to-vector here?
955     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
956
957     // We directly match byte blends in the backend as they match the VSELECT
958     // condition form.
959     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
960
961     // SSE41 brings specific instructions for doing vector sign extend even in
962     // cases where we don't have SRA.
963     for (MVT VT : MVT::integer_vector_valuetypes()) {
964       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i8, Custom);
965       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i16, Custom);
966       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i32, Custom);
967     }
968
969     // SSE41 also has vector sign/zero extending loads, PMOV[SZ]X
970     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i16, MVT::v8i8,  Legal);
971     setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i8,  Legal);
972     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i8,  Legal);
973     setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
974     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
975     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
976
977     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i16, MVT::v8i8,  Legal);
978     setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i8,  Legal);
979     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i8,  Legal);
980     setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
981     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
982     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
983
984     // i8 and i16 vectors are custom because the source register and source
985     // source memory operand types are not the same width.  f32 vectors are
986     // custom since the immediate controlling the insert encodes additional
987     // information.
988     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
989     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
990     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
991     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
992
993     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
994     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
995     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
996     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
997
998     // FIXME: these should be Legal, but that's only for the case where
999     // the index is constant.  For now custom expand to deal with that.
1000     if (Subtarget->is64Bit()) {
1001       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1002       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1003     }
1004   }
1005
1006   if (Subtarget->hasSSE2()) {
1007     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
1008     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
1009
1010     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
1011     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
1012
1013     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
1014     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
1015
1016     // In the customized shift lowering, the legal cases in AVX2 will be
1017     // recognized.
1018     setOperationAction(ISD::SRL,               MVT::v2i64, Custom);
1019     setOperationAction(ISD::SRL,               MVT::v4i32, Custom);
1020
1021     setOperationAction(ISD::SHL,               MVT::v2i64, Custom);
1022     setOperationAction(ISD::SHL,               MVT::v4i32, Custom);
1023
1024     setOperationAction(ISD::SRA,               MVT::v4i32, Custom);
1025   }
1026
1027   if (!Subtarget->useSoftFloat() && Subtarget->hasFp256()) {
1028     addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1029     addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1030     addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1031     addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1032     addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1033     addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1034
1035     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1036     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1037     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1038
1039     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1040     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1041     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1042     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1043     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1044     setOperationAction(ISD::FFLOOR,             MVT::v8f32, Legal);
1045     setOperationAction(ISD::FCEIL,              MVT::v8f32, Legal);
1046     setOperationAction(ISD::FTRUNC,             MVT::v8f32, Legal);
1047     setOperationAction(ISD::FRINT,              MVT::v8f32, Legal);
1048     setOperationAction(ISD::FNEARBYINT,         MVT::v8f32, Legal);
1049     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1050     setOperationAction(ISD::FABS,               MVT::v8f32, Custom);
1051
1052     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1053     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1054     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1055     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1056     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1057     setOperationAction(ISD::FFLOOR,             MVT::v4f64, Legal);
1058     setOperationAction(ISD::FCEIL,              MVT::v4f64, Legal);
1059     setOperationAction(ISD::FTRUNC,             MVT::v4f64, Legal);
1060     setOperationAction(ISD::FRINT,              MVT::v4f64, Legal);
1061     setOperationAction(ISD::FNEARBYINT,         MVT::v4f64, Legal);
1062     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1063     setOperationAction(ISD::FABS,               MVT::v4f64, Custom);
1064
1065     // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1066     // even though v8i16 is a legal type.
1067     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i16, Promote);
1068     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i16, Promote);
1069     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1070
1071     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i16, Promote);
1072     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1073     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1074
1075     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i8,  Custom);
1076     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i16, Custom);
1077
1078     for (MVT VT : MVT::fp_vector_valuetypes())
1079       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4f32, Legal);
1080
1081     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1082     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1083
1084     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1085     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1086
1087     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1088     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1089
1090     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1091     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1092     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1093     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1094
1095     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1096     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1097     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1098
1099     setOperationAction(ISD::SIGN_EXTEND,       MVT::v4i64, Custom);
1100     setOperationAction(ISD::SIGN_EXTEND,       MVT::v8i32, Custom);
1101     setOperationAction(ISD::SIGN_EXTEND,       MVT::v16i16, Custom);
1102     setOperationAction(ISD::ZERO_EXTEND,       MVT::v4i64, Custom);
1103     setOperationAction(ISD::ZERO_EXTEND,       MVT::v8i32, Custom);
1104     setOperationAction(ISD::ZERO_EXTEND,       MVT::v16i16, Custom);
1105     setOperationAction(ISD::ANY_EXTEND,        MVT::v4i64, Custom);
1106     setOperationAction(ISD::ANY_EXTEND,        MVT::v8i32, Custom);
1107     setOperationAction(ISD::ANY_EXTEND,        MVT::v16i16, Custom);
1108     setOperationAction(ISD::TRUNCATE,          MVT::v16i8, Custom);
1109     setOperationAction(ISD::TRUNCATE,          MVT::v8i16, Custom);
1110     setOperationAction(ISD::TRUNCATE,          MVT::v4i32, Custom);
1111
1112     if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1113       setOperationAction(ISD::FMA,             MVT::v8f32, Legal);
1114       setOperationAction(ISD::FMA,             MVT::v4f64, Legal);
1115       setOperationAction(ISD::FMA,             MVT::v4f32, Legal);
1116       setOperationAction(ISD::FMA,             MVT::v2f64, Legal);
1117       setOperationAction(ISD::FMA,             MVT::f32, Legal);
1118       setOperationAction(ISD::FMA,             MVT::f64, Legal);
1119     }
1120
1121     if (Subtarget->hasInt256()) {
1122       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1123       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1124       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1125       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1126
1127       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1128       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1129       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1130       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1131
1132       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1133       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1134       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1135       setOperationAction(ISD::MUL,             MVT::v32i8, Custom);
1136
1137       setOperationAction(ISD::UMUL_LOHI,       MVT::v8i32, Custom);
1138       setOperationAction(ISD::SMUL_LOHI,       MVT::v8i32, Custom);
1139       setOperationAction(ISD::MULHU,           MVT::v16i16, Legal);
1140       setOperationAction(ISD::MULHS,           MVT::v16i16, Legal);
1141
1142       // The custom lowering for UINT_TO_FP for v8i32 becomes interesting
1143       // when we have a 256bit-wide blend with immediate.
1144       setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Custom);
1145
1146       // Only provide customized ctpop vector bit twiddling for vector types we
1147       // know to perform better than using the popcnt instructions on each
1148       // vector element. If popcnt isn't supported, always provide the custom
1149       // version.
1150       if (!Subtarget->hasPOPCNT())
1151         setOperationAction(ISD::CTPOP,           MVT::v4i64, Custom);
1152
1153       // Custom CTPOP always performs better on natively supported v8i32
1154       setOperationAction(ISD::CTPOP,             MVT::v8i32, Custom);
1155
1156       // AVX2 also has wider vector sign/zero extending loads, VPMOV[SZ]X
1157       setLoadExtAction(ISD::SEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1158       setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32,  MVT::v8i8,  Legal);
1159       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i8,  Legal);
1160       setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32,  MVT::v8i16, Legal);
1161       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i16, Legal);
1162       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i32, Legal);
1163
1164       setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1165       setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32,  MVT::v8i8,  Legal);
1166       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i8,  Legal);
1167       setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32,  MVT::v8i16, Legal);
1168       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i16, Legal);
1169       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i32, Legal);
1170     } else {
1171       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1172       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1173       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1174       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1175
1176       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1177       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1178       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1179       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1180
1181       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1182       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1183       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1184       setOperationAction(ISD::MUL,             MVT::v32i8, Custom);
1185     }
1186
1187     // In the customized shift lowering, the legal cases in AVX2 will be
1188     // recognized.
1189     setOperationAction(ISD::SRL,               MVT::v4i64, Custom);
1190     setOperationAction(ISD::SRL,               MVT::v8i32, Custom);
1191
1192     setOperationAction(ISD::SHL,               MVT::v4i64, Custom);
1193     setOperationAction(ISD::SHL,               MVT::v8i32, Custom);
1194
1195     setOperationAction(ISD::SRA,               MVT::v8i32, Custom);
1196
1197     // Custom lower several nodes for 256-bit types.
1198     for (MVT VT : MVT::vector_valuetypes()) {
1199       if (VT.getScalarSizeInBits() >= 32) {
1200         setOperationAction(ISD::MLOAD,  VT, Legal);
1201         setOperationAction(ISD::MSTORE, VT, Legal);
1202       }
1203       // Extract subvector is special because the value type
1204       // (result) is 128-bit but the source is 256-bit wide.
1205       if (VT.is128BitVector()) {
1206         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1207       }
1208       // Do not attempt to custom lower other non-256-bit vectors
1209       if (!VT.is256BitVector())
1210         continue;
1211
1212       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1213       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1214       setOperationAction(ISD::VSELECT,            VT, Custom);
1215       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1216       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1217       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1218       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1219       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1220     }
1221
1222     if (Subtarget->hasInt256())
1223       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1224
1225
1226     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1227     for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1228       MVT VT = (MVT::SimpleValueType)i;
1229
1230       // Do not attempt to promote non-256-bit vectors
1231       if (!VT.is256BitVector())
1232         continue;
1233
1234       setOperationAction(ISD::AND,    VT, Promote);
1235       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1236       setOperationAction(ISD::OR,     VT, Promote);
1237       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1238       setOperationAction(ISD::XOR,    VT, Promote);
1239       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1240       setOperationAction(ISD::LOAD,   VT, Promote);
1241       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1242       setOperationAction(ISD::SELECT, VT, Promote);
1243       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1244     }
1245   }
1246
1247   if (!Subtarget->useSoftFloat() && Subtarget->hasAVX512()) {
1248     addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1249     addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1250     addRegisterClass(MVT::v8i64,  &X86::VR512RegClass);
1251     addRegisterClass(MVT::v8f64,  &X86::VR512RegClass);
1252
1253     addRegisterClass(MVT::i1,     &X86::VK1RegClass);
1254     addRegisterClass(MVT::v8i1,   &X86::VK8RegClass);
1255     addRegisterClass(MVT::v16i1,  &X86::VK16RegClass);
1256
1257     for (MVT VT : MVT::fp_vector_valuetypes())
1258       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8f32, Legal);
1259
1260     setOperationAction(ISD::BR_CC,              MVT::i1,    Expand);
1261     setOperationAction(ISD::SETCC,              MVT::i1,    Custom);
1262     setOperationAction(ISD::XOR,                MVT::i1,    Legal);
1263     setOperationAction(ISD::OR,                 MVT::i1,    Legal);
1264     setOperationAction(ISD::AND,                MVT::i1,    Legal);
1265     setOperationAction(ISD::LOAD,               MVT::v16f32, Legal);
1266     setOperationAction(ISD::LOAD,               MVT::v8f64, Legal);
1267     setOperationAction(ISD::LOAD,               MVT::v8i64, Legal);
1268     setOperationAction(ISD::LOAD,               MVT::v16i32, Legal);
1269     setOperationAction(ISD::LOAD,               MVT::v16i1, Legal);
1270
1271     setOperationAction(ISD::FADD,               MVT::v16f32, Legal);
1272     setOperationAction(ISD::FSUB,               MVT::v16f32, Legal);
1273     setOperationAction(ISD::FMUL,               MVT::v16f32, Legal);
1274     setOperationAction(ISD::FDIV,               MVT::v16f32, Legal);
1275     setOperationAction(ISD::FSQRT,              MVT::v16f32, Legal);
1276     setOperationAction(ISD::FNEG,               MVT::v16f32, Custom);
1277
1278     setOperationAction(ISD::FADD,               MVT::v8f64, Legal);
1279     setOperationAction(ISD::FSUB,               MVT::v8f64, Legal);
1280     setOperationAction(ISD::FMUL,               MVT::v8f64, Legal);
1281     setOperationAction(ISD::FDIV,               MVT::v8f64, Legal);
1282     setOperationAction(ISD::FSQRT,              MVT::v8f64, Legal);
1283     setOperationAction(ISD::FNEG,               MVT::v8f64, Custom);
1284     setOperationAction(ISD::FMA,                MVT::v8f64, Legal);
1285     setOperationAction(ISD::FMA,                MVT::v16f32, Legal);
1286
1287     setOperationAction(ISD::FP_TO_SINT,         MVT::i32, Legal);
1288     setOperationAction(ISD::FP_TO_UINT,         MVT::i32, Legal);
1289     setOperationAction(ISD::SINT_TO_FP,         MVT::i32, Legal);
1290     setOperationAction(ISD::UINT_TO_FP,         MVT::i32, Legal);
1291     if (Subtarget->is64Bit()) {
1292       setOperationAction(ISD::FP_TO_UINT,       MVT::i64, Legal);
1293       setOperationAction(ISD::FP_TO_SINT,       MVT::i64, Legal);
1294       setOperationAction(ISD::SINT_TO_FP,       MVT::i64, Legal);
1295       setOperationAction(ISD::UINT_TO_FP,       MVT::i64, Legal);
1296     }
1297     setOperationAction(ISD::FP_TO_SINT,         MVT::v16i32, Legal);
1298     setOperationAction(ISD::FP_TO_UINT,         MVT::v16i32, Legal);
1299     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i32, Legal);
1300     setOperationAction(ISD::FP_TO_UINT,         MVT::v4i32, Legal);
1301     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i32, Legal);
1302     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i1,   Custom);
1303     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i1,  Custom);
1304     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i8,  Promote);
1305     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i16, Promote);
1306     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i32, Legal);
1307     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i32, Legal);
1308     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Legal);
1309     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i8, Custom);
1310     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i16, Custom);
1311     setOperationAction(ISD::FP_ROUND,           MVT::v8f32, Legal);
1312     setOperationAction(ISD::FP_EXTEND,          MVT::v8f32, Legal);
1313
1314     setOperationAction(ISD::TRUNCATE,           MVT::i1, Custom);
1315     setOperationAction(ISD::TRUNCATE,           MVT::v16i8, Custom);
1316     setOperationAction(ISD::TRUNCATE,           MVT::v8i32, Custom);
1317     if (Subtarget->hasDQI()) {
1318       setOperationAction(ISD::TRUNCATE,           MVT::v2i1, Custom);
1319       setOperationAction(ISD::TRUNCATE,           MVT::v4i1, Custom);
1320     }
1321     setOperationAction(ISD::TRUNCATE,           MVT::v8i1, Custom);
1322     setOperationAction(ISD::TRUNCATE,           MVT::v16i1, Custom);
1323     setOperationAction(ISD::TRUNCATE,           MVT::v16i16, Custom);
1324     setOperationAction(ISD::ZERO_EXTEND,        MVT::v16i32, Custom);
1325     setOperationAction(ISD::ZERO_EXTEND,        MVT::v8i64, Custom);
1326     setOperationAction(ISD::ANY_EXTEND,         MVT::v16i32, Custom);
1327     setOperationAction(ISD::ANY_EXTEND,         MVT::v8i64, Custom);
1328     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i32, Custom);
1329     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i64, Custom);
1330     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i8, Custom);
1331     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i16, Custom);
1332     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i16, Custom);
1333     if (Subtarget->hasDQI()) {
1334       setOperationAction(ISD::SIGN_EXTEND,        MVT::v4i32, Custom);
1335       setOperationAction(ISD::SIGN_EXTEND,        MVT::v2i64, Custom);
1336     }
1337     setOperationAction(ISD::FFLOOR,             MVT::v16f32, Legal);
1338     setOperationAction(ISD::FFLOOR,             MVT::v8f64, Legal);
1339     setOperationAction(ISD::FCEIL,              MVT::v16f32, Legal);
1340     setOperationAction(ISD::FCEIL,              MVT::v8f64, Legal);
1341     setOperationAction(ISD::FTRUNC,             MVT::v16f32, Legal);
1342     setOperationAction(ISD::FTRUNC,             MVT::v8f64, Legal);
1343     setOperationAction(ISD::FRINT,              MVT::v16f32, Legal);
1344     setOperationAction(ISD::FRINT,              MVT::v8f64, Legal);
1345     setOperationAction(ISD::FNEARBYINT,         MVT::v16f32, Legal);
1346     setOperationAction(ISD::FNEARBYINT,         MVT::v8f64, Legal);
1347
1348     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8f64,  Custom);
1349     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i64,  Custom);
1350     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16f32,  Custom);
1351     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i32,  Custom);
1352     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i1, Legal);
1353
1354     setOperationAction(ISD::SETCC,              MVT::v16i1, Custom);
1355     setOperationAction(ISD::SETCC,              MVT::v8i1, Custom);
1356
1357     setOperationAction(ISD::MUL,              MVT::v8i64, Custom);
1358
1359     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1,  Custom);
1360     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1361     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i1, Custom);
1362     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i1, Custom);
1363     setOperationAction(ISD::BUILD_VECTOR,       MVT::v8i1, Custom);
1364     setOperationAction(ISD::BUILD_VECTOR,       MVT::v16i1, Custom);
1365     setOperationAction(ISD::SELECT,             MVT::v8f64, Custom);
1366     setOperationAction(ISD::SELECT,             MVT::v8i64, Custom);
1367     setOperationAction(ISD::SELECT,             MVT::v16f32, 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
1471     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1472       const MVT VT = (MVT::SimpleValueType)i;
1473
1474       const unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1475
1476       // Do not attempt to promote non-512-bit vectors.
1477       if (!VT.is512BitVector())
1478         continue;
1479
1480       if (EltSize < 32) {
1481         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1482         setOperationAction(ISD::VSELECT,             VT, Legal);
1483       }
1484     }
1485   }
1486
1487   if (!Subtarget->useSoftFloat() && Subtarget->hasVLX()) {
1488     addRegisterClass(MVT::v4i1,   &X86::VK4RegClass);
1489     addRegisterClass(MVT::v2i1,   &X86::VK2RegClass);
1490
1491     setOperationAction(ISD::SETCC,              MVT::v4i1, Custom);
1492     setOperationAction(ISD::SETCC,              MVT::v2i1, Custom);
1493     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4i1, Custom);
1494     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i1, Custom);
1495     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v8i1, Custom);
1496     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v4i1, Custom);
1497
1498     setOperationAction(ISD::AND,                MVT::v8i32, Legal);
1499     setOperationAction(ISD::OR,                 MVT::v8i32, Legal);
1500     setOperationAction(ISD::XOR,                MVT::v8i32, Legal);
1501     setOperationAction(ISD::AND,                MVT::v4i32, Legal);
1502     setOperationAction(ISD::OR,                 MVT::v4i32, Legal);
1503     setOperationAction(ISD::XOR,                MVT::v4i32, Legal);
1504   }
1505
1506   // We want to custom lower some of our intrinsics.
1507   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1508   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1509   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1510   if (!Subtarget->is64Bit())
1511     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1512
1513   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1514   // handle type legalization for these operations here.
1515   //
1516   // FIXME: We really should do custom legalization for addition and
1517   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1518   // than generic legalization for 64-bit multiplication-with-overflow, though.
1519   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1520     // Add/Sub/Mul with overflow operations are custom lowered.
1521     MVT VT = IntVTs[i];
1522     setOperationAction(ISD::SADDO, VT, Custom);
1523     setOperationAction(ISD::UADDO, VT, Custom);
1524     setOperationAction(ISD::SSUBO, VT, Custom);
1525     setOperationAction(ISD::USUBO, VT, Custom);
1526     setOperationAction(ISD::SMULO, VT, Custom);
1527     setOperationAction(ISD::UMULO, VT, Custom);
1528   }
1529
1530
1531   if (!Subtarget->is64Bit()) {
1532     // These libcalls are not available in 32-bit.
1533     setLibcallName(RTLIB::SHL_I128, nullptr);
1534     setLibcallName(RTLIB::SRL_I128, nullptr);
1535     setLibcallName(RTLIB::SRA_I128, nullptr);
1536   }
1537
1538   // Combine sin / cos into one node or libcall if possible.
1539   if (Subtarget->hasSinCos()) {
1540     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1541     setLibcallName(RTLIB::SINCOS_F64, "sincos");
1542     if (Subtarget->isTargetDarwin()) {
1543       // For MacOSX, we don't want the normal expansion of a libcall to sincos.
1544       // We want to issue a libcall to __sincos_stret to avoid memory traffic.
1545       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1546       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1547     }
1548   }
1549
1550   if (Subtarget->isTargetWin64()) {
1551     setOperationAction(ISD::SDIV, MVT::i128, Custom);
1552     setOperationAction(ISD::UDIV, MVT::i128, Custom);
1553     setOperationAction(ISD::SREM, MVT::i128, Custom);
1554     setOperationAction(ISD::UREM, MVT::i128, Custom);
1555     setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1556     setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1557   }
1558
1559   // We have target-specific dag combine patterns for the following nodes:
1560   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1561   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1562   setTargetDAGCombine(ISD::BITCAST);
1563   setTargetDAGCombine(ISD::VSELECT);
1564   setTargetDAGCombine(ISD::SELECT);
1565   setTargetDAGCombine(ISD::SHL);
1566   setTargetDAGCombine(ISD::SRA);
1567   setTargetDAGCombine(ISD::SRL);
1568   setTargetDAGCombine(ISD::OR);
1569   setTargetDAGCombine(ISD::AND);
1570   setTargetDAGCombine(ISD::ADD);
1571   setTargetDAGCombine(ISD::FADD);
1572   setTargetDAGCombine(ISD::FSUB);
1573   setTargetDAGCombine(ISD::FMA);
1574   setTargetDAGCombine(ISD::SUB);
1575   setTargetDAGCombine(ISD::LOAD);
1576   setTargetDAGCombine(ISD::MLOAD);
1577   setTargetDAGCombine(ISD::STORE);
1578   setTargetDAGCombine(ISD::MSTORE);
1579   setTargetDAGCombine(ISD::ZERO_EXTEND);
1580   setTargetDAGCombine(ISD::ANY_EXTEND);
1581   setTargetDAGCombine(ISD::SIGN_EXTEND);
1582   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1583   setTargetDAGCombine(ISD::TRUNCATE);
1584   setTargetDAGCombine(ISD::SINT_TO_FP);
1585   setTargetDAGCombine(ISD::SETCC);
1586   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1587   setTargetDAGCombine(ISD::BUILD_VECTOR);
1588   setTargetDAGCombine(ISD::MUL);
1589   setTargetDAGCombine(ISD::XOR);
1590
1591   computeRegisterProperties(Subtarget->getRegisterInfo());
1592
1593   // On Darwin, -Os means optimize for size without hurting performance,
1594   // do not reduce the limit.
1595   MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1596   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1597   MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1598   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1599   MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1600   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1601   setPrefLoopAlignment(4); // 2^4 bytes.
1602
1603   // Predictable cmov don't hurt on atom because it's in-order.
1604   PredictableSelectIsExpensive = !Subtarget->isAtom();
1605   EnableExtLdPromotion = true;
1606   setPrefFunctionAlignment(4); // 2^4 bytes.
1607
1608   verifyIntrinsicTables();
1609 }
1610
1611 // This has so far only been implemented for 64-bit MachO.
1612 bool X86TargetLowering::useLoadStackGuardNode() const {
1613   return Subtarget->isTargetMachO() && Subtarget->is64Bit();
1614 }
1615
1616 TargetLoweringBase::LegalizeTypeAction
1617 X86TargetLowering::getPreferredVectorAction(EVT VT) const {
1618   if (ExperimentalVectorWideningLegalization &&
1619       VT.getVectorNumElements() != 1 &&
1620       VT.getVectorElementType().getSimpleVT() != MVT::i1)
1621     return TypeWidenVector;
1622
1623   return TargetLoweringBase::getPreferredVectorAction(VT);
1624 }
1625
1626 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1627   if (!VT.isVector())
1628     return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1629
1630   const unsigned NumElts = VT.getVectorNumElements();
1631   const EVT EltVT = VT.getVectorElementType();
1632   if (VT.is512BitVector()) {
1633     if (Subtarget->hasAVX512())
1634       if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1635           EltVT == MVT::f32 || EltVT == MVT::f64)
1636         switch(NumElts) {
1637         case  8: return MVT::v8i1;
1638         case 16: return MVT::v16i1;
1639       }
1640     if (Subtarget->hasBWI())
1641       if (EltVT == MVT::i8 || EltVT == MVT::i16)
1642         switch(NumElts) {
1643         case 32: return MVT::v32i1;
1644         case 64: return MVT::v64i1;
1645       }
1646   }
1647
1648   if (VT.is256BitVector() || VT.is128BitVector()) {
1649     if (Subtarget->hasVLX())
1650       if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1651           EltVT == MVT::f32 || EltVT == MVT::f64)
1652         switch(NumElts) {
1653         case 2: return MVT::v2i1;
1654         case 4: return MVT::v4i1;
1655         case 8: return MVT::v8i1;
1656       }
1657     if (Subtarget->hasBWI() && Subtarget->hasVLX())
1658       if (EltVT == MVT::i8 || EltVT == MVT::i16)
1659         switch(NumElts) {
1660         case  8: return MVT::v8i1;
1661         case 16: return MVT::v16i1;
1662         case 32: return MVT::v32i1;
1663       }
1664   }
1665
1666   return VT.changeVectorElementTypeToInteger();
1667 }
1668
1669 /// Helper for getByValTypeAlignment to determine
1670 /// the desired ByVal argument alignment.
1671 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1672   if (MaxAlign == 16)
1673     return;
1674   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1675     if (VTy->getBitWidth() == 128)
1676       MaxAlign = 16;
1677   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1678     unsigned EltAlign = 0;
1679     getMaxByValAlign(ATy->getElementType(), EltAlign);
1680     if (EltAlign > MaxAlign)
1681       MaxAlign = EltAlign;
1682   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1683     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1684       unsigned EltAlign = 0;
1685       getMaxByValAlign(STy->getElementType(i), EltAlign);
1686       if (EltAlign > MaxAlign)
1687         MaxAlign = EltAlign;
1688       if (MaxAlign == 16)
1689         break;
1690     }
1691   }
1692 }
1693
1694 /// Return the desired alignment for ByVal aggregate
1695 /// function arguments in the caller parameter area. For X86, aggregates
1696 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1697 /// are at 4-byte boundaries.
1698 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1699   if (Subtarget->is64Bit()) {
1700     // Max of 8 and alignment of type.
1701     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1702     if (TyAlign > 8)
1703       return TyAlign;
1704     return 8;
1705   }
1706
1707   unsigned Align = 4;
1708   if (Subtarget->hasSSE1())
1709     getMaxByValAlign(Ty, Align);
1710   return Align;
1711 }
1712
1713 /// Returns the target specific optimal type for load
1714 /// and store operations as a result of memset, memcpy, and memmove
1715 /// lowering. If DstAlign is zero that means it's safe to destination
1716 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1717 /// means there isn't a need to check it against alignment requirement,
1718 /// probably because the source does not need to be loaded. If 'IsMemset' is
1719 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1720 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1721 /// source is constant so it does not need to be loaded.
1722 /// It returns EVT::Other if the type should be determined using generic
1723 /// target-independent logic.
1724 EVT
1725 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1726                                        unsigned DstAlign, unsigned SrcAlign,
1727                                        bool IsMemset, bool ZeroMemset,
1728                                        bool MemcpyStrSrc,
1729                                        MachineFunction &MF) const {
1730   const Function *F = MF.getFunction();
1731   if ((!IsMemset || ZeroMemset) &&
1732       !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
1733     if (Size >= 16 &&
1734         (Subtarget->isUnalignedMemAccessFast() ||
1735          ((DstAlign == 0 || DstAlign >= 16) &&
1736           (SrcAlign == 0 || SrcAlign >= 16)))) {
1737       if (Size >= 32) {
1738         if (Subtarget->hasInt256())
1739           return MVT::v8i32;
1740         if (Subtarget->hasFp256())
1741           return MVT::v8f32;
1742       }
1743       if (Subtarget->hasSSE2())
1744         return MVT::v4i32;
1745       if (Subtarget->hasSSE1())
1746         return MVT::v4f32;
1747     } else if (!MemcpyStrSrc && Size >= 8 &&
1748                !Subtarget->is64Bit() &&
1749                Subtarget->hasSSE2()) {
1750       // Do not use f64 to lower memcpy if source is string constant. It's
1751       // better to use i32 to avoid the loads.
1752       return MVT::f64;
1753     }
1754   }
1755   if (Subtarget->is64Bit() && Size >= 8)
1756     return MVT::i64;
1757   return MVT::i32;
1758 }
1759
1760 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1761   if (VT == MVT::f32)
1762     return X86ScalarSSEf32;
1763   else if (VT == MVT::f64)
1764     return X86ScalarSSEf64;
1765   return true;
1766 }
1767
1768 bool
1769 X86TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
1770                                                   unsigned,
1771                                                   unsigned,
1772                                                   bool *Fast) const {
1773   if (Fast)
1774     *Fast = Subtarget->isUnalignedMemAccessFast();
1775   return true;
1776 }
1777
1778 /// Return the entry encoding for a jump table in the
1779 /// current function.  The returned value is a member of the
1780 /// MachineJumpTableInfo::JTEntryKind enum.
1781 unsigned X86TargetLowering::getJumpTableEncoding() const {
1782   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1783   // symbol.
1784   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1785       Subtarget->isPICStyleGOT())
1786     return MachineJumpTableInfo::EK_Custom32;
1787
1788   // Otherwise, use the normal jump table encoding heuristics.
1789   return TargetLowering::getJumpTableEncoding();
1790 }
1791
1792 bool X86TargetLowering::useSoftFloat() const {
1793   return Subtarget->useSoftFloat();
1794 }
1795
1796 const MCExpr *
1797 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1798                                              const MachineBasicBlock *MBB,
1799                                              unsigned uid,MCContext &Ctx) const{
1800   assert(MBB->getParent()->getTarget().getRelocationModel() == Reloc::PIC_ &&
1801          Subtarget->isPICStyleGOT());
1802   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1803   // entries.
1804   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1805                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1806 }
1807
1808 /// Returns relocation base for the given PIC jumptable.
1809 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1810                                                     SelectionDAG &DAG) const {
1811   if (!Subtarget->is64Bit())
1812     // This doesn't have SDLoc associated with it, but is not really the
1813     // same as a Register.
1814     return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy());
1815   return Table;
1816 }
1817
1818 /// This returns the relocation base for the given PIC jumptable,
1819 /// the same as getPICJumpTableRelocBase, but as an MCExpr.
1820 const MCExpr *X86TargetLowering::
1821 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1822                              MCContext &Ctx) const {
1823   // X86-64 uses RIP relative addressing based on the jump table label.
1824   if (Subtarget->isPICStyleRIPRel())
1825     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1826
1827   // Otherwise, the reference is relative to the PIC base.
1828   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1829 }
1830
1831 std::pair<const TargetRegisterClass *, uint8_t>
1832 X86TargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
1833                                            MVT VT) const {
1834   const TargetRegisterClass *RRC = nullptr;
1835   uint8_t Cost = 1;
1836   switch (VT.SimpleTy) {
1837   default:
1838     return TargetLowering::findRepresentativeClass(TRI, VT);
1839   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1840     RRC = Subtarget->is64Bit() ? &X86::GR64RegClass : &X86::GR32RegClass;
1841     break;
1842   case MVT::x86mmx:
1843     RRC = &X86::VR64RegClass;
1844     break;
1845   case MVT::f32: case MVT::f64:
1846   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1847   case MVT::v4f32: case MVT::v2f64:
1848   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1849   case MVT::v4f64:
1850     RRC = &X86::VR128RegClass;
1851     break;
1852   }
1853   return std::make_pair(RRC, Cost);
1854 }
1855
1856 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1857                                                unsigned &Offset) const {
1858   if (!Subtarget->isTargetLinux())
1859     return false;
1860
1861   if (Subtarget->is64Bit()) {
1862     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1863     Offset = 0x28;
1864     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1865       AddressSpace = 256;
1866     else
1867       AddressSpace = 257;
1868   } else {
1869     // %gs:0x14 on i386
1870     Offset = 0x14;
1871     AddressSpace = 256;
1872   }
1873   return true;
1874 }
1875
1876 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1877                                             unsigned DestAS) const {
1878   assert(SrcAS != DestAS && "Expected different address spaces!");
1879
1880   return SrcAS < 256 && DestAS < 256;
1881 }
1882
1883 //===----------------------------------------------------------------------===//
1884 //               Return Value Calling Convention Implementation
1885 //===----------------------------------------------------------------------===//
1886
1887 #include "X86GenCallingConv.inc"
1888
1889 bool
1890 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1891                                   MachineFunction &MF, bool isVarArg,
1892                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1893                         LLVMContext &Context) const {
1894   SmallVector<CCValAssign, 16> RVLocs;
1895   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
1896   return CCInfo.CheckReturn(Outs, RetCC_X86);
1897 }
1898
1899 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
1900   static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
1901   return ScratchRegs;
1902 }
1903
1904 SDValue
1905 X86TargetLowering::LowerReturn(SDValue Chain,
1906                                CallingConv::ID CallConv, bool isVarArg,
1907                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1908                                const SmallVectorImpl<SDValue> &OutVals,
1909                                SDLoc dl, SelectionDAG &DAG) const {
1910   MachineFunction &MF = DAG.getMachineFunction();
1911   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1912
1913   SmallVector<CCValAssign, 16> RVLocs;
1914   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, *DAG.getContext());
1915   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1916
1917   SDValue Flag;
1918   SmallVector<SDValue, 6> RetOps;
1919   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1920   // Operand #1 = Bytes To Pop
1921   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(), dl,
1922                    MVT::i16));
1923
1924   // Copy the result values into the output registers.
1925   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1926     CCValAssign &VA = RVLocs[i];
1927     assert(VA.isRegLoc() && "Can only return in registers!");
1928     SDValue ValToCopy = OutVals[i];
1929     EVT ValVT = ValToCopy.getValueType();
1930
1931     // Promote values to the appropriate types.
1932     if (VA.getLocInfo() == CCValAssign::SExt)
1933       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1934     else if (VA.getLocInfo() == CCValAssign::ZExt)
1935       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1936     else if (VA.getLocInfo() == CCValAssign::AExt) {
1937       if (ValVT.getScalarType() == MVT::i1)
1938         ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1939       else
1940         ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1941     }   
1942     else if (VA.getLocInfo() == CCValAssign::BCvt)
1943       ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1944
1945     assert(VA.getLocInfo() != CCValAssign::FPExt &&
1946            "Unexpected FP-extend for return value.");
1947
1948     // If this is x86-64, and we disabled SSE, we can't return FP values,
1949     // or SSE or MMX vectors.
1950     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1951          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1952           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1953       report_fatal_error("SSE register return with SSE disabled");
1954     }
1955     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1956     // llvm-gcc has never done it right and no one has noticed, so this
1957     // should be OK for now.
1958     if (ValVT == MVT::f64 &&
1959         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1960       report_fatal_error("SSE2 register return with SSE2 disabled");
1961
1962     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1963     // the RET instruction and handled by the FP Stackifier.
1964     if (VA.getLocReg() == X86::FP0 ||
1965         VA.getLocReg() == X86::FP1) {
1966       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1967       // change the value to the FP stack register class.
1968       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1969         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1970       RetOps.push_back(ValToCopy);
1971       // Don't emit a copytoreg.
1972       continue;
1973     }
1974
1975     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1976     // which is returned in RAX / RDX.
1977     if (Subtarget->is64Bit()) {
1978       if (ValVT == MVT::x86mmx) {
1979         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1980           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1981           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1982                                   ValToCopy);
1983           // If we don't have SSE2 available, convert to v4f32 so the generated
1984           // register is legal.
1985           if (!Subtarget->hasSSE2())
1986             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1987         }
1988       }
1989     }
1990
1991     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1992     Flag = Chain.getValue(1);
1993     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1994   }
1995
1996   // The x86-64 ABIs require that for returning structs by value we copy
1997   // the sret argument into %rax/%eax (depending on ABI) for the return.
1998   // Win32 requires us to put the sret argument to %eax as well.
1999   // We saved the argument into a virtual register in the entry block,
2000   // so now we copy the value out and into %rax/%eax.
2001   //
2002   // Checking Function.hasStructRetAttr() here is insufficient because the IR
2003   // may not have an explicit sret argument. If FuncInfo.CanLowerReturn is
2004   // false, then an sret argument may be implicitly inserted in the SelDAG. In
2005   // either case FuncInfo->setSRetReturnReg() will have been called.
2006   if (unsigned SRetReg = FuncInfo->getSRetReturnReg()) {
2007     assert((Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC()) &&
2008            "No need for an sret register");
2009     SDValue Val = DAG.getCopyFromReg(Chain, dl, SRetReg, getPointerTy());
2010
2011     unsigned RetValReg
2012         = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
2013           X86::RAX : X86::EAX;
2014     Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
2015     Flag = Chain.getValue(1);
2016
2017     // RAX/EAX now acts like a return value.
2018     RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
2019   }
2020
2021   RetOps[0] = Chain;  // Update chain.
2022
2023   // Add the flag if we have it.
2024   if (Flag.getNode())
2025     RetOps.push_back(Flag);
2026
2027   return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
2028 }
2029
2030 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2031   if (N->getNumValues() != 1)
2032     return false;
2033   if (!N->hasNUsesOfValue(1, 0))
2034     return false;
2035
2036   SDValue TCChain = Chain;
2037   SDNode *Copy = *N->use_begin();
2038   if (Copy->getOpcode() == ISD::CopyToReg) {
2039     // If the copy has a glue operand, we conservatively assume it isn't safe to
2040     // perform a tail call.
2041     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2042       return false;
2043     TCChain = Copy->getOperand(0);
2044   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
2045     return false;
2046
2047   bool HasRet = false;
2048   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2049        UI != UE; ++UI) {
2050     if (UI->getOpcode() != X86ISD::RET_FLAG)
2051       return false;
2052     // If we are returning more than one value, we can definitely
2053     // not make a tail call see PR19530
2054     if (UI->getNumOperands() > 4)
2055       return false;
2056     if (UI->getNumOperands() == 4 &&
2057         UI->getOperand(UI->getNumOperands()-1).getValueType() != MVT::Glue)
2058       return false;
2059     HasRet = true;
2060   }
2061
2062   if (!HasRet)
2063     return false;
2064
2065   Chain = TCChain;
2066   return true;
2067 }
2068
2069 EVT
2070 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
2071                                             ISD::NodeType ExtendKind) const {
2072   MVT ReturnMVT;
2073   // TODO: Is this also valid on 32-bit?
2074   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
2075     ReturnMVT = MVT::i8;
2076   else
2077     ReturnMVT = MVT::i32;
2078
2079   EVT MinVT = getRegisterType(Context, ReturnMVT);
2080   return VT.bitsLT(MinVT) ? MinVT : VT;
2081 }
2082
2083 /// Lower the result values of a call into the
2084 /// appropriate copies out of appropriate physical registers.
2085 ///
2086 SDValue
2087 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2088                                    CallingConv::ID CallConv, bool isVarArg,
2089                                    const SmallVectorImpl<ISD::InputArg> &Ins,
2090                                    SDLoc dl, SelectionDAG &DAG,
2091                                    SmallVectorImpl<SDValue> &InVals) const {
2092
2093   // Assign locations to each value returned by this call.
2094   SmallVector<CCValAssign, 16> RVLocs;
2095   bool Is64Bit = Subtarget->is64Bit();
2096   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2097                  *DAG.getContext());
2098   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2099
2100   // Copy all of the result registers out of their specified physreg.
2101   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2102     CCValAssign &VA = RVLocs[i];
2103     EVT CopyVT = VA.getLocVT();
2104
2105     // If this is x86-64, and we disabled SSE, we can't return FP values
2106     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2107         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2108       report_fatal_error("SSE register return with SSE disabled");
2109     }
2110
2111     // If we prefer to use the value in xmm registers, copy it out as f80 and
2112     // use a truncate to move it from fp stack reg to xmm reg.
2113     bool RoundAfterCopy = false;
2114     if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
2115         isScalarFPTypeInSSEReg(VA.getValVT())) {
2116       CopyVT = MVT::f80;
2117       RoundAfterCopy = (CopyVT != VA.getLocVT());
2118     }
2119
2120     Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2121                                CopyVT, InFlag).getValue(1);
2122     SDValue Val = Chain.getValue(0);
2123
2124     if (RoundAfterCopy)
2125       Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2126                         // This truncation won't change the value.
2127                         DAG.getIntPtrConstant(1, dl));
2128
2129     InFlag = Chain.getValue(2);
2130     InVals.push_back(Val);
2131   }
2132
2133   return Chain;
2134 }
2135
2136 //===----------------------------------------------------------------------===//
2137 //                C & StdCall & Fast Calling Convention implementation
2138 //===----------------------------------------------------------------------===//
2139 //  StdCall calling convention seems to be standard for many Windows' API
2140 //  routines and around. It differs from C calling convention just a little:
2141 //  callee should clean up the stack, not caller. Symbols should be also
2142 //  decorated in some fancy way :) It doesn't support any vector arguments.
2143 //  For info on fast calling convention see Fast Calling Convention (tail call)
2144 //  implementation LowerX86_32FastCCCallTo.
2145
2146 /// CallIsStructReturn - Determines whether a call uses struct return
2147 /// semantics.
2148 enum StructReturnType {
2149   NotStructReturn,
2150   RegStructReturn,
2151   StackStructReturn
2152 };
2153 static StructReturnType
2154 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2155   if (Outs.empty())
2156     return NotStructReturn;
2157
2158   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2159   if (!Flags.isSRet())
2160     return NotStructReturn;
2161   if (Flags.isInReg())
2162     return RegStructReturn;
2163   return StackStructReturn;
2164 }
2165
2166 /// Determines whether a function uses struct return semantics.
2167 static StructReturnType
2168 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2169   if (Ins.empty())
2170     return NotStructReturn;
2171
2172   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2173   if (!Flags.isSRet())
2174     return NotStructReturn;
2175   if (Flags.isInReg())
2176     return RegStructReturn;
2177   return StackStructReturn;
2178 }
2179
2180 /// Make a copy of an aggregate at address specified by "Src" to address
2181 /// "Dst" with size and alignment information specified by the specific
2182 /// parameter attribute. The copy will be passed as a byval function parameter.
2183 static SDValue
2184 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2185                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2186                           SDLoc dl) {
2187   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
2188
2189   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2190                        /*isVolatile*/false, /*AlwaysInline=*/true,
2191                        /*isTailCall*/false,
2192                        MachinePointerInfo(), MachinePointerInfo());
2193 }
2194
2195 /// Return true if the calling convention is one that
2196 /// supports tail call optimization.
2197 static bool IsTailCallConvention(CallingConv::ID CC) {
2198   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2199           CC == CallingConv::HiPE);
2200 }
2201
2202 /// \brief Return true if the calling convention is a C calling convention.
2203 static bool IsCCallConvention(CallingConv::ID CC) {
2204   return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2205           CC == CallingConv::X86_64_SysV);
2206 }
2207
2208 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2209   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2210     return false;
2211
2212   CallSite CS(CI);
2213   CallingConv::ID CalleeCC = CS.getCallingConv();
2214   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2215     return false;
2216
2217   return true;
2218 }
2219
2220 /// Return true if the function is being made into
2221 /// a tailcall target by changing its ABI.
2222 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2223                                    bool GuaranteedTailCallOpt) {
2224   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2225 }
2226
2227 SDValue
2228 X86TargetLowering::LowerMemArgument(SDValue Chain,
2229                                     CallingConv::ID CallConv,
2230                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2231                                     SDLoc dl, SelectionDAG &DAG,
2232                                     const CCValAssign &VA,
2233                                     MachineFrameInfo *MFI,
2234                                     unsigned i) const {
2235   // Create the nodes corresponding to a load from this parameter slot.
2236   ISD::ArgFlagsTy Flags = Ins[i].Flags;
2237   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(
2238       CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2239   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2240   EVT ValVT;
2241
2242   // If value is passed by pointer we have address passed instead of the value
2243   // itself.
2244   if (VA.getLocInfo() == CCValAssign::Indirect)
2245     ValVT = VA.getLocVT();
2246   else
2247     ValVT = VA.getValVT();
2248
2249   // FIXME: For now, all byval parameter objects are marked mutable. This can be
2250   // changed with more analysis.
2251   // In case of tail call optimization mark all arguments mutable. Since they
2252   // could be overwritten by lowering of arguments in case of a tail call.
2253   if (Flags.isByVal()) {
2254     unsigned Bytes = Flags.getByValSize();
2255     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2256     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2257     return DAG.getFrameIndex(FI, getPointerTy());
2258   } else {
2259     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2260                                     VA.getLocMemOffset(), isImmutable);
2261     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2262     return DAG.getLoad(ValVT, dl, Chain, FIN,
2263                        MachinePointerInfo::getFixedStack(FI),
2264                        false, false, false, 0);
2265   }
2266 }
2267
2268 // FIXME: Get this from tablegen.
2269 static ArrayRef<MCPhysReg> get64BitArgumentGPRs(CallingConv::ID CallConv,
2270                                                 const X86Subtarget *Subtarget) {
2271   assert(Subtarget->is64Bit());
2272
2273   if (Subtarget->isCallingConvWin64(CallConv)) {
2274     static const MCPhysReg GPR64ArgRegsWin64[] = {
2275       X86::RCX, X86::RDX, X86::R8,  X86::R9
2276     };
2277     return makeArrayRef(std::begin(GPR64ArgRegsWin64), std::end(GPR64ArgRegsWin64));
2278   }
2279
2280   static const MCPhysReg GPR64ArgRegs64Bit[] = {
2281     X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2282   };
2283   return makeArrayRef(std::begin(GPR64ArgRegs64Bit), std::end(GPR64ArgRegs64Bit));
2284 }
2285
2286 // FIXME: Get this from tablegen.
2287 static ArrayRef<MCPhysReg> get64BitArgumentXMMs(MachineFunction &MF,
2288                                                 CallingConv::ID CallConv,
2289                                                 const X86Subtarget *Subtarget) {
2290   assert(Subtarget->is64Bit());
2291   if (Subtarget->isCallingConvWin64(CallConv)) {
2292     // The XMM registers which might contain var arg parameters are shadowed
2293     // in their paired GPR.  So we only need to save the GPR to their home
2294     // slots.
2295     // TODO: __vectorcall will change this.
2296     return None;
2297   }
2298
2299   const Function *Fn = MF.getFunction();
2300   bool NoImplicitFloatOps = Fn->hasFnAttribute(Attribute::NoImplicitFloat);
2301   bool isSoftFloat = Subtarget->useSoftFloat();
2302   assert(!(isSoftFloat && NoImplicitFloatOps) &&
2303          "SSE register cannot be used when SSE is disabled!");
2304   if (isSoftFloat || NoImplicitFloatOps || !Subtarget->hasSSE1())
2305     // Kernel mode asks for SSE to be disabled, so there are no XMM argument
2306     // registers.
2307     return None;
2308
2309   static const MCPhysReg XMMArgRegs64Bit[] = {
2310     X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2311     X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2312   };
2313   return makeArrayRef(std::begin(XMMArgRegs64Bit), std::end(XMMArgRegs64Bit));
2314 }
2315
2316 SDValue
2317 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2318                                         CallingConv::ID CallConv,
2319                                         bool isVarArg,
2320                                       const SmallVectorImpl<ISD::InputArg> &Ins,
2321                                         SDLoc dl,
2322                                         SelectionDAG &DAG,
2323                                         SmallVectorImpl<SDValue> &InVals)
2324                                           const {
2325   MachineFunction &MF = DAG.getMachineFunction();
2326   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2327   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
2328
2329   const Function* Fn = MF.getFunction();
2330   if (Fn->hasExternalLinkage() &&
2331       Subtarget->isTargetCygMing() &&
2332       Fn->getName() == "main")
2333     FuncInfo->setForceFramePointer(true);
2334
2335   MachineFrameInfo *MFI = MF.getFrameInfo();
2336   bool Is64Bit = Subtarget->is64Bit();
2337   bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2338
2339   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2340          "Var args not supported with calling convention fastcc, ghc or hipe");
2341
2342   // Assign locations to all of the incoming arguments.
2343   SmallVector<CCValAssign, 16> ArgLocs;
2344   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2345
2346   // Allocate shadow area for Win64
2347   if (IsWin64)
2348     CCInfo.AllocateStack(32, 8);
2349
2350   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2351
2352   unsigned LastVal = ~0U;
2353   SDValue ArgValue;
2354   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2355     CCValAssign &VA = ArgLocs[i];
2356     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2357     // places.
2358     assert(VA.getValNo() != LastVal &&
2359            "Don't support value assigned to multiple locs yet");
2360     (void)LastVal;
2361     LastVal = VA.getValNo();
2362
2363     if (VA.isRegLoc()) {
2364       EVT RegVT = VA.getLocVT();
2365       const TargetRegisterClass *RC;
2366       if (RegVT == MVT::i32)
2367         RC = &X86::GR32RegClass;
2368       else if (Is64Bit && RegVT == MVT::i64)
2369         RC = &X86::GR64RegClass;
2370       else if (RegVT == MVT::f32)
2371         RC = &X86::FR32RegClass;
2372       else if (RegVT == MVT::f64)
2373         RC = &X86::FR64RegClass;
2374       else if (RegVT.is512BitVector())
2375         RC = &X86::VR512RegClass;
2376       else if (RegVT.is256BitVector())
2377         RC = &X86::VR256RegClass;
2378       else if (RegVT.is128BitVector())
2379         RC = &X86::VR128RegClass;
2380       else if (RegVT == MVT::x86mmx)
2381         RC = &X86::VR64RegClass;
2382       else if (RegVT == MVT::i1)
2383         RC = &X86::VK1RegClass;
2384       else if (RegVT == MVT::v8i1)
2385         RC = &X86::VK8RegClass;
2386       else if (RegVT == MVT::v16i1)
2387         RC = &X86::VK16RegClass;
2388       else if (RegVT == MVT::v32i1)
2389         RC = &X86::VK32RegClass;
2390       else if (RegVT == MVT::v64i1)
2391         RC = &X86::VK64RegClass;
2392       else
2393         llvm_unreachable("Unknown argument type!");
2394
2395       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2396       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2397
2398       // If this is an 8 or 16-bit value, it is really passed promoted to 32
2399       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
2400       // right size.
2401       if (VA.getLocInfo() == CCValAssign::SExt)
2402         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2403                                DAG.getValueType(VA.getValVT()));
2404       else if (VA.getLocInfo() == CCValAssign::ZExt)
2405         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2406                                DAG.getValueType(VA.getValVT()));
2407       else if (VA.getLocInfo() == CCValAssign::BCvt)
2408         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2409
2410       if (VA.isExtInLoc()) {
2411         // Handle MMX values passed in XMM regs.
2412         if (RegVT.isVector() && VA.getValVT().getScalarType() != MVT::i1)
2413           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2414         else
2415           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2416       }
2417     } else {
2418       assert(VA.isMemLoc());
2419       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2420     }
2421
2422     // If value is passed via pointer - do a load.
2423     if (VA.getLocInfo() == CCValAssign::Indirect)
2424       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2425                              MachinePointerInfo(), false, false, false, 0);
2426
2427     InVals.push_back(ArgValue);
2428   }
2429
2430   if (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC()) {
2431     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2432       // The x86-64 ABIs require that for returning structs by value we copy
2433       // the sret argument into %rax/%eax (depending on ABI) for the return.
2434       // Win32 requires us to put the sret argument to %eax as well.
2435       // Save the argument into a virtual register so that we can access it
2436       // from the return points.
2437       if (Ins[i].Flags.isSRet()) {
2438         unsigned Reg = FuncInfo->getSRetReturnReg();
2439         if (!Reg) {
2440           MVT PtrTy = getPointerTy();
2441           Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2442           FuncInfo->setSRetReturnReg(Reg);
2443         }
2444         SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2445         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2446         break;
2447       }
2448     }
2449   }
2450
2451   unsigned StackSize = CCInfo.getNextStackOffset();
2452   // Align stack specially for tail calls.
2453   if (FuncIsMadeTailCallSafe(CallConv,
2454                              MF.getTarget().Options.GuaranteedTailCallOpt))
2455     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2456
2457   // If the function takes variable number of arguments, make a frame index for
2458   // the start of the first vararg value... for expansion of llvm.va_start. We
2459   // can skip this if there are no va_start calls.
2460   if (MFI->hasVAStart() &&
2461       (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2462                    CallConv != CallingConv::X86_ThisCall))) {
2463     FuncInfo->setVarArgsFrameIndex(
2464         MFI->CreateFixedObject(1, StackSize, true));
2465   }
2466
2467   MachineModuleInfo &MMI = MF.getMMI();
2468   const Function *WinEHParent = nullptr;
2469   if (IsWin64 && MMI.hasWinEHFuncInfo(Fn))
2470     WinEHParent = MMI.getWinEHParent(Fn);
2471   bool IsWinEHOutlined = WinEHParent && WinEHParent != Fn;
2472   bool IsWinEHParent = WinEHParent && WinEHParent == Fn;
2473
2474   // Figure out if XMM registers are in use.
2475   assert(!(Subtarget->useSoftFloat() &&
2476            Fn->hasFnAttribute(Attribute::NoImplicitFloat)) &&
2477          "SSE register cannot be used when SSE is disabled!");
2478
2479   // 64-bit calling conventions support varargs and register parameters, so we
2480   // have to do extra work to spill them in the prologue.
2481   if (Is64Bit && isVarArg && MFI->hasVAStart()) {
2482     // Find the first unallocated argument registers.
2483     ArrayRef<MCPhysReg> ArgGPRs = get64BitArgumentGPRs(CallConv, Subtarget);
2484     ArrayRef<MCPhysReg> ArgXMMs = get64BitArgumentXMMs(MF, CallConv, Subtarget);
2485     unsigned NumIntRegs = CCInfo.getFirstUnallocated(ArgGPRs);
2486     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(ArgXMMs);
2487     assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2488            "SSE register cannot be used when SSE is disabled!");
2489
2490     // Gather all the live in physical registers.
2491     SmallVector<SDValue, 6> LiveGPRs;
2492     SmallVector<SDValue, 8> LiveXMMRegs;
2493     SDValue ALVal;
2494     for (MCPhysReg Reg : ArgGPRs.slice(NumIntRegs)) {
2495       unsigned GPR = MF.addLiveIn(Reg, &X86::GR64RegClass);
2496       LiveGPRs.push_back(
2497           DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64));
2498     }
2499     if (!ArgXMMs.empty()) {
2500       unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2501       ALVal = DAG.getCopyFromReg(Chain, dl, AL, MVT::i8);
2502       for (MCPhysReg Reg : ArgXMMs.slice(NumXMMRegs)) {
2503         unsigned XMMReg = MF.addLiveIn(Reg, &X86::VR128RegClass);
2504         LiveXMMRegs.push_back(
2505             DAG.getCopyFromReg(Chain, dl, XMMReg, MVT::v4f32));
2506       }
2507     }
2508
2509     if (IsWin64) {
2510       // Get to the caller-allocated home save location.  Add 8 to account
2511       // for the return address.
2512       int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2513       FuncInfo->setRegSaveFrameIndex(
2514           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2515       // Fixup to set vararg frame on shadow area (4 x i64).
2516       if (NumIntRegs < 4)
2517         FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2518     } else {
2519       // For X86-64, if there are vararg parameters that are passed via
2520       // registers, then we must store them to their spots on the stack so
2521       // they may be loaded by deferencing the result of va_next.
2522       FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2523       FuncInfo->setVarArgsFPOffset(ArgGPRs.size() * 8 + NumXMMRegs * 16);
2524       FuncInfo->setRegSaveFrameIndex(MFI->CreateStackObject(
2525           ArgGPRs.size() * 8 + ArgXMMs.size() * 16, 16, false));
2526     }
2527
2528     // Store the integer parameter registers.
2529     SmallVector<SDValue, 8> MemOps;
2530     SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2531                                       getPointerTy());
2532     unsigned Offset = FuncInfo->getVarArgsGPOffset();
2533     for (SDValue Val : LiveGPRs) {
2534       SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2535                                 DAG.getIntPtrConstant(Offset, dl));
2536       SDValue Store =
2537         DAG.getStore(Val.getValue(1), dl, Val, FIN,
2538                      MachinePointerInfo::getFixedStack(
2539                        FuncInfo->getRegSaveFrameIndex(), Offset),
2540                      false, false, 0);
2541       MemOps.push_back(Store);
2542       Offset += 8;
2543     }
2544
2545     if (!ArgXMMs.empty() && NumXMMRegs != ArgXMMs.size()) {
2546       // Now store the XMM (fp + vector) parameter registers.
2547       SmallVector<SDValue, 12> SaveXMMOps;
2548       SaveXMMOps.push_back(Chain);
2549       SaveXMMOps.push_back(ALVal);
2550       SaveXMMOps.push_back(DAG.getIntPtrConstant(
2551                              FuncInfo->getRegSaveFrameIndex(), dl));
2552       SaveXMMOps.push_back(DAG.getIntPtrConstant(
2553                              FuncInfo->getVarArgsFPOffset(), dl));
2554       SaveXMMOps.insert(SaveXMMOps.end(), LiveXMMRegs.begin(),
2555                         LiveXMMRegs.end());
2556       MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2557                                    MVT::Other, SaveXMMOps));
2558     }
2559
2560     if (!MemOps.empty())
2561       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2562   } else if (IsWinEHOutlined) {
2563     // Get to the caller-allocated home save location.  Add 8 to account
2564     // for the return address.
2565     int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2566     FuncInfo->setRegSaveFrameIndex(MFI->CreateFixedObject(
2567         /*Size=*/1, /*SPOffset=*/HomeOffset + 8, /*Immutable=*/false));
2568
2569     MMI.getWinEHFuncInfo(Fn)
2570         .CatchHandlerParentFrameObjIdx[const_cast<Function *>(Fn)] =
2571         FuncInfo->getRegSaveFrameIndex();
2572
2573     // Store the second integer parameter (rdx) into rsp+16 relative to the
2574     // stack pointer at the entry of the function.
2575     SDValue RSFIN =
2576         DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(), getPointerTy());
2577     unsigned GPR = MF.addLiveIn(X86::RDX, &X86::GR64RegClass);
2578     SDValue Val = DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64);
2579     Chain = DAG.getStore(
2580         Val.getValue(1), dl, Val, RSFIN,
2581         MachinePointerInfo::getFixedStack(FuncInfo->getRegSaveFrameIndex()),
2582         /*isVolatile=*/true, /*isNonTemporal=*/false, /*Alignment=*/0);
2583   }
2584
2585   if (isVarArg && MFI->hasMustTailInVarArgFunc()) {
2586     // Find the largest legal vector type.
2587     MVT VecVT = MVT::Other;
2588     // FIXME: Only some x86_32 calling conventions support AVX512.
2589     if (Subtarget->hasAVX512() &&
2590         (Is64Bit || (CallConv == CallingConv::X86_VectorCall ||
2591                      CallConv == CallingConv::Intel_OCL_BI)))
2592       VecVT = MVT::v16f32;
2593     else if (Subtarget->hasAVX())
2594       VecVT = MVT::v8f32;
2595     else if (Subtarget->hasSSE2())
2596       VecVT = MVT::v4f32;
2597
2598     // We forward some GPRs and some vector types.
2599     SmallVector<MVT, 2> RegParmTypes;
2600     MVT IntVT = Is64Bit ? MVT::i64 : MVT::i32;
2601     RegParmTypes.push_back(IntVT);
2602     if (VecVT != MVT::Other)
2603       RegParmTypes.push_back(VecVT);
2604
2605     // Compute the set of forwarded registers. The rest are scratch.
2606     SmallVectorImpl<ForwardedRegister> &Forwards =
2607         FuncInfo->getForwardedMustTailRegParms();
2608     CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes, CC_X86);
2609
2610     // Conservatively forward AL on x86_64, since it might be used for varargs.
2611     if (Is64Bit && !CCInfo.isAllocated(X86::AL)) {
2612       unsigned ALVReg = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2613       Forwards.push_back(ForwardedRegister(ALVReg, X86::AL, MVT::i8));
2614     }
2615
2616     // Copy all forwards from physical to virtual registers.
2617     for (ForwardedRegister &F : Forwards) {
2618       // FIXME: Can we use a less constrained schedule?
2619       SDValue RegVal = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
2620       F.VReg = MF.getRegInfo().createVirtualRegister(getRegClassFor(F.VT));
2621       Chain = DAG.getCopyToReg(Chain, dl, F.VReg, RegVal);
2622     }
2623   }
2624
2625   // Some CCs need callee pop.
2626   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2627                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2628     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2629   } else {
2630     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2631     // If this is an sret function, the return should pop the hidden pointer.
2632     if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2633         !Subtarget->getTargetTriple().isOSMSVCRT() &&
2634         argsAreStructReturn(Ins) == StackStructReturn)
2635       FuncInfo->setBytesToPopOnReturn(4);
2636   }
2637
2638   if (!Is64Bit) {
2639     // RegSaveFrameIndex is X86-64 only.
2640     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2641     if (CallConv == CallingConv::X86_FastCall ||
2642         CallConv == CallingConv::X86_ThisCall)
2643       // fastcc functions can't have varargs.
2644       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2645   }
2646
2647   FuncInfo->setArgumentStackSize(StackSize);
2648
2649   if (IsWinEHParent) {
2650     int UnwindHelpFI = MFI->CreateStackObject(8, 8, /*isSS=*/false);
2651     SDValue StackSlot = DAG.getFrameIndex(UnwindHelpFI, MVT::i64);
2652     MMI.getWinEHFuncInfo(MF.getFunction()).UnwindHelpFrameIdx = UnwindHelpFI;
2653     SDValue Neg2 = DAG.getConstant(-2, dl, MVT::i64);
2654     Chain = DAG.getStore(Chain, dl, Neg2, StackSlot,
2655                          MachinePointerInfo::getFixedStack(UnwindHelpFI),
2656                          /*isVolatile=*/true,
2657                          /*isNonTemporal=*/false, /*Alignment=*/0);
2658   }
2659
2660   return Chain;
2661 }
2662
2663 SDValue
2664 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2665                                     SDValue StackPtr, SDValue Arg,
2666                                     SDLoc dl, SelectionDAG &DAG,
2667                                     const CCValAssign &VA,
2668                                     ISD::ArgFlagsTy Flags) const {
2669   unsigned LocMemOffset = VA.getLocMemOffset();
2670   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
2671   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2672   if (Flags.isByVal())
2673     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2674
2675   return DAG.getStore(Chain, dl, Arg, PtrOff,
2676                       MachinePointerInfo::getStack(LocMemOffset),
2677                       false, false, 0);
2678 }
2679
2680 /// Emit a load of return address if tail call
2681 /// optimization is performed and it is required.
2682 SDValue
2683 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2684                                            SDValue &OutRetAddr, SDValue Chain,
2685                                            bool IsTailCall, bool Is64Bit,
2686                                            int FPDiff, SDLoc dl) const {
2687   // Adjust the Return address stack slot.
2688   EVT VT = getPointerTy();
2689   OutRetAddr = getReturnAddressFrameIndex(DAG);
2690
2691   // Load the "old" Return address.
2692   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2693                            false, false, false, 0);
2694   return SDValue(OutRetAddr.getNode(), 1);
2695 }
2696
2697 /// Emit a store of the return address if tail call
2698 /// optimization is performed and it is required (FPDiff!=0).
2699 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2700                                         SDValue Chain, SDValue RetAddrFrIdx,
2701                                         EVT PtrVT, unsigned SlotSize,
2702                                         int FPDiff, SDLoc dl) {
2703   // Store the return address to the appropriate stack slot.
2704   if (!FPDiff) return Chain;
2705   // Calculate the new stack slot for the return address.
2706   int NewReturnAddrFI =
2707     MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2708                                          false);
2709   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2710   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2711                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2712                        false, false, 0);
2713   return Chain;
2714 }
2715
2716 SDValue
2717 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2718                              SmallVectorImpl<SDValue> &InVals) const {
2719   SelectionDAG &DAG                     = CLI.DAG;
2720   SDLoc &dl                             = CLI.DL;
2721   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2722   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
2723   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
2724   SDValue Chain                         = CLI.Chain;
2725   SDValue Callee                        = CLI.Callee;
2726   CallingConv::ID CallConv              = CLI.CallConv;
2727   bool &isTailCall                      = CLI.IsTailCall;
2728   bool isVarArg                         = CLI.IsVarArg;
2729
2730   MachineFunction &MF = DAG.getMachineFunction();
2731   bool Is64Bit        = Subtarget->is64Bit();
2732   bool IsWin64        = Subtarget->isCallingConvWin64(CallConv);
2733   StructReturnType SR = callIsStructReturn(Outs);
2734   bool IsSibcall      = false;
2735   X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2736
2737   if (MF.getTarget().Options.DisableTailCalls)
2738     isTailCall = false;
2739
2740   bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
2741   if (IsMustTail) {
2742     // Force this to be a tail call.  The verifier rules are enough to ensure
2743     // that we can lower this successfully without moving the return address
2744     // around.
2745     isTailCall = true;
2746   } else if (isTailCall) {
2747     // Check if it's really possible to do a tail call.
2748     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2749                     isVarArg, SR != NotStructReturn,
2750                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2751                     Outs, OutVals, Ins, DAG);
2752
2753     // Sibcalls are automatically detected tailcalls which do not require
2754     // ABI changes.
2755     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2756       IsSibcall = true;
2757
2758     if (isTailCall)
2759       ++NumTailCalls;
2760   }
2761
2762   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2763          "Var args not supported with calling convention fastcc, ghc or hipe");
2764
2765   // Analyze operands of the call, assigning locations to each operand.
2766   SmallVector<CCValAssign, 16> ArgLocs;
2767   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2768
2769   // Allocate shadow area for Win64
2770   if (IsWin64)
2771     CCInfo.AllocateStack(32, 8);
2772
2773   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2774
2775   // Get a count of how many bytes are to be pushed on the stack.
2776   unsigned NumBytes = CCInfo.getNextStackOffset();
2777   if (IsSibcall)
2778     // This is a sibcall. The memory operands are available in caller's
2779     // own caller's stack.
2780     NumBytes = 0;
2781   else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
2782            IsTailCallConvention(CallConv))
2783     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2784
2785   int FPDiff = 0;
2786   if (isTailCall && !IsSibcall && !IsMustTail) {
2787     // Lower arguments at fp - stackoffset + fpdiff.
2788     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2789
2790     FPDiff = NumBytesCallerPushed - NumBytes;
2791
2792     // Set the delta of movement of the returnaddr stackslot.
2793     // But only set if delta is greater than previous delta.
2794     if (FPDiff < X86Info->getTCReturnAddrDelta())
2795       X86Info->setTCReturnAddrDelta(FPDiff);
2796   }
2797
2798   unsigned NumBytesToPush = NumBytes;
2799   unsigned NumBytesToPop = NumBytes;
2800
2801   // If we have an inalloca argument, all stack space has already been allocated
2802   // for us and be right at the top of the stack.  We don't support multiple
2803   // arguments passed in memory when using inalloca.
2804   if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
2805     NumBytesToPush = 0;
2806     if (!ArgLocs.back().isMemLoc())
2807       report_fatal_error("cannot use inalloca attribute on a register "
2808                          "parameter");
2809     if (ArgLocs.back().getLocMemOffset() != 0)
2810       report_fatal_error("any parameter with the inalloca attribute must be "
2811                          "the only memory argument");
2812   }
2813
2814   if (!IsSibcall)
2815     Chain = DAG.getCALLSEQ_START(
2816         Chain, DAG.getIntPtrConstant(NumBytesToPush, dl, true), dl);
2817
2818   SDValue RetAddrFrIdx;
2819   // Load return address for tail calls.
2820   if (isTailCall && FPDiff)
2821     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2822                                     Is64Bit, FPDiff, dl);
2823
2824   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2825   SmallVector<SDValue, 8> MemOpChains;
2826   SDValue StackPtr;
2827
2828   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2829   // of tail call optimization arguments are handle later.
2830   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
2831   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2832     // Skip inalloca arguments, they have already been written.
2833     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2834     if (Flags.isInAlloca())
2835       continue;
2836
2837     CCValAssign &VA = ArgLocs[i];
2838     EVT RegVT = VA.getLocVT();
2839     SDValue Arg = OutVals[i];
2840     bool isByVal = Flags.isByVal();
2841
2842     // Promote the value if needed.
2843     switch (VA.getLocInfo()) {
2844     default: llvm_unreachable("Unknown loc info!");
2845     case CCValAssign::Full: break;
2846     case CCValAssign::SExt:
2847       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2848       break;
2849     case CCValAssign::ZExt:
2850       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2851       break;
2852     case CCValAssign::AExt:
2853       if (Arg.getValueType().getScalarType() == MVT::i1)
2854         Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2855       else if (RegVT.is128BitVector()) {
2856         // Special case: passing MMX values in XMM registers.
2857         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2858         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2859         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2860       } else
2861         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2862       break;
2863     case CCValAssign::BCvt:
2864       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2865       break;
2866     case CCValAssign::Indirect: {
2867       // Store the argument.
2868       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2869       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2870       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2871                            MachinePointerInfo::getFixedStack(FI),
2872                            false, false, 0);
2873       Arg = SpillSlot;
2874       break;
2875     }
2876     }
2877
2878     if (VA.isRegLoc()) {
2879       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2880       if (isVarArg && IsWin64) {
2881         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2882         // shadow reg if callee is a varargs function.
2883         unsigned ShadowReg = 0;
2884         switch (VA.getLocReg()) {
2885         case X86::XMM0: ShadowReg = X86::RCX; break;
2886         case X86::XMM1: ShadowReg = X86::RDX; break;
2887         case X86::XMM2: ShadowReg = X86::R8; break;
2888         case X86::XMM3: ShadowReg = X86::R9; break;
2889         }
2890         if (ShadowReg)
2891           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2892       }
2893     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2894       assert(VA.isMemLoc());
2895       if (!StackPtr.getNode())
2896         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2897                                       getPointerTy());
2898       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2899                                              dl, DAG, VA, Flags));
2900     }
2901   }
2902
2903   if (!MemOpChains.empty())
2904     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
2905
2906   if (Subtarget->isPICStyleGOT()) {
2907     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2908     // GOT pointer.
2909     if (!isTailCall) {
2910       RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2911                DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
2912     } else {
2913       // If we are tail calling and generating PIC/GOT style code load the
2914       // address of the callee into ECX. The value in ecx is used as target of
2915       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2916       // for tail calls on PIC/GOT architectures. Normally we would just put the
2917       // address of GOT into ebx and then call target@PLT. But for tail calls
2918       // ebx would be restored (since ebx is callee saved) before jumping to the
2919       // target@PLT.
2920
2921       // Note: The actual moving to ECX is done further down.
2922       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2923       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2924           !G->getGlobal()->hasProtectedVisibility())
2925         Callee = LowerGlobalAddress(Callee, DAG);
2926       else if (isa<ExternalSymbolSDNode>(Callee))
2927         Callee = LowerExternalSymbol(Callee, DAG);
2928     }
2929   }
2930
2931   if (Is64Bit && isVarArg && !IsWin64 && !IsMustTail) {
2932     // From AMD64 ABI document:
2933     // For calls that may call functions that use varargs or stdargs
2934     // (prototype-less calls or calls to functions containing ellipsis (...) in
2935     // the declaration) %al is used as hidden argument to specify the number
2936     // of SSE registers used. The contents of %al do not need to match exactly
2937     // the number of registers, but must be an ubound on the number of SSE
2938     // registers used and is in the range 0 - 8 inclusive.
2939
2940     // Count the number of XMM registers allocated.
2941     static const MCPhysReg XMMArgRegs[] = {
2942       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2943       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2944     };
2945     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs);
2946     assert((Subtarget->hasSSE1() || !NumXMMRegs)
2947            && "SSE registers cannot be used when SSE is disabled");
2948
2949     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2950                                         DAG.getConstant(NumXMMRegs, dl,
2951                                                         MVT::i8)));
2952   }
2953
2954   if (isVarArg && IsMustTail) {
2955     const auto &Forwards = X86Info->getForwardedMustTailRegParms();
2956     for (const auto &F : Forwards) {
2957       SDValue Val = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
2958       RegsToPass.push_back(std::make_pair(unsigned(F.PReg), Val));
2959     }
2960   }
2961
2962   // For tail calls lower the arguments to the 'real' stack slots.  Sibcalls
2963   // don't need this because the eligibility check rejects calls that require
2964   // shuffling arguments passed in memory.
2965   if (!IsSibcall && isTailCall) {
2966     // Force all the incoming stack arguments to be loaded from the stack
2967     // before any new outgoing arguments are stored to the stack, because the
2968     // outgoing stack slots may alias the incoming argument stack slots, and
2969     // the alias isn't otherwise explicit. This is slightly more conservative
2970     // than necessary, because it means that each store effectively depends
2971     // on every argument instead of just those arguments it would clobber.
2972     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2973
2974     SmallVector<SDValue, 8> MemOpChains2;
2975     SDValue FIN;
2976     int FI = 0;
2977     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2978       CCValAssign &VA = ArgLocs[i];
2979       if (VA.isRegLoc())
2980         continue;
2981       assert(VA.isMemLoc());
2982       SDValue Arg = OutVals[i];
2983       ISD::ArgFlagsTy Flags = Outs[i].Flags;
2984       // Skip inalloca arguments.  They don't require any work.
2985       if (Flags.isInAlloca())
2986         continue;
2987       // Create frame index.
2988       int32_t Offset = VA.getLocMemOffset()+FPDiff;
2989       uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2990       FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2991       FIN = DAG.getFrameIndex(FI, getPointerTy());
2992
2993       if (Flags.isByVal()) {
2994         // Copy relative to framepointer.
2995         SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset(), dl);
2996         if (!StackPtr.getNode())
2997           StackPtr = DAG.getCopyFromReg(Chain, dl,
2998                                         RegInfo->getStackRegister(),
2999                                         getPointerTy());
3000         Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
3001
3002         MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
3003                                                          ArgChain,
3004                                                          Flags, DAG, dl));
3005       } else {
3006         // Store relative to framepointer.
3007         MemOpChains2.push_back(
3008           DAG.getStore(ArgChain, dl, Arg, FIN,
3009                        MachinePointerInfo::getFixedStack(FI),
3010                        false, false, 0));
3011       }
3012     }
3013
3014     if (!MemOpChains2.empty())
3015       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
3016
3017     // Store the return address to the appropriate stack slot.
3018     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
3019                                      getPointerTy(), RegInfo->getSlotSize(),
3020                                      FPDiff, dl);
3021   }
3022
3023   // Build a sequence of copy-to-reg nodes chained together with token chain
3024   // and flag operands which copy the outgoing args into registers.
3025   SDValue InFlag;
3026   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
3027     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
3028                              RegsToPass[i].second, InFlag);
3029     InFlag = Chain.getValue(1);
3030   }
3031
3032   if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
3033     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
3034     // In the 64-bit large code model, we have to make all calls
3035     // through a register, since the call instruction's 32-bit
3036     // pc-relative offset may not be large enough to hold the whole
3037     // address.
3038   } else if (Callee->getOpcode() == ISD::GlobalAddress) {
3039     // If the callee is a GlobalAddress node (quite common, every direct call
3040     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
3041     // it.
3042     GlobalAddressSDNode* G = cast<GlobalAddressSDNode>(Callee);
3043
3044     // We should use extra load for direct calls to dllimported functions in
3045     // non-JIT mode.
3046     const GlobalValue *GV = G->getGlobal();
3047     if (!GV->hasDLLImportStorageClass()) {
3048       unsigned char OpFlags = 0;
3049       bool ExtraLoad = false;
3050       unsigned WrapperKind = ISD::DELETED_NODE;
3051
3052       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
3053       // external symbols most go through the PLT in PIC mode.  If the symbol
3054       // has hidden or protected visibility, or if it is static or local, then
3055       // we don't need to use the PLT - we can directly call it.
3056       if (Subtarget->isTargetELF() &&
3057           DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
3058           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
3059         OpFlags = X86II::MO_PLT;
3060       } else if (Subtarget->isPICStyleStubAny() &&
3061                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
3062                  (!Subtarget->getTargetTriple().isMacOSX() ||
3063                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3064         // PC-relative references to external symbols should go through $stub,
3065         // unless we're building with the leopard linker or later, which
3066         // automatically synthesizes these stubs.
3067         OpFlags = X86II::MO_DARWIN_STUB;
3068       } else if (Subtarget->isPICStyleRIPRel() && isa<Function>(GV) &&
3069                  cast<Function>(GV)->hasFnAttribute(Attribute::NonLazyBind)) {
3070         // If the function is marked as non-lazy, generate an indirect call
3071         // which loads from the GOT directly. This avoids runtime overhead
3072         // at the cost of eager binding (and one extra byte of encoding).
3073         OpFlags = X86II::MO_GOTPCREL;
3074         WrapperKind = X86ISD::WrapperRIP;
3075         ExtraLoad = true;
3076       }
3077
3078       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
3079                                           G->getOffset(), OpFlags);
3080
3081       // Add a wrapper if needed.
3082       if (WrapperKind != ISD::DELETED_NODE)
3083         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
3084       // Add extra indirection if needed.
3085       if (ExtraLoad)
3086         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
3087                              MachinePointerInfo::getGOT(),
3088                              false, false, false, 0);
3089     }
3090   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3091     unsigned char OpFlags = 0;
3092
3093     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
3094     // external symbols should go through the PLT.
3095     if (Subtarget->isTargetELF() &&
3096         DAG.getTarget().getRelocationModel() == Reloc::PIC_) {
3097       OpFlags = X86II::MO_PLT;
3098     } else if (Subtarget->isPICStyleStubAny() &&
3099                (!Subtarget->getTargetTriple().isMacOSX() ||
3100                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3101       // PC-relative references to external symbols should go through $stub,
3102       // unless we're building with the leopard linker or later, which
3103       // automatically synthesizes these stubs.
3104       OpFlags = X86II::MO_DARWIN_STUB;
3105     }
3106
3107     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
3108                                          OpFlags);
3109   } else if (Subtarget->isTarget64BitILP32() &&
3110              Callee->getValueType(0) == MVT::i32) {
3111     // Zero-extend the 32-bit Callee address into a 64-bit according to x32 ABI
3112     Callee = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, Callee);
3113   }
3114
3115   // Returns a chain & a flag for retval copy to use.
3116   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3117   SmallVector<SDValue, 8> Ops;
3118
3119   if (!IsSibcall && isTailCall) {
3120     Chain = DAG.getCALLSEQ_END(Chain,
3121                                DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3122                                DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
3123     InFlag = Chain.getValue(1);
3124   }
3125
3126   Ops.push_back(Chain);
3127   Ops.push_back(Callee);
3128
3129   if (isTailCall)
3130     Ops.push_back(DAG.getConstant(FPDiff, dl, MVT::i32));
3131
3132   // Add argument registers to the end of the list so that they are known live
3133   // into the call.
3134   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3135     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3136                                   RegsToPass[i].second.getValueType()));
3137
3138   // Add a register mask operand representing the call-preserved registers.
3139   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
3140   const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
3141   assert(Mask && "Missing call preserved mask for calling convention");
3142   Ops.push_back(DAG.getRegisterMask(Mask));
3143
3144   if (InFlag.getNode())
3145     Ops.push_back(InFlag);
3146
3147   if (isTailCall) {
3148     // We used to do:
3149     //// If this is the first return lowered for this function, add the regs
3150     //// to the liveout set for the function.
3151     // This isn't right, although it's probably harmless on x86; liveouts
3152     // should be computed from returns not tail calls.  Consider a void
3153     // function making a tail call to a function returning int.
3154     MF.getFrameInfo()->setHasTailCall();
3155     return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
3156   }
3157
3158   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
3159   InFlag = Chain.getValue(1);
3160
3161   // Create the CALLSEQ_END node.
3162   unsigned NumBytesForCalleeToPop;
3163   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
3164                        DAG.getTarget().Options.GuaranteedTailCallOpt))
3165     NumBytesForCalleeToPop = NumBytes;    // Callee pops everything
3166   else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
3167            !Subtarget->getTargetTriple().isOSMSVCRT() &&
3168            SR == StackStructReturn)
3169     // If this is a call to a struct-return function, the callee
3170     // pops the hidden struct pointer, so we have to push it back.
3171     // This is common for Darwin/X86, Linux & Mingw32 targets.
3172     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
3173     NumBytesForCalleeToPop = 4;
3174   else
3175     NumBytesForCalleeToPop = 0;  // Callee pops nothing.
3176
3177   // Returns a flag for retval copy to use.
3178   if (!IsSibcall) {
3179     Chain = DAG.getCALLSEQ_END(Chain,
3180                                DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3181                                DAG.getIntPtrConstant(NumBytesForCalleeToPop, dl,
3182                                                      true),
3183                                InFlag, dl);
3184     InFlag = Chain.getValue(1);
3185   }
3186
3187   // Handle result values, copying them out of physregs into vregs that we
3188   // return.
3189   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3190                          Ins, dl, DAG, InVals);
3191 }
3192
3193 //===----------------------------------------------------------------------===//
3194 //                Fast Calling Convention (tail call) implementation
3195 //===----------------------------------------------------------------------===//
3196
3197 //  Like std call, callee cleans arguments, convention except that ECX is
3198 //  reserved for storing the tail called function address. Only 2 registers are
3199 //  free for argument passing (inreg). Tail call optimization is performed
3200 //  provided:
3201 //                * tailcallopt is enabled
3202 //                * caller/callee are fastcc
3203 //  On X86_64 architecture with GOT-style position independent code only local
3204 //  (within module) calls are supported at the moment.
3205 //  To keep the stack aligned according to platform abi the function
3206 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
3207 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3208 //  If a tail called function callee has more arguments than the caller the
3209 //  caller needs to make sure that there is room to move the RETADDR to. This is
3210 //  achieved by reserving an area the size of the argument delta right after the
3211 //  original RETADDR, but before the saved framepointer or the spilled registers
3212 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3213 //  stack layout:
3214 //    arg1
3215 //    arg2
3216 //    RETADDR
3217 //    [ new RETADDR
3218 //      move area ]
3219 //    (possible EBP)
3220 //    ESI
3221 //    EDI
3222 //    local1 ..
3223
3224 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
3225 /// for a 16 byte align requirement.
3226 unsigned
3227 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3228                                                SelectionDAG& DAG) const {
3229   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3230   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
3231   unsigned StackAlignment = TFI.getStackAlignment();
3232   uint64_t AlignMask = StackAlignment - 1;
3233   int64_t Offset = StackSize;
3234   unsigned SlotSize = RegInfo->getSlotSize();
3235   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3236     // Number smaller than 12 so just add the difference.
3237     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3238   } else {
3239     // Mask out lower bits, add stackalignment once plus the 12 bytes.
3240     Offset = ((~AlignMask) & Offset) + StackAlignment +
3241       (StackAlignment-SlotSize);
3242   }
3243   return Offset;
3244 }
3245
3246 /// MatchingStackOffset - Return true if the given stack call argument is
3247 /// already available in the same position (relatively) of the caller's
3248 /// incoming argument stack.
3249 static
3250 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3251                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3252                          const X86InstrInfo *TII) {
3253   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3254   int FI = INT_MAX;
3255   if (Arg.getOpcode() == ISD::CopyFromReg) {
3256     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3257     if (!TargetRegisterInfo::isVirtualRegister(VR))
3258       return false;
3259     MachineInstr *Def = MRI->getVRegDef(VR);
3260     if (!Def)
3261       return false;
3262     if (!Flags.isByVal()) {
3263       if (!TII->isLoadFromStackSlot(Def, FI))
3264         return false;
3265     } else {
3266       unsigned Opcode = Def->getOpcode();
3267       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r ||
3268            Opcode == X86::LEA64_32r) &&
3269           Def->getOperand(1).isFI()) {
3270         FI = Def->getOperand(1).getIndex();
3271         Bytes = Flags.getByValSize();
3272       } else
3273         return false;
3274     }
3275   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3276     if (Flags.isByVal())
3277       // ByVal argument is passed in as a pointer but it's now being
3278       // dereferenced. e.g.
3279       // define @foo(%struct.X* %A) {
3280       //   tail call @bar(%struct.X* byval %A)
3281       // }
3282       return false;
3283     SDValue Ptr = Ld->getBasePtr();
3284     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3285     if (!FINode)
3286       return false;
3287     FI = FINode->getIndex();
3288   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3289     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3290     FI = FINode->getIndex();
3291     Bytes = Flags.getByValSize();
3292   } else
3293     return false;
3294
3295   assert(FI != INT_MAX);
3296   if (!MFI->isFixedObjectIndex(FI))
3297     return false;
3298   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3299 }
3300
3301 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3302 /// for tail call optimization. Targets which want to do tail call
3303 /// optimization should implement this function.
3304 bool
3305 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3306                                                      CallingConv::ID CalleeCC,
3307                                                      bool isVarArg,
3308                                                      bool isCalleeStructRet,
3309                                                      bool isCallerStructRet,
3310                                                      Type *RetTy,
3311                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
3312                                     const SmallVectorImpl<SDValue> &OutVals,
3313                                     const SmallVectorImpl<ISD::InputArg> &Ins,
3314                                                      SelectionDAG &DAG) const {
3315   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3316     return false;
3317
3318   // If -tailcallopt is specified, make fastcc functions tail-callable.
3319   const MachineFunction &MF = DAG.getMachineFunction();
3320   const Function *CallerF = MF.getFunction();
3321
3322   // If the function return type is x86_fp80 and the callee return type is not,
3323   // then the FP_EXTEND of the call result is not a nop. It's not safe to
3324   // perform a tailcall optimization here.
3325   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3326     return false;
3327
3328   CallingConv::ID CallerCC = CallerF->getCallingConv();
3329   bool CCMatch = CallerCC == CalleeCC;
3330   bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3331   bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3332
3333   // Win64 functions have extra shadow space for argument homing. Don't do the
3334   // sibcall if the caller and callee have mismatched expectations for this
3335   // space.
3336   if (IsCalleeWin64 != IsCallerWin64)
3337     return false;
3338
3339   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3340     if (IsTailCallConvention(CalleeCC) && CCMatch)
3341       return true;
3342     return false;
3343   }
3344
3345   // Look for obvious safe cases to perform tail call optimization that do not
3346   // require ABI changes. This is what gcc calls sibcall.
3347
3348   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3349   // emit a special epilogue.
3350   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3351   if (RegInfo->needsStackRealignment(MF))
3352     return false;
3353
3354   // Also avoid sibcall optimization if either caller or callee uses struct
3355   // return semantics.
3356   if (isCalleeStructRet || isCallerStructRet)
3357     return false;
3358
3359   // An stdcall/thiscall caller is expected to clean up its arguments; the
3360   // callee isn't going to do that.
3361   // FIXME: this is more restrictive than needed. We could produce a tailcall
3362   // when the stack adjustment matches. For example, with a thiscall that takes
3363   // only one argument.
3364   if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3365                    CallerCC == CallingConv::X86_ThisCall))
3366     return false;
3367
3368   // Do not sibcall optimize vararg calls unless all arguments are passed via
3369   // registers.
3370   if (isVarArg && !Outs.empty()) {
3371
3372     // Optimizing for varargs on Win64 is unlikely to be safe without
3373     // additional testing.
3374     if (IsCalleeWin64 || IsCallerWin64)
3375       return false;
3376
3377     SmallVector<CCValAssign, 16> ArgLocs;
3378     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3379                    *DAG.getContext());
3380
3381     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3382     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3383       if (!ArgLocs[i].isRegLoc())
3384         return false;
3385   }
3386
3387   // If the call result is in ST0 / ST1, it needs to be popped off the x87
3388   // stack.  Therefore, if it's not used by the call it is not safe to optimize
3389   // this into a sibcall.
3390   bool Unused = false;
3391   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3392     if (!Ins[i].Used) {
3393       Unused = true;
3394       break;
3395     }
3396   }
3397   if (Unused) {
3398     SmallVector<CCValAssign, 16> RVLocs;
3399     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(), RVLocs,
3400                    *DAG.getContext());
3401     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3402     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3403       CCValAssign &VA = RVLocs[i];
3404       if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
3405         return false;
3406     }
3407   }
3408
3409   // If the calling conventions do not match, then we'd better make sure the
3410   // results are returned in the same way as what the caller expects.
3411   if (!CCMatch) {
3412     SmallVector<CCValAssign, 16> RVLocs1;
3413     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
3414                     *DAG.getContext());
3415     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3416
3417     SmallVector<CCValAssign, 16> RVLocs2;
3418     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
3419                     *DAG.getContext());
3420     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3421
3422     if (RVLocs1.size() != RVLocs2.size())
3423       return false;
3424     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3425       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3426         return false;
3427       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3428         return false;
3429       if (RVLocs1[i].isRegLoc()) {
3430         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3431           return false;
3432       } else {
3433         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3434           return false;
3435       }
3436     }
3437   }
3438
3439   // If the callee takes no arguments then go on to check the results of the
3440   // call.
3441   if (!Outs.empty()) {
3442     // Check if stack adjustment is needed. For now, do not do this if any
3443     // argument is passed on the stack.
3444     SmallVector<CCValAssign, 16> ArgLocs;
3445     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3446                    *DAG.getContext());
3447
3448     // Allocate shadow area for Win64
3449     if (IsCalleeWin64)
3450       CCInfo.AllocateStack(32, 8);
3451
3452     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3453     if (CCInfo.getNextStackOffset()) {
3454       MachineFunction &MF = DAG.getMachineFunction();
3455       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3456         return false;
3457
3458       // Check if the arguments are already laid out in the right way as
3459       // the caller's fixed stack objects.
3460       MachineFrameInfo *MFI = MF.getFrameInfo();
3461       const MachineRegisterInfo *MRI = &MF.getRegInfo();
3462       const X86InstrInfo *TII = Subtarget->getInstrInfo();
3463       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3464         CCValAssign &VA = ArgLocs[i];
3465         SDValue Arg = OutVals[i];
3466         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3467         if (VA.getLocInfo() == CCValAssign::Indirect)
3468           return false;
3469         if (!VA.isRegLoc()) {
3470           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3471                                    MFI, MRI, TII))
3472             return false;
3473         }
3474       }
3475     }
3476
3477     // If the tailcall address may be in a register, then make sure it's
3478     // possible to register allocate for it. In 32-bit, the call address can
3479     // only target EAX, EDX, or ECX since the tail call must be scheduled after
3480     // callee-saved registers are restored. These happen to be the same
3481     // registers used to pass 'inreg' arguments so watch out for those.
3482     if (!Subtarget->is64Bit() &&
3483         ((!isa<GlobalAddressSDNode>(Callee) &&
3484           !isa<ExternalSymbolSDNode>(Callee)) ||
3485          DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3486       unsigned NumInRegs = 0;
3487       // In PIC we need an extra register to formulate the address computation
3488       // for the callee.
3489       unsigned MaxInRegs =
3490         (DAG.getTarget().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3491
3492       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3493         CCValAssign &VA = ArgLocs[i];
3494         if (!VA.isRegLoc())
3495           continue;
3496         unsigned Reg = VA.getLocReg();
3497         switch (Reg) {
3498         default: break;
3499         case X86::EAX: case X86::EDX: case X86::ECX:
3500           if (++NumInRegs == MaxInRegs)
3501             return false;
3502           break;
3503         }
3504       }
3505     }
3506   }
3507
3508   return true;
3509 }
3510
3511 FastISel *
3512 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3513                                   const TargetLibraryInfo *libInfo) const {
3514   return X86::createFastISel(funcInfo, libInfo);
3515 }
3516
3517 //===----------------------------------------------------------------------===//
3518 //                           Other Lowering Hooks
3519 //===----------------------------------------------------------------------===//
3520
3521 static bool MayFoldLoad(SDValue Op) {
3522   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3523 }
3524
3525 static bool MayFoldIntoStore(SDValue Op) {
3526   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3527 }
3528
3529 static bool isTargetShuffle(unsigned Opcode) {
3530   switch(Opcode) {
3531   default: return false;
3532   case X86ISD::BLENDI:
3533   case X86ISD::PSHUFB:
3534   case X86ISD::PSHUFD:
3535   case X86ISD::PSHUFHW:
3536   case X86ISD::PSHUFLW:
3537   case X86ISD::SHUFP:
3538   case X86ISD::PALIGNR:
3539   case X86ISD::MOVLHPS:
3540   case X86ISD::MOVLHPD:
3541   case X86ISD::MOVHLPS:
3542   case X86ISD::MOVLPS:
3543   case X86ISD::MOVLPD:
3544   case X86ISD::MOVSHDUP:
3545   case X86ISD::MOVSLDUP:
3546   case X86ISD::MOVDDUP:
3547   case X86ISD::MOVSS:
3548   case X86ISD::MOVSD:
3549   case X86ISD::UNPCKL:
3550   case X86ISD::UNPCKH:
3551   case X86ISD::VPERMILPI:
3552   case X86ISD::VPERM2X128:
3553   case X86ISD::VPERMI:
3554     return true;
3555   }
3556 }
3557
3558 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3559                                     SDValue V1, unsigned TargetMask,
3560                                     SelectionDAG &DAG) {
3561   switch(Opc) {
3562   default: llvm_unreachable("Unknown x86 shuffle node");
3563   case X86ISD::PSHUFD:
3564   case X86ISD::PSHUFHW:
3565   case X86ISD::PSHUFLW:
3566   case X86ISD::VPERMILPI:
3567   case X86ISD::VPERMI:
3568     return DAG.getNode(Opc, dl, VT, V1,
3569                        DAG.getConstant(TargetMask, dl, MVT::i8));
3570   }
3571 }
3572
3573 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3574                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
3575   switch(Opc) {
3576   default: llvm_unreachable("Unknown x86 shuffle node");
3577   case X86ISD::MOVLHPS:
3578   case X86ISD::MOVLHPD:
3579   case X86ISD::MOVHLPS:
3580   case X86ISD::MOVLPS:
3581   case X86ISD::MOVLPD:
3582   case X86ISD::MOVSS:
3583   case X86ISD::MOVSD:
3584   case X86ISD::UNPCKL:
3585   case X86ISD::UNPCKH:
3586     return DAG.getNode(Opc, dl, VT, V1, V2);
3587   }
3588 }
3589
3590 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3591   MachineFunction &MF = DAG.getMachineFunction();
3592   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3593   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3594   int ReturnAddrIndex = FuncInfo->getRAIndex();
3595
3596   if (ReturnAddrIndex == 0) {
3597     // Set up a frame object for the return address.
3598     unsigned SlotSize = RegInfo->getSlotSize();
3599     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3600                                                            -(int64_t)SlotSize,
3601                                                            false);
3602     FuncInfo->setRAIndex(ReturnAddrIndex);
3603   }
3604
3605   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3606 }
3607
3608 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3609                                        bool hasSymbolicDisplacement) {
3610   // Offset should fit into 32 bit immediate field.
3611   if (!isInt<32>(Offset))
3612     return false;
3613
3614   // If we don't have a symbolic displacement - we don't have any extra
3615   // restrictions.
3616   if (!hasSymbolicDisplacement)
3617     return true;
3618
3619   // FIXME: Some tweaks might be needed for medium code model.
3620   if (M != CodeModel::Small && M != CodeModel::Kernel)
3621     return false;
3622
3623   // For small code model we assume that latest object is 16MB before end of 31
3624   // bits boundary. We may also accept pretty large negative constants knowing
3625   // that all objects are in the positive half of address space.
3626   if (M == CodeModel::Small && Offset < 16*1024*1024)
3627     return true;
3628
3629   // For kernel code model we know that all object resist in the negative half
3630   // of 32bits address space. We may not accept negative offsets, since they may
3631   // be just off and we may accept pretty large positive ones.
3632   if (M == CodeModel::Kernel && Offset >= 0)
3633     return true;
3634
3635   return false;
3636 }
3637
3638 /// isCalleePop - Determines whether the callee is required to pop its
3639 /// own arguments. Callee pop is necessary to support tail calls.
3640 bool X86::isCalleePop(CallingConv::ID CallingConv,
3641                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3642   switch (CallingConv) {
3643   default:
3644     return false;
3645   case CallingConv::X86_StdCall:
3646   case CallingConv::X86_FastCall:
3647   case CallingConv::X86_ThisCall:
3648     return !is64Bit;
3649   case CallingConv::Fast:
3650   case CallingConv::GHC:
3651   case CallingConv::HiPE:
3652     if (IsVarArg)
3653       return false;
3654     return TailCallOpt;
3655   }
3656 }
3657
3658 /// \brief Return true if the condition is an unsigned comparison operation.
3659 static bool isX86CCUnsigned(unsigned X86CC) {
3660   switch (X86CC) {
3661   default: llvm_unreachable("Invalid integer condition!");
3662   case X86::COND_E:     return true;
3663   case X86::COND_G:     return false;
3664   case X86::COND_GE:    return false;
3665   case X86::COND_L:     return false;
3666   case X86::COND_LE:    return false;
3667   case X86::COND_NE:    return true;
3668   case X86::COND_B:     return true;
3669   case X86::COND_A:     return true;
3670   case X86::COND_BE:    return true;
3671   case X86::COND_AE:    return true;
3672   }
3673   llvm_unreachable("covered switch fell through?!");
3674 }
3675
3676 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3677 /// specific condition code, returning the condition code and the LHS/RHS of the
3678 /// comparison to make.
3679 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, SDLoc DL, bool isFP,
3680                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3681   if (!isFP) {
3682     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3683       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3684         // X > -1   -> X == 0, jump !sign.
3685         RHS = DAG.getConstant(0, DL, RHS.getValueType());
3686         return X86::COND_NS;
3687       }
3688       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3689         // X < 0   -> X == 0, jump on sign.
3690         return X86::COND_S;
3691       }
3692       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3693         // X < 1   -> X <= 0
3694         RHS = DAG.getConstant(0, DL, RHS.getValueType());
3695         return X86::COND_LE;
3696       }
3697     }
3698
3699     switch (SetCCOpcode) {
3700     default: llvm_unreachable("Invalid integer condition!");
3701     case ISD::SETEQ:  return X86::COND_E;
3702     case ISD::SETGT:  return X86::COND_G;
3703     case ISD::SETGE:  return X86::COND_GE;
3704     case ISD::SETLT:  return X86::COND_L;
3705     case ISD::SETLE:  return X86::COND_LE;
3706     case ISD::SETNE:  return X86::COND_NE;
3707     case ISD::SETULT: return X86::COND_B;
3708     case ISD::SETUGT: return X86::COND_A;
3709     case ISD::SETULE: return X86::COND_BE;
3710     case ISD::SETUGE: return X86::COND_AE;
3711     }
3712   }
3713
3714   // First determine if it is required or is profitable to flip the operands.
3715
3716   // If LHS is a foldable load, but RHS is not, flip the condition.
3717   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3718       !ISD::isNON_EXTLoad(RHS.getNode())) {
3719     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3720     std::swap(LHS, RHS);
3721   }
3722
3723   switch (SetCCOpcode) {
3724   default: break;
3725   case ISD::SETOLT:
3726   case ISD::SETOLE:
3727   case ISD::SETUGT:
3728   case ISD::SETUGE:
3729     std::swap(LHS, RHS);
3730     break;
3731   }
3732
3733   // On a floating point condition, the flags are set as follows:
3734   // ZF  PF  CF   op
3735   //  0 | 0 | 0 | X > Y
3736   //  0 | 0 | 1 | X < Y
3737   //  1 | 0 | 0 | X == Y
3738   //  1 | 1 | 1 | unordered
3739   switch (SetCCOpcode) {
3740   default: llvm_unreachable("Condcode should be pre-legalized away");
3741   case ISD::SETUEQ:
3742   case ISD::SETEQ:   return X86::COND_E;
3743   case ISD::SETOLT:              // flipped
3744   case ISD::SETOGT:
3745   case ISD::SETGT:   return X86::COND_A;
3746   case ISD::SETOLE:              // flipped
3747   case ISD::SETOGE:
3748   case ISD::SETGE:   return X86::COND_AE;
3749   case ISD::SETUGT:              // flipped
3750   case ISD::SETULT:
3751   case ISD::SETLT:   return X86::COND_B;
3752   case ISD::SETUGE:              // flipped
3753   case ISD::SETULE:
3754   case ISD::SETLE:   return X86::COND_BE;
3755   case ISD::SETONE:
3756   case ISD::SETNE:   return X86::COND_NE;
3757   case ISD::SETUO:   return X86::COND_P;
3758   case ISD::SETO:    return X86::COND_NP;
3759   case ISD::SETOEQ:
3760   case ISD::SETUNE:  return X86::COND_INVALID;
3761   }
3762 }
3763
3764 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3765 /// code. Current x86 isa includes the following FP cmov instructions:
3766 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3767 static bool hasFPCMov(unsigned X86CC) {
3768   switch (X86CC) {
3769   default:
3770     return false;
3771   case X86::COND_B:
3772   case X86::COND_BE:
3773   case X86::COND_E:
3774   case X86::COND_P:
3775   case X86::COND_A:
3776   case X86::COND_AE:
3777   case X86::COND_NE:
3778   case X86::COND_NP:
3779     return true;
3780   }
3781 }
3782
3783 /// isFPImmLegal - Returns true if the target can instruction select the
3784 /// specified FP immediate natively. If false, the legalizer will
3785 /// materialize the FP immediate as a load from a constant pool.
3786 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3787   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3788     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3789       return true;
3790   }
3791   return false;
3792 }
3793
3794 bool X86TargetLowering::shouldReduceLoadWidth(SDNode *Load,
3795                                               ISD::LoadExtType ExtTy,
3796                                               EVT NewVT) const {
3797   // "ELF Handling for Thread-Local Storage" specifies that R_X86_64_GOTTPOFF
3798   // relocation target a movq or addq instruction: don't let the load shrink.
3799   SDValue BasePtr = cast<LoadSDNode>(Load)->getBasePtr();
3800   if (BasePtr.getOpcode() == X86ISD::WrapperRIP)
3801     if (const auto *GA = dyn_cast<GlobalAddressSDNode>(BasePtr.getOperand(0)))
3802       return GA->getTargetFlags() != X86II::MO_GOTTPOFF;
3803   return true;
3804 }
3805
3806 /// \brief Returns true if it is beneficial to convert a load of a constant
3807 /// to just the constant itself.
3808 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
3809                                                           Type *Ty) const {
3810   assert(Ty->isIntegerTy());
3811
3812   unsigned BitSize = Ty->getPrimitiveSizeInBits();
3813   if (BitSize == 0 || BitSize > 64)
3814     return false;
3815   return true;
3816 }
3817
3818 bool X86TargetLowering::isExtractSubvectorCheap(EVT ResVT,
3819                                                 unsigned Index) const {
3820   if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
3821     return false;
3822
3823   return (Index == 0 || Index == ResVT.getVectorNumElements());
3824 }
3825
3826 bool X86TargetLowering::isCheapToSpeculateCttz() const {
3827   // Speculate cttz only if we can directly use TZCNT.
3828   return Subtarget->hasBMI();
3829 }
3830
3831 bool X86TargetLowering::isCheapToSpeculateCtlz() const {
3832   // Speculate ctlz only if we can directly use LZCNT.
3833   return Subtarget->hasLZCNT();
3834 }
3835
3836 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3837 /// the specified range (L, H].
3838 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3839   return (Val < 0) || (Val >= Low && Val < Hi);
3840 }
3841
3842 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3843 /// specified value.
3844 static bool isUndefOrEqual(int Val, int CmpVal) {
3845   return (Val < 0 || Val == CmpVal);
3846 }
3847
3848 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3849 /// from position Pos and ending in Pos+Size, falls within the specified
3850 /// sequential range (Low, Low+Size]. or is undef.
3851 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3852                                        unsigned Pos, unsigned Size, int Low) {
3853   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3854     if (!isUndefOrEqual(Mask[i], Low))
3855       return false;
3856   return true;
3857 }
3858
3859 /// isVEXTRACTIndex - Return true if the specified
3860 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
3861 /// suitable for instruction that extract 128 or 256 bit vectors
3862 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
3863   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
3864   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3865     return false;
3866
3867   // The index should be aligned on a vecWidth-bit boundary.
3868   uint64_t Index =
3869     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3870
3871   MVT VT = N->getSimpleValueType(0);
3872   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
3873   bool Result = (Index * ElSize) % vecWidth == 0;
3874
3875   return Result;
3876 }
3877
3878 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
3879 /// operand specifies a subvector insert that is suitable for input to
3880 /// insertion of 128 or 256-bit subvectors
3881 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
3882   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
3883   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3884     return false;
3885   // The index should be aligned on a vecWidth-bit boundary.
3886   uint64_t Index =
3887     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3888
3889   MVT VT = N->getSimpleValueType(0);
3890   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
3891   bool Result = (Index * ElSize) % vecWidth == 0;
3892
3893   return Result;
3894 }
3895
3896 bool X86::isVINSERT128Index(SDNode *N) {
3897   return isVINSERTIndex(N, 128);
3898 }
3899
3900 bool X86::isVINSERT256Index(SDNode *N) {
3901   return isVINSERTIndex(N, 256);
3902 }
3903
3904 bool X86::isVEXTRACT128Index(SDNode *N) {
3905   return isVEXTRACTIndex(N, 128);
3906 }
3907
3908 bool X86::isVEXTRACT256Index(SDNode *N) {
3909   return isVEXTRACTIndex(N, 256);
3910 }
3911
3912 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
3913   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
3914   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3915     llvm_unreachable("Illegal extract subvector for VEXTRACT");
3916
3917   uint64_t Index =
3918     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3919
3920   MVT VecVT = N->getOperand(0).getSimpleValueType();
3921   MVT ElVT = VecVT.getVectorElementType();
3922
3923   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
3924   return Index / NumElemsPerChunk;
3925 }
3926
3927 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
3928   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
3929   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3930     llvm_unreachable("Illegal insert subvector for VINSERT");
3931
3932   uint64_t Index =
3933     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3934
3935   MVT VecVT = N->getSimpleValueType(0);
3936   MVT ElVT = VecVT.getVectorElementType();
3937
3938   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
3939   return Index / NumElemsPerChunk;
3940 }
3941
3942 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
3943 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
3944 /// and VINSERTI128 instructions.
3945 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
3946   return getExtractVEXTRACTImmediate(N, 128);
3947 }
3948
3949 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
3950 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
3951 /// and VINSERTI64x4 instructions.
3952 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
3953   return getExtractVEXTRACTImmediate(N, 256);
3954 }
3955
3956 /// getInsertVINSERT128Immediate - Return the appropriate immediate
3957 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
3958 /// and VINSERTI128 instructions.
3959 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
3960   return getInsertVINSERTImmediate(N, 128);
3961 }
3962
3963 /// getInsertVINSERT256Immediate - Return the appropriate immediate
3964 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
3965 /// and VINSERTI64x4 instructions.
3966 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
3967   return getInsertVINSERTImmediate(N, 256);
3968 }
3969
3970 /// isZero - Returns true if Elt is a constant integer zero
3971 static bool isZero(SDValue V) {
3972   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
3973   return C && C->isNullValue();
3974 }
3975
3976 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
3977 /// constant +0.0.
3978 bool X86::isZeroNode(SDValue Elt) {
3979   if (isZero(Elt))
3980     return true;
3981   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
3982     return CFP->getValueAPF().isPosZero();
3983   return false;
3984 }
3985
3986 /// getZeroVector - Returns a vector of specified type with all zero elements.
3987 ///
3988 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
3989                              SelectionDAG &DAG, SDLoc dl) {
3990   assert(VT.isVector() && "Expected a vector type");
3991
3992   // Always build SSE zero vectors as <4 x i32> bitcasted
3993   // to their dest type. This ensures they get CSE'd.
3994   SDValue Vec;
3995   if (VT.is128BitVector()) {  // SSE
3996     if (Subtarget->hasSSE2()) {  // SSE2
3997       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
3998       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3999     } else { // SSE1
4000       SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4001       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4002     }
4003   } else if (VT.is256BitVector()) { // AVX
4004     if (Subtarget->hasInt256()) { // AVX2
4005       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4006       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4007       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4008     } else {
4009       // 256-bit logic and arithmetic instructions in AVX are all
4010       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4011       SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4012       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4013       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
4014     }
4015   } else if (VT.is512BitVector()) { // AVX-512
4016       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4017       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4018                         Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4019       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4020   } else if (VT.getScalarType() == MVT::i1) {
4021
4022     assert((Subtarget->hasBWI() || VT.getVectorNumElements() <= 16)
4023             && "Unexpected vector type");
4024     assert((Subtarget->hasVLX() || VT.getVectorNumElements() >= 8)
4025             && "Unexpected vector type");
4026     SDValue Cst = DAG.getConstant(0, dl, MVT::i1);
4027     SmallVector<SDValue, 64> Ops(VT.getVectorNumElements(), Cst);
4028     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
4029   } else
4030     llvm_unreachable("Unexpected vector type");
4031
4032   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4033 }
4034
4035 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
4036                                 SelectionDAG &DAG, SDLoc dl,
4037                                 unsigned vectorWidth) {
4038   assert((vectorWidth == 128 || vectorWidth == 256) &&
4039          "Unsupported vector width");
4040   EVT VT = Vec.getValueType();
4041   EVT ElVT = VT.getVectorElementType();
4042   unsigned Factor = VT.getSizeInBits()/vectorWidth;
4043   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
4044                                   VT.getVectorNumElements()/Factor);
4045
4046   // Extract from UNDEF is UNDEF.
4047   if (Vec.getOpcode() == ISD::UNDEF)
4048     return DAG.getUNDEF(ResultVT);
4049
4050   // Extract the relevant vectorWidth bits.  Generate an EXTRACT_SUBVECTOR
4051   unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
4052
4053   // This is the index of the first element of the vectorWidth-bit chunk
4054   // we want.
4055   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / vectorWidth)
4056                                * ElemsPerChunk);
4057
4058   // If the input is a buildvector just emit a smaller one.
4059   if (Vec.getOpcode() == ISD::BUILD_VECTOR)
4060     return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
4061                        makeArrayRef(Vec->op_begin() + NormalizedIdxVal,
4062                                     ElemsPerChunk));
4063
4064   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal, dl);
4065   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec, VecIdx);
4066 }
4067
4068 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
4069 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
4070 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
4071 /// instructions or a simple subregister reference. Idx is an index in the
4072 /// 128 bits we want.  It need not be aligned to a 128-bit boundary.  That makes
4073 /// lowering EXTRACT_VECTOR_ELT operations easier.
4074 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
4075                                    SelectionDAG &DAG, SDLoc dl) {
4076   assert((Vec.getValueType().is256BitVector() ||
4077           Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
4078   return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
4079 }
4080
4081 /// Generate a DAG to grab 256-bits from a 512-bit vector.
4082 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
4083                                    SelectionDAG &DAG, SDLoc dl) {
4084   assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
4085   return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
4086 }
4087
4088 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
4089                                unsigned IdxVal, SelectionDAG &DAG,
4090                                SDLoc dl, unsigned vectorWidth) {
4091   assert((vectorWidth == 128 || vectorWidth == 256) &&
4092          "Unsupported vector width");
4093   // Inserting UNDEF is Result
4094   if (Vec.getOpcode() == ISD::UNDEF)
4095     return Result;
4096   EVT VT = Vec.getValueType();
4097   EVT ElVT = VT.getVectorElementType();
4098   EVT ResultVT = Result.getValueType();
4099
4100   // Insert the relevant vectorWidth bits.
4101   unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
4102
4103   // This is the index of the first element of the vectorWidth-bit chunk
4104   // we want.
4105   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/vectorWidth)
4106                                * ElemsPerChunk);
4107
4108   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal, dl);
4109   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec, VecIdx);
4110 }
4111
4112 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
4113 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
4114 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
4115 /// simple superregister reference.  Idx is an index in the 128 bits
4116 /// we want.  It need not be aligned to a 128-bit boundary.  That makes
4117 /// lowering INSERT_VECTOR_ELT operations easier.
4118 static SDValue Insert128BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4119                                   SelectionDAG &DAG, SDLoc dl) {
4120   assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
4121
4122   // For insertion into the zero index (low half) of a 256-bit vector, it is
4123   // more efficient to generate a blend with immediate instead of an insert*128.
4124   // We are still creating an INSERT_SUBVECTOR below with an undef node to
4125   // extend the subvector to the size of the result vector. Make sure that
4126   // we are not recursing on that node by checking for undef here.
4127   if (IdxVal == 0 && Result.getValueType().is256BitVector() &&
4128       Result.getOpcode() != ISD::UNDEF) {
4129     EVT ResultVT = Result.getValueType();
4130     SDValue ZeroIndex = DAG.getIntPtrConstant(0, dl);
4131     SDValue Undef = DAG.getUNDEF(ResultVT);
4132     SDValue Vec256 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Undef,
4133                                  Vec, ZeroIndex);
4134
4135     // The blend instruction, and therefore its mask, depend on the data type.
4136     MVT ScalarType = ResultVT.getScalarType().getSimpleVT();
4137     if (ScalarType.isFloatingPoint()) {
4138       // Choose either vblendps (float) or vblendpd (double).
4139       unsigned ScalarSize = ScalarType.getSizeInBits();
4140       assert((ScalarSize == 64 || ScalarSize == 32) && "Unknown float type");
4141       unsigned MaskVal = (ScalarSize == 64) ? 0x03 : 0x0f;
4142       SDValue Mask = DAG.getConstant(MaskVal, dl, MVT::i8);
4143       return DAG.getNode(X86ISD::BLENDI, dl, ResultVT, Result, Vec256, Mask);
4144     }
4145
4146     const X86Subtarget &Subtarget =
4147     static_cast<const X86Subtarget &>(DAG.getSubtarget());
4148
4149     // AVX2 is needed for 256-bit integer blend support.
4150     // Integers must be cast to 32-bit because there is only vpblendd;
4151     // vpblendw can't be used for this because it has a handicapped mask.
4152
4153     // If we don't have AVX2, then cast to float. Using a wrong domain blend
4154     // is still more efficient than using the wrong domain vinsertf128 that
4155     // will be created by InsertSubVector().
4156     MVT CastVT = Subtarget.hasAVX2() ? MVT::v8i32 : MVT::v8f32;
4157
4158     SDValue Mask = DAG.getConstant(0x0f, dl, MVT::i8);
4159     Vec256 = DAG.getNode(ISD::BITCAST, dl, CastVT, Vec256);
4160     Vec256 = DAG.getNode(X86ISD::BLENDI, dl, CastVT, Result, Vec256, Mask);
4161     return DAG.getNode(ISD::BITCAST, dl, ResultVT, Vec256);
4162   }
4163
4164   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
4165 }
4166
4167 static SDValue Insert256BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4168                                   SelectionDAG &DAG, SDLoc dl) {
4169   assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
4170   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
4171 }
4172
4173 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
4174 /// instructions. This is used because creating CONCAT_VECTOR nodes of
4175 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
4176 /// large BUILD_VECTORS.
4177 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
4178                                    unsigned NumElems, SelectionDAG &DAG,
4179                                    SDLoc dl) {
4180   SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4181   return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
4182 }
4183
4184 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
4185                                    unsigned NumElems, SelectionDAG &DAG,
4186                                    SDLoc dl) {
4187   SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4188   return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
4189 }
4190
4191 /// getOnesVector - Returns a vector of specified type with all bits set.
4192 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4193 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4194 /// Then bitcast to their original type, ensuring they get CSE'd.
4195 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4196                              SDLoc dl) {
4197   assert(VT.isVector() && "Expected a vector type");
4198
4199   SDValue Cst = DAG.getConstant(~0U, dl, MVT::i32);
4200   SDValue Vec;
4201   if (VT.is256BitVector()) {
4202     if (HasInt256) { // AVX2
4203       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4204       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4205     } else { // AVX
4206       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4207       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4208     }
4209   } else if (VT.is128BitVector()) {
4210     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4211   } else
4212     llvm_unreachable("Unexpected vector type");
4213
4214   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4215 }
4216
4217 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4218 /// operation of specified width.
4219 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4220                        SDValue V2) {
4221   unsigned NumElems = VT.getVectorNumElements();
4222   SmallVector<int, 8> Mask;
4223   Mask.push_back(NumElems);
4224   for (unsigned i = 1; i != NumElems; ++i)
4225     Mask.push_back(i);
4226   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4227 }
4228
4229 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4230 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4231                           SDValue V2) {
4232   unsigned NumElems = VT.getVectorNumElements();
4233   SmallVector<int, 8> Mask;
4234   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4235     Mask.push_back(i);
4236     Mask.push_back(i + NumElems);
4237   }
4238   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4239 }
4240
4241 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4242 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4243                           SDValue V2) {
4244   unsigned NumElems = VT.getVectorNumElements();
4245   SmallVector<int, 8> Mask;
4246   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4247     Mask.push_back(i + Half);
4248     Mask.push_back(i + NumElems + Half);
4249   }
4250   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4251 }
4252
4253 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4254 /// vector of zero or undef vector.  This produces a shuffle where the low
4255 /// element of V2 is swizzled into the zero/undef vector, landing at element
4256 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
4257 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4258                                            bool IsZero,
4259                                            const X86Subtarget *Subtarget,
4260                                            SelectionDAG &DAG) {
4261   MVT VT = V2.getSimpleValueType();
4262   SDValue V1 = IsZero
4263     ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
4264   unsigned NumElems = VT.getVectorNumElements();
4265   SmallVector<int, 16> MaskVec;
4266   for (unsigned i = 0; i != NumElems; ++i)
4267     // If this is the insertion idx, put the low elt of V2 here.
4268     MaskVec.push_back(i == Idx ? NumElems : i);
4269   return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
4270 }
4271
4272 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
4273 /// target specific opcode. Returns true if the Mask could be calculated. Sets
4274 /// IsUnary to true if only uses one source. Note that this will set IsUnary for
4275 /// shuffles which use a single input multiple times, and in those cases it will
4276 /// adjust the mask to only have indices within that single input.
4277 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4278                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
4279   unsigned NumElems = VT.getVectorNumElements();
4280   SDValue ImmN;
4281
4282   IsUnary = false;
4283   bool IsFakeUnary = false;
4284   switch(N->getOpcode()) {
4285   case X86ISD::BLENDI:
4286     ImmN = N->getOperand(N->getNumOperands()-1);
4287     DecodeBLENDMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4288     break;
4289   case X86ISD::SHUFP:
4290     ImmN = N->getOperand(N->getNumOperands()-1);
4291     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4292     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4293     break;
4294   case X86ISD::UNPCKH:
4295     DecodeUNPCKHMask(VT, Mask);
4296     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4297     break;
4298   case X86ISD::UNPCKL:
4299     DecodeUNPCKLMask(VT, Mask);
4300     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4301     break;
4302   case X86ISD::MOVHLPS:
4303     DecodeMOVHLPSMask(NumElems, Mask);
4304     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4305     break;
4306   case X86ISD::MOVLHPS:
4307     DecodeMOVLHPSMask(NumElems, Mask);
4308     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4309     break;
4310   case X86ISD::PALIGNR:
4311     ImmN = N->getOperand(N->getNumOperands()-1);
4312     DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4313     break;
4314   case X86ISD::PSHUFD:
4315   case X86ISD::VPERMILPI:
4316     ImmN = N->getOperand(N->getNumOperands()-1);
4317     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4318     IsUnary = true;
4319     break;
4320   case X86ISD::PSHUFHW:
4321     ImmN = N->getOperand(N->getNumOperands()-1);
4322     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4323     IsUnary = true;
4324     break;
4325   case X86ISD::PSHUFLW:
4326     ImmN = N->getOperand(N->getNumOperands()-1);
4327     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4328     IsUnary = true;
4329     break;
4330   case X86ISD::PSHUFB: {
4331     IsUnary = true;
4332     SDValue MaskNode = N->getOperand(1);
4333     while (MaskNode->getOpcode() == ISD::BITCAST)
4334       MaskNode = MaskNode->getOperand(0);
4335
4336     if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
4337       // If we have a build-vector, then things are easy.
4338       EVT VT = MaskNode.getValueType();
4339       assert(VT.isVector() &&
4340              "Can't produce a non-vector with a build_vector!");
4341       if (!VT.isInteger())
4342         return false;
4343
4344       int NumBytesPerElement = VT.getVectorElementType().getSizeInBits() / 8;
4345
4346       SmallVector<uint64_t, 32> RawMask;
4347       for (int i = 0, e = MaskNode->getNumOperands(); i < e; ++i) {
4348         SDValue Op = MaskNode->getOperand(i);
4349         if (Op->getOpcode() == ISD::UNDEF) {
4350           RawMask.push_back((uint64_t)SM_SentinelUndef);
4351           continue;
4352         }
4353         auto *CN = dyn_cast<ConstantSDNode>(Op.getNode());
4354         if (!CN)
4355           return false;
4356         APInt MaskElement = CN->getAPIntValue();
4357
4358         // We now have to decode the element which could be any integer size and
4359         // extract each byte of it.
4360         for (int j = 0; j < NumBytesPerElement; ++j) {
4361           // Note that this is x86 and so always little endian: the low byte is
4362           // the first byte of the mask.
4363           RawMask.push_back(MaskElement.getLoBits(8).getZExtValue());
4364           MaskElement = MaskElement.lshr(8);
4365         }
4366       }
4367       DecodePSHUFBMask(RawMask, Mask);
4368       break;
4369     }
4370
4371     auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
4372     if (!MaskLoad)
4373       return false;
4374
4375     SDValue Ptr = MaskLoad->getBasePtr();
4376     if (Ptr->getOpcode() == X86ISD::Wrapper ||
4377         Ptr->getOpcode() == X86ISD::WrapperRIP)
4378       Ptr = Ptr->getOperand(0);
4379
4380     auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
4381     if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
4382       return false;
4383
4384     if (auto *C = dyn_cast<Constant>(MaskCP->getConstVal())) {
4385       DecodePSHUFBMask(C, Mask);
4386       if (Mask.empty())
4387         return false;
4388       break;
4389     }
4390
4391     return false;
4392   }
4393   case X86ISD::VPERMI:
4394     ImmN = N->getOperand(N->getNumOperands()-1);
4395     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4396     IsUnary = true;
4397     break;
4398   case X86ISD::MOVSS:
4399   case X86ISD::MOVSD:
4400     DecodeScalarMoveMask(VT, /* IsLoad */ false, Mask);
4401     break;
4402   case X86ISD::VPERM2X128:
4403     ImmN = N->getOperand(N->getNumOperands()-1);
4404     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4405     if (Mask.empty()) return false;
4406     break;
4407   case X86ISD::MOVSLDUP:
4408     DecodeMOVSLDUPMask(VT, Mask);
4409     IsUnary = true;
4410     break;
4411   case X86ISD::MOVSHDUP:
4412     DecodeMOVSHDUPMask(VT, Mask);
4413     IsUnary = true;
4414     break;
4415   case X86ISD::MOVDDUP:
4416     DecodeMOVDDUPMask(VT, Mask);
4417     IsUnary = true;
4418     break;
4419   case X86ISD::MOVLHPD:
4420   case X86ISD::MOVLPD:
4421   case X86ISD::MOVLPS:
4422     // Not yet implemented
4423     return false;
4424   default: llvm_unreachable("unknown target shuffle node");
4425   }
4426
4427   // If we have a fake unary shuffle, the shuffle mask is spread across two
4428   // inputs that are actually the same node. Re-map the mask to always point
4429   // into the first input.
4430   if (IsFakeUnary)
4431     for (int &M : Mask)
4432       if (M >= (int)Mask.size())
4433         M -= Mask.size();
4434
4435   return true;
4436 }
4437
4438 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4439 /// element of the result of the vector shuffle.
4440 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4441                                    unsigned Depth) {
4442   if (Depth == 6)
4443     return SDValue();  // Limit search depth.
4444
4445   SDValue V = SDValue(N, 0);
4446   EVT VT = V.getValueType();
4447   unsigned Opcode = V.getOpcode();
4448
4449   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4450   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4451     int Elt = SV->getMaskElt(Index);
4452
4453     if (Elt < 0)
4454       return DAG.getUNDEF(VT.getVectorElementType());
4455
4456     unsigned NumElems = VT.getVectorNumElements();
4457     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4458                                          : SV->getOperand(1);
4459     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4460   }
4461
4462   // Recurse into target specific vector shuffles to find scalars.
4463   if (isTargetShuffle(Opcode)) {
4464     MVT ShufVT = V.getSimpleValueType();
4465     unsigned NumElems = ShufVT.getVectorNumElements();
4466     SmallVector<int, 16> ShuffleMask;
4467     bool IsUnary;
4468
4469     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4470       return SDValue();
4471
4472     int Elt = ShuffleMask[Index];
4473     if (Elt < 0)
4474       return DAG.getUNDEF(ShufVT.getVectorElementType());
4475
4476     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4477                                          : N->getOperand(1);
4478     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4479                                Depth+1);
4480   }
4481
4482   // Actual nodes that may contain scalar elements
4483   if (Opcode == ISD::BITCAST) {
4484     V = V.getOperand(0);
4485     EVT SrcVT = V.getValueType();
4486     unsigned NumElems = VT.getVectorNumElements();
4487
4488     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4489       return SDValue();
4490   }
4491
4492   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4493     return (Index == 0) ? V.getOperand(0)
4494                         : DAG.getUNDEF(VT.getVectorElementType());
4495
4496   if (V.getOpcode() == ISD::BUILD_VECTOR)
4497     return V.getOperand(Index);
4498
4499   return SDValue();
4500 }
4501
4502 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4503 ///
4504 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4505                                        unsigned NumNonZero, unsigned NumZero,
4506                                        SelectionDAG &DAG,
4507                                        const X86Subtarget* Subtarget,
4508                                        const TargetLowering &TLI) {
4509   if (NumNonZero > 8)
4510     return SDValue();
4511
4512   SDLoc dl(Op);
4513   SDValue V;
4514   bool First = true;
4515
4516   // SSE4.1 - use PINSRB to insert each byte directly.
4517   if (Subtarget->hasSSE41()) {
4518     for (unsigned i = 0; i < 16; ++i) {
4519       bool isNonZero = (NonZeros & (1 << i)) != 0;
4520       if (isNonZero) {
4521         if (First) {
4522           if (NumZero)
4523             V = getZeroVector(MVT::v16i8, Subtarget, DAG, dl);
4524           else
4525             V = DAG.getUNDEF(MVT::v16i8);
4526           First = false;
4527         }
4528         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4529                         MVT::v16i8, V, Op.getOperand(i),
4530                         DAG.getIntPtrConstant(i, dl));
4531       }
4532     }
4533
4534     return V;
4535   }
4536
4537   // Pre-SSE4.1 - merge byte pairs and insert with PINSRW.
4538   for (unsigned i = 0; i < 16; ++i) {
4539     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4540     if (ThisIsNonZero && First) {
4541       if (NumZero)
4542         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4543       else
4544         V = DAG.getUNDEF(MVT::v8i16);
4545       First = false;
4546     }
4547
4548     if ((i & 1) != 0) {
4549       SDValue ThisElt, LastElt;
4550       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4551       if (LastIsNonZero) {
4552         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4553                               MVT::i16, Op.getOperand(i-1));
4554       }
4555       if (ThisIsNonZero) {
4556         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4557         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4558                               ThisElt, DAG.getConstant(8, dl, MVT::i8));
4559         if (LastIsNonZero)
4560           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4561       } else
4562         ThisElt = LastElt;
4563
4564       if (ThisElt.getNode())
4565         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4566                         DAG.getIntPtrConstant(i/2, dl));
4567     }
4568   }
4569
4570   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4571 }
4572
4573 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4574 ///
4575 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4576                                      unsigned NumNonZero, unsigned NumZero,
4577                                      SelectionDAG &DAG,
4578                                      const X86Subtarget* Subtarget,
4579                                      const TargetLowering &TLI) {
4580   if (NumNonZero > 4)
4581     return SDValue();
4582
4583   SDLoc dl(Op);
4584   SDValue V;
4585   bool First = true;
4586   for (unsigned i = 0; i < 8; ++i) {
4587     bool isNonZero = (NonZeros & (1 << i)) != 0;
4588     if (isNonZero) {
4589       if (First) {
4590         if (NumZero)
4591           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4592         else
4593           V = DAG.getUNDEF(MVT::v8i16);
4594         First = false;
4595       }
4596       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4597                       MVT::v8i16, V, Op.getOperand(i),
4598                       DAG.getIntPtrConstant(i, dl));
4599     }
4600   }
4601
4602   return V;
4603 }
4604
4605 /// LowerBuildVectorv4x32 - Custom lower build_vector of v4i32 or v4f32.
4606 static SDValue LowerBuildVectorv4x32(SDValue Op, SelectionDAG &DAG,
4607                                      const X86Subtarget *Subtarget,
4608                                      const TargetLowering &TLI) {
4609   // Find all zeroable elements.
4610   std::bitset<4> Zeroable;
4611   for (int i=0; i < 4; ++i) {
4612     SDValue Elt = Op->getOperand(i);
4613     Zeroable[i] = (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt));
4614   }
4615   assert(Zeroable.size() - Zeroable.count() > 1 &&
4616          "We expect at least two non-zero elements!");
4617
4618   // We only know how to deal with build_vector nodes where elements are either
4619   // zeroable or extract_vector_elt with constant index.
4620   SDValue FirstNonZero;
4621   unsigned FirstNonZeroIdx;
4622   for (unsigned i=0; i < 4; ++i) {
4623     if (Zeroable[i])
4624       continue;
4625     SDValue Elt = Op->getOperand(i);
4626     if (Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4627         !isa<ConstantSDNode>(Elt.getOperand(1)))
4628       return SDValue();
4629     // Make sure that this node is extracting from a 128-bit vector.
4630     MVT VT = Elt.getOperand(0).getSimpleValueType();
4631     if (!VT.is128BitVector())
4632       return SDValue();
4633     if (!FirstNonZero.getNode()) {
4634       FirstNonZero = Elt;
4635       FirstNonZeroIdx = i;
4636     }
4637   }
4638
4639   assert(FirstNonZero.getNode() && "Unexpected build vector of all zeros!");
4640   SDValue V1 = FirstNonZero.getOperand(0);
4641   MVT VT = V1.getSimpleValueType();
4642
4643   // See if this build_vector can be lowered as a blend with zero.
4644   SDValue Elt;
4645   unsigned EltMaskIdx, EltIdx;
4646   int Mask[4];
4647   for (EltIdx = 0; EltIdx < 4; ++EltIdx) {
4648     if (Zeroable[EltIdx]) {
4649       // The zero vector will be on the right hand side.
4650       Mask[EltIdx] = EltIdx+4;
4651       continue;
4652     }
4653
4654     Elt = Op->getOperand(EltIdx);
4655     // By construction, Elt is a EXTRACT_VECTOR_ELT with constant index.
4656     EltMaskIdx = cast<ConstantSDNode>(Elt.getOperand(1))->getZExtValue();
4657     if (Elt.getOperand(0) != V1 || EltMaskIdx != EltIdx)
4658       break;
4659     Mask[EltIdx] = EltIdx;
4660   }
4661
4662   if (EltIdx == 4) {
4663     // Let the shuffle legalizer deal with blend operations.
4664     SDValue VZero = getZeroVector(VT, Subtarget, DAG, SDLoc(Op));
4665     if (V1.getSimpleValueType() != VT)
4666       V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), VT, V1);
4667     return DAG.getVectorShuffle(VT, SDLoc(V1), V1, VZero, &Mask[0]);
4668   }
4669
4670   // See if we can lower this build_vector to a INSERTPS.
4671   if (!Subtarget->hasSSE41())
4672     return SDValue();
4673
4674   SDValue V2 = Elt.getOperand(0);
4675   if (Elt == FirstNonZero && EltIdx == FirstNonZeroIdx)
4676     V1 = SDValue();
4677
4678   bool CanFold = true;
4679   for (unsigned i = EltIdx + 1; i < 4 && CanFold; ++i) {
4680     if (Zeroable[i])
4681       continue;
4682
4683     SDValue Current = Op->getOperand(i);
4684     SDValue SrcVector = Current->getOperand(0);
4685     if (!V1.getNode())
4686       V1 = SrcVector;
4687     CanFold = SrcVector == V1 &&
4688       cast<ConstantSDNode>(Current.getOperand(1))->getZExtValue() == i;
4689   }
4690
4691   if (!CanFold)
4692     return SDValue();
4693
4694   assert(V1.getNode() && "Expected at least two non-zero elements!");
4695   if (V1.getSimpleValueType() != MVT::v4f32)
4696     V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), MVT::v4f32, V1);
4697   if (V2.getSimpleValueType() != MVT::v4f32)
4698     V2 = DAG.getNode(ISD::BITCAST, SDLoc(V2), MVT::v4f32, V2);
4699
4700   // Ok, we can emit an INSERTPS instruction.
4701   unsigned ZMask = Zeroable.to_ulong();
4702
4703   unsigned InsertPSMask = EltMaskIdx << 6 | EltIdx << 4 | ZMask;
4704   assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
4705   SDLoc DL(Op);
4706   SDValue Result = DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
4707                                DAG.getIntPtrConstant(InsertPSMask, DL));
4708   return DAG.getNode(ISD::BITCAST, DL, VT, Result);
4709 }
4710
4711 /// Return a vector logical shift node.
4712 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4713                          unsigned NumBits, SelectionDAG &DAG,
4714                          const TargetLowering &TLI, SDLoc dl) {
4715   assert(VT.is128BitVector() && "Unknown type for VShift");
4716   MVT ShVT = MVT::v2i64;
4717   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
4718   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4719   MVT ScalarShiftTy = TLI.getScalarShiftAmountTy(SrcOp.getValueType());
4720   assert(NumBits % 8 == 0 && "Only support byte sized shifts");
4721   SDValue ShiftVal = DAG.getConstant(NumBits/8, dl, ScalarShiftTy);
4722   return DAG.getNode(ISD::BITCAST, dl, VT,
4723                      DAG.getNode(Opc, dl, ShVT, SrcOp, ShiftVal));
4724 }
4725
4726 static SDValue
4727 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
4728
4729   // Check if the scalar load can be widened into a vector load. And if
4730   // the address is "base + cst" see if the cst can be "absorbed" into
4731   // the shuffle mask.
4732   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4733     SDValue Ptr = LD->getBasePtr();
4734     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4735       return SDValue();
4736     EVT PVT = LD->getValueType(0);
4737     if (PVT != MVT::i32 && PVT != MVT::f32)
4738       return SDValue();
4739
4740     int FI = -1;
4741     int64_t Offset = 0;
4742     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4743       FI = FINode->getIndex();
4744       Offset = 0;
4745     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4746                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4747       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4748       Offset = Ptr.getConstantOperandVal(1);
4749       Ptr = Ptr.getOperand(0);
4750     } else {
4751       return SDValue();
4752     }
4753
4754     // FIXME: 256-bit vector instructions don't require a strict alignment,
4755     // improve this code to support it better.
4756     unsigned RequiredAlign = VT.getSizeInBits()/8;
4757     SDValue Chain = LD->getChain();
4758     // Make sure the stack object alignment is at least 16 or 32.
4759     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4760     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
4761       if (MFI->isFixedObjectIndex(FI)) {
4762         // Can't change the alignment. FIXME: It's possible to compute
4763         // the exact stack offset and reference FI + adjust offset instead.
4764         // If someone *really* cares about this. That's the way to implement it.
4765         return SDValue();
4766       } else {
4767         MFI->setObjectAlignment(FI, RequiredAlign);
4768       }
4769     }
4770
4771     // (Offset % 16 or 32) must be multiple of 4. Then address is then
4772     // Ptr + (Offset & ~15).
4773     if (Offset < 0)
4774       return SDValue();
4775     if ((Offset % RequiredAlign) & 3)
4776       return SDValue();
4777     int64_t StartOffset = Offset & ~(RequiredAlign-1);
4778     if (StartOffset) {
4779       SDLoc DL(Ptr);
4780       Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
4781                         DAG.getConstant(StartOffset, DL, Ptr.getValueType()));
4782     }
4783
4784     int EltNo = (Offset - StartOffset) >> 2;
4785     unsigned NumElems = VT.getVectorNumElements();
4786
4787     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
4788     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
4789                              LD->getPointerInfo().getWithOffset(StartOffset),
4790                              false, false, false, 0);
4791
4792     SmallVector<int, 8> Mask(NumElems, EltNo);
4793
4794     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
4795   }
4796
4797   return SDValue();
4798 }
4799
4800 /// Given the initializing elements 'Elts' of a vector of type 'VT', see if the
4801 /// elements can be replaced by a single large load which has the same value as
4802 /// a build_vector or insert_subvector whose loaded operands are 'Elts'.
4803 ///
4804 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4805 ///
4806 /// FIXME: we'd also like to handle the case where the last elements are zero
4807 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4808 /// There's even a handy isZeroNode for that purpose.
4809 static SDValue EltsFromConsecutiveLoads(EVT VT, ArrayRef<SDValue> Elts,
4810                                         SDLoc &DL, SelectionDAG &DAG,
4811                                         bool isAfterLegalize) {
4812   unsigned NumElems = Elts.size();
4813
4814   LoadSDNode *LDBase = nullptr;
4815   unsigned LastLoadedElt = -1U;
4816
4817   // For each element in the initializer, see if we've found a load or an undef.
4818   // If we don't find an initial load element, or later load elements are
4819   // non-consecutive, bail out.
4820   for (unsigned i = 0; i < NumElems; ++i) {
4821     SDValue Elt = Elts[i];
4822     // Look through a bitcast.
4823     if (Elt.getNode() && Elt.getOpcode() == ISD::BITCAST)
4824       Elt = Elt.getOperand(0);
4825     if (!Elt.getNode() ||
4826         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
4827       return SDValue();
4828     if (!LDBase) {
4829       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
4830         return SDValue();
4831       LDBase = cast<LoadSDNode>(Elt.getNode());
4832       LastLoadedElt = i;
4833       continue;
4834     }
4835     if (Elt.getOpcode() == ISD::UNDEF)
4836       continue;
4837
4838     LoadSDNode *LD = cast<LoadSDNode>(Elt);
4839     EVT LdVT = Elt.getValueType();
4840     // Each loaded element must be the correct fractional portion of the
4841     // requested vector load.
4842     if (LdVT.getSizeInBits() != VT.getSizeInBits() / NumElems)
4843       return SDValue();
4844     if (!DAG.isConsecutiveLoad(LD, LDBase, LdVT.getSizeInBits() / 8, i))
4845       return SDValue();
4846     LastLoadedElt = i;
4847   }
4848
4849   // If we have found an entire vector of loads and undefs, then return a large
4850   // load of the entire vector width starting at the base pointer.  If we found
4851   // consecutive loads for the low half, generate a vzext_load node.
4852   if (LastLoadedElt == NumElems - 1) {
4853     assert(LDBase && "Did not find base load for merging consecutive loads");
4854     EVT EltVT = LDBase->getValueType(0);
4855     // Ensure that the input vector size for the merged loads matches the
4856     // cumulative size of the input elements.
4857     if (VT.getSizeInBits() != EltVT.getSizeInBits() * NumElems)
4858       return SDValue();
4859
4860     if (isAfterLegalize &&
4861         !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
4862       return SDValue();
4863
4864     SDValue NewLd = SDValue();
4865
4866     NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4867                         LDBase->getPointerInfo(), LDBase->isVolatile(),
4868                         LDBase->isNonTemporal(), LDBase->isInvariant(),
4869                         LDBase->getAlignment());
4870
4871     if (LDBase->hasAnyUseOfValue(1)) {
4872       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
4873                                      SDValue(LDBase, 1),
4874                                      SDValue(NewLd.getNode(), 1));
4875       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
4876       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
4877                              SDValue(NewLd.getNode(), 1));
4878     }
4879
4880     return NewLd;
4881   }
4882
4883   //TODO: The code below fires only for for loading the low v2i32 / v2f32
4884   //of a v4i32 / v4f32. It's probably worth generalizing.
4885   EVT EltVT = VT.getVectorElementType();
4886   if (NumElems == 4 && LastLoadedElt == 1 && (EltVT.getSizeInBits() == 32) &&
4887       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
4888     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
4889     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
4890     SDValue ResNode =
4891         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
4892                                 LDBase->getPointerInfo(),
4893                                 LDBase->getAlignment(),
4894                                 false/*isVolatile*/, true/*ReadMem*/,
4895                                 false/*WriteMem*/);
4896
4897     // Make sure the newly-created LOAD is in the same position as LDBase in
4898     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
4899     // update uses of LDBase's output chain to use the TokenFactor.
4900     if (LDBase->hasAnyUseOfValue(1)) {
4901       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
4902                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
4903       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
4904       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
4905                              SDValue(ResNode.getNode(), 1));
4906     }
4907
4908     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
4909   }
4910   return SDValue();
4911 }
4912
4913 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
4914 /// to generate a splat value for the following cases:
4915 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
4916 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
4917 /// a scalar load, or a constant.
4918 /// The VBROADCAST node is returned when a pattern is found,
4919 /// or SDValue() otherwise.
4920 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
4921                                     SelectionDAG &DAG) {
4922   // VBROADCAST requires AVX.
4923   // TODO: Splats could be generated for non-AVX CPUs using SSE
4924   // instructions, but there's less potential gain for only 128-bit vectors.
4925   if (!Subtarget->hasAVX())
4926     return SDValue();
4927
4928   MVT VT = Op.getSimpleValueType();
4929   SDLoc dl(Op);
4930
4931   assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
4932          "Unsupported vector type for broadcast.");
4933
4934   SDValue Ld;
4935   bool ConstSplatVal;
4936
4937   switch (Op.getOpcode()) {
4938     default:
4939       // Unknown pattern found.
4940       return SDValue();
4941
4942     case ISD::BUILD_VECTOR: {
4943       auto *BVOp = cast<BuildVectorSDNode>(Op.getNode());
4944       BitVector UndefElements;
4945       SDValue Splat = BVOp->getSplatValue(&UndefElements);
4946
4947       // We need a splat of a single value to use broadcast, and it doesn't
4948       // make any sense if the value is only in one element of the vector.
4949       if (!Splat || (VT.getVectorNumElements() - UndefElements.count()) <= 1)
4950         return SDValue();
4951
4952       Ld = Splat;
4953       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
4954                        Ld.getOpcode() == ISD::ConstantFP);
4955
4956       // Make sure that all of the users of a non-constant load are from the
4957       // BUILD_VECTOR node.
4958       if (!ConstSplatVal && !BVOp->isOnlyUserOf(Ld.getNode()))
4959         return SDValue();
4960       break;
4961     }
4962
4963     case ISD::VECTOR_SHUFFLE: {
4964       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
4965
4966       // Shuffles must have a splat mask where the first element is
4967       // broadcasted.
4968       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
4969         return SDValue();
4970
4971       SDValue Sc = Op.getOperand(0);
4972       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
4973           Sc.getOpcode() != ISD::BUILD_VECTOR) {
4974
4975         if (!Subtarget->hasInt256())
4976           return SDValue();
4977
4978         // Use the register form of the broadcast instruction available on AVX2.
4979         if (VT.getSizeInBits() >= 256)
4980           Sc = Extract128BitVector(Sc, 0, DAG, dl);
4981         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
4982       }
4983
4984       Ld = Sc.getOperand(0);
4985       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
4986                        Ld.getOpcode() == ISD::ConstantFP);
4987
4988       // The scalar_to_vector node and the suspected
4989       // load node must have exactly one user.
4990       // Constants may have multiple users.
4991
4992       // AVX-512 has register version of the broadcast
4993       bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
4994         Ld.getValueType().getSizeInBits() >= 32;
4995       if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
4996           !hasRegVer))
4997         return SDValue();
4998       break;
4999     }
5000   }
5001
5002   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5003   bool IsGE256 = (VT.getSizeInBits() >= 256);
5004
5005   // When optimizing for size, generate up to 5 extra bytes for a broadcast
5006   // instruction to save 8 or more bytes of constant pool data.
5007   // TODO: If multiple splats are generated to load the same constant,
5008   // it may be detrimental to overall size. There needs to be a way to detect
5009   // that condition to know if this is truly a size win.
5010   const Function *F = DAG.getMachineFunction().getFunction();
5011   bool OptForSize = F->hasFnAttribute(Attribute::OptimizeForSize);
5012
5013   // Handle broadcasting a single constant scalar from the constant pool
5014   // into a vector.
5015   // On Sandybridge (no AVX2), it is still better to load a constant vector
5016   // from the constant pool and not to broadcast it from a scalar.
5017   // But override that restriction when optimizing for size.
5018   // TODO: Check if splatting is recommended for other AVX-capable CPUs.
5019   if (ConstSplatVal && (Subtarget->hasAVX2() || OptForSize)) {
5020     EVT CVT = Ld.getValueType();
5021     assert(!CVT.isVector() && "Must not broadcast a vector type");
5022
5023     // Splat f32, i32, v4f64, v4i64 in all cases with AVX2.
5024     // For size optimization, also splat v2f64 and v2i64, and for size opt
5025     // with AVX2, also splat i8 and i16.
5026     // With pattern matching, the VBROADCAST node may become a VMOVDDUP.
5027     if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5028         (OptForSize && (ScalarSize == 64 || Subtarget->hasAVX2()))) {
5029       const Constant *C = nullptr;
5030       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5031         C = CI->getConstantIntValue();
5032       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5033         C = CF->getConstantFPValue();
5034
5035       assert(C && "Invalid constant type");
5036
5037       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5038       SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
5039       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5040       Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5041                        MachinePointerInfo::getConstantPool(),
5042                        false, false, false, Alignment);
5043
5044       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5045     }
5046   }
5047
5048   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5049
5050   // Handle AVX2 in-register broadcasts.
5051   if (!IsLoad && Subtarget->hasInt256() &&
5052       (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5053     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5054
5055   // The scalar source must be a normal load.
5056   if (!IsLoad)
5057     return SDValue();
5058
5059   if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5060       (Subtarget->hasVLX() && ScalarSize == 64))
5061     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5062
5063   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5064   // double since there is no vbroadcastsd xmm
5065   if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5066     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5067       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5068   }
5069
5070   // Unsupported broadcast.
5071   return SDValue();
5072 }
5073
5074 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
5075 /// underlying vector and index.
5076 ///
5077 /// Modifies \p ExtractedFromVec to the real vector and returns the real
5078 /// index.
5079 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
5080                                          SDValue ExtIdx) {
5081   int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5082   if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
5083     return Idx;
5084
5085   // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
5086   // lowered this:
5087   //   (extract_vector_elt (v8f32 %vreg1), Constant<6>)
5088   // to:
5089   //   (extract_vector_elt (vector_shuffle<2,u,u,u>
5090   //                           (extract_subvector (v8f32 %vreg0), Constant<4>),
5091   //                           undef)
5092   //                       Constant<0>)
5093   // In this case the vector is the extract_subvector expression and the index
5094   // is 2, as specified by the shuffle.
5095   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
5096   SDValue ShuffleVec = SVOp->getOperand(0);
5097   MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
5098   assert(ShuffleVecVT.getVectorElementType() ==
5099          ExtractedFromVec.getSimpleValueType().getVectorElementType());
5100
5101   int ShuffleIdx = SVOp->getMaskElt(Idx);
5102   if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
5103     ExtractedFromVec = ShuffleVec;
5104     return ShuffleIdx;
5105   }
5106   return Idx;
5107 }
5108
5109 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5110   MVT VT = Op.getSimpleValueType();
5111
5112   // Skip if insert_vec_elt is not supported.
5113   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5114   if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5115     return SDValue();
5116
5117   SDLoc DL(Op);
5118   unsigned NumElems = Op.getNumOperands();
5119
5120   SDValue VecIn1;
5121   SDValue VecIn2;
5122   SmallVector<unsigned, 4> InsertIndices;
5123   SmallVector<int, 8> Mask(NumElems, -1);
5124
5125   for (unsigned i = 0; i != NumElems; ++i) {
5126     unsigned Opc = Op.getOperand(i).getOpcode();
5127
5128     if (Opc == ISD::UNDEF)
5129       continue;
5130
5131     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5132       // Quit if more than 1 elements need inserting.
5133       if (InsertIndices.size() > 1)
5134         return SDValue();
5135
5136       InsertIndices.push_back(i);
5137       continue;
5138     }
5139
5140     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5141     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5142     // Quit if non-constant index.
5143     if (!isa<ConstantSDNode>(ExtIdx))
5144       return SDValue();
5145     int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5146
5147     // Quit if extracted from vector of different type.
5148     if (ExtractedFromVec.getValueType() != VT)
5149       return SDValue();
5150
5151     if (!VecIn1.getNode())
5152       VecIn1 = ExtractedFromVec;
5153     else if (VecIn1 != ExtractedFromVec) {
5154       if (!VecIn2.getNode())
5155         VecIn2 = ExtractedFromVec;
5156       else if (VecIn2 != ExtractedFromVec)
5157         // Quit if more than 2 vectors to shuffle
5158         return SDValue();
5159     }
5160
5161     if (ExtractedFromVec == VecIn1)
5162       Mask[i] = Idx;
5163     else if (ExtractedFromVec == VecIn2)
5164       Mask[i] = Idx + NumElems;
5165   }
5166
5167   if (!VecIn1.getNode())
5168     return SDValue();
5169
5170   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5171   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5172   for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5173     unsigned Idx = InsertIndices[i];
5174     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5175                      DAG.getIntPtrConstant(Idx, DL));
5176   }
5177
5178   return NV;
5179 }
5180
5181 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5182 SDValue
5183 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5184
5185   MVT VT = Op.getSimpleValueType();
5186   assert((VT.getVectorElementType() == MVT::i1) && (VT.getSizeInBits() <= 16) &&
5187          "Unexpected type in LowerBUILD_VECTORvXi1!");
5188
5189   SDLoc dl(Op);
5190   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5191     SDValue Cst = DAG.getTargetConstant(0, dl, MVT::i1);
5192     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5193     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5194   }
5195
5196   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5197     SDValue Cst = DAG.getTargetConstant(1, dl, MVT::i1);
5198     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5199     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5200   }
5201
5202   bool AllContants = true;
5203   uint64_t Immediate = 0;
5204   int NonConstIdx = -1;
5205   bool IsSplat = true;
5206   unsigned NumNonConsts = 0;
5207   unsigned NumConsts = 0;
5208   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5209     SDValue In = Op.getOperand(idx);
5210     if (In.getOpcode() == ISD::UNDEF)
5211       continue;
5212     if (!isa<ConstantSDNode>(In)) {
5213       AllContants = false;
5214       NonConstIdx = idx;
5215       NumNonConsts++;
5216     } else {
5217       NumConsts++;
5218       if (cast<ConstantSDNode>(In)->getZExtValue())
5219       Immediate |= (1ULL << idx);
5220     }
5221     if (In != Op.getOperand(0))
5222       IsSplat = false;
5223   }
5224
5225   if (AllContants) {
5226     SDValue FullMask = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1,
5227       DAG.getConstant(Immediate, dl, MVT::i16));
5228     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, FullMask,
5229                        DAG.getIntPtrConstant(0, dl));
5230   }
5231
5232   if (NumNonConsts == 1 && NonConstIdx != 0) {
5233     SDValue DstVec;
5234     if (NumConsts) {
5235       SDValue VecAsImm = DAG.getConstant(Immediate, dl,
5236                                          MVT::getIntegerVT(VT.getSizeInBits()));
5237       DstVec = DAG.getNode(ISD::BITCAST, dl, VT, VecAsImm);
5238     }
5239     else
5240       DstVec = DAG.getUNDEF(VT);
5241     return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5242                        Op.getOperand(NonConstIdx),
5243                        DAG.getIntPtrConstant(NonConstIdx, dl));
5244   }
5245   if (!IsSplat && (NonConstIdx != 0))
5246     llvm_unreachable("Unsupported BUILD_VECTOR operation");
5247   MVT SelectVT = (VT == MVT::v16i1)? MVT::i16 : MVT::i8;
5248   SDValue Select;
5249   if (IsSplat)
5250     Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
5251                           DAG.getConstant(-1, dl, SelectVT),
5252                           DAG.getConstant(0, dl, SelectVT));
5253   else
5254     Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
5255                          DAG.getConstant((Immediate | 1), dl, SelectVT),
5256                          DAG.getConstant(Immediate, dl, SelectVT));
5257   return DAG.getNode(ISD::BITCAST, dl, VT, Select);
5258 }
5259
5260 /// \brief Return true if \p N implements a horizontal binop and return the
5261 /// operands for the horizontal binop into V0 and V1.
5262 ///
5263 /// This is a helper function of LowerToHorizontalOp().
5264 /// This function checks that the build_vector \p N in input implements a
5265 /// horizontal operation. Parameter \p Opcode defines the kind of horizontal
5266 /// operation to match.
5267 /// For example, if \p Opcode is equal to ISD::ADD, then this function
5268 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
5269 /// is equal to ISD::SUB, then this function checks if this is a horizontal
5270 /// arithmetic sub.
5271 ///
5272 /// This function only analyzes elements of \p N whose indices are
5273 /// in range [BaseIdx, LastIdx).
5274 static bool isHorizontalBinOp(const BuildVectorSDNode *N, unsigned Opcode,
5275                               SelectionDAG &DAG,
5276                               unsigned BaseIdx, unsigned LastIdx,
5277                               SDValue &V0, SDValue &V1) {
5278   EVT VT = N->getValueType(0);
5279
5280   assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
5281   assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
5282          "Invalid Vector in input!");
5283
5284   bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
5285   bool CanFold = true;
5286   unsigned ExpectedVExtractIdx = BaseIdx;
5287   unsigned NumElts = LastIdx - BaseIdx;
5288   V0 = DAG.getUNDEF(VT);
5289   V1 = DAG.getUNDEF(VT);
5290
5291   // Check if N implements a horizontal binop.
5292   for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
5293     SDValue Op = N->getOperand(i + BaseIdx);
5294
5295     // Skip UNDEFs.
5296     if (Op->getOpcode() == ISD::UNDEF) {
5297       // Update the expected vector extract index.
5298       if (i * 2 == NumElts)
5299         ExpectedVExtractIdx = BaseIdx;
5300       ExpectedVExtractIdx += 2;
5301       continue;
5302     }
5303
5304     CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
5305
5306     if (!CanFold)
5307       break;
5308
5309     SDValue Op0 = Op.getOperand(0);
5310     SDValue Op1 = Op.getOperand(1);
5311
5312     // Try to match the following pattern:
5313     // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
5314     CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5315         Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5316         Op0.getOperand(0) == Op1.getOperand(0) &&
5317         isa<ConstantSDNode>(Op0.getOperand(1)) &&
5318         isa<ConstantSDNode>(Op1.getOperand(1)));
5319     if (!CanFold)
5320       break;
5321
5322     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5323     unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
5324
5325     if (i * 2 < NumElts) {
5326       if (V0.getOpcode() == ISD::UNDEF) {
5327         V0 = Op0.getOperand(0);
5328         if (V0.getValueType() != VT)
5329           return false;
5330       }
5331     } else {
5332       if (V1.getOpcode() == ISD::UNDEF) {
5333         V1 = Op0.getOperand(0);
5334         if (V1.getValueType() != VT)
5335           return false;
5336       }
5337       if (i * 2 == NumElts)
5338         ExpectedVExtractIdx = BaseIdx;
5339     }
5340
5341     SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
5342     if (I0 == ExpectedVExtractIdx)
5343       CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
5344     else if (IsCommutable && I1 == ExpectedVExtractIdx) {
5345       // Try to match the following dag sequence:
5346       // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
5347       CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
5348     } else
5349       CanFold = false;
5350
5351     ExpectedVExtractIdx += 2;
5352   }
5353
5354   return CanFold;
5355 }
5356
5357 /// \brief Emit a sequence of two 128-bit horizontal add/sub followed by
5358 /// a concat_vector.
5359 ///
5360 /// This is a helper function of LowerToHorizontalOp().
5361 /// This function expects two 256-bit vectors called V0 and V1.
5362 /// At first, each vector is split into two separate 128-bit vectors.
5363 /// Then, the resulting 128-bit vectors are used to implement two
5364 /// horizontal binary operations.
5365 ///
5366 /// The kind of horizontal binary operation is defined by \p X86Opcode.
5367 ///
5368 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
5369 /// the two new horizontal binop.
5370 /// When Mode is set, the first horizontal binop dag node would take as input
5371 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
5372 /// horizontal binop dag node would take as input the lower 128-bit of V1
5373 /// and the upper 128-bit of V1.
5374 ///   Example:
5375 ///     HADD V0_LO, V0_HI
5376 ///     HADD V1_LO, V1_HI
5377 ///
5378 /// Otherwise, the first horizontal binop dag node takes as input the lower
5379 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
5380 /// dag node takes the the upper 128-bit of V0 and the upper 128-bit of V1.
5381 ///   Example:
5382 ///     HADD V0_LO, V1_LO
5383 ///     HADD V0_HI, V1_HI
5384 ///
5385 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
5386 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
5387 /// the upper 128-bits of the result.
5388 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
5389                                      SDLoc DL, SelectionDAG &DAG,
5390                                      unsigned X86Opcode, bool Mode,
5391                                      bool isUndefLO, bool isUndefHI) {
5392   EVT VT = V0.getValueType();
5393   assert(VT.is256BitVector() && VT == V1.getValueType() &&
5394          "Invalid nodes in input!");
5395
5396   unsigned NumElts = VT.getVectorNumElements();
5397   SDValue V0_LO = Extract128BitVector(V0, 0, DAG, DL);
5398   SDValue V0_HI = Extract128BitVector(V0, NumElts/2, DAG, DL);
5399   SDValue V1_LO = Extract128BitVector(V1, 0, DAG, DL);
5400   SDValue V1_HI = Extract128BitVector(V1, NumElts/2, DAG, DL);
5401   EVT NewVT = V0_LO.getValueType();
5402
5403   SDValue LO = DAG.getUNDEF(NewVT);
5404   SDValue HI = DAG.getUNDEF(NewVT);
5405
5406   if (Mode) {
5407     // Don't emit a horizontal binop if the result is expected to be UNDEF.
5408     if (!isUndefLO && V0->getOpcode() != ISD::UNDEF)
5409       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
5410     if (!isUndefHI && V1->getOpcode() != ISD::UNDEF)
5411       HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
5412   } else {
5413     // Don't emit a horizontal binop if the result is expected to be UNDEF.
5414     if (!isUndefLO && (V0_LO->getOpcode() != ISD::UNDEF ||
5415                        V1_LO->getOpcode() != ISD::UNDEF))
5416       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
5417
5418     if (!isUndefHI && (V0_HI->getOpcode() != ISD::UNDEF ||
5419                        V1_HI->getOpcode() != ISD::UNDEF))
5420       HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
5421   }
5422
5423   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
5424 }
5425
5426 /// Try to fold a build_vector that performs an 'addsub' to an X86ISD::ADDSUB
5427 /// node.
5428 static SDValue LowerToAddSub(const BuildVectorSDNode *BV,
5429                              const X86Subtarget *Subtarget, SelectionDAG &DAG) {
5430   EVT VT = BV->getValueType(0);
5431   if ((!Subtarget->hasSSE3() || (VT != MVT::v4f32 && VT != MVT::v2f64)) &&
5432       (!Subtarget->hasAVX() || (VT != MVT::v8f32 && VT != MVT::v4f64)))
5433     return SDValue();
5434
5435   SDLoc DL(BV);
5436   unsigned NumElts = VT.getVectorNumElements();
5437   SDValue InVec0 = DAG.getUNDEF(VT);
5438   SDValue InVec1 = DAG.getUNDEF(VT);
5439
5440   assert((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v4f32 ||
5441           VT == MVT::v2f64) && "build_vector with an invalid type found!");
5442
5443   // Odd-numbered elements in the input build vector are obtained from
5444   // adding two integer/float elements.
5445   // Even-numbered elements in the input build vector are obtained from
5446   // subtracting two integer/float elements.
5447   unsigned ExpectedOpcode = ISD::FSUB;
5448   unsigned NextExpectedOpcode = ISD::FADD;
5449   bool AddFound = false;
5450   bool SubFound = false;
5451
5452   for (unsigned i = 0, e = NumElts; i != e; ++i) {
5453     SDValue Op = BV->getOperand(i);
5454
5455     // Skip 'undef' values.
5456     unsigned Opcode = Op.getOpcode();
5457     if (Opcode == ISD::UNDEF) {
5458       std::swap(ExpectedOpcode, NextExpectedOpcode);
5459       continue;
5460     }
5461
5462     // Early exit if we found an unexpected opcode.
5463     if (Opcode != ExpectedOpcode)
5464       return SDValue();
5465
5466     SDValue Op0 = Op.getOperand(0);
5467     SDValue Op1 = Op.getOperand(1);
5468
5469     // Try to match the following pattern:
5470     // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
5471     // Early exit if we cannot match that sequence.
5472     if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5473         Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5474         !isa<ConstantSDNode>(Op0.getOperand(1)) ||
5475         !isa<ConstantSDNode>(Op1.getOperand(1)) ||
5476         Op0.getOperand(1) != Op1.getOperand(1))
5477       return SDValue();
5478
5479     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5480     if (I0 != i)
5481       return SDValue();
5482
5483     // We found a valid add/sub node. Update the information accordingly.
5484     if (i & 1)
5485       AddFound = true;
5486     else
5487       SubFound = true;
5488
5489     // Update InVec0 and InVec1.
5490     if (InVec0.getOpcode() == ISD::UNDEF) {
5491       InVec0 = Op0.getOperand(0);
5492       if (InVec0.getValueType() != VT)
5493         return SDValue();
5494     }
5495     if (InVec1.getOpcode() == ISD::UNDEF) {
5496       InVec1 = Op1.getOperand(0);
5497       if (InVec1.getValueType() != VT)
5498         return SDValue();
5499     }
5500
5501     // Make sure that operands in input to each add/sub node always
5502     // come from a same pair of vectors.
5503     if (InVec0 != Op0.getOperand(0)) {
5504       if (ExpectedOpcode == ISD::FSUB)
5505         return SDValue();
5506
5507       // FADD is commutable. Try to commute the operands
5508       // and then test again.
5509       std::swap(Op0, Op1);
5510       if (InVec0 != Op0.getOperand(0))
5511         return SDValue();
5512     }
5513
5514     if (InVec1 != Op1.getOperand(0))
5515       return SDValue();
5516
5517     // Update the pair of expected opcodes.
5518     std::swap(ExpectedOpcode, NextExpectedOpcode);
5519   }
5520
5521   // Don't try to fold this build_vector into an ADDSUB if the inputs are undef.
5522   if (AddFound && SubFound && InVec0.getOpcode() != ISD::UNDEF &&
5523       InVec1.getOpcode() != ISD::UNDEF)
5524     return DAG.getNode(X86ISD::ADDSUB, DL, VT, InVec0, InVec1);
5525
5526   return SDValue();
5527 }
5528
5529 /// Lower BUILD_VECTOR to a horizontal add/sub operation if possible.
5530 static SDValue LowerToHorizontalOp(const BuildVectorSDNode *BV,
5531                                    const X86Subtarget *Subtarget,
5532                                    SelectionDAG &DAG) {
5533   EVT VT = BV->getValueType(0);
5534   unsigned NumElts = VT.getVectorNumElements();
5535   unsigned NumUndefsLO = 0;
5536   unsigned NumUndefsHI = 0;
5537   unsigned Half = NumElts/2;
5538
5539   // Count the number of UNDEF operands in the build_vector in input.
5540   for (unsigned i = 0, e = Half; i != e; ++i)
5541     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
5542       NumUndefsLO++;
5543
5544   for (unsigned i = Half, e = NumElts; i != e; ++i)
5545     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
5546       NumUndefsHI++;
5547
5548   // Early exit if this is either a build_vector of all UNDEFs or all the
5549   // operands but one are UNDEF.
5550   if (NumUndefsLO + NumUndefsHI + 1 >= NumElts)
5551     return SDValue();
5552
5553   SDLoc DL(BV);
5554   SDValue InVec0, InVec1;
5555   if ((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) {
5556     // Try to match an SSE3 float HADD/HSUB.
5557     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
5558       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
5559
5560     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
5561       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
5562   } else if ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) {
5563     // Try to match an SSSE3 integer HADD/HSUB.
5564     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
5565       return DAG.getNode(X86ISD::HADD, DL, VT, InVec0, InVec1);
5566
5567     if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
5568       return DAG.getNode(X86ISD::HSUB, DL, VT, InVec0, InVec1);
5569   }
5570
5571   if (!Subtarget->hasAVX())
5572     return SDValue();
5573
5574   if ((VT == MVT::v8f32 || VT == MVT::v4f64)) {
5575     // Try to match an AVX horizontal add/sub of packed single/double
5576     // precision floating point values from 256-bit vectors.
5577     SDValue InVec2, InVec3;
5578     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, Half, InVec0, InVec1) &&
5579         isHorizontalBinOp(BV, ISD::FADD, DAG, Half, NumElts, InVec2, InVec3) &&
5580         ((InVec0.getOpcode() == ISD::UNDEF ||
5581           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5582         ((InVec1.getOpcode() == ISD::UNDEF ||
5583           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5584       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
5585
5586     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, Half, InVec0, InVec1) &&
5587         isHorizontalBinOp(BV, ISD::FSUB, DAG, Half, NumElts, InVec2, InVec3) &&
5588         ((InVec0.getOpcode() == ISD::UNDEF ||
5589           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5590         ((InVec1.getOpcode() == ISD::UNDEF ||
5591           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5592       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
5593   } else if (VT == MVT::v8i32 || VT == MVT::v16i16) {
5594     // Try to match an AVX2 horizontal add/sub of signed integers.
5595     SDValue InVec2, InVec3;
5596     unsigned X86Opcode;
5597     bool CanFold = true;
5598
5599     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
5600         isHorizontalBinOp(BV, ISD::ADD, DAG, Half, NumElts, InVec2, InVec3) &&
5601         ((InVec0.getOpcode() == ISD::UNDEF ||
5602           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5603         ((InVec1.getOpcode() == ISD::UNDEF ||
5604           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5605       X86Opcode = X86ISD::HADD;
5606     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, Half, InVec0, InVec1) &&
5607         isHorizontalBinOp(BV, ISD::SUB, DAG, Half, NumElts, InVec2, InVec3) &&
5608         ((InVec0.getOpcode() == ISD::UNDEF ||
5609           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5610         ((InVec1.getOpcode() == ISD::UNDEF ||
5611           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5612       X86Opcode = X86ISD::HSUB;
5613     else
5614       CanFold = false;
5615
5616     if (CanFold) {
5617       // Fold this build_vector into a single horizontal add/sub.
5618       // Do this only if the target has AVX2.
5619       if (Subtarget->hasAVX2())
5620         return DAG.getNode(X86Opcode, DL, VT, InVec0, InVec1);
5621
5622       // Do not try to expand this build_vector into a pair of horizontal
5623       // add/sub if we can emit a pair of scalar add/sub.
5624       if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
5625         return SDValue();
5626
5627       // Convert this build_vector into a pair of horizontal binop followed by
5628       // a concat vector.
5629       bool isUndefLO = NumUndefsLO == Half;
5630       bool isUndefHI = NumUndefsHI == Half;
5631       return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, false,
5632                                    isUndefLO, isUndefHI);
5633     }
5634   }
5635
5636   if ((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
5637        VT == MVT::v16i16) && Subtarget->hasAVX()) {
5638     unsigned X86Opcode;
5639     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
5640       X86Opcode = X86ISD::HADD;
5641     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
5642       X86Opcode = X86ISD::HSUB;
5643     else if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
5644       X86Opcode = X86ISD::FHADD;
5645     else if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
5646       X86Opcode = X86ISD::FHSUB;
5647     else
5648       return SDValue();
5649
5650     // Don't try to expand this build_vector into a pair of horizontal add/sub
5651     // if we can simply emit a pair of scalar add/sub.
5652     if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
5653       return SDValue();
5654
5655     // Convert this build_vector into two horizontal add/sub followed by
5656     // a concat vector.
5657     bool isUndefLO = NumUndefsLO == Half;
5658     bool isUndefHI = NumUndefsHI == Half;
5659     return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
5660                                  isUndefLO, isUndefHI);
5661   }
5662
5663   return SDValue();
5664 }
5665
5666 SDValue
5667 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5668   SDLoc dl(Op);
5669
5670   MVT VT = Op.getSimpleValueType();
5671   MVT ExtVT = VT.getVectorElementType();
5672   unsigned NumElems = Op.getNumOperands();
5673
5674   // Generate vectors for predicate vectors.
5675   if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
5676     return LowerBUILD_VECTORvXi1(Op, DAG);
5677
5678   // Vectors containing all zeros can be matched by pxor and xorps later
5679   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5680     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5681     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5682     if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
5683       return Op;
5684
5685     return getZeroVector(VT, Subtarget, DAG, dl);
5686   }
5687
5688   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5689   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5690   // vpcmpeqd on 256-bit vectors.
5691   if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
5692     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
5693       return Op;
5694
5695     if (!VT.is512BitVector())
5696       return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
5697   }
5698
5699   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(Op.getNode());
5700   if (SDValue AddSub = LowerToAddSub(BV, Subtarget, DAG))
5701     return AddSub;
5702   if (SDValue HorizontalOp = LowerToHorizontalOp(BV, Subtarget, DAG))
5703     return HorizontalOp;
5704   if (SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG))
5705     return Broadcast;
5706
5707   unsigned EVTBits = ExtVT.getSizeInBits();
5708
5709   unsigned NumZero  = 0;
5710   unsigned NumNonZero = 0;
5711   unsigned NonZeros = 0;
5712   bool IsAllConstants = true;
5713   SmallSet<SDValue, 8> Values;
5714   for (unsigned i = 0; i < NumElems; ++i) {
5715     SDValue Elt = Op.getOperand(i);
5716     if (Elt.getOpcode() == ISD::UNDEF)
5717       continue;
5718     Values.insert(Elt);
5719     if (Elt.getOpcode() != ISD::Constant &&
5720         Elt.getOpcode() != ISD::ConstantFP)
5721       IsAllConstants = false;
5722     if (X86::isZeroNode(Elt))
5723       NumZero++;
5724     else {
5725       NonZeros |= (1 << i);
5726       NumNonZero++;
5727     }
5728   }
5729
5730   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
5731   if (NumNonZero == 0)
5732     return DAG.getUNDEF(VT);
5733
5734   // Special case for single non-zero, non-undef, element.
5735   if (NumNonZero == 1) {
5736     unsigned Idx = countTrailingZeros(NonZeros);
5737     SDValue Item = Op.getOperand(Idx);
5738
5739     // If this is an insertion of an i64 value on x86-32, and if the top bits of
5740     // the value are obviously zero, truncate the value to i32 and do the
5741     // insertion that way.  Only do this if the value is non-constant or if the
5742     // value is a constant being inserted into element 0.  It is cheaper to do
5743     // a constant pool load than it is to do a movd + shuffle.
5744     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5745         (!IsAllConstants || Idx == 0)) {
5746       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5747         // Handle SSE only.
5748         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5749         EVT VecVT = MVT::v4i32;
5750
5751         // Truncate the value (which may itself be a constant) to i32, and
5752         // convert it to a vector with movd (S2V+shuffle to zero extend).
5753         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5754         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5755         return DAG.getNode(
5756             ISD::BITCAST, dl, VT,
5757             getShuffleVectorZeroOrUndef(Item, Idx * 2, true, Subtarget, DAG));
5758       }
5759     }
5760
5761     // If we have a constant or non-constant insertion into the low element of
5762     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5763     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
5764     // depending on what the source datatype is.
5765     if (Idx == 0) {
5766       if (NumZero == 0)
5767         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5768
5769       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5770           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5771         if (VT.is512BitVector()) {
5772           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
5773           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
5774                              Item, DAG.getIntPtrConstant(0, dl));
5775         }
5776         assert((VT.is128BitVector() || VT.is256BitVector()) &&
5777                "Expected an SSE value type!");
5778         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5779         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5780         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5781       }
5782
5783       // We can't directly insert an i8 or i16 into a vector, so zero extend
5784       // it to i32 first.
5785       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5786         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5787         if (VT.is256BitVector()) {
5788           if (Subtarget->hasAVX()) {
5789             Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v8i32, Item);
5790             Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5791           } else {
5792             // Without AVX, we need to extend to a 128-bit vector and then
5793             // insert into the 256-bit vector.
5794             Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5795             SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
5796             Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
5797           }
5798         } else {
5799           assert(VT.is128BitVector() && "Expected an SSE value type!");
5800           Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5801           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5802         }
5803         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5804       }
5805     }
5806
5807     // Is it a vector logical left shift?
5808     if (NumElems == 2 && Idx == 1 &&
5809         X86::isZeroNode(Op.getOperand(0)) &&
5810         !X86::isZeroNode(Op.getOperand(1))) {
5811       unsigned NumBits = VT.getSizeInBits();
5812       return getVShift(true, VT,
5813                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5814                                    VT, Op.getOperand(1)),
5815                        NumBits/2, DAG, *this, dl);
5816     }
5817
5818     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5819       return SDValue();
5820
5821     // Otherwise, if this is a vector with i32 or f32 elements, and the element
5822     // is a non-constant being inserted into an element other than the low one,
5823     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
5824     // movd/movss) to move this into the low element, then shuffle it into
5825     // place.
5826     if (EVTBits == 32) {
5827       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5828       return getShuffleVectorZeroOrUndef(Item, Idx, NumZero > 0, Subtarget, DAG);
5829     }
5830   }
5831
5832   // Splat is obviously ok. Let legalizer expand it to a shuffle.
5833   if (Values.size() == 1) {
5834     if (EVTBits == 32) {
5835       // Instead of a shuffle like this:
5836       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
5837       // Check if it's possible to issue this instead.
5838       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
5839       unsigned Idx = countTrailingZeros(NonZeros);
5840       SDValue Item = Op.getOperand(Idx);
5841       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
5842         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
5843     }
5844     return SDValue();
5845   }
5846
5847   // A vector full of immediates; various special cases are already
5848   // handled, so this is best done with a single constant-pool load.
5849   if (IsAllConstants)
5850     return SDValue();
5851
5852   // For AVX-length vectors, see if we can use a vector load to get all of the
5853   // elements, otherwise build the individual 128-bit pieces and use
5854   // shuffles to put them in place.
5855   if (VT.is256BitVector() || VT.is512BitVector()) {
5856     SmallVector<SDValue, 64> V(Op->op_begin(), Op->op_begin() + NumElems);
5857
5858     // Check for a build vector of consecutive loads.
5859     if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
5860       return LD;
5861
5862     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
5863
5864     // Build both the lower and upper subvector.
5865     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
5866                                 makeArrayRef(&V[0], NumElems/2));
5867     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
5868                                 makeArrayRef(&V[NumElems / 2], NumElems/2));
5869
5870     // Recreate the wider vector with the lower and upper part.
5871     if (VT.is256BitVector())
5872       return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
5873     return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
5874   }
5875
5876   // Let legalizer expand 2-wide build_vectors.
5877   if (EVTBits == 64) {
5878     if (NumNonZero == 1) {
5879       // One half is zero or undef.
5880       unsigned Idx = countTrailingZeros(NonZeros);
5881       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
5882                                  Op.getOperand(Idx));
5883       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
5884     }
5885     return SDValue();
5886   }
5887
5888   // If element VT is < 32 bits, convert it to inserts into a zero vector.
5889   if (EVTBits == 8 && NumElems == 16)
5890     if (SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
5891                                         Subtarget, *this))
5892       return V;
5893
5894   if (EVTBits == 16 && NumElems == 8)
5895     if (SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
5896                                       Subtarget, *this))
5897       return V;
5898
5899   // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
5900   if (EVTBits == 32 && NumElems == 4)
5901     if (SDValue V = LowerBuildVectorv4x32(Op, DAG, Subtarget, *this))
5902       return V;
5903
5904   // If element VT is == 32 bits, turn it into a number of shuffles.
5905   SmallVector<SDValue, 8> V(NumElems);
5906   if (NumElems == 4 && NumZero > 0) {
5907     for (unsigned i = 0; i < 4; ++i) {
5908       bool isZero = !(NonZeros & (1 << i));
5909       if (isZero)
5910         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
5911       else
5912         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5913     }
5914
5915     for (unsigned i = 0; i < 2; ++i) {
5916       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
5917         default: break;
5918         case 0:
5919           V[i] = V[i*2];  // Must be a zero vector.
5920           break;
5921         case 1:
5922           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
5923           break;
5924         case 2:
5925           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
5926           break;
5927         case 3:
5928           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
5929           break;
5930       }
5931     }
5932
5933     bool Reverse1 = (NonZeros & 0x3) == 2;
5934     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
5935     int MaskVec[] = {
5936       Reverse1 ? 1 : 0,
5937       Reverse1 ? 0 : 1,
5938       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
5939       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
5940     };
5941     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
5942   }
5943
5944   if (Values.size() > 1 && VT.is128BitVector()) {
5945     // Check for a build vector of consecutive loads.
5946     for (unsigned i = 0; i < NumElems; ++i)
5947       V[i] = Op.getOperand(i);
5948
5949     // Check for elements which are consecutive loads.
5950     if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
5951       return LD;
5952
5953     // Check for a build vector from mostly shuffle plus few inserting.
5954     if (SDValue Sh = buildFromShuffleMostly(Op, DAG))
5955       return Sh;
5956
5957     // For SSE 4.1, use insertps to put the high elements into the low element.
5958     if (Subtarget->hasSSE41()) {
5959       SDValue Result;
5960       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
5961         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
5962       else
5963         Result = DAG.getUNDEF(VT);
5964
5965       for (unsigned i = 1; i < NumElems; ++i) {
5966         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
5967         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
5968                              Op.getOperand(i), DAG.getIntPtrConstant(i, dl));
5969       }
5970       return Result;
5971     }
5972
5973     // Otherwise, expand into a number of unpckl*, start by extending each of
5974     // our (non-undef) elements to the full vector width with the element in the
5975     // bottom slot of the vector (which generates no code for SSE).
5976     for (unsigned i = 0; i < NumElems; ++i) {
5977       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
5978         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5979       else
5980         V[i] = DAG.getUNDEF(VT);
5981     }
5982
5983     // Next, we iteratively mix elements, e.g. for v4f32:
5984     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
5985     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
5986     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
5987     unsigned EltStride = NumElems >> 1;
5988     while (EltStride != 0) {
5989       for (unsigned i = 0; i < EltStride; ++i) {
5990         // If V[i+EltStride] is undef and this is the first round of mixing,
5991         // then it is safe to just drop this shuffle: V[i] is already in the
5992         // right place, the one element (since it's the first round) being
5993         // inserted as undef can be dropped.  This isn't safe for successive
5994         // rounds because they will permute elements within both vectors.
5995         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
5996             EltStride == NumElems/2)
5997           continue;
5998
5999         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6000       }
6001       EltStride >>= 1;
6002     }
6003     return V[0];
6004   }
6005   return SDValue();
6006 }
6007
6008 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
6009 // to create 256-bit vectors from two other 128-bit ones.
6010 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6011   SDLoc dl(Op);
6012   MVT ResVT = Op.getSimpleValueType();
6013
6014   assert((ResVT.is256BitVector() ||
6015           ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6016
6017   SDValue V1 = Op.getOperand(0);
6018   SDValue V2 = Op.getOperand(1);
6019   unsigned NumElems = ResVT.getVectorNumElements();
6020   if (ResVT.is256BitVector())
6021     return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6022
6023   if (Op.getNumOperands() == 4) {
6024     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6025                                 ResVT.getVectorNumElements()/2);
6026     SDValue V3 = Op.getOperand(2);
6027     SDValue V4 = Op.getOperand(3);
6028     return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6029       Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6030   }
6031   return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6032 }
6033
6034 static SDValue LowerCONCAT_VECTORSvXi1(SDValue Op,
6035                                        const X86Subtarget *Subtarget,
6036                                        SelectionDAG & DAG) {
6037   SDLoc dl(Op);
6038   MVT ResVT = Op.getSimpleValueType();
6039   unsigned NumOfOperands = Op.getNumOperands();
6040
6041   assert(isPowerOf2_32(NumOfOperands) &&
6042          "Unexpected number of operands in CONCAT_VECTORS");
6043
6044   if (NumOfOperands > 2) {
6045     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6046                                   ResVT.getVectorNumElements()/2);
6047     SmallVector<SDValue, 2> Ops;
6048     for (unsigned i = 0; i < NumOfOperands/2; i++)
6049       Ops.push_back(Op.getOperand(i));
6050     SDValue Lo = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6051     Ops.clear();
6052     for (unsigned i = NumOfOperands/2; i < NumOfOperands; i++)
6053       Ops.push_back(Op.getOperand(i));
6054     SDValue Hi = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6055     return DAG.getNode(ISD::CONCAT_VECTORS, dl, ResVT, Lo, Hi);
6056   }
6057
6058   SDValue V1 = Op.getOperand(0);
6059   SDValue V2 = Op.getOperand(1);
6060   bool IsZeroV1 = ISD::isBuildVectorAllZeros(V1.getNode());
6061   bool IsZeroV2 = ISD::isBuildVectorAllZeros(V2.getNode());
6062
6063   if (IsZeroV1 && IsZeroV2)
6064     return getZeroVector(ResVT, Subtarget, DAG, dl);
6065
6066   SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
6067   SDValue Undef = DAG.getUNDEF(ResVT);
6068   unsigned NumElems = ResVT.getVectorNumElements();
6069   SDValue ShiftBits = DAG.getConstant(NumElems/2, dl, MVT::i8);
6070
6071   V2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V2, ZeroIdx);
6072   V2 = DAG.getNode(X86ISD::VSHLI, dl, ResVT, V2, ShiftBits);
6073   if (IsZeroV1)
6074     return V2;
6075
6076   V1 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V1, ZeroIdx);
6077   // Zero the upper bits of V1
6078   V1 = DAG.getNode(X86ISD::VSHLI, dl, ResVT, V1, ShiftBits);
6079   V1 = DAG.getNode(X86ISD::VSRLI, dl, ResVT, V1, ShiftBits);
6080   if (IsZeroV2)
6081     return V1;
6082   return DAG.getNode(ISD::OR, dl, ResVT, V1, V2);
6083 }
6084
6085 static SDValue LowerCONCAT_VECTORS(SDValue Op,
6086                                    const X86Subtarget *Subtarget,
6087                                    SelectionDAG &DAG) {
6088   MVT VT = Op.getSimpleValueType();
6089   if (VT.getVectorElementType() == MVT::i1)
6090     return LowerCONCAT_VECTORSvXi1(Op, Subtarget, DAG);
6091
6092   assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6093          (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6094           Op.getNumOperands() == 4)));
6095
6096   // AVX can use the vinsertf128 instruction to create 256-bit vectors
6097   // from two other 128-bit ones.
6098
6099   // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6100   return LowerAVXCONCAT_VECTORS(Op, DAG);
6101 }
6102
6103
6104 //===----------------------------------------------------------------------===//
6105 // Vector shuffle lowering
6106 //
6107 // This is an experimental code path for lowering vector shuffles on x86. It is
6108 // designed to handle arbitrary vector shuffles and blends, gracefully
6109 // degrading performance as necessary. It works hard to recognize idiomatic
6110 // shuffles and lower them to optimal instruction patterns without leaving
6111 // a framework that allows reasonably efficient handling of all vector shuffle
6112 // patterns.
6113 //===----------------------------------------------------------------------===//
6114
6115 /// \brief Tiny helper function to identify a no-op mask.
6116 ///
6117 /// This is a somewhat boring predicate function. It checks whether the mask
6118 /// array input, which is assumed to be a single-input shuffle mask of the kind
6119 /// used by the X86 shuffle instructions (not a fully general
6120 /// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
6121 /// in-place shuffle are 'no-op's.
6122 static bool isNoopShuffleMask(ArrayRef<int> Mask) {
6123   for (int i = 0, Size = Mask.size(); i < Size; ++i)
6124     if (Mask[i] != -1 && Mask[i] != i)
6125       return false;
6126   return true;
6127 }
6128
6129 /// \brief Helper function to classify a mask as a single-input mask.
6130 ///
6131 /// This isn't a generic single-input test because in the vector shuffle
6132 /// lowering we canonicalize single inputs to be the first input operand. This
6133 /// means we can more quickly test for a single input by only checking whether
6134 /// an input from the second operand exists. We also assume that the size of
6135 /// mask corresponds to the size of the input vectors which isn't true in the
6136 /// fully general case.
6137 static bool isSingleInputShuffleMask(ArrayRef<int> Mask) {
6138   for (int M : Mask)
6139     if (M >= (int)Mask.size())
6140       return false;
6141   return true;
6142 }
6143
6144 /// \brief Test whether there are elements crossing 128-bit lanes in this
6145 /// shuffle mask.
6146 ///
6147 /// X86 divides up its shuffles into in-lane and cross-lane shuffle operations
6148 /// and we routinely test for these.
6149 static bool is128BitLaneCrossingShuffleMask(MVT VT, ArrayRef<int> Mask) {
6150   int LaneSize = 128 / VT.getScalarSizeInBits();
6151   int Size = Mask.size();
6152   for (int i = 0; i < Size; ++i)
6153     if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
6154       return true;
6155   return false;
6156 }
6157
6158 /// \brief Test whether a shuffle mask is equivalent within each 128-bit lane.
6159 ///
6160 /// This checks a shuffle mask to see if it is performing the same
6161 /// 128-bit lane-relative shuffle in each 128-bit lane. This trivially implies
6162 /// that it is also not lane-crossing. It may however involve a blend from the
6163 /// same lane of a second vector.
6164 ///
6165 /// The specific repeated shuffle mask is populated in \p RepeatedMask, as it is
6166 /// non-trivial to compute in the face of undef lanes. The representation is
6167 /// *not* suitable for use with existing 128-bit shuffles as it will contain
6168 /// entries from both V1 and V2 inputs to the wider mask.
6169 static bool
6170 is128BitLaneRepeatedShuffleMask(MVT VT, ArrayRef<int> Mask,
6171                                 SmallVectorImpl<int> &RepeatedMask) {
6172   int LaneSize = 128 / VT.getScalarSizeInBits();
6173   RepeatedMask.resize(LaneSize, -1);
6174   int Size = Mask.size();
6175   for (int i = 0; i < Size; ++i) {
6176     if (Mask[i] < 0)
6177       continue;
6178     if ((Mask[i] % Size) / LaneSize != i / LaneSize)
6179       // This entry crosses lanes, so there is no way to model this shuffle.
6180       return false;
6181
6182     // Ok, handle the in-lane shuffles by detecting if and when they repeat.
6183     if (RepeatedMask[i % LaneSize] == -1)
6184       // This is the first non-undef entry in this slot of a 128-bit lane.
6185       RepeatedMask[i % LaneSize] =
6186           Mask[i] < Size ? Mask[i] % LaneSize : Mask[i] % LaneSize + Size;
6187     else if (RepeatedMask[i % LaneSize] + (i / LaneSize) * LaneSize != Mask[i])
6188       // Found a mismatch with the repeated mask.
6189       return false;
6190   }
6191   return true;
6192 }
6193
6194 /// \brief Checks whether a shuffle mask is equivalent to an explicit list of
6195 /// arguments.
6196 ///
6197 /// This is a fast way to test a shuffle mask against a fixed pattern:
6198 ///
6199 ///   if (isShuffleEquivalent(Mask, 3, 2, {1, 0})) { ... }
6200 ///
6201 /// It returns true if the mask is exactly as wide as the argument list, and
6202 /// each element of the mask is either -1 (signifying undef) or the value given
6203 /// in the argument.
6204 static bool isShuffleEquivalent(SDValue V1, SDValue V2, ArrayRef<int> Mask,
6205                                 ArrayRef<int> ExpectedMask) {
6206   if (Mask.size() != ExpectedMask.size())
6207     return false;
6208
6209   int Size = Mask.size();
6210
6211   // If the values are build vectors, we can look through them to find
6212   // equivalent inputs that make the shuffles equivalent.
6213   auto *BV1 = dyn_cast<BuildVectorSDNode>(V1);
6214   auto *BV2 = dyn_cast<BuildVectorSDNode>(V2);
6215
6216   for (int i = 0; i < Size; ++i)
6217     if (Mask[i] != -1 && Mask[i] != ExpectedMask[i]) {
6218       auto *MaskBV = Mask[i] < Size ? BV1 : BV2;
6219       auto *ExpectedBV = ExpectedMask[i] < Size ? BV1 : BV2;
6220       if (!MaskBV || !ExpectedBV ||
6221           MaskBV->getOperand(Mask[i] % Size) !=
6222               ExpectedBV->getOperand(ExpectedMask[i] % Size))
6223         return false;
6224     }
6225
6226   return true;
6227 }
6228
6229 /// \brief Get a 4-lane 8-bit shuffle immediate for a mask.
6230 ///
6231 /// This helper function produces an 8-bit shuffle immediate corresponding to
6232 /// the ubiquitous shuffle encoding scheme used in x86 instructions for
6233 /// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
6234 /// example.
6235 ///
6236 /// NB: We rely heavily on "undef" masks preserving the input lane.
6237 static SDValue getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask, SDLoc DL,
6238                                           SelectionDAG &DAG) {
6239   assert(Mask.size() == 4 && "Only 4-lane shuffle masks");
6240   assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!");
6241   assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!");
6242   assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!");
6243   assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!");
6244
6245   unsigned Imm = 0;
6246   Imm |= (Mask[0] == -1 ? 0 : Mask[0]) << 0;
6247   Imm |= (Mask[1] == -1 ? 1 : Mask[1]) << 2;
6248   Imm |= (Mask[2] == -1 ? 2 : Mask[2]) << 4;
6249   Imm |= (Mask[3] == -1 ? 3 : Mask[3]) << 6;
6250   return DAG.getConstant(Imm, DL, MVT::i8);
6251 }
6252
6253 /// \brief Try to emit a blend instruction for a shuffle using bit math.
6254 ///
6255 /// This is used as a fallback approach when first class blend instructions are
6256 /// unavailable. Currently it is only suitable for integer vectors, but could
6257 /// be generalized for floating point vectors if desirable.
6258 static SDValue lowerVectorShuffleAsBitBlend(SDLoc DL, MVT VT, SDValue V1,
6259                                             SDValue V2, ArrayRef<int> Mask,
6260                                             SelectionDAG &DAG) {
6261   assert(VT.isInteger() && "Only supports integer vector types!");
6262   MVT EltVT = VT.getScalarType();
6263   int NumEltBits = EltVT.getSizeInBits();
6264   SDValue Zero = DAG.getConstant(0, DL, EltVT);
6265   SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
6266                                     EltVT);
6267   SmallVector<SDValue, 16> MaskOps;
6268   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6269     if (Mask[i] != -1 && Mask[i] != i && Mask[i] != i + Size)
6270       return SDValue(); // Shuffled input!
6271     MaskOps.push_back(Mask[i] < Size ? AllOnes : Zero);
6272   }
6273
6274   SDValue V1Mask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, MaskOps);
6275   V1 = DAG.getNode(ISD::AND, DL, VT, V1, V1Mask);
6276   // We have to cast V2 around.
6277   MVT MaskVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
6278   V2 = DAG.getNode(ISD::BITCAST, DL, VT,
6279                    DAG.getNode(X86ISD::ANDNP, DL, MaskVT,
6280                                DAG.getNode(ISD::BITCAST, DL, MaskVT, V1Mask),
6281                                DAG.getNode(ISD::BITCAST, DL, MaskVT, V2)));
6282   return DAG.getNode(ISD::OR, DL, VT, V1, V2);
6283 }
6284
6285 /// \brief Try to emit a blend instruction for a shuffle.
6286 ///
6287 /// This doesn't do any checks for the availability of instructions for blending
6288 /// these values. It relies on the availability of the X86ISD::BLENDI pattern to
6289 /// be matched in the backend with the type given. What it does check for is
6290 /// that the shuffle mask is in fact a blend.
6291 static SDValue lowerVectorShuffleAsBlend(SDLoc DL, MVT VT, SDValue V1,
6292                                          SDValue V2, ArrayRef<int> Mask,
6293                                          const X86Subtarget *Subtarget,
6294                                          SelectionDAG &DAG) {
6295   unsigned BlendMask = 0;
6296   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6297     if (Mask[i] >= Size) {
6298       if (Mask[i] != i + Size)
6299         return SDValue(); // Shuffled V2 input!
6300       BlendMask |= 1u << i;
6301       continue;
6302     }
6303     if (Mask[i] >= 0 && Mask[i] != i)
6304       return SDValue(); // Shuffled V1 input!
6305   }
6306   switch (VT.SimpleTy) {
6307   case MVT::v2f64:
6308   case MVT::v4f32:
6309   case MVT::v4f64:
6310   case MVT::v8f32:
6311     return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V2,
6312                        DAG.getConstant(BlendMask, DL, MVT::i8));
6313
6314   case MVT::v4i64:
6315   case MVT::v8i32:
6316     assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6317     // FALLTHROUGH
6318   case MVT::v2i64:
6319   case MVT::v4i32:
6320     // If we have AVX2 it is faster to use VPBLENDD when the shuffle fits into
6321     // that instruction.
6322     if (Subtarget->hasAVX2()) {
6323       // Scale the blend by the number of 32-bit dwords per element.
6324       int Scale =  VT.getScalarSizeInBits() / 32;
6325       BlendMask = 0;
6326       for (int i = 0, Size = Mask.size(); i < Size; ++i)
6327         if (Mask[i] >= Size)
6328           for (int j = 0; j < Scale; ++j)
6329             BlendMask |= 1u << (i * Scale + j);
6330
6331       MVT BlendVT = VT.getSizeInBits() > 128 ? MVT::v8i32 : MVT::v4i32;
6332       V1 = DAG.getNode(ISD::BITCAST, DL, BlendVT, V1);
6333       V2 = DAG.getNode(ISD::BITCAST, DL, BlendVT, V2);
6334       return DAG.getNode(ISD::BITCAST, DL, VT,
6335                          DAG.getNode(X86ISD::BLENDI, DL, BlendVT, V1, V2,
6336                                      DAG.getConstant(BlendMask, DL, MVT::i8)));
6337     }
6338     // FALLTHROUGH
6339   case MVT::v8i16: {
6340     // For integer shuffles we need to expand the mask and cast the inputs to
6341     // v8i16s prior to blending.
6342     int Scale = 8 / VT.getVectorNumElements();
6343     BlendMask = 0;
6344     for (int i = 0, Size = Mask.size(); i < Size; ++i)
6345       if (Mask[i] >= Size)
6346         for (int j = 0; j < Scale; ++j)
6347           BlendMask |= 1u << (i * Scale + j);
6348
6349     V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1);
6350     V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V2);
6351     return DAG.getNode(ISD::BITCAST, DL, VT,
6352                        DAG.getNode(X86ISD::BLENDI, DL, MVT::v8i16, V1, V2,
6353                                    DAG.getConstant(BlendMask, DL, MVT::i8)));
6354   }
6355
6356   case MVT::v16i16: {
6357     assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6358     SmallVector<int, 8> RepeatedMask;
6359     if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
6360       // We can lower these with PBLENDW which is mirrored across 128-bit lanes.
6361       assert(RepeatedMask.size() == 8 && "Repeated mask size doesn't match!");
6362       BlendMask = 0;
6363       for (int i = 0; i < 8; ++i)
6364         if (RepeatedMask[i] >= 16)
6365           BlendMask |= 1u << i;
6366       return DAG.getNode(X86ISD::BLENDI, DL, MVT::v16i16, V1, V2,
6367                          DAG.getConstant(BlendMask, DL, MVT::i8));
6368     }
6369   }
6370     // FALLTHROUGH
6371   case MVT::v16i8:
6372   case MVT::v32i8: {
6373     assert((VT.getSizeInBits() == 128 || Subtarget->hasAVX2()) &&
6374            "256-bit byte-blends require AVX2 support!");
6375
6376     // Scale the blend by the number of bytes per element.
6377     int Scale = VT.getScalarSizeInBits() / 8;
6378
6379     // This form of blend is always done on bytes. Compute the byte vector
6380     // type.
6381     MVT BlendVT = MVT::getVectorVT(MVT::i8, VT.getSizeInBits() / 8);
6382
6383     // Compute the VSELECT mask. Note that VSELECT is really confusing in the
6384     // mix of LLVM's code generator and the x86 backend. We tell the code
6385     // generator that boolean values in the elements of an x86 vector register
6386     // are -1 for true and 0 for false. We then use the LLVM semantics of 'true'
6387     // mapping a select to operand #1, and 'false' mapping to operand #2. The
6388     // reality in x86 is that vector masks (pre-AVX-512) use only the high bit
6389     // of the element (the remaining are ignored) and 0 in that high bit would
6390     // mean operand #1 while 1 in the high bit would mean operand #2. So while
6391     // the LLVM model for boolean values in vector elements gets the relevant
6392     // bit set, it is set backwards and over constrained relative to x86's
6393     // actual model.
6394     SmallVector<SDValue, 32> VSELECTMask;
6395     for (int i = 0, Size = Mask.size(); i < Size; ++i)
6396       for (int j = 0; j < Scale; ++j)
6397         VSELECTMask.push_back(
6398             Mask[i] < 0 ? DAG.getUNDEF(MVT::i8)
6399                         : DAG.getConstant(Mask[i] < Size ? -1 : 0, DL,
6400                                           MVT::i8));
6401
6402     V1 = DAG.getNode(ISD::BITCAST, DL, BlendVT, V1);
6403     V2 = DAG.getNode(ISD::BITCAST, DL, BlendVT, V2);
6404     return DAG.getNode(
6405         ISD::BITCAST, DL, VT,
6406         DAG.getNode(ISD::VSELECT, DL, BlendVT,
6407                     DAG.getNode(ISD::BUILD_VECTOR, DL, BlendVT, VSELECTMask),
6408                     V1, V2));
6409   }
6410
6411   default:
6412     llvm_unreachable("Not a supported integer vector type!");
6413   }
6414 }
6415
6416 /// \brief Try to lower as a blend of elements from two inputs followed by
6417 /// a single-input permutation.
6418 ///
6419 /// This matches the pattern where we can blend elements from two inputs and
6420 /// then reduce the shuffle to a single-input permutation.
6421 static SDValue lowerVectorShuffleAsBlendAndPermute(SDLoc DL, MVT VT, SDValue V1,
6422                                                    SDValue V2,
6423                                                    ArrayRef<int> Mask,
6424                                                    SelectionDAG &DAG) {
6425   // We build up the blend mask while checking whether a blend is a viable way
6426   // to reduce the shuffle.
6427   SmallVector<int, 32> BlendMask(Mask.size(), -1);
6428   SmallVector<int, 32> PermuteMask(Mask.size(), -1);
6429
6430   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6431     if (Mask[i] < 0)
6432       continue;
6433
6434     assert(Mask[i] < Size * 2 && "Shuffle input is out of bounds.");
6435
6436     if (BlendMask[Mask[i] % Size] == -1)
6437       BlendMask[Mask[i] % Size] = Mask[i];
6438     else if (BlendMask[Mask[i] % Size] != Mask[i])
6439       return SDValue(); // Can't blend in the needed input!
6440
6441     PermuteMask[i] = Mask[i] % Size;
6442   }
6443
6444   SDValue V = DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
6445   return DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), PermuteMask);
6446 }
6447
6448 /// \brief Generic routine to decompose a shuffle and blend into indepndent
6449 /// blends and permutes.
6450 ///
6451 /// This matches the extremely common pattern for handling combined
6452 /// shuffle+blend operations on newer X86 ISAs where we have very fast blend
6453 /// operations. It will try to pick the best arrangement of shuffles and
6454 /// blends.
6455 static SDValue lowerVectorShuffleAsDecomposedShuffleBlend(SDLoc DL, MVT VT,
6456                                                           SDValue V1,
6457                                                           SDValue V2,
6458                                                           ArrayRef<int> Mask,
6459                                                           SelectionDAG &DAG) {
6460   // Shuffle the input elements into the desired positions in V1 and V2 and
6461   // blend them together.
6462   SmallVector<int, 32> V1Mask(Mask.size(), -1);
6463   SmallVector<int, 32> V2Mask(Mask.size(), -1);
6464   SmallVector<int, 32> BlendMask(Mask.size(), -1);
6465   for (int i = 0, Size = Mask.size(); i < Size; ++i)
6466     if (Mask[i] >= 0 && Mask[i] < Size) {
6467       V1Mask[i] = Mask[i];
6468       BlendMask[i] = i;
6469     } else if (Mask[i] >= Size) {
6470       V2Mask[i] = Mask[i] - Size;
6471       BlendMask[i] = i + Size;
6472     }
6473
6474   // Try to lower with the simpler initial blend strategy unless one of the
6475   // input shuffles would be a no-op. We prefer to shuffle inputs as the
6476   // shuffle may be able to fold with a load or other benefit. However, when
6477   // we'll have to do 2x as many shuffles in order to achieve this, blending
6478   // first is a better strategy.
6479   if (!isNoopShuffleMask(V1Mask) && !isNoopShuffleMask(V2Mask))
6480     if (SDValue BlendPerm =
6481             lowerVectorShuffleAsBlendAndPermute(DL, VT, V1, V2, Mask, DAG))
6482       return BlendPerm;
6483
6484   V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
6485   V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
6486   return DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
6487 }
6488
6489 /// \brief Try to lower a vector shuffle as a byte rotation.
6490 ///
6491 /// SSSE3 has a generic PALIGNR instruction in x86 that will do an arbitrary
6492 /// byte-rotation of the concatenation of two vectors; pre-SSSE3 can use
6493 /// a PSRLDQ/PSLLDQ/POR pattern to get a similar effect. This routine will
6494 /// try to generically lower a vector shuffle through such an pattern. It
6495 /// does not check for the profitability of lowering either as PALIGNR or
6496 /// PSRLDQ/PSLLDQ/POR, only whether the mask is valid to lower in that form.
6497 /// This matches shuffle vectors that look like:
6498 ///
6499 ///   v8i16 [11, 12, 13, 14, 15, 0, 1, 2]
6500 ///
6501 /// Essentially it concatenates V1 and V2, shifts right by some number of
6502 /// elements, and takes the low elements as the result. Note that while this is
6503 /// specified as a *right shift* because x86 is little-endian, it is a *left
6504 /// rotate* of the vector lanes.
6505 static SDValue lowerVectorShuffleAsByteRotate(SDLoc DL, MVT VT, SDValue V1,
6506                                               SDValue V2,
6507                                               ArrayRef<int> Mask,
6508                                               const X86Subtarget *Subtarget,
6509                                               SelectionDAG &DAG) {
6510   assert(!isNoopShuffleMask(Mask) && "We shouldn't lower no-op shuffles!");
6511
6512   int NumElts = Mask.size();
6513   int NumLanes = VT.getSizeInBits() / 128;
6514   int NumLaneElts = NumElts / NumLanes;
6515
6516   // We need to detect various ways of spelling a rotation:
6517   //   [11, 12, 13, 14, 15,  0,  1,  2]
6518   //   [-1, 12, 13, 14, -1, -1,  1, -1]
6519   //   [-1, -1, -1, -1, -1, -1,  1,  2]
6520   //   [ 3,  4,  5,  6,  7,  8,  9, 10]
6521   //   [-1,  4,  5,  6, -1, -1,  9, -1]
6522   //   [-1,  4,  5,  6, -1, -1, -1, -1]
6523   int Rotation = 0;
6524   SDValue Lo, Hi;
6525   for (int l = 0; l < NumElts; l += NumLaneElts) {
6526     for (int i = 0; i < NumLaneElts; ++i) {
6527       if (Mask[l + i] == -1)
6528         continue;
6529       assert(Mask[l + i] >= 0 && "Only -1 is a valid negative mask element!");
6530
6531       // Get the mod-Size index and lane correct it.
6532       int LaneIdx = (Mask[l + i] % NumElts) - l;
6533       // Make sure it was in this lane.
6534       if (LaneIdx < 0 || LaneIdx >= NumLaneElts)
6535         return SDValue();
6536
6537       // Determine where a rotated vector would have started.
6538       int StartIdx = i - LaneIdx;
6539       if (StartIdx == 0)
6540         // The identity rotation isn't interesting, stop.
6541         return SDValue();
6542
6543       // If we found the tail of a vector the rotation must be the missing
6544       // front. If we found the head of a vector, it must be how much of the
6545       // head.
6546       int CandidateRotation = StartIdx < 0 ? -StartIdx : NumLaneElts - StartIdx;
6547
6548       if (Rotation == 0)
6549         Rotation = CandidateRotation;
6550       else if (Rotation != CandidateRotation)
6551         // The rotations don't match, so we can't match this mask.
6552         return SDValue();
6553
6554       // Compute which value this mask is pointing at.
6555       SDValue MaskV = Mask[l + i] < NumElts ? V1 : V2;
6556
6557       // Compute which of the two target values this index should be assigned
6558       // to. This reflects whether the high elements are remaining or the low
6559       // elements are remaining.
6560       SDValue &TargetV = StartIdx < 0 ? Hi : Lo;
6561
6562       // Either set up this value if we've not encountered it before, or check
6563       // that it remains consistent.
6564       if (!TargetV)
6565         TargetV = MaskV;
6566       else if (TargetV != MaskV)
6567         // This may be a rotation, but it pulls from the inputs in some
6568         // unsupported interleaving.
6569         return SDValue();
6570     }
6571   }
6572
6573   // Check that we successfully analyzed the mask, and normalize the results.
6574   assert(Rotation != 0 && "Failed to locate a viable rotation!");
6575   assert((Lo || Hi) && "Failed to find a rotated input vector!");
6576   if (!Lo)
6577     Lo = Hi;
6578   else if (!Hi)
6579     Hi = Lo;
6580
6581   // The actual rotate instruction rotates bytes, so we need to scale the
6582   // rotation based on how many bytes are in the vector lane.
6583   int Scale = 16 / NumLaneElts;
6584
6585   // SSSE3 targets can use the palignr instruction.
6586   if (Subtarget->hasSSSE3()) {
6587     // Cast the inputs to i8 vector of correct length to match PALIGNR.
6588     MVT AlignVT = MVT::getVectorVT(MVT::i8, 16 * NumLanes);
6589     Lo = DAG.getNode(ISD::BITCAST, DL, AlignVT, Lo);
6590     Hi = DAG.getNode(ISD::BITCAST, DL, AlignVT, Hi);
6591
6592     return DAG.getNode(ISD::BITCAST, DL, VT,
6593                        DAG.getNode(X86ISD::PALIGNR, DL, AlignVT, Hi, Lo,
6594                                    DAG.getConstant(Rotation * Scale, DL,
6595                                                    MVT::i8)));
6596   }
6597
6598   assert(VT.getSizeInBits() == 128 &&
6599          "Rotate-based lowering only supports 128-bit lowering!");
6600   assert(Mask.size() <= 16 &&
6601          "Can shuffle at most 16 bytes in a 128-bit vector!");
6602
6603   // Default SSE2 implementation
6604   int LoByteShift = 16 - Rotation * Scale;
6605   int HiByteShift = Rotation * Scale;
6606
6607   // Cast the inputs to v2i64 to match PSLLDQ/PSRLDQ.
6608   Lo = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Lo);
6609   Hi = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Hi);
6610
6611   SDValue LoShift = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v2i64, Lo,
6612                                 DAG.getConstant(LoByteShift, DL, MVT::i8));
6613   SDValue HiShift = DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v2i64, Hi,
6614                                 DAG.getConstant(HiByteShift, DL, MVT::i8));
6615   return DAG.getNode(ISD::BITCAST, DL, VT,
6616                      DAG.getNode(ISD::OR, DL, MVT::v2i64, LoShift, HiShift));
6617 }
6618
6619 /// \brief Compute whether each element of a shuffle is zeroable.
6620 ///
6621 /// A "zeroable" vector shuffle element is one which can be lowered to zero.
6622 /// Either it is an undef element in the shuffle mask, the element of the input
6623 /// referenced is undef, or the element of the input referenced is known to be
6624 /// zero. Many x86 shuffles can zero lanes cheaply and we often want to handle
6625 /// as many lanes with this technique as possible to simplify the remaining
6626 /// shuffle.
6627 static SmallBitVector computeZeroableShuffleElements(ArrayRef<int> Mask,
6628                                                      SDValue V1, SDValue V2) {
6629   SmallBitVector Zeroable(Mask.size(), false);
6630
6631   while (V1.getOpcode() == ISD::BITCAST)
6632     V1 = V1->getOperand(0);
6633   while (V2.getOpcode() == ISD::BITCAST)
6634     V2 = V2->getOperand(0);
6635
6636   bool V1IsZero = ISD::isBuildVectorAllZeros(V1.getNode());
6637   bool V2IsZero = ISD::isBuildVectorAllZeros(V2.getNode());
6638
6639   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6640     int M = Mask[i];
6641     // Handle the easy cases.
6642     if (M < 0 || (M >= 0 && M < Size && V1IsZero) || (M >= Size && V2IsZero)) {
6643       Zeroable[i] = true;
6644       continue;
6645     }
6646
6647     // If this is an index into a build_vector node (which has the same number
6648     // of elements), dig out the input value and use it.
6649     SDValue V = M < Size ? V1 : V2;
6650     if (V.getOpcode() != ISD::BUILD_VECTOR || Size != (int)V.getNumOperands())
6651       continue;
6652
6653     SDValue Input = V.getOperand(M % Size);
6654     // The UNDEF opcode check really should be dead code here, but not quite
6655     // worth asserting on (it isn't invalid, just unexpected).
6656     if (Input.getOpcode() == ISD::UNDEF || X86::isZeroNode(Input))
6657       Zeroable[i] = true;
6658   }
6659
6660   return Zeroable;
6661 }
6662
6663 /// \brief Try to emit a bitmask instruction for a shuffle.
6664 ///
6665 /// This handles cases where we can model a blend exactly as a bitmask due to
6666 /// one of the inputs being zeroable.
6667 static SDValue lowerVectorShuffleAsBitMask(SDLoc DL, MVT VT, SDValue V1,
6668                                            SDValue V2, ArrayRef<int> Mask,
6669                                            SelectionDAG &DAG) {
6670   MVT EltVT = VT.getScalarType();
6671   int NumEltBits = EltVT.getSizeInBits();
6672   MVT IntEltVT = MVT::getIntegerVT(NumEltBits);
6673   SDValue Zero = DAG.getConstant(0, DL, IntEltVT);
6674   SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
6675                                     IntEltVT);
6676   if (EltVT.isFloatingPoint()) {
6677     Zero = DAG.getNode(ISD::BITCAST, DL, EltVT, Zero);
6678     AllOnes = DAG.getNode(ISD::BITCAST, DL, EltVT, AllOnes);
6679   }
6680   SmallVector<SDValue, 16> VMaskOps(Mask.size(), Zero);
6681   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6682   SDValue V;
6683   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6684     if (Zeroable[i])
6685       continue;
6686     if (Mask[i] % Size != i)
6687       return SDValue(); // Not a blend.
6688     if (!V)
6689       V = Mask[i] < Size ? V1 : V2;
6690     else if (V != (Mask[i] < Size ? V1 : V2))
6691       return SDValue(); // Can only let one input through the mask.
6692
6693     VMaskOps[i] = AllOnes;
6694   }
6695   if (!V)
6696     return SDValue(); // No non-zeroable elements!
6697
6698   SDValue VMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, VMaskOps);
6699   V = DAG.getNode(VT.isFloatingPoint()
6700                   ? (unsigned) X86ISD::FAND : (unsigned) ISD::AND,
6701                   DL, VT, V, VMask);
6702   return V;
6703 }
6704
6705 /// \brief Try to lower a vector shuffle as a bit shift (shifts in zeros).
6706 ///
6707 /// Attempts to match a shuffle mask against the PSLL(W/D/Q/DQ) and
6708 /// PSRL(W/D/Q/DQ) SSE2 and AVX2 logical bit-shift instructions. The function
6709 /// matches elements from one of the input vectors shuffled to the left or
6710 /// right with zeroable elements 'shifted in'. It handles both the strictly
6711 /// bit-wise element shifts and the byte shift across an entire 128-bit double
6712 /// quad word lane.
6713 ///
6714 /// PSHL : (little-endian) left bit shift.
6715 /// [ zz, 0, zz,  2 ]
6716 /// [ -1, 4, zz, -1 ]
6717 /// PSRL : (little-endian) right bit shift.
6718 /// [  1, zz,  3, zz]
6719 /// [ -1, -1,  7, zz]
6720 /// PSLLDQ : (little-endian) left byte shift
6721 /// [ zz,  0,  1,  2,  3,  4,  5,  6]
6722 /// [ zz, zz, -1, -1,  2,  3,  4, -1]
6723 /// [ zz, zz, zz, zz, zz, zz, -1,  1]
6724 /// PSRLDQ : (little-endian) right byte shift
6725 /// [  5, 6,  7, zz, zz, zz, zz, zz]
6726 /// [ -1, 5,  6,  7, zz, zz, zz, zz]
6727 /// [  1, 2, -1, -1, -1, -1, zz, zz]
6728 static SDValue lowerVectorShuffleAsShift(SDLoc DL, MVT VT, SDValue V1,
6729                                          SDValue V2, ArrayRef<int> Mask,
6730                                          SelectionDAG &DAG) {
6731   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6732
6733   int Size = Mask.size();
6734   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
6735
6736   auto CheckZeros = [&](int Shift, int Scale, bool Left) {
6737     for (int i = 0; i < Size; i += Scale)
6738       for (int j = 0; j < Shift; ++j)
6739         if (!Zeroable[i + j + (Left ? 0 : (Scale - Shift))])
6740           return false;
6741
6742     return true;
6743   };
6744
6745   auto MatchShift = [&](int Shift, int Scale, bool Left, SDValue V) {
6746     for (int i = 0; i != Size; i += Scale) {
6747       unsigned Pos = Left ? i + Shift : i;
6748       unsigned Low = Left ? i : i + Shift;
6749       unsigned Len = Scale - Shift;
6750       if (!isSequentialOrUndefInRange(Mask, Pos, Len,
6751                                       Low + (V == V1 ? 0 : Size)))
6752         return SDValue();
6753     }
6754
6755     int ShiftEltBits = VT.getScalarSizeInBits() * Scale;
6756     bool ByteShift = ShiftEltBits > 64;
6757     unsigned OpCode = Left ? (ByteShift ? X86ISD::VSHLDQ : X86ISD::VSHLI)
6758                            : (ByteShift ? X86ISD::VSRLDQ : X86ISD::VSRLI);
6759     int ShiftAmt = Shift * VT.getScalarSizeInBits() / (ByteShift ? 8 : 1);
6760
6761     // Normalize the scale for byte shifts to still produce an i64 element
6762     // type.
6763     Scale = ByteShift ? Scale / 2 : Scale;
6764
6765     // We need to round trip through the appropriate type for the shift.
6766     MVT ShiftSVT = MVT::getIntegerVT(VT.getScalarSizeInBits() * Scale);
6767     MVT ShiftVT = MVT::getVectorVT(ShiftSVT, Size / Scale);
6768     assert(DAG.getTargetLoweringInfo().isTypeLegal(ShiftVT) &&
6769            "Illegal integer vector type");
6770     V = DAG.getNode(ISD::BITCAST, DL, ShiftVT, V);
6771
6772     V = DAG.getNode(OpCode, DL, ShiftVT, V,
6773                     DAG.getConstant(ShiftAmt, DL, MVT::i8));
6774     return DAG.getNode(ISD::BITCAST, DL, VT, V);
6775   };
6776
6777   // SSE/AVX supports logical shifts up to 64-bit integers - so we can just
6778   // keep doubling the size of the integer elements up to that. We can
6779   // then shift the elements of the integer vector by whole multiples of
6780   // their width within the elements of the larger integer vector. Test each
6781   // multiple to see if we can find a match with the moved element indices
6782   // and that the shifted in elements are all zeroable.
6783   for (int Scale = 2; Scale * VT.getScalarSizeInBits() <= 128; Scale *= 2)
6784     for (int Shift = 1; Shift != Scale; ++Shift)
6785       for (bool Left : {true, false})
6786         if (CheckZeros(Shift, Scale, Left))
6787           for (SDValue V : {V1, V2})
6788             if (SDValue Match = MatchShift(Shift, Scale, Left, V))
6789               return Match;
6790
6791   // no match
6792   return SDValue();
6793 }
6794
6795 /// \brief Lower a vector shuffle as a zero or any extension.
6796 ///
6797 /// Given a specific number of elements, element bit width, and extension
6798 /// stride, produce either a zero or any extension based on the available
6799 /// features of the subtarget.
6800 static SDValue lowerVectorShuffleAsSpecificZeroOrAnyExtend(
6801     SDLoc DL, MVT VT, int Scale, bool AnyExt, SDValue InputV,
6802     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
6803   assert(Scale > 1 && "Need a scale to extend.");
6804   int NumElements = VT.getVectorNumElements();
6805   int EltBits = VT.getScalarSizeInBits();
6806   assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
6807          "Only 8, 16, and 32 bit elements can be extended.");
6808   assert(Scale * EltBits <= 64 && "Cannot zero extend past 64 bits.");
6809
6810   // Found a valid zext mask! Try various lowering strategies based on the
6811   // input type and available ISA extensions.
6812   if (Subtarget->hasSSE41()) {
6813     MVT ExtVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits * Scale),
6814                                  NumElements / Scale);
6815     return DAG.getNode(ISD::BITCAST, DL, VT,
6816                        DAG.getNode(X86ISD::VZEXT, DL, ExtVT, InputV));
6817   }
6818
6819   // For any extends we can cheat for larger element sizes and use shuffle
6820   // instructions that can fold with a load and/or copy.
6821   if (AnyExt && EltBits == 32) {
6822     int PSHUFDMask[4] = {0, -1, 1, -1};
6823     return DAG.getNode(
6824         ISD::BITCAST, DL, VT,
6825         DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
6826                     DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, InputV),
6827                     getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
6828   }
6829   if (AnyExt && EltBits == 16 && Scale > 2) {
6830     int PSHUFDMask[4] = {0, -1, 0, -1};
6831     InputV = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
6832                          DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, InputV),
6833                          getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG));
6834     int PSHUFHWMask[4] = {1, -1, -1, -1};
6835     return DAG.getNode(
6836         ISD::BITCAST, DL, VT,
6837         DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16,
6838                     DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, InputV),
6839                     getV4X86ShuffleImm8ForMask(PSHUFHWMask, DL, DAG)));
6840   }
6841
6842   // If this would require more than 2 unpack instructions to expand, use
6843   // pshufb when available. We can only use more than 2 unpack instructions
6844   // when zero extending i8 elements which also makes it easier to use pshufb.
6845   if (Scale > 4 && EltBits == 8 && Subtarget->hasSSSE3()) {
6846     assert(NumElements == 16 && "Unexpected byte vector width!");
6847     SDValue PSHUFBMask[16];
6848     for (int i = 0; i < 16; ++i)
6849       PSHUFBMask[i] =
6850           DAG.getConstant((i % Scale == 0) ? i / Scale : 0x80, DL, MVT::i8);
6851     InputV = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, InputV);
6852     return DAG.getNode(ISD::BITCAST, DL, VT,
6853                        DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, InputV,
6854                                    DAG.getNode(ISD::BUILD_VECTOR, DL,
6855                                                MVT::v16i8, PSHUFBMask)));
6856   }
6857
6858   // Otherwise emit a sequence of unpacks.
6859   do {
6860     MVT InputVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits), NumElements);
6861     SDValue Ext = AnyExt ? DAG.getUNDEF(InputVT)
6862                          : getZeroVector(InputVT, Subtarget, DAG, DL);
6863     InputV = DAG.getNode(ISD::BITCAST, DL, InputVT, InputV);
6864     InputV = DAG.getNode(X86ISD::UNPCKL, DL, InputVT, InputV, Ext);
6865     Scale /= 2;
6866     EltBits *= 2;
6867     NumElements /= 2;
6868   } while (Scale > 1);
6869   return DAG.getNode(ISD::BITCAST, DL, VT, InputV);
6870 }
6871
6872 /// \brief Try to lower a vector shuffle as a zero extension on any microarch.
6873 ///
6874 /// This routine will try to do everything in its power to cleverly lower
6875 /// a shuffle which happens to match the pattern of a zero extend. It doesn't
6876 /// check for the profitability of this lowering,  it tries to aggressively
6877 /// match this pattern. It will use all of the micro-architectural details it
6878 /// can to emit an efficient lowering. It handles both blends with all-zero
6879 /// inputs to explicitly zero-extend and undef-lanes (sometimes undef due to
6880 /// masking out later).
6881 ///
6882 /// The reason we have dedicated lowering for zext-style shuffles is that they
6883 /// are both incredibly common and often quite performance sensitive.
6884 static SDValue lowerVectorShuffleAsZeroOrAnyExtend(
6885     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
6886     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
6887   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6888
6889   int Bits = VT.getSizeInBits();
6890   int NumElements = VT.getVectorNumElements();
6891   assert(VT.getScalarSizeInBits() <= 32 &&
6892          "Exceeds 32-bit integer zero extension limit");
6893   assert((int)Mask.size() == NumElements && "Unexpected shuffle mask size");
6894
6895   // Define a helper function to check a particular ext-scale and lower to it if
6896   // valid.
6897   auto Lower = [&](int Scale) -> SDValue {
6898     SDValue InputV;
6899     bool AnyExt = true;
6900     for (int i = 0; i < NumElements; ++i) {
6901       if (Mask[i] == -1)
6902         continue; // Valid anywhere but doesn't tell us anything.
6903       if (i % Scale != 0) {
6904         // Each of the extended elements need to be zeroable.
6905         if (!Zeroable[i])
6906           return SDValue();
6907
6908         // We no longer are in the anyext case.
6909         AnyExt = false;
6910         continue;
6911       }
6912
6913       // Each of the base elements needs to be consecutive indices into the
6914       // same input vector.
6915       SDValue V = Mask[i] < NumElements ? V1 : V2;
6916       if (!InputV)
6917         InputV = V;
6918       else if (InputV != V)
6919         return SDValue(); // Flip-flopping inputs.
6920
6921       if (Mask[i] % NumElements != i / Scale)
6922         return SDValue(); // Non-consecutive strided elements.
6923     }
6924
6925     // If we fail to find an input, we have a zero-shuffle which should always
6926     // have already been handled.
6927     // FIXME: Maybe handle this here in case during blending we end up with one?
6928     if (!InputV)
6929       return SDValue();
6930
6931     return lowerVectorShuffleAsSpecificZeroOrAnyExtend(
6932         DL, VT, Scale, AnyExt, InputV, Subtarget, DAG);
6933   };
6934
6935   // The widest scale possible for extending is to a 64-bit integer.
6936   assert(Bits % 64 == 0 &&
6937          "The number of bits in a vector must be divisible by 64 on x86!");
6938   int NumExtElements = Bits / 64;
6939
6940   // Each iteration, try extending the elements half as much, but into twice as
6941   // many elements.
6942   for (; NumExtElements < NumElements; NumExtElements *= 2) {
6943     assert(NumElements % NumExtElements == 0 &&
6944            "The input vector size must be divisible by the extended size.");
6945     if (SDValue V = Lower(NumElements / NumExtElements))
6946       return V;
6947   }
6948
6949   // General extends failed, but 128-bit vectors may be able to use MOVQ.
6950   if (Bits != 128)
6951     return SDValue();
6952
6953   // Returns one of the source operands if the shuffle can be reduced to a
6954   // MOVQ, copying the lower 64-bits and zero-extending to the upper 64-bits.
6955   auto CanZExtLowHalf = [&]() {
6956     for (int i = NumElements / 2; i != NumElements; ++i)
6957       if (!Zeroable[i])
6958         return SDValue();
6959     if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, 0))
6960       return V1;
6961     if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, NumElements))
6962       return V2;
6963     return SDValue();
6964   };
6965
6966   if (SDValue V = CanZExtLowHalf()) {
6967     V = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, V);
6968     V = DAG.getNode(X86ISD::VZEXT_MOVL, DL, MVT::v2i64, V);
6969     return DAG.getNode(ISD::BITCAST, DL, VT, V);
6970   }
6971
6972   // No viable ext lowering found.
6973   return SDValue();
6974 }
6975
6976 /// \brief Try to get a scalar value for a specific element of a vector.
6977 ///
6978 /// Looks through BUILD_VECTOR and SCALAR_TO_VECTOR nodes to find a scalar.
6979 static SDValue getScalarValueForVectorElement(SDValue V, int Idx,
6980                                               SelectionDAG &DAG) {
6981   MVT VT = V.getSimpleValueType();
6982   MVT EltVT = VT.getVectorElementType();
6983   while (V.getOpcode() == ISD::BITCAST)
6984     V = V.getOperand(0);
6985   // If the bitcasts shift the element size, we can't extract an equivalent
6986   // element from it.
6987   MVT NewVT = V.getSimpleValueType();
6988   if (!NewVT.isVector() || NewVT.getScalarSizeInBits() != VT.getScalarSizeInBits())
6989     return SDValue();
6990
6991   if (V.getOpcode() == ISD::BUILD_VECTOR ||
6992       (Idx == 0 && V.getOpcode() == ISD::SCALAR_TO_VECTOR)) {
6993     // Ensure the scalar operand is the same size as the destination.
6994     // FIXME: Add support for scalar truncation where possible.
6995     SDValue S = V.getOperand(Idx);
6996     if (EltVT.getSizeInBits() == S.getSimpleValueType().getSizeInBits())
6997       return DAG.getNode(ISD::BITCAST, SDLoc(V), EltVT, S);
6998   }
6999
7000   return SDValue();
7001 }
7002
7003 /// \brief Helper to test for a load that can be folded with x86 shuffles.
7004 ///
7005 /// This is particularly important because the set of instructions varies
7006 /// significantly based on whether the operand is a load or not.
7007 static bool isShuffleFoldableLoad(SDValue V) {
7008   while (V.getOpcode() == ISD::BITCAST)
7009     V = V.getOperand(0);
7010
7011   return ISD::isNON_EXTLoad(V.getNode());
7012 }
7013
7014 /// \brief Try to lower insertion of a single element into a zero vector.
7015 ///
7016 /// This is a common pattern that we have especially efficient patterns to lower
7017 /// across all subtarget feature sets.
7018 static SDValue lowerVectorShuffleAsElementInsertion(
7019     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7020     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7021   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7022   MVT ExtVT = VT;
7023   MVT EltVT = VT.getVectorElementType();
7024
7025   int V2Index = std::find_if(Mask.begin(), Mask.end(),
7026                              [&Mask](int M) { return M >= (int)Mask.size(); }) -
7027                 Mask.begin();
7028   bool IsV1Zeroable = true;
7029   for (int i = 0, Size = Mask.size(); i < Size; ++i)
7030     if (i != V2Index && !Zeroable[i]) {
7031       IsV1Zeroable = false;
7032       break;
7033     }
7034
7035   // Check for a single input from a SCALAR_TO_VECTOR node.
7036   // FIXME: All of this should be canonicalized into INSERT_VECTOR_ELT and
7037   // all the smarts here sunk into that routine. However, the current
7038   // lowering of BUILD_VECTOR makes that nearly impossible until the old
7039   // vector shuffle lowering is dead.
7040   if (SDValue V2S = getScalarValueForVectorElement(
7041           V2, Mask[V2Index] - Mask.size(), DAG)) {
7042     // We need to zext the scalar if it is smaller than an i32.
7043     V2S = DAG.getNode(ISD::BITCAST, DL, EltVT, V2S);
7044     if (EltVT == MVT::i8 || EltVT == MVT::i16) {
7045       // Using zext to expand a narrow element won't work for non-zero
7046       // insertions.
7047       if (!IsV1Zeroable)
7048         return SDValue();
7049
7050       // Zero-extend directly to i32.
7051       ExtVT = MVT::v4i32;
7052       V2S = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, V2S);
7053     }
7054     V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, ExtVT, V2S);
7055   } else if (Mask[V2Index] != (int)Mask.size() || EltVT == MVT::i8 ||
7056              EltVT == MVT::i16) {
7057     // Either not inserting from the low element of the input or the input
7058     // element size is too small to use VZEXT_MOVL to clear the high bits.
7059     return SDValue();
7060   }
7061
7062   if (!IsV1Zeroable) {
7063     // If V1 can't be treated as a zero vector we have fewer options to lower
7064     // this. We can't support integer vectors or non-zero targets cheaply, and
7065     // the V1 elements can't be permuted in any way.
7066     assert(VT == ExtVT && "Cannot change extended type when non-zeroable!");
7067     if (!VT.isFloatingPoint() || V2Index != 0)
7068       return SDValue();
7069     SmallVector<int, 8> V1Mask(Mask.begin(), Mask.end());
7070     V1Mask[V2Index] = -1;
7071     if (!isNoopShuffleMask(V1Mask))
7072       return SDValue();
7073     // This is essentially a special case blend operation, but if we have
7074     // general purpose blend operations, they are always faster. Bail and let
7075     // the rest of the lowering handle these as blends.
7076     if (Subtarget->hasSSE41())
7077       return SDValue();
7078
7079     // Otherwise, use MOVSD or MOVSS.
7080     assert((EltVT == MVT::f32 || EltVT == MVT::f64) &&
7081            "Only two types of floating point element types to handle!");
7082     return DAG.getNode(EltVT == MVT::f32 ? X86ISD::MOVSS : X86ISD::MOVSD, DL,
7083                        ExtVT, V1, V2);
7084   }
7085
7086   // This lowering only works for the low element with floating point vectors.
7087   if (VT.isFloatingPoint() && V2Index != 0)
7088     return SDValue();
7089
7090   V2 = DAG.getNode(X86ISD::VZEXT_MOVL, DL, ExtVT, V2);
7091   if (ExtVT != VT)
7092     V2 = DAG.getNode(ISD::BITCAST, DL, VT, V2);
7093
7094   if (V2Index != 0) {
7095     // If we have 4 or fewer lanes we can cheaply shuffle the element into
7096     // the desired position. Otherwise it is more efficient to do a vector
7097     // shift left. We know that we can do a vector shift left because all
7098     // the inputs are zero.
7099     if (VT.isFloatingPoint() || VT.getVectorNumElements() <= 4) {
7100       SmallVector<int, 4> V2Shuffle(Mask.size(), 1);
7101       V2Shuffle[V2Index] = 0;
7102       V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Shuffle);
7103     } else {
7104       V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, V2);
7105       V2 = DAG.getNode(
7106           X86ISD::VSHLDQ, DL, MVT::v2i64, V2,
7107           DAG.getConstant(
7108               V2Index * EltVT.getSizeInBits()/8, DL,
7109               DAG.getTargetLoweringInfo().getScalarShiftAmountTy(MVT::v2i64)));
7110       V2 = DAG.getNode(ISD::BITCAST, DL, VT, V2);
7111     }
7112   }
7113   return V2;
7114 }
7115
7116 /// \brief Try to lower broadcast of a single element.
7117 ///
7118 /// For convenience, this code also bundles all of the subtarget feature set
7119 /// filtering. While a little annoying to re-dispatch on type here, there isn't
7120 /// a convenient way to factor it out.
7121 static SDValue lowerVectorShuffleAsBroadcast(SDLoc DL, MVT VT, SDValue V,
7122                                              ArrayRef<int> Mask,
7123                                              const X86Subtarget *Subtarget,
7124                                              SelectionDAG &DAG) {
7125   if (!Subtarget->hasAVX())
7126     return SDValue();
7127   if (VT.isInteger() && !Subtarget->hasAVX2())
7128     return SDValue();
7129
7130   // Check that the mask is a broadcast.
7131   int BroadcastIdx = -1;
7132   for (int M : Mask)
7133     if (M >= 0 && BroadcastIdx == -1)
7134       BroadcastIdx = M;
7135     else if (M >= 0 && M != BroadcastIdx)
7136       return SDValue();
7137
7138   assert(BroadcastIdx < (int)Mask.size() && "We only expect to be called with "
7139                                             "a sorted mask where the broadcast "
7140                                             "comes from V1.");
7141
7142   // Go up the chain of (vector) values to find a scalar load that we can
7143   // combine with the broadcast.
7144   for (;;) {
7145     switch (V.getOpcode()) {
7146     case ISD::CONCAT_VECTORS: {
7147       int OperandSize = Mask.size() / V.getNumOperands();
7148       V = V.getOperand(BroadcastIdx / OperandSize);
7149       BroadcastIdx %= OperandSize;
7150       continue;
7151     }
7152
7153     case ISD::INSERT_SUBVECTOR: {
7154       SDValue VOuter = V.getOperand(0), VInner = V.getOperand(1);
7155       auto ConstantIdx = dyn_cast<ConstantSDNode>(V.getOperand(2));
7156       if (!ConstantIdx)
7157         break;
7158
7159       int BeginIdx = (int)ConstantIdx->getZExtValue();
7160       int EndIdx =
7161           BeginIdx + (int)VInner.getValueType().getVectorNumElements();
7162       if (BroadcastIdx >= BeginIdx && BroadcastIdx < EndIdx) {
7163         BroadcastIdx -= BeginIdx;
7164         V = VInner;
7165       } else {
7166         V = VOuter;
7167       }
7168       continue;
7169     }
7170     }
7171     break;
7172   }
7173
7174   // Check if this is a broadcast of a scalar. We special case lowering
7175   // for scalars so that we can more effectively fold with loads.
7176   if (V.getOpcode() == ISD::BUILD_VECTOR ||
7177       (V.getOpcode() == ISD::SCALAR_TO_VECTOR && BroadcastIdx == 0)) {
7178     V = V.getOperand(BroadcastIdx);
7179
7180     // If the scalar isn't a load, we can't broadcast from it in AVX1.
7181     // Only AVX2 has register broadcasts.
7182     if (!Subtarget->hasAVX2() && !isShuffleFoldableLoad(V))
7183       return SDValue();
7184   } else if (BroadcastIdx != 0 || !Subtarget->hasAVX2()) {
7185     // We can't broadcast from a vector register without AVX2, and we can only
7186     // broadcast from the zero-element of a vector register.
7187     return SDValue();
7188   }
7189
7190   return DAG.getNode(X86ISD::VBROADCAST, DL, VT, V);
7191 }
7192
7193 // Check for whether we can use INSERTPS to perform the shuffle. We only use
7194 // INSERTPS when the V1 elements are already in the correct locations
7195 // because otherwise we can just always use two SHUFPS instructions which
7196 // are much smaller to encode than a SHUFPS and an INSERTPS. We can also
7197 // perform INSERTPS if a single V1 element is out of place and all V2
7198 // elements are zeroable.
7199 static SDValue lowerVectorShuffleAsInsertPS(SDValue Op, SDValue V1, SDValue V2,
7200                                             ArrayRef<int> Mask,
7201                                             SelectionDAG &DAG) {
7202   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
7203   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7204   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7205   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7206
7207   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7208
7209   unsigned ZMask = 0;
7210   int V1DstIndex = -1;
7211   int V2DstIndex = -1;
7212   bool V1UsedInPlace = false;
7213
7214   for (int i = 0; i < 4; ++i) {
7215     // Synthesize a zero mask from the zeroable elements (includes undefs).
7216     if (Zeroable[i]) {
7217       ZMask |= 1 << i;
7218       continue;
7219     }
7220
7221     // Flag if we use any V1 inputs in place.
7222     if (i == Mask[i]) {
7223       V1UsedInPlace = true;
7224       continue;
7225     }
7226
7227     // We can only insert a single non-zeroable element.
7228     if (V1DstIndex != -1 || V2DstIndex != -1)
7229       return SDValue();
7230
7231     if (Mask[i] < 4) {
7232       // V1 input out of place for insertion.
7233       V1DstIndex = i;
7234     } else {
7235       // V2 input for insertion.
7236       V2DstIndex = i;
7237     }
7238   }
7239
7240   // Don't bother if we have no (non-zeroable) element for insertion.
7241   if (V1DstIndex == -1 && V2DstIndex == -1)
7242     return SDValue();
7243
7244   // Determine element insertion src/dst indices. The src index is from the
7245   // start of the inserted vector, not the start of the concatenated vector.
7246   unsigned V2SrcIndex = 0;
7247   if (V1DstIndex != -1) {
7248     // If we have a V1 input out of place, we use V1 as the V2 element insertion
7249     // and don't use the original V2 at all.
7250     V2SrcIndex = Mask[V1DstIndex];
7251     V2DstIndex = V1DstIndex;
7252     V2 = V1;
7253   } else {
7254     V2SrcIndex = Mask[V2DstIndex] - 4;
7255   }
7256
7257   // If no V1 inputs are used in place, then the result is created only from
7258   // the zero mask and the V2 insertion - so remove V1 dependency.
7259   if (!V1UsedInPlace)
7260     V1 = DAG.getUNDEF(MVT::v4f32);
7261
7262   unsigned InsertPSMask = V2SrcIndex << 6 | V2DstIndex << 4 | ZMask;
7263   assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
7264
7265   // Insert the V2 element into the desired position.
7266   SDLoc DL(Op);
7267   return DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
7268                      DAG.getConstant(InsertPSMask, DL, MVT::i8));
7269 }
7270
7271 /// \brief Try to lower a shuffle as a permute of the inputs followed by an
7272 /// UNPCK instruction.
7273 ///
7274 /// This specifically targets cases where we end up with alternating between
7275 /// the two inputs, and so can permute them into something that feeds a single
7276 /// UNPCK instruction. Note that this routine only targets integer vectors
7277 /// because for floating point vectors we have a generalized SHUFPS lowering
7278 /// strategy that handles everything that doesn't *exactly* match an unpack,
7279 /// making this clever lowering unnecessary.
7280 static SDValue lowerVectorShuffleAsUnpack(SDLoc DL, MVT VT, SDValue V1,
7281                                           SDValue V2, ArrayRef<int> Mask,
7282                                           SelectionDAG &DAG) {
7283   assert(!VT.isFloatingPoint() &&
7284          "This routine only supports integer vectors.");
7285   assert(!isSingleInputShuffleMask(Mask) &&
7286          "This routine should only be used when blending two inputs.");
7287   assert(Mask.size() >= 2 && "Single element masks are invalid.");
7288
7289   int Size = Mask.size();
7290
7291   int NumLoInputs = std::count_if(Mask.begin(), Mask.end(), [Size](int M) {
7292     return M >= 0 && M % Size < Size / 2;
7293   });
7294   int NumHiInputs = std::count_if(
7295       Mask.begin(), Mask.end(), [Size](int M) { return M % Size >= Size / 2; });
7296
7297   bool UnpackLo = NumLoInputs >= NumHiInputs;
7298
7299   auto TryUnpack = [&](MVT UnpackVT, int Scale) {
7300     SmallVector<int, 32> V1Mask(Mask.size(), -1);
7301     SmallVector<int, 32> V2Mask(Mask.size(), -1);
7302
7303     for (int i = 0; i < Size; ++i) {
7304       if (Mask[i] < 0)
7305         continue;
7306
7307       // Each element of the unpack contains Scale elements from this mask.
7308       int UnpackIdx = i / Scale;
7309
7310       // We only handle the case where V1 feeds the first slots of the unpack.
7311       // We rely on canonicalization to ensure this is the case.
7312       if ((UnpackIdx % 2 == 0) != (Mask[i] < Size))
7313         return SDValue();
7314
7315       // Setup the mask for this input. The indexing is tricky as we have to
7316       // handle the unpack stride.
7317       SmallVectorImpl<int> &VMask = (UnpackIdx % 2 == 0) ? V1Mask : V2Mask;
7318       VMask[(UnpackIdx / 2) * Scale + i % Scale + (UnpackLo ? 0 : Size / 2)] =
7319           Mask[i] % Size;
7320     }
7321
7322     // If we will have to shuffle both inputs to use the unpack, check whether
7323     // we can just unpack first and shuffle the result. If so, skip this unpack.
7324     if ((NumLoInputs == 0 || NumHiInputs == 0) && !isNoopShuffleMask(V1Mask) &&
7325         !isNoopShuffleMask(V2Mask))
7326       return SDValue();
7327
7328     // Shuffle the inputs into place.
7329     V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
7330     V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
7331
7332     // Cast the inputs to the type we will use to unpack them.
7333     V1 = DAG.getNode(ISD::BITCAST, DL, UnpackVT, V1);
7334     V2 = DAG.getNode(ISD::BITCAST, DL, UnpackVT, V2);
7335
7336     // Unpack the inputs and cast the result back to the desired type.
7337     return DAG.getNode(ISD::BITCAST, DL, VT,
7338                        DAG.getNode(UnpackLo ? X86ISD::UNPCKL : X86ISD::UNPCKH,
7339                                    DL, UnpackVT, V1, V2));
7340   };
7341
7342   // We try each unpack from the largest to the smallest to try and find one
7343   // that fits this mask.
7344   int OrigNumElements = VT.getVectorNumElements();
7345   int OrigScalarSize = VT.getScalarSizeInBits();
7346   for (int ScalarSize = 64; ScalarSize >= OrigScalarSize; ScalarSize /= 2) {
7347     int Scale = ScalarSize / OrigScalarSize;
7348     int NumElements = OrigNumElements / Scale;
7349     MVT UnpackVT = MVT::getVectorVT(MVT::getIntegerVT(ScalarSize), NumElements);
7350     if (SDValue Unpack = TryUnpack(UnpackVT, Scale))
7351       return Unpack;
7352   }
7353
7354   // If none of the unpack-rooted lowerings worked (or were profitable) try an
7355   // initial unpack.
7356   if (NumLoInputs == 0 || NumHiInputs == 0) {
7357     assert((NumLoInputs > 0 || NumHiInputs > 0) &&
7358            "We have to have *some* inputs!");
7359     int HalfOffset = NumLoInputs == 0 ? Size / 2 : 0;
7360
7361     // FIXME: We could consider the total complexity of the permute of each
7362     // possible unpacking. Or at the least we should consider how many
7363     // half-crossings are created.
7364     // FIXME: We could consider commuting the unpacks.
7365
7366     SmallVector<int, 32> PermMask;
7367     PermMask.assign(Size, -1);
7368     for (int i = 0; i < Size; ++i) {
7369       if (Mask[i] < 0)
7370         continue;
7371
7372       assert(Mask[i] % Size >= HalfOffset && "Found input from wrong half!");
7373
7374       PermMask[i] =
7375           2 * ((Mask[i] % Size) - HalfOffset) + (Mask[i] < Size ? 0 : 1);
7376     }
7377     return DAG.getVectorShuffle(
7378         VT, DL, DAG.getNode(NumLoInputs == 0 ? X86ISD::UNPCKH : X86ISD::UNPCKL,
7379                             DL, VT, V1, V2),
7380         DAG.getUNDEF(VT), PermMask);
7381   }
7382
7383   return SDValue();
7384 }
7385
7386 /// \brief Handle lowering of 2-lane 64-bit floating point shuffles.
7387 ///
7388 /// This is the basis function for the 2-lane 64-bit shuffles as we have full
7389 /// support for floating point shuffles but not integer shuffles. These
7390 /// instructions will incur a domain crossing penalty on some chips though so
7391 /// it is better to avoid lowering through this for integer vectors where
7392 /// possible.
7393 static SDValue lowerV2F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7394                                        const X86Subtarget *Subtarget,
7395                                        SelectionDAG &DAG) {
7396   SDLoc DL(Op);
7397   assert(Op.getSimpleValueType() == MVT::v2f64 && "Bad shuffle type!");
7398   assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7399   assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7400   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7401   ArrayRef<int> Mask = SVOp->getMask();
7402   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7403
7404   if (isSingleInputShuffleMask(Mask)) {
7405     // Use low duplicate instructions for masks that match their pattern.
7406     if (Subtarget->hasSSE3())
7407       if (isShuffleEquivalent(V1, V2, Mask, {0, 0}))
7408         return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v2f64, V1);
7409
7410     // Straight shuffle of a single input vector. Simulate this by using the
7411     // single input as both of the "inputs" to this instruction..
7412     unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
7413
7414     if (Subtarget->hasAVX()) {
7415       // If we have AVX, we can use VPERMILPS which will allow folding a load
7416       // into the shuffle.
7417       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v2f64, V1,
7418                          DAG.getConstant(SHUFPDMask, DL, MVT::i8));
7419     }
7420
7421     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V1,
7422                        DAG.getConstant(SHUFPDMask, DL, MVT::i8));
7423   }
7424   assert(Mask[0] >= 0 && Mask[0] < 2 && "Non-canonicalized blend!");
7425   assert(Mask[1] >= 2 && "Non-canonicalized blend!");
7426
7427   // If we have a single input, insert that into V1 if we can do so cheaply.
7428   if ((Mask[0] >= 2) + (Mask[1] >= 2) == 1) {
7429     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7430             DL, MVT::v2f64, V1, V2, Mask, Subtarget, DAG))
7431       return Insertion;
7432     // Try inverting the insertion since for v2 masks it is easy to do and we
7433     // can't reliably sort the mask one way or the other.
7434     int InverseMask[2] = {Mask[0] < 0 ? -1 : (Mask[0] ^ 2),
7435                           Mask[1] < 0 ? -1 : (Mask[1] ^ 2)};
7436     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7437             DL, MVT::v2f64, V2, V1, InverseMask, Subtarget, DAG))
7438       return Insertion;
7439   }
7440
7441   // Try to use one of the special instruction patterns to handle two common
7442   // blend patterns if a zero-blend above didn't work.
7443   if (isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
7444       isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7445     if (SDValue V1S = getScalarValueForVectorElement(V1, Mask[0], DAG))
7446       // We can either use a special instruction to load over the low double or
7447       // to move just the low double.
7448       return DAG.getNode(
7449           isShuffleFoldableLoad(V1S) ? X86ISD::MOVLPD : X86ISD::MOVSD,
7450           DL, MVT::v2f64, V2,
7451           DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64, V1S));
7452
7453   if (Subtarget->hasSSE41())
7454     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2f64, V1, V2, Mask,
7455                                                   Subtarget, DAG))
7456       return Blend;
7457
7458   // Use dedicated unpack instructions for masks that match their pattern.
7459   if (isShuffleEquivalent(V1, V2, Mask, {0, 2}))
7460     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2f64, V1, V2);
7461   if (isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7462     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2f64, V1, V2);
7463
7464   unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
7465   return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V2,
7466                      DAG.getConstant(SHUFPDMask, DL, MVT::i8));
7467 }
7468
7469 /// \brief Handle lowering of 2-lane 64-bit integer shuffles.
7470 ///
7471 /// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
7472 /// the integer unit to minimize domain crossing penalties. However, for blends
7473 /// it falls back to the floating point shuffle operation with appropriate bit
7474 /// casting.
7475 static SDValue lowerV2I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7476                                        const X86Subtarget *Subtarget,
7477                                        SelectionDAG &DAG) {
7478   SDLoc DL(Op);
7479   assert(Op.getSimpleValueType() == MVT::v2i64 && "Bad shuffle type!");
7480   assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7481   assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7482   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7483   ArrayRef<int> Mask = SVOp->getMask();
7484   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7485
7486   if (isSingleInputShuffleMask(Mask)) {
7487     // Check for being able to broadcast a single element.
7488     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v2i64, V1,
7489                                                           Mask, Subtarget, DAG))
7490       return Broadcast;
7491
7492     // Straight shuffle of a single input vector. For everything from SSE2
7493     // onward this has a single fast instruction with no scary immediates.
7494     // We have to map the mask as it is actually a v4i32 shuffle instruction.
7495     V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V1);
7496     int WidenedMask[4] = {
7497         std::max(Mask[0], 0) * 2, std::max(Mask[0], 0) * 2 + 1,
7498         std::max(Mask[1], 0) * 2, std::max(Mask[1], 0) * 2 + 1};
7499     return DAG.getNode(
7500         ISD::BITCAST, DL, MVT::v2i64,
7501         DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
7502                     getV4X86ShuffleImm8ForMask(WidenedMask, DL, DAG)));
7503   }
7504   assert(Mask[0] != -1 && "No undef lanes in multi-input v2 shuffles!");
7505   assert(Mask[1] != -1 && "No undef lanes in multi-input v2 shuffles!");
7506   assert(Mask[0] < 2 && "We sort V1 to be the first input.");
7507   assert(Mask[1] >= 2 && "We sort V2 to be the second input.");
7508
7509   // If we have a blend of two PACKUS operations an the blend aligns with the
7510   // low and half halves, we can just merge the PACKUS operations. This is
7511   // particularly important as it lets us merge shuffles that this routine itself
7512   // creates.
7513   auto GetPackNode = [](SDValue V) {
7514     while (V.getOpcode() == ISD::BITCAST)
7515       V = V.getOperand(0);
7516
7517     return V.getOpcode() == X86ISD::PACKUS ? V : SDValue();
7518   };
7519   if (SDValue V1Pack = GetPackNode(V1))
7520     if (SDValue V2Pack = GetPackNode(V2))
7521       return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7522                          DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8,
7523                                      Mask[0] == 0 ? V1Pack.getOperand(0)
7524                                                   : V1Pack.getOperand(1),
7525                                      Mask[1] == 2 ? V2Pack.getOperand(0)
7526                                                   : V2Pack.getOperand(1)));
7527
7528   // Try to use shift instructions.
7529   if (SDValue Shift =
7530           lowerVectorShuffleAsShift(DL, MVT::v2i64, V1, V2, Mask, DAG))
7531     return Shift;
7532
7533   // When loading a scalar and then shuffling it into a vector we can often do
7534   // the insertion cheaply.
7535   if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7536           DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
7537     return Insertion;
7538   // Try inverting the insertion since for v2 masks it is easy to do and we
7539   // can't reliably sort the mask one way or the other.
7540   int InverseMask[2] = {Mask[0] ^ 2, Mask[1] ^ 2};
7541   if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7542           DL, MVT::v2i64, V2, V1, InverseMask, Subtarget, DAG))
7543     return Insertion;
7544
7545   // We have different paths for blend lowering, but they all must use the
7546   // *exact* same predicate.
7547   bool IsBlendSupported = Subtarget->hasSSE41();
7548   if (IsBlendSupported)
7549     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2i64, V1, V2, Mask,
7550                                                   Subtarget, DAG))
7551       return Blend;
7552
7553   // Use dedicated unpack instructions for masks that match their pattern.
7554   if (isShuffleEquivalent(V1, V2, Mask, {0, 2}))
7555     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, V1, V2);
7556   if (isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7557     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2i64, V1, V2);
7558
7559   // Try to use byte rotation instructions.
7560   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
7561   if (Subtarget->hasSSSE3())
7562     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
7563             DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
7564       return Rotate;
7565
7566   // If we have direct support for blends, we should lower by decomposing into
7567   // a permute. That will be faster than the domain cross.
7568   if (IsBlendSupported)
7569     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v2i64, V1, V2,
7570                                                       Mask, DAG);
7571
7572   // We implement this with SHUFPD which is pretty lame because it will likely
7573   // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
7574   // However, all the alternatives are still more cycles and newer chips don't
7575   // have this problem. It would be really nice if x86 had better shuffles here.
7576   V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V1);
7577   V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V2);
7578   return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7579                      DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
7580 }
7581
7582 /// \brief Test whether this can be lowered with a single SHUFPS instruction.
7583 ///
7584 /// This is used to disable more specialized lowerings when the shufps lowering
7585 /// will happen to be efficient.
7586 static bool isSingleSHUFPSMask(ArrayRef<int> Mask) {
7587   // This routine only handles 128-bit shufps.
7588   assert(Mask.size() == 4 && "Unsupported mask size!");
7589
7590   // To lower with a single SHUFPS we need to have the low half and high half
7591   // each requiring a single input.
7592   if (Mask[0] != -1 && Mask[1] != -1 && (Mask[0] < 4) != (Mask[1] < 4))
7593     return false;
7594   if (Mask[2] != -1 && Mask[3] != -1 && (Mask[2] < 4) != (Mask[3] < 4))
7595     return false;
7596
7597   return true;
7598 }
7599
7600 /// \brief Lower a vector shuffle using the SHUFPS instruction.
7601 ///
7602 /// This is a helper routine dedicated to lowering vector shuffles using SHUFPS.
7603 /// It makes no assumptions about whether this is the *best* lowering, it simply
7604 /// uses it.
7605 static SDValue lowerVectorShuffleWithSHUFPS(SDLoc DL, MVT VT,
7606                                             ArrayRef<int> Mask, SDValue V1,
7607                                             SDValue V2, SelectionDAG &DAG) {
7608   SDValue LowV = V1, HighV = V2;
7609   int NewMask[4] = {Mask[0], Mask[1], Mask[2], Mask[3]};
7610
7611   int NumV2Elements =
7612       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7613
7614   if (NumV2Elements == 1) {
7615     int V2Index =
7616         std::find_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; }) -
7617         Mask.begin();
7618
7619     // Compute the index adjacent to V2Index and in the same half by toggling
7620     // the low bit.
7621     int V2AdjIndex = V2Index ^ 1;
7622
7623     if (Mask[V2AdjIndex] == -1) {
7624       // Handles all the cases where we have a single V2 element and an undef.
7625       // This will only ever happen in the high lanes because we commute the
7626       // vector otherwise.
7627       if (V2Index < 2)
7628         std::swap(LowV, HighV);
7629       NewMask[V2Index] -= 4;
7630     } else {
7631       // Handle the case where the V2 element ends up adjacent to a V1 element.
7632       // To make this work, blend them together as the first step.
7633       int V1Index = V2AdjIndex;
7634       int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
7635       V2 = DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
7636                        getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
7637
7638       // Now proceed to reconstruct the final blend as we have the necessary
7639       // high or low half formed.
7640       if (V2Index < 2) {
7641         LowV = V2;
7642         HighV = V1;
7643       } else {
7644         HighV = V2;
7645       }
7646       NewMask[V1Index] = 2; // We put the V1 element in V2[2].
7647       NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
7648     }
7649   } else if (NumV2Elements == 2) {
7650     if (Mask[0] < 4 && Mask[1] < 4) {
7651       // Handle the easy case where we have V1 in the low lanes and V2 in the
7652       // high lanes.
7653       NewMask[2] -= 4;
7654       NewMask[3] -= 4;
7655     } else if (Mask[2] < 4 && Mask[3] < 4) {
7656       // We also handle the reversed case because this utility may get called
7657       // when we detect a SHUFPS pattern but can't easily commute the shuffle to
7658       // arrange things in the right direction.
7659       NewMask[0] -= 4;
7660       NewMask[1] -= 4;
7661       HighV = V1;
7662       LowV = V2;
7663     } else {
7664       // We have a mixture of V1 and V2 in both low and high lanes. Rather than
7665       // trying to place elements directly, just blend them and set up the final
7666       // shuffle to place them.
7667
7668       // The first two blend mask elements are for V1, the second two are for
7669       // V2.
7670       int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
7671                           Mask[2] < 4 ? Mask[2] : Mask[3],
7672                           (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
7673                           (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
7674       V1 = DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
7675                        getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
7676
7677       // Now we do a normal shuffle of V1 by giving V1 as both operands to
7678       // a blend.
7679       LowV = HighV = V1;
7680       NewMask[0] = Mask[0] < 4 ? 0 : 2;
7681       NewMask[1] = Mask[0] < 4 ? 2 : 0;
7682       NewMask[2] = Mask[2] < 4 ? 1 : 3;
7683       NewMask[3] = Mask[2] < 4 ? 3 : 1;
7684     }
7685   }
7686   return DAG.getNode(X86ISD::SHUFP, DL, VT, LowV, HighV,
7687                      getV4X86ShuffleImm8ForMask(NewMask, DL, DAG));
7688 }
7689
7690 /// \brief Lower 4-lane 32-bit floating point shuffles.
7691 ///
7692 /// Uses instructions exclusively from the floating point unit to minimize
7693 /// domain crossing penalties, as these are sufficient to implement all v4f32
7694 /// shuffles.
7695 static SDValue lowerV4F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7696                                        const X86Subtarget *Subtarget,
7697                                        SelectionDAG &DAG) {
7698   SDLoc DL(Op);
7699   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
7700   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7701   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7702   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7703   ArrayRef<int> Mask = SVOp->getMask();
7704   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7705
7706   int NumV2Elements =
7707       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7708
7709   if (NumV2Elements == 0) {
7710     // Check for being able to broadcast a single element.
7711     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f32, V1,
7712                                                           Mask, Subtarget, DAG))
7713       return Broadcast;
7714
7715     // Use even/odd duplicate instructions for masks that match their pattern.
7716     if (Subtarget->hasSSE3()) {
7717       if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
7718         return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v4f32, V1);
7719       if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3}))
7720         return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v4f32, V1);
7721     }
7722
7723     if (Subtarget->hasAVX()) {
7724       // If we have AVX, we can use VPERMILPS which will allow folding a load
7725       // into the shuffle.
7726       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f32, V1,
7727                          getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
7728     }
7729
7730     // Otherwise, use a straight shuffle of a single input vector. We pass the
7731     // input vector to both operands to simulate this with a SHUFPS.
7732     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
7733                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
7734   }
7735
7736   // There are special ways we can lower some single-element blends. However, we
7737   // have custom ways we can lower more complex single-element blends below that
7738   // we defer to if both this and BLENDPS fail to match, so restrict this to
7739   // when the V2 input is targeting element 0 of the mask -- that is the fast
7740   // case here.
7741   if (NumV2Elements == 1 && Mask[0] >= 4)
7742     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4f32, V1, V2,
7743                                                          Mask, Subtarget, DAG))
7744       return V;
7745
7746   if (Subtarget->hasSSE41()) {
7747     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f32, V1, V2, Mask,
7748                                                   Subtarget, DAG))
7749       return Blend;
7750
7751     // Use INSERTPS if we can complete the shuffle efficiently.
7752     if (SDValue V = lowerVectorShuffleAsInsertPS(Op, V1, V2, Mask, DAG))
7753       return V;
7754
7755     if (!isSingleSHUFPSMask(Mask))
7756       if (SDValue BlendPerm = lowerVectorShuffleAsBlendAndPermute(
7757               DL, MVT::v4f32, V1, V2, Mask, DAG))
7758         return BlendPerm;
7759   }
7760
7761   // Use dedicated unpack instructions for masks that match their pattern.
7762   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 1, 5}))
7763     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V1, V2);
7764   if (isShuffleEquivalent(V1, V2, Mask, {2, 6, 3, 7}))
7765     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V1, V2);
7766   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 5, 1}))
7767     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V2, V1);
7768   if (isShuffleEquivalent(V1, V2, Mask, {6, 2, 7, 3}))
7769     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V2, V1);
7770
7771   // Otherwise fall back to a SHUFPS lowering strategy.
7772   return lowerVectorShuffleWithSHUFPS(DL, MVT::v4f32, Mask, V1, V2, DAG);
7773 }
7774
7775 /// \brief Lower 4-lane i32 vector shuffles.
7776 ///
7777 /// We try to handle these with integer-domain shuffles where we can, but for
7778 /// blends we use the floating point domain blend instructions.
7779 static SDValue lowerV4I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7780                                        const X86Subtarget *Subtarget,
7781                                        SelectionDAG &DAG) {
7782   SDLoc DL(Op);
7783   assert(Op.getSimpleValueType() == MVT::v4i32 && "Bad shuffle type!");
7784   assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
7785   assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
7786   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7787   ArrayRef<int> Mask = SVOp->getMask();
7788   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7789
7790   // Whenever we can lower this as a zext, that instruction is strictly faster
7791   // than any alternative. It also allows us to fold memory operands into the
7792   // shuffle in many cases.
7793   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v4i32, V1, V2,
7794                                                          Mask, Subtarget, DAG))
7795     return ZExt;
7796
7797   int NumV2Elements =
7798       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7799
7800   if (NumV2Elements == 0) {
7801     // Check for being able to broadcast a single element.
7802     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i32, V1,
7803                                                           Mask, Subtarget, DAG))
7804       return Broadcast;
7805
7806     // Straight shuffle of a single input vector. For everything from SSE2
7807     // onward this has a single fast instruction with no scary immediates.
7808     // We coerce the shuffle pattern to be compatible with UNPCK instructions
7809     // but we aren't actually going to use the UNPCK instruction because doing
7810     // so prevents folding a load into this instruction or making a copy.
7811     const int UnpackLoMask[] = {0, 0, 1, 1};
7812     const int UnpackHiMask[] = {2, 2, 3, 3};
7813     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 1, 1}))
7814       Mask = UnpackLoMask;
7815     else if (isShuffleEquivalent(V1, V2, Mask, {2, 2, 3, 3}))
7816       Mask = UnpackHiMask;
7817
7818     return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
7819                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
7820   }
7821
7822   // Try to use shift instructions.
7823   if (SDValue Shift =
7824           lowerVectorShuffleAsShift(DL, MVT::v4i32, V1, V2, Mask, DAG))
7825     return Shift;
7826
7827   // There are special ways we can lower some single-element blends.
7828   if (NumV2Elements == 1)
7829     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4i32, V1, V2,
7830                                                          Mask, Subtarget, DAG))
7831       return V;
7832
7833   // We have different paths for blend lowering, but they all must use the
7834   // *exact* same predicate.
7835   bool IsBlendSupported = Subtarget->hasSSE41();
7836   if (IsBlendSupported)
7837     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i32, V1, V2, Mask,
7838                                                   Subtarget, DAG))
7839       return Blend;
7840
7841   if (SDValue Masked =
7842           lowerVectorShuffleAsBitMask(DL, MVT::v4i32, V1, V2, Mask, DAG))
7843     return Masked;
7844
7845   // Use dedicated unpack instructions for masks that match their pattern.
7846   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 1, 5}))
7847     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V1, V2);
7848   if (isShuffleEquivalent(V1, V2, Mask, {2, 6, 3, 7}))
7849     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V1, V2);
7850   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 5, 1}))
7851     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V2, V1);
7852   if (isShuffleEquivalent(V1, V2, Mask, {6, 2, 7, 3}))
7853     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V2, V1);
7854
7855   // Try to use byte rotation instructions.
7856   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
7857   if (Subtarget->hasSSSE3())
7858     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
7859             DL, MVT::v4i32, V1, V2, Mask, Subtarget, DAG))
7860       return Rotate;
7861
7862   // If we have direct support for blends, we should lower by decomposing into
7863   // a permute. That will be faster than the domain cross.
7864   if (IsBlendSupported)
7865     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i32, V1, V2,
7866                                                       Mask, DAG);
7867
7868   // Try to lower by permuting the inputs into an unpack instruction.
7869   if (SDValue Unpack =
7870           lowerVectorShuffleAsUnpack(DL, MVT::v4i32, V1, V2, Mask, DAG))
7871     return Unpack;
7872
7873   // We implement this with SHUFPS because it can blend from two vectors.
7874   // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
7875   // up the inputs, bypassing domain shift penalties that we would encur if we
7876   // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
7877   // relevant.
7878   return DAG.getNode(ISD::BITCAST, DL, MVT::v4i32,
7879                      DAG.getVectorShuffle(
7880                          MVT::v4f32, DL,
7881                          DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V1),
7882                          DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V2), Mask));
7883 }
7884
7885 /// \brief Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
7886 /// shuffle lowering, and the most complex part.
7887 ///
7888 /// The lowering strategy is to try to form pairs of input lanes which are
7889 /// targeted at the same half of the final vector, and then use a dword shuffle
7890 /// to place them onto the right half, and finally unpack the paired lanes into
7891 /// their final position.
7892 ///
7893 /// The exact breakdown of how to form these dword pairs and align them on the
7894 /// correct sides is really tricky. See the comments within the function for
7895 /// more of the details.
7896 ///
7897 /// This code also handles repeated 128-bit lanes of v8i16 shuffles, but each
7898 /// lane must shuffle the *exact* same way. In fact, you must pass a v8 Mask to
7899 /// this routine for it to work correctly. To shuffle a 256-bit or 512-bit i16
7900 /// vector, form the analogous 128-bit 8-element Mask.
7901 static SDValue lowerV8I16GeneralSingleInputVectorShuffle(
7902     SDLoc DL, MVT VT, SDValue V, MutableArrayRef<int> Mask,
7903     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7904   assert(VT.getScalarType() == MVT::i16 && "Bad input type!");
7905   MVT PSHUFDVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
7906
7907   assert(Mask.size() == 8 && "Shuffle mask length doen't match!");
7908   MutableArrayRef<int> LoMask = Mask.slice(0, 4);
7909   MutableArrayRef<int> HiMask = Mask.slice(4, 4);
7910
7911   SmallVector<int, 4> LoInputs;
7912   std::copy_if(LoMask.begin(), LoMask.end(), std::back_inserter(LoInputs),
7913                [](int M) { return M >= 0; });
7914   std::sort(LoInputs.begin(), LoInputs.end());
7915   LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()), LoInputs.end());
7916   SmallVector<int, 4> HiInputs;
7917   std::copy_if(HiMask.begin(), HiMask.end(), std::back_inserter(HiInputs),
7918                [](int M) { return M >= 0; });
7919   std::sort(HiInputs.begin(), HiInputs.end());
7920   HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()), HiInputs.end());
7921   int NumLToL =
7922       std::lower_bound(LoInputs.begin(), LoInputs.end(), 4) - LoInputs.begin();
7923   int NumHToL = LoInputs.size() - NumLToL;
7924   int NumLToH =
7925       std::lower_bound(HiInputs.begin(), HiInputs.end(), 4) - HiInputs.begin();
7926   int NumHToH = HiInputs.size() - NumLToH;
7927   MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
7928   MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
7929   MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
7930   MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
7931
7932   // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
7933   // such inputs we can swap two of the dwords across the half mark and end up
7934   // with <=2 inputs to each half in each half. Once there, we can fall through
7935   // to the generic code below. For example:
7936   //
7937   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
7938   // Mask:  [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
7939   //
7940   // However in some very rare cases we have a 1-into-3 or 3-into-1 on one half
7941   // and an existing 2-into-2 on the other half. In this case we may have to
7942   // pre-shuffle the 2-into-2 half to avoid turning it into a 3-into-1 or
7943   // 1-into-3 which could cause us to cycle endlessly fixing each side in turn.
7944   // Fortunately, we don't have to handle anything but a 2-into-2 pattern
7945   // because any other situation (including a 3-into-1 or 1-into-3 in the other
7946   // half than the one we target for fixing) will be fixed when we re-enter this
7947   // path. We will also combine away any sequence of PSHUFD instructions that
7948   // result into a single instruction. Here is an example of the tricky case:
7949   //
7950   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
7951   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -THIS-IS-BAD!!!!-> [5, 7, 1, 0, 4, 7, 5, 3]
7952   //
7953   // This now has a 1-into-3 in the high half! Instead, we do two shuffles:
7954   //
7955   // Input: [a, b, c, d, e, f, g, h] PSHUFHW[0,2,1,3]-> [a, b, c, d, e, g, f, h]
7956   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -----------------> [3, 7, 1, 0, 2, 7, 3, 6]
7957   //
7958   // Input: [a, b, c, d, e, g, f, h] -PSHUFD[0,2,1,3]-> [a, b, e, g, c, d, f, h]
7959   // Mask:  [3, 7, 1, 0, 2, 7, 3, 6] -----------------> [5, 7, 1, 0, 4, 7, 5, 6]
7960   //
7961   // The result is fine to be handled by the generic logic.
7962   auto balanceSides = [&](ArrayRef<int> AToAInputs, ArrayRef<int> BToAInputs,
7963                           ArrayRef<int> BToBInputs, ArrayRef<int> AToBInputs,
7964                           int AOffset, int BOffset) {
7965     assert((AToAInputs.size() == 3 || AToAInputs.size() == 1) &&
7966            "Must call this with A having 3 or 1 inputs from the A half.");
7967     assert((BToAInputs.size() == 1 || BToAInputs.size() == 3) &&
7968            "Must call this with B having 1 or 3 inputs from the B half.");
7969     assert(AToAInputs.size() + BToAInputs.size() == 4 &&
7970            "Must call this with either 3:1 or 1:3 inputs (summing to 4).");
7971
7972     // Compute the index of dword with only one word among the three inputs in
7973     // a half by taking the sum of the half with three inputs and subtracting
7974     // the sum of the actual three inputs. The difference is the remaining
7975     // slot.
7976     int ADWord, BDWord;
7977     int &TripleDWord = AToAInputs.size() == 3 ? ADWord : BDWord;
7978     int &OneInputDWord = AToAInputs.size() == 3 ? BDWord : ADWord;
7979     int TripleInputOffset = AToAInputs.size() == 3 ? AOffset : BOffset;
7980     ArrayRef<int> TripleInputs = AToAInputs.size() == 3 ? AToAInputs : BToAInputs;
7981     int OneInput = AToAInputs.size() == 3 ? BToAInputs[0] : AToAInputs[0];
7982     int TripleInputSum = 0 + 1 + 2 + 3 + (4 * TripleInputOffset);
7983     int TripleNonInputIdx =
7984         TripleInputSum - std::accumulate(TripleInputs.begin(), TripleInputs.end(), 0);
7985     TripleDWord = TripleNonInputIdx / 2;
7986
7987     // We use xor with one to compute the adjacent DWord to whichever one the
7988     // OneInput is in.
7989     OneInputDWord = (OneInput / 2) ^ 1;
7990
7991     // Check for one tricky case: We're fixing a 3<-1 or a 1<-3 shuffle for AToA
7992     // and BToA inputs. If there is also such a problem with the BToB and AToB
7993     // inputs, we don't try to fix it necessarily -- we'll recurse and see it in
7994     // the next pass. However, if we have a 2<-2 in the BToB and AToB inputs, it
7995     // is essential that we don't *create* a 3<-1 as then we might oscillate.
7996     if (BToBInputs.size() == 2 && AToBInputs.size() == 2) {
7997       // Compute how many inputs will be flipped by swapping these DWords. We
7998       // need
7999       // to balance this to ensure we don't form a 3-1 shuffle in the other
8000       // half.
8001       int NumFlippedAToBInputs =
8002           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord) +
8003           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord + 1);
8004       int NumFlippedBToBInputs =
8005           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord) +
8006           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord + 1);
8007       if ((NumFlippedAToBInputs == 1 &&
8008            (NumFlippedBToBInputs == 0 || NumFlippedBToBInputs == 2)) ||
8009           (NumFlippedBToBInputs == 1 &&
8010            (NumFlippedAToBInputs == 0 || NumFlippedAToBInputs == 2))) {
8011         // We choose whether to fix the A half or B half based on whether that
8012         // half has zero flipped inputs. At zero, we may not be able to fix it
8013         // with that half. We also bias towards fixing the B half because that
8014         // will more commonly be the high half, and we have to bias one way.
8015         auto FixFlippedInputs = [&V, &DL, &Mask, &DAG](int PinnedIdx, int DWord,
8016                                                        ArrayRef<int> Inputs) {
8017           int FixIdx = PinnedIdx ^ 1; // The adjacent slot to the pinned slot.
8018           bool IsFixIdxInput = std::find(Inputs.begin(), Inputs.end(),
8019                                          PinnedIdx ^ 1) != Inputs.end();
8020           // Determine whether the free index is in the flipped dword or the
8021           // unflipped dword based on where the pinned index is. We use this bit
8022           // in an xor to conditionally select the adjacent dword.
8023           int FixFreeIdx = 2 * (DWord ^ (PinnedIdx / 2 == DWord));
8024           bool IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
8025                                              FixFreeIdx) != Inputs.end();
8026           if (IsFixIdxInput == IsFixFreeIdxInput)
8027             FixFreeIdx += 1;
8028           IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
8029                                         FixFreeIdx) != Inputs.end();
8030           assert(IsFixIdxInput != IsFixFreeIdxInput &&
8031                  "We need to be changing the number of flipped inputs!");
8032           int PSHUFHalfMask[] = {0, 1, 2, 3};
8033           std::swap(PSHUFHalfMask[FixFreeIdx % 4], PSHUFHalfMask[FixIdx % 4]);
8034           V = DAG.getNode(FixIdx < 4 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW, DL,
8035                           MVT::v8i16, V,
8036                           getV4X86ShuffleImm8ForMask(PSHUFHalfMask, DL, DAG));
8037
8038           for (int &M : Mask)
8039             if (M != -1 && M == FixIdx)
8040               M = FixFreeIdx;
8041             else if (M != -1 && M == FixFreeIdx)
8042               M = FixIdx;
8043         };
8044         if (NumFlippedBToBInputs != 0) {
8045           int BPinnedIdx =
8046               BToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
8047           FixFlippedInputs(BPinnedIdx, BDWord, BToBInputs);
8048         } else {
8049           assert(NumFlippedAToBInputs != 0 && "Impossible given predicates!");
8050           int APinnedIdx =
8051               AToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
8052           FixFlippedInputs(APinnedIdx, ADWord, AToBInputs);
8053         }
8054       }
8055     }
8056
8057     int PSHUFDMask[] = {0, 1, 2, 3};
8058     PSHUFDMask[ADWord] = BDWord;
8059     PSHUFDMask[BDWord] = ADWord;
8060     V = DAG.getNode(ISD::BITCAST, DL, VT,
8061                     DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT,
8062                                 DAG.getNode(ISD::BITCAST, DL, PSHUFDVT, V),
8063                                 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL,
8064                                                            DAG)));
8065
8066     // Adjust the mask to match the new locations of A and B.
8067     for (int &M : Mask)
8068       if (M != -1 && M/2 == ADWord)
8069         M = 2 * BDWord + M % 2;
8070       else if (M != -1 && M/2 == BDWord)
8071         M = 2 * ADWord + M % 2;
8072
8073     // Recurse back into this routine to re-compute state now that this isn't
8074     // a 3 and 1 problem.
8075     return lowerV8I16GeneralSingleInputVectorShuffle(DL, VT, V, Mask, Subtarget,
8076                                                      DAG);
8077   };
8078   if ((NumLToL == 3 && NumHToL == 1) || (NumLToL == 1 && NumHToL == 3))
8079     return balanceSides(LToLInputs, HToLInputs, HToHInputs, LToHInputs, 0, 4);
8080   else if ((NumHToH == 3 && NumLToH == 1) || (NumHToH == 1 && NumLToH == 3))
8081     return balanceSides(HToHInputs, LToHInputs, LToLInputs, HToLInputs, 4, 0);
8082
8083   // At this point there are at most two inputs to the low and high halves from
8084   // each half. That means the inputs can always be grouped into dwords and
8085   // those dwords can then be moved to the correct half with a dword shuffle.
8086   // We use at most one low and one high word shuffle to collect these paired
8087   // inputs into dwords, and finally a dword shuffle to place them.
8088   int PSHUFLMask[4] = {-1, -1, -1, -1};
8089   int PSHUFHMask[4] = {-1, -1, -1, -1};
8090   int PSHUFDMask[4] = {-1, -1, -1, -1};
8091
8092   // First fix the masks for all the inputs that are staying in their
8093   // original halves. This will then dictate the targets of the cross-half
8094   // shuffles.
8095   auto fixInPlaceInputs =
8096       [&PSHUFDMask](ArrayRef<int> InPlaceInputs, ArrayRef<int> IncomingInputs,
8097                     MutableArrayRef<int> SourceHalfMask,
8098                     MutableArrayRef<int> HalfMask, int HalfOffset) {
8099     if (InPlaceInputs.empty())
8100       return;
8101     if (InPlaceInputs.size() == 1) {
8102       SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8103           InPlaceInputs[0] - HalfOffset;
8104       PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
8105       return;
8106     }
8107     if (IncomingInputs.empty()) {
8108       // Just fix all of the in place inputs.
8109       for (int Input : InPlaceInputs) {
8110         SourceHalfMask[Input - HalfOffset] = Input - HalfOffset;
8111         PSHUFDMask[Input / 2] = Input / 2;
8112       }
8113       return;
8114     }
8115
8116     assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!");
8117     SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8118         InPlaceInputs[0] - HalfOffset;
8119     // Put the second input next to the first so that they are packed into
8120     // a dword. We find the adjacent index by toggling the low bit.
8121     int AdjIndex = InPlaceInputs[0] ^ 1;
8122     SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
8123     std::replace(HalfMask.begin(), HalfMask.end(), InPlaceInputs[1], AdjIndex);
8124     PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
8125   };
8126   fixInPlaceInputs(LToLInputs, HToLInputs, PSHUFLMask, LoMask, 0);
8127   fixInPlaceInputs(HToHInputs, LToHInputs, PSHUFHMask, HiMask, 4);
8128
8129   // Now gather the cross-half inputs and place them into a free dword of
8130   // their target half.
8131   // FIXME: This operation could almost certainly be simplified dramatically to
8132   // look more like the 3-1 fixing operation.
8133   auto moveInputsToRightHalf = [&PSHUFDMask](
8134       MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
8135       MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
8136       MutableArrayRef<int> FinalSourceHalfMask, int SourceOffset,
8137       int DestOffset) {
8138     auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
8139       return SourceHalfMask[Word] != -1 && SourceHalfMask[Word] != Word;
8140     };
8141     auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
8142                                                int Word) {
8143       int LowWord = Word & ~1;
8144       int HighWord = Word | 1;
8145       return isWordClobbered(SourceHalfMask, LowWord) ||
8146              isWordClobbered(SourceHalfMask, HighWord);
8147     };
8148
8149     if (IncomingInputs.empty())
8150       return;
8151
8152     if (ExistingInputs.empty()) {
8153       // Map any dwords with inputs from them into the right half.
8154       for (int Input : IncomingInputs) {
8155         // If the source half mask maps over the inputs, turn those into
8156         // swaps and use the swapped lane.
8157         if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
8158           if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] == -1) {
8159             SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
8160                 Input - SourceOffset;
8161             // We have to swap the uses in our half mask in one sweep.
8162             for (int &M : HalfMask)
8163               if (M == SourceHalfMask[Input - SourceOffset] + SourceOffset)
8164                 M = Input;
8165               else if (M == Input)
8166                 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8167           } else {
8168             assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==
8169                        Input - SourceOffset &&
8170                    "Previous placement doesn't match!");
8171           }
8172           // Note that this correctly re-maps both when we do a swap and when
8173           // we observe the other side of the swap above. We rely on that to
8174           // avoid swapping the members of the input list directly.
8175           Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8176         }
8177
8178         // Map the input's dword into the correct half.
8179         if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] == -1)
8180           PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
8181         else
8182           assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==
8183                      Input / 2 &&
8184                  "Previous placement doesn't match!");
8185       }
8186
8187       // And just directly shift any other-half mask elements to be same-half
8188       // as we will have mirrored the dword containing the element into the
8189       // same position within that half.
8190       for (int &M : HalfMask)
8191         if (M >= SourceOffset && M < SourceOffset + 4) {
8192           M = M - SourceOffset + DestOffset;
8193           assert(M >= 0 && "This should never wrap below zero!");
8194         }
8195       return;
8196     }
8197
8198     // Ensure we have the input in a viable dword of its current half. This
8199     // is particularly tricky because the original position may be clobbered
8200     // by inputs being moved and *staying* in that half.
8201     if (IncomingInputs.size() == 1) {
8202       if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8203         int InputFixed = std::find(std::begin(SourceHalfMask),
8204                                    std::end(SourceHalfMask), -1) -
8205                          std::begin(SourceHalfMask) + SourceOffset;
8206         SourceHalfMask[InputFixed - SourceOffset] =
8207             IncomingInputs[0] - SourceOffset;
8208         std::replace(HalfMask.begin(), HalfMask.end(), IncomingInputs[0],
8209                      InputFixed);
8210         IncomingInputs[0] = InputFixed;
8211       }
8212     } else if (IncomingInputs.size() == 2) {
8213       if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
8214           isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8215         // We have two non-adjacent or clobbered inputs we need to extract from
8216         // the source half. To do this, we need to map them into some adjacent
8217         // dword slot in the source mask.
8218         int InputsFixed[2] = {IncomingInputs[0] - SourceOffset,
8219                               IncomingInputs[1] - SourceOffset};
8220
8221         // If there is a free slot in the source half mask adjacent to one of
8222         // the inputs, place the other input in it. We use (Index XOR 1) to
8223         // compute an adjacent index.
8224         if (!isWordClobbered(SourceHalfMask, InputsFixed[0]) &&
8225             SourceHalfMask[InputsFixed[0] ^ 1] == -1) {
8226           SourceHalfMask[InputsFixed[0]] = InputsFixed[0];
8227           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8228           InputsFixed[1] = InputsFixed[0] ^ 1;
8229         } else if (!isWordClobbered(SourceHalfMask, InputsFixed[1]) &&
8230                    SourceHalfMask[InputsFixed[1] ^ 1] == -1) {
8231           SourceHalfMask[InputsFixed[1]] = InputsFixed[1];
8232           SourceHalfMask[InputsFixed[1] ^ 1] = InputsFixed[0];
8233           InputsFixed[0] = InputsFixed[1] ^ 1;
8234         } else if (SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] == -1 &&
8235                    SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] == -1) {
8236           // The two inputs are in the same DWord but it is clobbered and the
8237           // adjacent DWord isn't used at all. Move both inputs to the free
8238           // slot.
8239           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] = InputsFixed[0];
8240           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] = InputsFixed[1];
8241           InputsFixed[0] = 2 * ((InputsFixed[0] / 2) ^ 1);
8242           InputsFixed[1] = 2 * ((InputsFixed[0] / 2) ^ 1) + 1;
8243         } else {
8244           // The only way we hit this point is if there is no clobbering
8245           // (because there are no off-half inputs to this half) and there is no
8246           // free slot adjacent to one of the inputs. In this case, we have to
8247           // swap an input with a non-input.
8248           for (int i = 0; i < 4; ++i)
8249             assert((SourceHalfMask[i] == -1 || SourceHalfMask[i] == i) &&
8250                    "We can't handle any clobbers here!");
8251           assert(InputsFixed[1] != (InputsFixed[0] ^ 1) &&
8252                  "Cannot have adjacent inputs here!");
8253
8254           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8255           SourceHalfMask[InputsFixed[1]] = InputsFixed[0] ^ 1;
8256
8257           // We also have to update the final source mask in this case because
8258           // it may need to undo the above swap.
8259           for (int &M : FinalSourceHalfMask)
8260             if (M == (InputsFixed[0] ^ 1) + SourceOffset)
8261               M = InputsFixed[1] + SourceOffset;
8262             else if (M == InputsFixed[1] + SourceOffset)
8263               M = (InputsFixed[0] ^ 1) + SourceOffset;
8264
8265           InputsFixed[1] = InputsFixed[0] ^ 1;
8266         }
8267
8268         // Point everything at the fixed inputs.
8269         for (int &M : HalfMask)
8270           if (M == IncomingInputs[0])
8271             M = InputsFixed[0] + SourceOffset;
8272           else if (M == IncomingInputs[1])
8273             M = InputsFixed[1] + SourceOffset;
8274
8275         IncomingInputs[0] = InputsFixed[0] + SourceOffset;
8276         IncomingInputs[1] = InputsFixed[1] + SourceOffset;
8277       }
8278     } else {
8279       llvm_unreachable("Unhandled input size!");
8280     }
8281
8282     // Now hoist the DWord down to the right half.
8283     int FreeDWord = (PSHUFDMask[DestOffset / 2] == -1 ? 0 : 1) + DestOffset / 2;
8284     assert(PSHUFDMask[FreeDWord] == -1 && "DWord not free");
8285     PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
8286     for (int &M : HalfMask)
8287       for (int Input : IncomingInputs)
8288         if (M == Input)
8289           M = FreeDWord * 2 + Input % 2;
8290   };
8291   moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask, HiMask,
8292                         /*SourceOffset*/ 4, /*DestOffset*/ 0);
8293   moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask, LoMask,
8294                         /*SourceOffset*/ 0, /*DestOffset*/ 4);
8295
8296   // Now enact all the shuffles we've computed to move the inputs into their
8297   // target half.
8298   if (!isNoopShuffleMask(PSHUFLMask))
8299     V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
8300                     getV4X86ShuffleImm8ForMask(PSHUFLMask, DL, DAG));
8301   if (!isNoopShuffleMask(PSHUFHMask))
8302     V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
8303                     getV4X86ShuffleImm8ForMask(PSHUFHMask, DL, DAG));
8304   if (!isNoopShuffleMask(PSHUFDMask))
8305     V = DAG.getNode(ISD::BITCAST, DL, VT,
8306                     DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT,
8307                                 DAG.getNode(ISD::BITCAST, DL, PSHUFDVT, V),
8308                                 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL,
8309                                                            DAG)));
8310
8311   // At this point, each half should contain all its inputs, and we can then
8312   // just shuffle them into their final position.
8313   assert(std::count_if(LoMask.begin(), LoMask.end(),
8314                        [](int M) { return M >= 4; }) == 0 &&
8315          "Failed to lift all the high half inputs to the low mask!");
8316   assert(std::count_if(HiMask.begin(), HiMask.end(),
8317                        [](int M) { return M >= 0 && M < 4; }) == 0 &&
8318          "Failed to lift all the low half inputs to the high mask!");
8319
8320   // Do a half shuffle for the low mask.
8321   if (!isNoopShuffleMask(LoMask))
8322     V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
8323                     getV4X86ShuffleImm8ForMask(LoMask, DL, DAG));
8324
8325   // Do a half shuffle with the high mask after shifting its values down.
8326   for (int &M : HiMask)
8327     if (M >= 0)
8328       M -= 4;
8329   if (!isNoopShuffleMask(HiMask))
8330     V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
8331                     getV4X86ShuffleImm8ForMask(HiMask, DL, DAG));
8332
8333   return V;
8334 }
8335
8336 /// \brief Helper to form a PSHUFB-based shuffle+blend.
8337 static SDValue lowerVectorShuffleAsPSHUFB(SDLoc DL, MVT VT, SDValue V1,
8338                                           SDValue V2, ArrayRef<int> Mask,
8339                                           SelectionDAG &DAG, bool &V1InUse,
8340                                           bool &V2InUse) {
8341   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
8342   SDValue V1Mask[16];
8343   SDValue V2Mask[16];
8344   V1InUse = false;
8345   V2InUse = false;
8346
8347   int Size = Mask.size();
8348   int Scale = 16 / Size;
8349   for (int i = 0; i < 16; ++i) {
8350     if (Mask[i / Scale] == -1) {
8351       V1Mask[i] = V2Mask[i] = DAG.getUNDEF(MVT::i8);
8352     } else {
8353       const int ZeroMask = 0x80;
8354       int V1Idx = Mask[i / Scale] < Size ? Mask[i / Scale] * Scale + i % Scale
8355                                           : ZeroMask;
8356       int V2Idx = Mask[i / Scale] < Size
8357                       ? ZeroMask
8358                       : (Mask[i / Scale] - Size) * Scale + i % Scale;
8359       if (Zeroable[i / Scale])
8360         V1Idx = V2Idx = ZeroMask;
8361       V1Mask[i] = DAG.getConstant(V1Idx, DL, MVT::i8);
8362       V2Mask[i] = DAG.getConstant(V2Idx, DL, MVT::i8);
8363       V1InUse |= (ZeroMask != V1Idx);
8364       V2InUse |= (ZeroMask != V2Idx);
8365     }
8366   }
8367
8368   if (V1InUse)
8369     V1 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
8370                      DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, V1),
8371                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V1Mask));
8372   if (V2InUse)
8373     V2 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
8374                      DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, V2),
8375                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V2Mask));
8376
8377   // If we need shuffled inputs from both, blend the two.
8378   SDValue V;
8379   if (V1InUse && V2InUse)
8380     V = DAG.getNode(ISD::OR, DL, MVT::v16i8, V1, V2);
8381   else
8382     V = V1InUse ? V1 : V2;
8383
8384   // Cast the result back to the correct type.
8385   return DAG.getNode(ISD::BITCAST, DL, VT, V);
8386 }
8387
8388 /// \brief Generic lowering of 8-lane i16 shuffles.
8389 ///
8390 /// This handles both single-input shuffles and combined shuffle/blends with
8391 /// two inputs. The single input shuffles are immediately delegated to
8392 /// a dedicated lowering routine.
8393 ///
8394 /// The blends are lowered in one of three fundamental ways. If there are few
8395 /// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
8396 /// of the input is significantly cheaper when lowered as an interleaving of
8397 /// the two inputs, try to interleave them. Otherwise, blend the low and high
8398 /// halves of the inputs separately (making them have relatively few inputs)
8399 /// and then concatenate them.
8400 static SDValue lowerV8I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8401                                        const X86Subtarget *Subtarget,
8402                                        SelectionDAG &DAG) {
8403   SDLoc DL(Op);
8404   assert(Op.getSimpleValueType() == MVT::v8i16 && "Bad shuffle type!");
8405   assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
8406   assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
8407   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8408   ArrayRef<int> OrigMask = SVOp->getMask();
8409   int MaskStorage[8] = {OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
8410                         OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7]};
8411   MutableArrayRef<int> Mask(MaskStorage);
8412
8413   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
8414
8415   // Whenever we can lower this as a zext, that instruction is strictly faster
8416   // than any alternative.
8417   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
8418           DL, MVT::v8i16, V1, V2, OrigMask, Subtarget, DAG))
8419     return ZExt;
8420
8421   auto isV1 = [](int M) { return M >= 0 && M < 8; };
8422   (void)isV1;
8423   auto isV2 = [](int M) { return M >= 8; };
8424
8425   int NumV2Inputs = std::count_if(Mask.begin(), Mask.end(), isV2);
8426
8427   if (NumV2Inputs == 0) {
8428     // Check for being able to broadcast a single element.
8429     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i16, V1,
8430                                                           Mask, Subtarget, DAG))
8431       return Broadcast;
8432
8433     // Try to use shift instructions.
8434     if (SDValue Shift =
8435             lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V1, Mask, DAG))
8436       return Shift;
8437
8438     // Use dedicated unpack instructions for masks that match their pattern.
8439     if (isShuffleEquivalent(V1, V1, Mask, {0, 0, 1, 1, 2, 2, 3, 3}))
8440       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V1, V1);
8441     if (isShuffleEquivalent(V1, V1, Mask, {4, 4, 5, 5, 6, 6, 7, 7}))
8442       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V1, V1);
8443
8444     // Try to use byte rotation instructions.
8445     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(DL, MVT::v8i16, V1, V1,
8446                                                         Mask, Subtarget, DAG))
8447       return Rotate;
8448
8449     return lowerV8I16GeneralSingleInputVectorShuffle(DL, MVT::v8i16, V1, Mask,
8450                                                      Subtarget, DAG);
8451   }
8452
8453   assert(std::any_of(Mask.begin(), Mask.end(), isV1) &&
8454          "All single-input shuffles should be canonicalized to be V1-input "
8455          "shuffles.");
8456
8457   // Try to use shift instructions.
8458   if (SDValue Shift =
8459           lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V2, Mask, DAG))
8460     return Shift;
8461
8462   // There are special ways we can lower some single-element blends.
8463   if (NumV2Inputs == 1)
8464     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v8i16, V1, V2,
8465                                                          Mask, Subtarget, DAG))
8466       return V;
8467
8468   // We have different paths for blend lowering, but they all must use the
8469   // *exact* same predicate.
8470   bool IsBlendSupported = Subtarget->hasSSE41();
8471   if (IsBlendSupported)
8472     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i16, V1, V2, Mask,
8473                                                   Subtarget, DAG))
8474       return Blend;
8475
8476   if (SDValue Masked =
8477           lowerVectorShuffleAsBitMask(DL, MVT::v8i16, V1, V2, Mask, DAG))
8478     return Masked;
8479
8480   // Use dedicated unpack instructions for masks that match their pattern.
8481   if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 2, 10, 3, 11}))
8482     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V1, V2);
8483   if (isShuffleEquivalent(V1, V2, Mask, {4, 12, 5, 13, 6, 14, 7, 15}))
8484     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V1, V2);
8485
8486   // Try to use byte rotation instructions.
8487   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8488           DL, MVT::v8i16, V1, V2, Mask, Subtarget, DAG))
8489     return Rotate;
8490
8491   if (SDValue BitBlend =
8492           lowerVectorShuffleAsBitBlend(DL, MVT::v8i16, V1, V2, Mask, DAG))
8493     return BitBlend;
8494
8495   if (SDValue Unpack =
8496           lowerVectorShuffleAsUnpack(DL, MVT::v8i16, V1, V2, Mask, DAG))
8497     return Unpack;
8498
8499   // If we can't directly blend but can use PSHUFB, that will be better as it
8500   // can both shuffle and set up the inefficient blend.
8501   if (!IsBlendSupported && Subtarget->hasSSSE3()) {
8502     bool V1InUse, V2InUse;
8503     return lowerVectorShuffleAsPSHUFB(DL, MVT::v8i16, V1, V2, Mask, DAG,
8504                                       V1InUse, V2InUse);
8505   }
8506
8507   // We can always bit-blend if we have to so the fallback strategy is to
8508   // decompose into single-input permutes and blends.
8509   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i16, V1, V2,
8510                                                       Mask, DAG);
8511 }
8512
8513 /// \brief Check whether a compaction lowering can be done by dropping even
8514 /// elements and compute how many times even elements must be dropped.
8515 ///
8516 /// This handles shuffles which take every Nth element where N is a power of
8517 /// two. Example shuffle masks:
8518 ///
8519 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14,  0,  2,  4,  6,  8, 10, 12, 14
8520 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30
8521 ///  N = 2:  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12
8522 ///  N = 2:  0,  4,  8, 12, 16, 20, 24, 28,  0,  4,  8, 12, 16, 20, 24, 28
8523 ///  N = 3:  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8
8524 ///  N = 3:  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24
8525 ///
8526 /// Any of these lanes can of course be undef.
8527 ///
8528 /// This routine only supports N <= 3.
8529 /// FIXME: Evaluate whether either AVX or AVX-512 have any opportunities here
8530 /// for larger N.
8531 ///
8532 /// \returns N above, or the number of times even elements must be dropped if
8533 /// there is such a number. Otherwise returns zero.
8534 static int canLowerByDroppingEvenElements(ArrayRef<int> Mask) {
8535   // Figure out whether we're looping over two inputs or just one.
8536   bool IsSingleInput = isSingleInputShuffleMask(Mask);
8537
8538   // The modulus for the shuffle vector entries is based on whether this is
8539   // a single input or not.
8540   int ShuffleModulus = Mask.size() * (IsSingleInput ? 1 : 2);
8541   assert(isPowerOf2_32((uint32_t)ShuffleModulus) &&
8542          "We should only be called with masks with a power-of-2 size!");
8543
8544   uint64_t ModMask = (uint64_t)ShuffleModulus - 1;
8545
8546   // We track whether the input is viable for all power-of-2 strides 2^1, 2^2,
8547   // and 2^3 simultaneously. This is because we may have ambiguity with
8548   // partially undef inputs.
8549   bool ViableForN[3] = {true, true, true};
8550
8551   for (int i = 0, e = Mask.size(); i < e; ++i) {
8552     // Ignore undef lanes, we'll optimistically collapse them to the pattern we
8553     // want.
8554     if (Mask[i] == -1)
8555       continue;
8556
8557     bool IsAnyViable = false;
8558     for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
8559       if (ViableForN[j]) {
8560         uint64_t N = j + 1;
8561
8562         // The shuffle mask must be equal to (i * 2^N) % M.
8563         if ((uint64_t)Mask[i] == (((uint64_t)i << N) & ModMask))
8564           IsAnyViable = true;
8565         else
8566           ViableForN[j] = false;
8567       }
8568     // Early exit if we exhaust the possible powers of two.
8569     if (!IsAnyViable)
8570       break;
8571   }
8572
8573   for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
8574     if (ViableForN[j])
8575       return j + 1;
8576
8577   // Return 0 as there is no viable power of two.
8578   return 0;
8579 }
8580
8581 /// \brief Generic lowering of v16i8 shuffles.
8582 ///
8583 /// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
8584 /// detect any complexity reducing interleaving. If that doesn't help, it uses
8585 /// UNPCK to spread the i8 elements across two i16-element vectors, and uses
8586 /// the existing lowering for v8i16 blends on each half, finally PACK-ing them
8587 /// back together.
8588 static SDValue lowerV16I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8589                                        const X86Subtarget *Subtarget,
8590                                        SelectionDAG &DAG) {
8591   SDLoc DL(Op);
8592   assert(Op.getSimpleValueType() == MVT::v16i8 && "Bad shuffle type!");
8593   assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
8594   assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
8595   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8596   ArrayRef<int> Mask = SVOp->getMask();
8597   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
8598
8599   // Try to use shift instructions.
8600   if (SDValue Shift =
8601           lowerVectorShuffleAsShift(DL, MVT::v16i8, V1, V2, Mask, DAG))
8602     return Shift;
8603
8604   // Try to use byte rotation instructions.
8605   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8606           DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
8607     return Rotate;
8608
8609   // Try to use a zext lowering.
8610   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
8611           DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
8612     return ZExt;
8613
8614   int NumV2Elements =
8615       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 16; });
8616
8617   // For single-input shuffles, there are some nicer lowering tricks we can use.
8618   if (NumV2Elements == 0) {
8619     // Check for being able to broadcast a single element.
8620     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i8, V1,
8621                                                           Mask, Subtarget, DAG))
8622       return Broadcast;
8623
8624     // Check whether we can widen this to an i16 shuffle by duplicating bytes.
8625     // Notably, this handles splat and partial-splat shuffles more efficiently.
8626     // However, it only makes sense if the pre-duplication shuffle simplifies
8627     // things significantly. Currently, this means we need to be able to
8628     // express the pre-duplication shuffle as an i16 shuffle.
8629     //
8630     // FIXME: We should check for other patterns which can be widened into an
8631     // i16 shuffle as well.
8632     auto canWidenViaDuplication = [](ArrayRef<int> Mask) {
8633       for (int i = 0; i < 16; i += 2)
8634         if (Mask[i] != -1 && Mask[i + 1] != -1 && Mask[i] != Mask[i + 1])
8635           return false;
8636
8637       return true;
8638     };
8639     auto tryToWidenViaDuplication = [&]() -> SDValue {
8640       if (!canWidenViaDuplication(Mask))
8641         return SDValue();
8642       SmallVector<int, 4> LoInputs;
8643       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(LoInputs),
8644                    [](int M) { return M >= 0 && M < 8; });
8645       std::sort(LoInputs.begin(), LoInputs.end());
8646       LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()),
8647                      LoInputs.end());
8648       SmallVector<int, 4> HiInputs;
8649       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(HiInputs),
8650                    [](int M) { return M >= 8; });
8651       std::sort(HiInputs.begin(), HiInputs.end());
8652       HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()),
8653                      HiInputs.end());
8654
8655       bool TargetLo = LoInputs.size() >= HiInputs.size();
8656       ArrayRef<int> InPlaceInputs = TargetLo ? LoInputs : HiInputs;
8657       ArrayRef<int> MovingInputs = TargetLo ? HiInputs : LoInputs;
8658
8659       int PreDupI16Shuffle[] = {-1, -1, -1, -1, -1, -1, -1, -1};
8660       SmallDenseMap<int, int, 8> LaneMap;
8661       for (int I : InPlaceInputs) {
8662         PreDupI16Shuffle[I/2] = I/2;
8663         LaneMap[I] = I;
8664       }
8665       int j = TargetLo ? 0 : 4, je = j + 4;
8666       for (int i = 0, ie = MovingInputs.size(); i < ie; ++i) {
8667         // Check if j is already a shuffle of this input. This happens when
8668         // there are two adjacent bytes after we move the low one.
8669         if (PreDupI16Shuffle[j] != MovingInputs[i] / 2) {
8670           // If we haven't yet mapped the input, search for a slot into which
8671           // we can map it.
8672           while (j < je && PreDupI16Shuffle[j] != -1)
8673             ++j;
8674
8675           if (j == je)
8676             // We can't place the inputs into a single half with a simple i16 shuffle, so bail.
8677             return SDValue();
8678
8679           // Map this input with the i16 shuffle.
8680           PreDupI16Shuffle[j] = MovingInputs[i] / 2;
8681         }
8682
8683         // Update the lane map based on the mapping we ended up with.
8684         LaneMap[MovingInputs[i]] = 2 * j + MovingInputs[i] % 2;
8685       }
8686       V1 = DAG.getNode(
8687           ISD::BITCAST, DL, MVT::v16i8,
8688           DAG.getVectorShuffle(MVT::v8i16, DL,
8689                                DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1),
8690                                DAG.getUNDEF(MVT::v8i16), PreDupI16Shuffle));
8691
8692       // Unpack the bytes to form the i16s that will be shuffled into place.
8693       V1 = DAG.getNode(TargetLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
8694                        MVT::v16i8, V1, V1);
8695
8696       int PostDupI16Shuffle[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8697       for (int i = 0; i < 16; ++i)
8698         if (Mask[i] != -1) {
8699           int MappedMask = LaneMap[Mask[i]] - (TargetLo ? 0 : 8);
8700           assert(MappedMask < 8 && "Invalid v8 shuffle mask!");
8701           if (PostDupI16Shuffle[i / 2] == -1)
8702             PostDupI16Shuffle[i / 2] = MappedMask;
8703           else
8704             assert(PostDupI16Shuffle[i / 2] == MappedMask &&
8705                    "Conflicting entrties in the original shuffle!");
8706         }
8707       return DAG.getNode(
8708           ISD::BITCAST, DL, MVT::v16i8,
8709           DAG.getVectorShuffle(MVT::v8i16, DL,
8710                                DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1),
8711                                DAG.getUNDEF(MVT::v8i16), PostDupI16Shuffle));
8712     };
8713     if (SDValue V = tryToWidenViaDuplication())
8714       return V;
8715   }
8716
8717   // Use dedicated unpack instructions for masks that match their pattern.
8718   if (isShuffleEquivalent(V1, V2, Mask, {// Low half.
8719                                          0, 16, 1, 17, 2, 18, 3, 19,
8720                                          // High half.
8721                                          4, 20, 5, 21, 6, 22, 7, 23}))
8722     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V1, V2);
8723   if (isShuffleEquivalent(V1, V2, Mask, {// Low half.
8724                                          8, 24, 9, 25, 10, 26, 11, 27,
8725                                          // High half.
8726                                          12, 28, 13, 29, 14, 30, 15, 31}))
8727     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V1, V2);
8728
8729   // Check for SSSE3 which lets us lower all v16i8 shuffles much more directly
8730   // with PSHUFB. It is important to do this before we attempt to generate any
8731   // blends but after all of the single-input lowerings. If the single input
8732   // lowerings can find an instruction sequence that is faster than a PSHUFB, we
8733   // want to preserve that and we can DAG combine any longer sequences into
8734   // a PSHUFB in the end. But once we start blending from multiple inputs,
8735   // the complexity of DAG combining bad patterns back into PSHUFB is too high,
8736   // and there are *very* few patterns that would actually be faster than the
8737   // PSHUFB approach because of its ability to zero lanes.
8738   //
8739   // FIXME: The only exceptions to the above are blends which are exact
8740   // interleavings with direct instructions supporting them. We currently don't
8741   // handle those well here.
8742   if (Subtarget->hasSSSE3()) {
8743     bool V1InUse = false;
8744     bool V2InUse = false;
8745
8746     SDValue PSHUFB = lowerVectorShuffleAsPSHUFB(DL, MVT::v16i8, V1, V2, Mask,
8747                                                 DAG, V1InUse, V2InUse);
8748
8749     // If both V1 and V2 are in use and we can use a direct blend or an unpack,
8750     // do so. This avoids using them to handle blends-with-zero which is
8751     // important as a single pshufb is significantly faster for that.
8752     if (V1InUse && V2InUse) {
8753       if (Subtarget->hasSSE41())
8754         if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i8, V1, V2,
8755                                                       Mask, Subtarget, DAG))
8756           return Blend;
8757
8758       // We can use an unpack to do the blending rather than an or in some
8759       // cases. Even though the or may be (very minorly) more efficient, we
8760       // preference this lowering because there are common cases where part of
8761       // the complexity of the shuffles goes away when we do the final blend as
8762       // an unpack.
8763       // FIXME: It might be worth trying to detect if the unpack-feeding
8764       // shuffles will both be pshufb, in which case we shouldn't bother with
8765       // this.
8766       if (SDValue Unpack =
8767               lowerVectorShuffleAsUnpack(DL, MVT::v16i8, V1, V2, Mask, DAG))
8768         return Unpack;
8769     }
8770
8771     return PSHUFB;
8772   }
8773
8774   // There are special ways we can lower some single-element blends.
8775   if (NumV2Elements == 1)
8776     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v16i8, V1, V2,
8777                                                          Mask, Subtarget, DAG))
8778       return V;
8779
8780   if (SDValue BitBlend =
8781           lowerVectorShuffleAsBitBlend(DL, MVT::v16i8, V1, V2, Mask, DAG))
8782     return BitBlend;
8783
8784   // Check whether a compaction lowering can be done. This handles shuffles
8785   // which take every Nth element for some even N. See the helper function for
8786   // details.
8787   //
8788   // We special case these as they can be particularly efficiently handled with
8789   // the PACKUSB instruction on x86 and they show up in common patterns of
8790   // rearranging bytes to truncate wide elements.
8791   if (int NumEvenDrops = canLowerByDroppingEvenElements(Mask)) {
8792     // NumEvenDrops is the power of two stride of the elements. Another way of
8793     // thinking about it is that we need to drop the even elements this many
8794     // times to get the original input.
8795     bool IsSingleInput = isSingleInputShuffleMask(Mask);
8796
8797     // First we need to zero all the dropped bytes.
8798     assert(NumEvenDrops <= 3 &&
8799            "No support for dropping even elements more than 3 times.");
8800     // We use the mask type to pick which bytes are preserved based on how many
8801     // elements are dropped.
8802     MVT MaskVTs[] = { MVT::v8i16, MVT::v4i32, MVT::v2i64 };
8803     SDValue ByteClearMask =
8804         DAG.getNode(ISD::BITCAST, DL, MVT::v16i8,
8805                     DAG.getConstant(0xFF, DL, MaskVTs[NumEvenDrops - 1]));
8806     V1 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V1, ByteClearMask);
8807     if (!IsSingleInput)
8808       V2 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V2, ByteClearMask);
8809
8810     // Now pack things back together.
8811     V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1);
8812     V2 = IsSingleInput ? V1 : DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V2);
8813     SDValue Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, V1, V2);
8814     for (int i = 1; i < NumEvenDrops; ++i) {
8815       Result = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, Result);
8816       Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, Result, Result);
8817     }
8818
8819     return Result;
8820   }
8821
8822   // Handle multi-input cases by blending single-input shuffles.
8823   if (NumV2Elements > 0)
8824     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v16i8, V1, V2,
8825                                                       Mask, DAG);
8826
8827   // The fallback path for single-input shuffles widens this into two v8i16
8828   // vectors with unpacks, shuffles those, and then pulls them back together
8829   // with a pack.
8830   SDValue V = V1;
8831
8832   int LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8833   int HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8834   for (int i = 0; i < 16; ++i)
8835     if (Mask[i] >= 0)
8836       (i < 8 ? LoBlendMask[i] : HiBlendMask[i % 8]) = Mask[i];
8837
8838   SDValue Zero = getZeroVector(MVT::v8i16, Subtarget, DAG, DL);
8839
8840   SDValue VLoHalf, VHiHalf;
8841   // Check if any of the odd lanes in the v16i8 are used. If not, we can mask
8842   // them out and avoid using UNPCK{L,H} to extract the elements of V as
8843   // i16s.
8844   if (std::none_of(std::begin(LoBlendMask), std::end(LoBlendMask),
8845                    [](int M) { return M >= 0 && M % 2 == 1; }) &&
8846       std::none_of(std::begin(HiBlendMask), std::end(HiBlendMask),
8847                    [](int M) { return M >= 0 && M % 2 == 1; })) {
8848     // Use a mask to drop the high bytes.
8849     VLoHalf = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V);
8850     VLoHalf = DAG.getNode(ISD::AND, DL, MVT::v8i16, VLoHalf,
8851                      DAG.getConstant(0x00FF, DL, MVT::v8i16));
8852
8853     // This will be a single vector shuffle instead of a blend so nuke VHiHalf.
8854     VHiHalf = DAG.getUNDEF(MVT::v8i16);
8855
8856     // Squash the masks to point directly into VLoHalf.
8857     for (int &M : LoBlendMask)
8858       if (M >= 0)
8859         M /= 2;
8860     for (int &M : HiBlendMask)
8861       if (M >= 0)
8862         M /= 2;
8863   } else {
8864     // Otherwise just unpack the low half of V into VLoHalf and the high half into
8865     // VHiHalf so that we can blend them as i16s.
8866     VLoHalf = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
8867                      DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V, Zero));
8868     VHiHalf = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
8869                      DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V, Zero));
8870   }
8871
8872   SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, LoBlendMask);
8873   SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, HiBlendMask);
8874
8875   return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
8876 }
8877
8878 /// \brief Dispatching routine to lower various 128-bit x86 vector shuffles.
8879 ///
8880 /// This routine breaks down the specific type of 128-bit shuffle and
8881 /// dispatches to the lowering routines accordingly.
8882 static SDValue lower128BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8883                                         MVT VT, const X86Subtarget *Subtarget,
8884                                         SelectionDAG &DAG) {
8885   switch (VT.SimpleTy) {
8886   case MVT::v2i64:
8887     return lowerV2I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
8888   case MVT::v2f64:
8889     return lowerV2F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
8890   case MVT::v4i32:
8891     return lowerV4I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
8892   case MVT::v4f32:
8893     return lowerV4F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
8894   case MVT::v8i16:
8895     return lowerV8I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
8896   case MVT::v16i8:
8897     return lowerV16I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
8898
8899   default:
8900     llvm_unreachable("Unimplemented!");
8901   }
8902 }
8903
8904 /// \brief Helper function to test whether a shuffle mask could be
8905 /// simplified by widening the elements being shuffled.
8906 ///
8907 /// Appends the mask for wider elements in WidenedMask if valid. Otherwise
8908 /// leaves it in an unspecified state.
8909 ///
8910 /// NOTE: This must handle normal vector shuffle masks and *target* vector
8911 /// shuffle masks. The latter have the special property of a '-2' representing
8912 /// a zero-ed lane of a vector.
8913 static bool canWidenShuffleElements(ArrayRef<int> Mask,
8914                                     SmallVectorImpl<int> &WidenedMask) {
8915   for (int i = 0, Size = Mask.size(); i < Size; i += 2) {
8916     // If both elements are undef, its trivial.
8917     if (Mask[i] == SM_SentinelUndef && Mask[i + 1] == SM_SentinelUndef) {
8918       WidenedMask.push_back(SM_SentinelUndef);
8919       continue;
8920     }
8921
8922     // Check for an undef mask and a mask value properly aligned to fit with
8923     // a pair of values. If we find such a case, use the non-undef mask's value.
8924     if (Mask[i] == SM_SentinelUndef && Mask[i + 1] >= 0 && Mask[i + 1] % 2 == 1) {
8925       WidenedMask.push_back(Mask[i + 1] / 2);
8926       continue;
8927     }
8928     if (Mask[i + 1] == SM_SentinelUndef && Mask[i] >= 0 && Mask[i] % 2 == 0) {
8929       WidenedMask.push_back(Mask[i] / 2);
8930       continue;
8931     }
8932
8933     // When zeroing, we need to spread the zeroing across both lanes to widen.
8934     if (Mask[i] == SM_SentinelZero || Mask[i + 1] == SM_SentinelZero) {
8935       if ((Mask[i] == SM_SentinelZero || Mask[i] == SM_SentinelUndef) &&
8936           (Mask[i + 1] == SM_SentinelZero || Mask[i + 1] == SM_SentinelUndef)) {
8937         WidenedMask.push_back(SM_SentinelZero);
8938         continue;
8939       }
8940       return false;
8941     }
8942
8943     // Finally check if the two mask values are adjacent and aligned with
8944     // a pair.
8945     if (Mask[i] != SM_SentinelUndef && Mask[i] % 2 == 0 && Mask[i] + 1 == Mask[i + 1]) {
8946       WidenedMask.push_back(Mask[i] / 2);
8947       continue;
8948     }
8949
8950     // Otherwise we can't safely widen the elements used in this shuffle.
8951     return false;
8952   }
8953   assert(WidenedMask.size() == Mask.size() / 2 &&
8954          "Incorrect size of mask after widening the elements!");
8955
8956   return true;
8957 }
8958
8959 /// \brief Generic routine to split vector shuffle into half-sized shuffles.
8960 ///
8961 /// This routine just extracts two subvectors, shuffles them independently, and
8962 /// then concatenates them back together. This should work effectively with all
8963 /// AVX vector shuffle types.
8964 static SDValue splitAndLowerVectorShuffle(SDLoc DL, MVT VT, SDValue V1,
8965                                           SDValue V2, ArrayRef<int> Mask,
8966                                           SelectionDAG &DAG) {
8967   assert(VT.getSizeInBits() >= 256 &&
8968          "Only for 256-bit or wider vector shuffles!");
8969   assert(V1.getSimpleValueType() == VT && "Bad operand type!");
8970   assert(V2.getSimpleValueType() == VT && "Bad operand type!");
8971
8972   ArrayRef<int> LoMask = Mask.slice(0, Mask.size() / 2);
8973   ArrayRef<int> HiMask = Mask.slice(Mask.size() / 2);
8974
8975   int NumElements = VT.getVectorNumElements();
8976   int SplitNumElements = NumElements / 2;
8977   MVT ScalarVT = VT.getScalarType();
8978   MVT SplitVT = MVT::getVectorVT(ScalarVT, NumElements / 2);
8979
8980   // Rather than splitting build-vectors, just build two narrower build
8981   // vectors. This helps shuffling with splats and zeros.
8982   auto SplitVector = [&](SDValue V) {
8983     while (V.getOpcode() == ISD::BITCAST)
8984       V = V->getOperand(0);
8985
8986     MVT OrigVT = V.getSimpleValueType();
8987     int OrigNumElements = OrigVT.getVectorNumElements();
8988     int OrigSplitNumElements = OrigNumElements / 2;
8989     MVT OrigScalarVT = OrigVT.getScalarType();
8990     MVT OrigSplitVT = MVT::getVectorVT(OrigScalarVT, OrigNumElements / 2);
8991
8992     SDValue LoV, HiV;
8993
8994     auto *BV = dyn_cast<BuildVectorSDNode>(V);
8995     if (!BV) {
8996       LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
8997                         DAG.getIntPtrConstant(0, DL));
8998       HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
8999                         DAG.getIntPtrConstant(OrigSplitNumElements, DL));
9000     } else {
9001
9002       SmallVector<SDValue, 16> LoOps, HiOps;
9003       for (int i = 0; i < OrigSplitNumElements; ++i) {
9004         LoOps.push_back(BV->getOperand(i));
9005         HiOps.push_back(BV->getOperand(i + OrigSplitNumElements));
9006       }
9007       LoV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, LoOps);
9008       HiV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, HiOps);
9009     }
9010     return std::make_pair(DAG.getNode(ISD::BITCAST, DL, SplitVT, LoV),
9011                           DAG.getNode(ISD::BITCAST, DL, SplitVT, HiV));
9012   };
9013
9014   SDValue LoV1, HiV1, LoV2, HiV2;
9015   std::tie(LoV1, HiV1) = SplitVector(V1);
9016   std::tie(LoV2, HiV2) = SplitVector(V2);
9017
9018   // Now create two 4-way blends of these half-width vectors.
9019   auto HalfBlend = [&](ArrayRef<int> HalfMask) {
9020     bool UseLoV1 = false, UseHiV1 = false, UseLoV2 = false, UseHiV2 = false;
9021     SmallVector<int, 32> V1BlendMask, V2BlendMask, BlendMask;
9022     for (int i = 0; i < SplitNumElements; ++i) {
9023       int M = HalfMask[i];
9024       if (M >= NumElements) {
9025         if (M >= NumElements + SplitNumElements)
9026           UseHiV2 = true;
9027         else
9028           UseLoV2 = true;
9029         V2BlendMask.push_back(M - NumElements);
9030         V1BlendMask.push_back(-1);
9031         BlendMask.push_back(SplitNumElements + i);
9032       } else if (M >= 0) {
9033         if (M >= SplitNumElements)
9034           UseHiV1 = true;
9035         else
9036           UseLoV1 = true;
9037         V2BlendMask.push_back(-1);
9038         V1BlendMask.push_back(M);
9039         BlendMask.push_back(i);
9040       } else {
9041         V2BlendMask.push_back(-1);
9042         V1BlendMask.push_back(-1);
9043         BlendMask.push_back(-1);
9044       }
9045     }
9046
9047     // Because the lowering happens after all combining takes place, we need to
9048     // manually combine these blend masks as much as possible so that we create
9049     // a minimal number of high-level vector shuffle nodes.
9050
9051     // First try just blending the halves of V1 or V2.
9052     if (!UseLoV1 && !UseHiV1 && !UseLoV2 && !UseHiV2)
9053       return DAG.getUNDEF(SplitVT);
9054     if (!UseLoV2 && !UseHiV2)
9055       return DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9056     if (!UseLoV1 && !UseHiV1)
9057       return DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9058
9059     SDValue V1Blend, V2Blend;
9060     if (UseLoV1 && UseHiV1) {
9061       V1Blend =
9062         DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9063     } else {
9064       // We only use half of V1 so map the usage down into the final blend mask.
9065       V1Blend = UseLoV1 ? LoV1 : HiV1;
9066       for (int i = 0; i < SplitNumElements; ++i)
9067         if (BlendMask[i] >= 0 && BlendMask[i] < SplitNumElements)
9068           BlendMask[i] = V1BlendMask[i] - (UseLoV1 ? 0 : SplitNumElements);
9069     }
9070     if (UseLoV2 && UseHiV2) {
9071       V2Blend =
9072         DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9073     } else {
9074       // We only use half of V2 so map the usage down into the final blend mask.
9075       V2Blend = UseLoV2 ? LoV2 : HiV2;
9076       for (int i = 0; i < SplitNumElements; ++i)
9077         if (BlendMask[i] >= SplitNumElements)
9078           BlendMask[i] = V2BlendMask[i] + (UseLoV2 ? SplitNumElements : 0);
9079     }
9080     return DAG.getVectorShuffle(SplitVT, DL, V1Blend, V2Blend, BlendMask);
9081   };
9082   SDValue Lo = HalfBlend(LoMask);
9083   SDValue Hi = HalfBlend(HiMask);
9084   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
9085 }
9086
9087 /// \brief Either split a vector in halves or decompose the shuffles and the
9088 /// blend.
9089 ///
9090 /// This is provided as a good fallback for many lowerings of non-single-input
9091 /// shuffles with more than one 128-bit lane. In those cases, we want to select
9092 /// between splitting the shuffle into 128-bit components and stitching those
9093 /// back together vs. extracting the single-input shuffles and blending those
9094 /// results.
9095 static SDValue lowerVectorShuffleAsSplitOrBlend(SDLoc DL, MVT VT, SDValue V1,
9096                                                 SDValue V2, ArrayRef<int> Mask,
9097                                                 SelectionDAG &DAG) {
9098   assert(!isSingleInputShuffleMask(Mask) && "This routine must not be used to "
9099                                             "lower single-input shuffles as it "
9100                                             "could then recurse on itself.");
9101   int Size = Mask.size();
9102
9103   // If this can be modeled as a broadcast of two elements followed by a blend,
9104   // prefer that lowering. This is especially important because broadcasts can
9105   // often fold with memory operands.
9106   auto DoBothBroadcast = [&] {
9107     int V1BroadcastIdx = -1, V2BroadcastIdx = -1;
9108     for (int M : Mask)
9109       if (M >= Size) {
9110         if (V2BroadcastIdx == -1)
9111           V2BroadcastIdx = M - Size;
9112         else if (M - Size != V2BroadcastIdx)
9113           return false;
9114       } else if (M >= 0) {
9115         if (V1BroadcastIdx == -1)
9116           V1BroadcastIdx = M;
9117         else if (M != V1BroadcastIdx)
9118           return false;
9119       }
9120     return true;
9121   };
9122   if (DoBothBroadcast())
9123     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask,
9124                                                       DAG);
9125
9126   // If the inputs all stem from a single 128-bit lane of each input, then we
9127   // split them rather than blending because the split will decompose to
9128   // unusually few instructions.
9129   int LaneCount = VT.getSizeInBits() / 128;
9130   int LaneSize = Size / LaneCount;
9131   SmallBitVector LaneInputs[2];
9132   LaneInputs[0].resize(LaneCount, false);
9133   LaneInputs[1].resize(LaneCount, false);
9134   for (int i = 0; i < Size; ++i)
9135     if (Mask[i] >= 0)
9136       LaneInputs[Mask[i] / Size][(Mask[i] % Size) / LaneSize] = true;
9137   if (LaneInputs[0].count() <= 1 && LaneInputs[1].count() <= 1)
9138     return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9139
9140   // Otherwise, just fall back to decomposed shuffles and a blend. This requires
9141   // that the decomposed single-input shuffles don't end up here.
9142   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9143 }
9144
9145 /// \brief Lower a vector shuffle crossing multiple 128-bit lanes as
9146 /// a permutation and blend of those lanes.
9147 ///
9148 /// This essentially blends the out-of-lane inputs to each lane into the lane
9149 /// from a permuted copy of the vector. This lowering strategy results in four
9150 /// instructions in the worst case for a single-input cross lane shuffle which
9151 /// is lower than any other fully general cross-lane shuffle strategy I'm aware
9152 /// of. Special cases for each particular shuffle pattern should be handled
9153 /// prior to trying this lowering.
9154 static SDValue lowerVectorShuffleAsLanePermuteAndBlend(SDLoc DL, MVT VT,
9155                                                        SDValue V1, SDValue V2,
9156                                                        ArrayRef<int> Mask,
9157                                                        SelectionDAG &DAG) {
9158   // FIXME: This should probably be generalized for 512-bit vectors as well.
9159   assert(VT.getSizeInBits() == 256 && "Only for 256-bit vector shuffles!");
9160   int LaneSize = Mask.size() / 2;
9161
9162   // If there are only inputs from one 128-bit lane, splitting will in fact be
9163   // less expensive. The flags track whether the given lane contains an element
9164   // that crosses to another lane.
9165   bool LaneCrossing[2] = {false, false};
9166   for (int i = 0, Size = Mask.size(); i < Size; ++i)
9167     if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
9168       LaneCrossing[(Mask[i] % Size) / LaneSize] = true;
9169   if (!LaneCrossing[0] || !LaneCrossing[1])
9170     return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9171
9172   if (isSingleInputShuffleMask(Mask)) {
9173     SmallVector<int, 32> FlippedBlendMask;
9174     for (int i = 0, Size = Mask.size(); i < Size; ++i)
9175       FlippedBlendMask.push_back(
9176           Mask[i] < 0 ? -1 : (((Mask[i] % Size) / LaneSize == i / LaneSize)
9177                                   ? Mask[i]
9178                                   : Mask[i] % LaneSize +
9179                                         (i / LaneSize) * LaneSize + Size));
9180
9181     // Flip the vector, and blend the results which should now be in-lane. The
9182     // VPERM2X128 mask uses the low 2 bits for the low source and bits 4 and
9183     // 5 for the high source. The value 3 selects the high half of source 2 and
9184     // the value 2 selects the low half of source 2. We only use source 2 to
9185     // allow folding it into a memory operand.
9186     unsigned PERMMask = 3 | 2 << 4;
9187     SDValue Flipped = DAG.getNode(X86ISD::VPERM2X128, DL, VT, DAG.getUNDEF(VT),
9188                                   V1, DAG.getConstant(PERMMask, DL, MVT::i8));
9189     return DAG.getVectorShuffle(VT, DL, V1, Flipped, FlippedBlendMask);
9190   }
9191
9192   // This now reduces to two single-input shuffles of V1 and V2 which at worst
9193   // will be handled by the above logic and a blend of the results, much like
9194   // other patterns in AVX.
9195   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9196 }
9197
9198 /// \brief Handle lowering 2-lane 128-bit shuffles.
9199 static SDValue lowerV2X128VectorShuffle(SDLoc DL, MVT VT, SDValue V1,
9200                                         SDValue V2, ArrayRef<int> Mask,
9201                                         const X86Subtarget *Subtarget,
9202                                         SelectionDAG &DAG) {
9203   // TODO: If minimizing size and one of the inputs is a zero vector and the
9204   // the zero vector has only one use, we could use a VPERM2X128 to save the
9205   // instruction bytes needed to explicitly generate the zero vector.
9206
9207   // Blends are faster and handle all the non-lane-crossing cases.
9208   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, VT, V1, V2, Mask,
9209                                                 Subtarget, DAG))
9210     return Blend;
9211
9212   bool IsV1Zero = ISD::isBuildVectorAllZeros(V1.getNode());
9213   bool IsV2Zero = ISD::isBuildVectorAllZeros(V2.getNode());
9214
9215   // If either input operand is a zero vector, use VPERM2X128 because its mask
9216   // allows us to replace the zero input with an implicit zero.
9217   if (!IsV1Zero && !IsV2Zero) {
9218     // Check for patterns which can be matched with a single insert of a 128-bit
9219     // subvector.
9220     bool OnlyUsesV1 = isShuffleEquivalent(V1, V2, Mask, {0, 1, 0, 1});
9221     if (OnlyUsesV1 || isShuffleEquivalent(V1, V2, Mask, {0, 1, 4, 5})) {
9222       MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(),
9223                                    VT.getVectorNumElements() / 2);
9224       SDValue LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V1,
9225                                 DAG.getIntPtrConstant(0, DL));
9226       SDValue HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT,
9227                                 OnlyUsesV1 ? V1 : V2,
9228                                 DAG.getIntPtrConstant(0, DL));
9229       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LoV, HiV);
9230     }
9231   }
9232
9233   // Otherwise form a 128-bit permutation. After accounting for undefs,
9234   // convert the 64-bit shuffle mask selection values into 128-bit
9235   // selection bits by dividing the indexes by 2 and shifting into positions
9236   // defined by a vperm2*128 instruction's immediate control byte.
9237
9238   // The immediate permute control byte looks like this:
9239   //    [1:0] - select 128 bits from sources for low half of destination
9240   //    [2]   - ignore
9241   //    [3]   - zero low half of destination
9242   //    [5:4] - select 128 bits from sources for high half of destination
9243   //    [6]   - ignore
9244   //    [7]   - zero high half of destination
9245
9246   int MaskLO = Mask[0];
9247   if (MaskLO == SM_SentinelUndef)
9248     MaskLO = Mask[1] == SM_SentinelUndef ? 0 : Mask[1];
9249
9250   int MaskHI = Mask[2];
9251   if (MaskHI == SM_SentinelUndef)
9252     MaskHI = Mask[3] == SM_SentinelUndef ? 0 : Mask[3];
9253
9254   unsigned PermMask = MaskLO / 2 | (MaskHI / 2) << 4;
9255
9256   // If either input is a zero vector, replace it with an undef input.
9257   // Shuffle mask values <  4 are selecting elements of V1.
9258   // Shuffle mask values >= 4 are selecting elements of V2.
9259   // Adjust each half of the permute mask by clearing the half that was
9260   // selecting the zero vector and setting the zero mask bit.
9261   if (IsV1Zero) {
9262     V1 = DAG.getUNDEF(VT);
9263     if (MaskLO < 4)
9264       PermMask = (PermMask & 0xf0) | 0x08;
9265     if (MaskHI < 4)
9266       PermMask = (PermMask & 0x0f) | 0x80;
9267   }
9268   if (IsV2Zero) {
9269     V2 = DAG.getUNDEF(VT);
9270     if (MaskLO >= 4)
9271       PermMask = (PermMask & 0xf0) | 0x08;
9272     if (MaskHI >= 4)
9273       PermMask = (PermMask & 0x0f) | 0x80;
9274   }
9275
9276   return DAG.getNode(X86ISD::VPERM2X128, DL, VT, V1, V2,
9277                      DAG.getConstant(PermMask, DL, MVT::i8));
9278 }
9279
9280 /// \brief Lower a vector shuffle by first fixing the 128-bit lanes and then
9281 /// shuffling each lane.
9282 ///
9283 /// This will only succeed when the result of fixing the 128-bit lanes results
9284 /// in a single-input non-lane-crossing shuffle with a repeating shuffle mask in
9285 /// each 128-bit lanes. This handles many cases where we can quickly blend away
9286 /// the lane crosses early and then use simpler shuffles within each lane.
9287 ///
9288 /// FIXME: It might be worthwhile at some point to support this without
9289 /// requiring the 128-bit lane-relative shuffles to be repeating, but currently
9290 /// in x86 only floating point has interesting non-repeating shuffles, and even
9291 /// those are still *marginally* more expensive.
9292 static SDValue lowerVectorShuffleByMerging128BitLanes(
9293     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
9294     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
9295   assert(!isSingleInputShuffleMask(Mask) &&
9296          "This is only useful with multiple inputs.");
9297
9298   int Size = Mask.size();
9299   int LaneSize = 128 / VT.getScalarSizeInBits();
9300   int NumLanes = Size / LaneSize;
9301   assert(NumLanes > 1 && "Only handles 256-bit and wider shuffles.");
9302
9303   // See if we can build a hypothetical 128-bit lane-fixing shuffle mask. Also
9304   // check whether the in-128-bit lane shuffles share a repeating pattern.
9305   SmallVector<int, 4> Lanes;
9306   Lanes.resize(NumLanes, -1);
9307   SmallVector<int, 4> InLaneMask;
9308   InLaneMask.resize(LaneSize, -1);
9309   for (int i = 0; i < Size; ++i) {
9310     if (Mask[i] < 0)
9311       continue;
9312
9313     int j = i / LaneSize;
9314
9315     if (Lanes[j] < 0) {
9316       // First entry we've seen for this lane.
9317       Lanes[j] = Mask[i] / LaneSize;
9318     } else if (Lanes[j] != Mask[i] / LaneSize) {
9319       // This doesn't match the lane selected previously!
9320       return SDValue();
9321     }
9322
9323     // Check that within each lane we have a consistent shuffle mask.
9324     int k = i % LaneSize;
9325     if (InLaneMask[k] < 0) {
9326       InLaneMask[k] = Mask[i] % LaneSize;
9327     } else if (InLaneMask[k] != Mask[i] % LaneSize) {
9328       // This doesn't fit a repeating in-lane mask.
9329       return SDValue();
9330     }
9331   }
9332
9333   // First shuffle the lanes into place.
9334   MVT LaneVT = MVT::getVectorVT(VT.isFloatingPoint() ? MVT::f64 : MVT::i64,
9335                                 VT.getSizeInBits() / 64);
9336   SmallVector<int, 8> LaneMask;
9337   LaneMask.resize(NumLanes * 2, -1);
9338   for (int i = 0; i < NumLanes; ++i)
9339     if (Lanes[i] >= 0) {
9340       LaneMask[2 * i + 0] = 2*Lanes[i] + 0;
9341       LaneMask[2 * i + 1] = 2*Lanes[i] + 1;
9342     }
9343
9344   V1 = DAG.getNode(ISD::BITCAST, DL, LaneVT, V1);
9345   V2 = DAG.getNode(ISD::BITCAST, DL, LaneVT, V2);
9346   SDValue LaneShuffle = DAG.getVectorShuffle(LaneVT, DL, V1, V2, LaneMask);
9347
9348   // Cast it back to the type we actually want.
9349   LaneShuffle = DAG.getNode(ISD::BITCAST, DL, VT, LaneShuffle);
9350
9351   // Now do a simple shuffle that isn't lane crossing.
9352   SmallVector<int, 8> NewMask;
9353   NewMask.resize(Size, -1);
9354   for (int i = 0; i < Size; ++i)
9355     if (Mask[i] >= 0)
9356       NewMask[i] = (i / LaneSize) * LaneSize + Mask[i] % LaneSize;
9357   assert(!is128BitLaneCrossingShuffleMask(VT, NewMask) &&
9358          "Must not introduce lane crosses at this point!");
9359
9360   return DAG.getVectorShuffle(VT, DL, LaneShuffle, DAG.getUNDEF(VT), NewMask);
9361 }
9362
9363 /// \brief Test whether the specified input (0 or 1) is in-place blended by the
9364 /// given mask.
9365 ///
9366 /// This returns true if the elements from a particular input are already in the
9367 /// slot required by the given mask and require no permutation.
9368 static bool isShuffleMaskInputInPlace(int Input, ArrayRef<int> Mask) {
9369   assert((Input == 0 || Input == 1) && "Only two inputs to shuffles.");
9370   int Size = Mask.size();
9371   for (int i = 0; i < Size; ++i)
9372     if (Mask[i] >= 0 && Mask[i] / Size == Input && Mask[i] % Size != i)
9373       return false;
9374
9375   return true;
9376 }
9377
9378 /// \brief Handle lowering of 4-lane 64-bit floating point shuffles.
9379 ///
9380 /// Also ends up handling lowering of 4-lane 64-bit integer shuffles when AVX2
9381 /// isn't available.
9382 static SDValue lowerV4F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9383                                        const X86Subtarget *Subtarget,
9384                                        SelectionDAG &DAG) {
9385   SDLoc DL(Op);
9386   assert(V1.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
9387   assert(V2.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
9388   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9389   ArrayRef<int> Mask = SVOp->getMask();
9390   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
9391
9392   SmallVector<int, 4> WidenedMask;
9393   if (canWidenShuffleElements(Mask, WidenedMask))
9394     return lowerV2X128VectorShuffle(DL, MVT::v4f64, V1, V2, Mask, Subtarget,
9395                                     DAG);
9396
9397   if (isSingleInputShuffleMask(Mask)) {
9398     // Check for being able to broadcast a single element.
9399     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f64, V1,
9400                                                           Mask, Subtarget, DAG))
9401       return Broadcast;
9402
9403     // Use low duplicate instructions for masks that match their pattern.
9404     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
9405       return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v4f64, V1);
9406
9407     if (!is128BitLaneCrossingShuffleMask(MVT::v4f64, Mask)) {
9408       // Non-half-crossing single input shuffles can be lowerid with an
9409       // interleaved permutation.
9410       unsigned VPERMILPMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1) |
9411                               ((Mask[2] == 3) << 2) | ((Mask[3] == 3) << 3);
9412       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f64, V1,
9413                          DAG.getConstant(VPERMILPMask, DL, MVT::i8));
9414     }
9415
9416     // With AVX2 we have direct support for this permutation.
9417     if (Subtarget->hasAVX2())
9418       return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4f64, V1,
9419                          getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
9420
9421     // Otherwise, fall back.
9422     return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v4f64, V1, V2, Mask,
9423                                                    DAG);
9424   }
9425
9426   // X86 has dedicated unpack instructions that can handle specific blend
9427   // operations: UNPCKH and UNPCKL.
9428   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 2, 6}))
9429     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V1, V2);
9430   if (isShuffleEquivalent(V1, V2, Mask, {1, 5, 3, 7}))
9431     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V1, V2);
9432   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 6, 2}))
9433     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V2, V1);
9434   if (isShuffleEquivalent(V1, V2, Mask, {5, 1, 7, 3}))
9435     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V2, V1);
9436
9437   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f64, V1, V2, Mask,
9438                                                 Subtarget, DAG))
9439     return Blend;
9440
9441   // Check if the blend happens to exactly fit that of SHUFPD.
9442   if ((Mask[0] == -1 || Mask[0] < 2) &&
9443       (Mask[1] == -1 || (Mask[1] >= 4 && Mask[1] < 6)) &&
9444       (Mask[2] == -1 || (Mask[2] >= 2 && Mask[2] < 4)) &&
9445       (Mask[3] == -1 || Mask[3] >= 6)) {
9446     unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 5) << 1) |
9447                           ((Mask[2] == 3) << 2) | ((Mask[3] == 7) << 3);
9448     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f64, V1, V2,
9449                        DAG.getConstant(SHUFPDMask, DL, MVT::i8));
9450   }
9451   if ((Mask[0] == -1 || (Mask[0] >= 4 && Mask[0] < 6)) &&
9452       (Mask[1] == -1 || Mask[1] < 2) &&
9453       (Mask[2] == -1 || Mask[2] >= 6) &&
9454       (Mask[3] == -1 || (Mask[3] >= 2 && Mask[3] < 4))) {
9455     unsigned SHUFPDMask = (Mask[0] == 5) | ((Mask[1] == 1) << 1) |
9456                           ((Mask[2] == 7) << 2) | ((Mask[3] == 3) << 3);
9457     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f64, V2, V1,
9458                        DAG.getConstant(SHUFPDMask, DL, MVT::i8));
9459   }
9460
9461   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9462   // shuffle. However, if we have AVX2 and either inputs are already in place,
9463   // we will be able to shuffle even across lanes the other input in a single
9464   // instruction so skip this pattern.
9465   if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
9466                                  isShuffleMaskInputInPlace(1, Mask))))
9467     if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9468             DL, MVT::v4f64, V1, V2, Mask, Subtarget, DAG))
9469       return Result;
9470
9471   // If we have AVX2 then we always want to lower with a blend because an v4 we
9472   // can fully permute the elements.
9473   if (Subtarget->hasAVX2())
9474     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4f64, V1, V2,
9475                                                       Mask, DAG);
9476
9477   // Otherwise fall back on generic lowering.
9478   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v4f64, V1, V2, Mask, DAG);
9479 }
9480
9481 /// \brief Handle lowering of 4-lane 64-bit integer shuffles.
9482 ///
9483 /// This routine is only called when we have AVX2 and thus a reasonable
9484 /// instruction set for v4i64 shuffling..
9485 static SDValue lowerV4I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9486                                        const X86Subtarget *Subtarget,
9487                                        SelectionDAG &DAG) {
9488   SDLoc DL(Op);
9489   assert(V1.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
9490   assert(V2.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
9491   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9492   ArrayRef<int> Mask = SVOp->getMask();
9493   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
9494   assert(Subtarget->hasAVX2() && "We can only lower v4i64 with AVX2!");
9495
9496   SmallVector<int, 4> WidenedMask;
9497   if (canWidenShuffleElements(Mask, WidenedMask))
9498     return lowerV2X128VectorShuffle(DL, MVT::v4i64, V1, V2, Mask, Subtarget,
9499                                     DAG);
9500
9501   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i64, V1, V2, Mask,
9502                                                 Subtarget, DAG))
9503     return Blend;
9504
9505   // Check for being able to broadcast a single element.
9506   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i64, V1,
9507                                                         Mask, Subtarget, DAG))
9508     return Broadcast;
9509
9510   // When the shuffle is mirrored between the 128-bit lanes of the unit, we can
9511   // use lower latency instructions that will operate on both 128-bit lanes.
9512   SmallVector<int, 2> RepeatedMask;
9513   if (is128BitLaneRepeatedShuffleMask(MVT::v4i64, Mask, RepeatedMask)) {
9514     if (isSingleInputShuffleMask(Mask)) {
9515       int PSHUFDMask[] = {-1, -1, -1, -1};
9516       for (int i = 0; i < 2; ++i)
9517         if (RepeatedMask[i] >= 0) {
9518           PSHUFDMask[2 * i] = 2 * RepeatedMask[i];
9519           PSHUFDMask[2 * i + 1] = 2 * RepeatedMask[i] + 1;
9520         }
9521       return DAG.getNode(
9522           ISD::BITCAST, DL, MVT::v4i64,
9523           DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32,
9524                       DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, V1),
9525                       getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
9526     }
9527   }
9528
9529   // AVX2 provides a direct instruction for permuting a single input across
9530   // lanes.
9531   if (isSingleInputShuffleMask(Mask))
9532     return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4i64, V1,
9533                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
9534
9535   // Try to use shift instructions.
9536   if (SDValue Shift =
9537           lowerVectorShuffleAsShift(DL, MVT::v4i64, V1, V2, Mask, DAG))
9538     return Shift;
9539
9540   // Use dedicated unpack instructions for masks that match their pattern.
9541   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 2, 6}))
9542     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V1, V2);
9543   if (isShuffleEquivalent(V1, V2, Mask, {1, 5, 3, 7}))
9544     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V1, V2);
9545   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 6, 2}))
9546     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V2, V1);
9547   if (isShuffleEquivalent(V1, V2, Mask, {5, 1, 7, 3}))
9548     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V2, V1);
9549
9550   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9551   // shuffle. However, if we have AVX2 and either inputs are already in place,
9552   // we will be able to shuffle even across lanes the other input in a single
9553   // instruction so skip this pattern.
9554   if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
9555                                  isShuffleMaskInputInPlace(1, Mask))))
9556     if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9557             DL, MVT::v4i64, V1, V2, Mask, Subtarget, DAG))
9558       return Result;
9559
9560   // Otherwise fall back on generic blend lowering.
9561   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i64, V1, V2,
9562                                                     Mask, DAG);
9563 }
9564
9565 /// \brief Handle lowering of 8-lane 32-bit floating point shuffles.
9566 ///
9567 /// Also ends up handling lowering of 8-lane 32-bit integer shuffles when AVX2
9568 /// isn't available.
9569 static SDValue lowerV8F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9570                                        const X86Subtarget *Subtarget,
9571                                        SelectionDAG &DAG) {
9572   SDLoc DL(Op);
9573   assert(V1.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
9574   assert(V2.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
9575   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9576   ArrayRef<int> Mask = SVOp->getMask();
9577   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9578
9579   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8f32, V1, V2, Mask,
9580                                                 Subtarget, DAG))
9581     return Blend;
9582
9583   // Check for being able to broadcast a single element.
9584   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8f32, V1,
9585                                                         Mask, Subtarget, DAG))
9586     return Broadcast;
9587
9588   // If the shuffle mask is repeated in each 128-bit lane, we have many more
9589   // options to efficiently lower the shuffle.
9590   SmallVector<int, 4> RepeatedMask;
9591   if (is128BitLaneRepeatedShuffleMask(MVT::v8f32, Mask, RepeatedMask)) {
9592     assert(RepeatedMask.size() == 4 &&
9593            "Repeated masks must be half the mask width!");
9594
9595     // Use even/odd duplicate instructions for masks that match their pattern.
9596     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2, 4, 4, 6, 6}))
9597       return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v8f32, V1);
9598     if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3, 5, 5, 7, 7}))
9599       return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v8f32, V1);
9600
9601     if (isSingleInputShuffleMask(Mask))
9602       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v8f32, V1,
9603                          getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
9604
9605     // Use dedicated unpack instructions for masks that match their pattern.
9606     if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 4, 12, 5, 13}))
9607       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V1, V2);
9608     if (isShuffleEquivalent(V1, V2, Mask, {2, 10, 3, 11, 6, 14, 7, 15}))
9609       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V1, V2);
9610     if (isShuffleEquivalent(V1, V2, Mask, {8, 0, 9, 1, 12, 4, 13, 5}))
9611       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V2, V1);
9612     if (isShuffleEquivalent(V1, V2, Mask, {10, 2, 11, 3, 14, 6, 15, 7}))
9613       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V2, V1);
9614
9615     // Otherwise, fall back to a SHUFPS sequence. Here it is important that we
9616     // have already handled any direct blends. We also need to squash the
9617     // repeated mask into a simulated v4f32 mask.
9618     for (int i = 0; i < 4; ++i)
9619       if (RepeatedMask[i] >= 8)
9620         RepeatedMask[i] -= 4;
9621     return lowerVectorShuffleWithSHUFPS(DL, MVT::v8f32, RepeatedMask, V1, V2, DAG);
9622   }
9623
9624   // If we have a single input shuffle with different shuffle patterns in the
9625   // two 128-bit lanes use the variable mask to VPERMILPS.
9626   if (isSingleInputShuffleMask(Mask)) {
9627     SDValue VPermMask[8];
9628     for (int i = 0; i < 8; ++i)
9629       VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
9630                                  : DAG.getConstant(Mask[i], DL, MVT::i32);
9631     if (!is128BitLaneCrossingShuffleMask(MVT::v8f32, Mask))
9632       return DAG.getNode(
9633           X86ISD::VPERMILPV, DL, MVT::v8f32, V1,
9634           DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask));
9635
9636     if (Subtarget->hasAVX2())
9637       return DAG.getNode(X86ISD::VPERMV, DL, MVT::v8f32,
9638                          DAG.getNode(ISD::BITCAST, DL, MVT::v8f32,
9639                                      DAG.getNode(ISD::BUILD_VECTOR, DL,
9640                                                  MVT::v8i32, VPermMask)),
9641                          V1);
9642
9643     // Otherwise, fall back.
9644     return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v8f32, V1, V2, Mask,
9645                                                    DAG);
9646   }
9647
9648   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9649   // shuffle.
9650   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9651           DL, MVT::v8f32, V1, V2, Mask, Subtarget, DAG))
9652     return Result;
9653
9654   // If we have AVX2 then we always want to lower with a blend because at v8 we
9655   // can fully permute the elements.
9656   if (Subtarget->hasAVX2())
9657     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8f32, V1, V2,
9658                                                       Mask, DAG);
9659
9660   // Otherwise fall back on generic lowering.
9661   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v8f32, V1, V2, Mask, DAG);
9662 }
9663
9664 /// \brief Handle lowering of 8-lane 32-bit integer shuffles.
9665 ///
9666 /// This routine is only called when we have AVX2 and thus a reasonable
9667 /// instruction set for v8i32 shuffling..
9668 static SDValue lowerV8I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9669                                        const X86Subtarget *Subtarget,
9670                                        SelectionDAG &DAG) {
9671   SDLoc DL(Op);
9672   assert(V1.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
9673   assert(V2.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
9674   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9675   ArrayRef<int> Mask = SVOp->getMask();
9676   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9677   assert(Subtarget->hasAVX2() && "We can only lower v8i32 with AVX2!");
9678
9679   // Whenever we can lower this as a zext, that instruction is strictly faster
9680   // than any alternative. It also allows us to fold memory operands into the
9681   // shuffle in many cases.
9682   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v8i32, V1, V2,
9683                                                          Mask, Subtarget, DAG))
9684     return ZExt;
9685
9686   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i32, V1, V2, Mask,
9687                                                 Subtarget, DAG))
9688     return Blend;
9689
9690   // Check for being able to broadcast a single element.
9691   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i32, V1,
9692                                                         Mask, Subtarget, DAG))
9693     return Broadcast;
9694
9695   // If the shuffle mask is repeated in each 128-bit lane we can use more
9696   // efficient instructions that mirror the shuffles across the two 128-bit
9697   // lanes.
9698   SmallVector<int, 4> RepeatedMask;
9699   if (is128BitLaneRepeatedShuffleMask(MVT::v8i32, Mask, RepeatedMask)) {
9700     assert(RepeatedMask.size() == 4 && "Unexpected repeated mask size!");
9701     if (isSingleInputShuffleMask(Mask))
9702       return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32, V1,
9703                          getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
9704
9705     // Use dedicated unpack instructions for masks that match their pattern.
9706     if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 4, 12, 5, 13}))
9707       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V1, V2);
9708     if (isShuffleEquivalent(V1, V2, Mask, {2, 10, 3, 11, 6, 14, 7, 15}))
9709       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V1, V2);
9710     if (isShuffleEquivalent(V1, V2, Mask, {8, 0, 9, 1, 12, 4, 13, 5}))
9711       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V2, V1);
9712     if (isShuffleEquivalent(V1, V2, Mask, {10, 2, 11, 3, 14, 6, 15, 7}))
9713       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V2, V1);
9714   }
9715
9716   // Try to use shift instructions.
9717   if (SDValue Shift =
9718           lowerVectorShuffleAsShift(DL, MVT::v8i32, V1, V2, Mask, DAG))
9719     return Shift;
9720
9721   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9722           DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
9723     return Rotate;
9724
9725   // If the shuffle patterns aren't repeated but it is a single input, directly
9726   // generate a cross-lane VPERMD instruction.
9727   if (isSingleInputShuffleMask(Mask)) {
9728     SDValue VPermMask[8];
9729     for (int i = 0; i < 8; ++i)
9730       VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
9731                                  : DAG.getConstant(Mask[i], DL, MVT::i32);
9732     return DAG.getNode(
9733         X86ISD::VPERMV, DL, MVT::v8i32,
9734         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask), V1);
9735   }
9736
9737   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9738   // shuffle.
9739   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9740           DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
9741     return Result;
9742
9743   // Otherwise fall back on generic blend lowering.
9744   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i32, V1, V2,
9745                                                     Mask, DAG);
9746 }
9747
9748 /// \brief Handle lowering of 16-lane 16-bit integer shuffles.
9749 ///
9750 /// This routine is only called when we have AVX2 and thus a reasonable
9751 /// instruction set for v16i16 shuffling..
9752 static SDValue lowerV16I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9753                                         const X86Subtarget *Subtarget,
9754                                         SelectionDAG &DAG) {
9755   SDLoc DL(Op);
9756   assert(V1.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
9757   assert(V2.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
9758   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9759   ArrayRef<int> Mask = SVOp->getMask();
9760   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
9761   assert(Subtarget->hasAVX2() && "We can only lower v16i16 with AVX2!");
9762
9763   // Whenever we can lower this as a zext, that instruction is strictly faster
9764   // than any alternative. It also allows us to fold memory operands into the
9765   // shuffle in many cases.
9766   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v16i16, V1, V2,
9767                                                          Mask, Subtarget, DAG))
9768     return ZExt;
9769
9770   // Check for being able to broadcast a single element.
9771   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i16, V1,
9772                                                         Mask, Subtarget, DAG))
9773     return Broadcast;
9774
9775   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i16, V1, V2, Mask,
9776                                                 Subtarget, DAG))
9777     return Blend;
9778
9779   // Use dedicated unpack instructions for masks that match their pattern.
9780   if (isShuffleEquivalent(V1, V2, Mask,
9781                           {// First 128-bit lane:
9782                            0, 16, 1, 17, 2, 18, 3, 19,
9783                            // Second 128-bit lane:
9784                            8, 24, 9, 25, 10, 26, 11, 27}))
9785     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i16, V1, V2);
9786   if (isShuffleEquivalent(V1, V2, Mask,
9787                           {// First 128-bit lane:
9788                            4, 20, 5, 21, 6, 22, 7, 23,
9789                            // Second 128-bit lane:
9790                            12, 28, 13, 29, 14, 30, 15, 31}))
9791     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i16, V1, V2);
9792
9793   // Try to use shift instructions.
9794   if (SDValue Shift =
9795           lowerVectorShuffleAsShift(DL, MVT::v16i16, V1, V2, Mask, DAG))
9796     return Shift;
9797
9798   // Try to use byte rotation instructions.
9799   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9800           DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
9801     return Rotate;
9802
9803   if (isSingleInputShuffleMask(Mask)) {
9804     // There are no generalized cross-lane shuffle operations available on i16
9805     // element types.
9806     if (is128BitLaneCrossingShuffleMask(MVT::v16i16, Mask))
9807       return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v16i16, V1, V2,
9808                                                      Mask, DAG);
9809
9810     SmallVector<int, 8> RepeatedMask;
9811     if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
9812       // As this is a single-input shuffle, the repeated mask should be
9813       // a strictly valid v8i16 mask that we can pass through to the v8i16
9814       // lowering to handle even the v16 case.
9815       return lowerV8I16GeneralSingleInputVectorShuffle(
9816           DL, MVT::v16i16, V1, RepeatedMask, Subtarget, DAG);
9817     }
9818
9819     SDValue PSHUFBMask[32];
9820     for (int i = 0; i < 16; ++i) {
9821       if (Mask[i] == -1) {
9822         PSHUFBMask[2 * i] = PSHUFBMask[2 * i + 1] = DAG.getUNDEF(MVT::i8);
9823         continue;
9824       }
9825
9826       int M = i < 8 ? Mask[i] : Mask[i] - 8;
9827       assert(M >= 0 && M < 8 && "Invalid single-input mask!");
9828       PSHUFBMask[2 * i] = DAG.getConstant(2 * M, DL, MVT::i8);
9829       PSHUFBMask[2 * i + 1] = DAG.getConstant(2 * M + 1, DL, MVT::i8);
9830     }
9831     return DAG.getNode(
9832         ISD::BITCAST, DL, MVT::v16i16,
9833         DAG.getNode(
9834             X86ISD::PSHUFB, DL, MVT::v32i8,
9835             DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, V1),
9836             DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, PSHUFBMask)));
9837   }
9838
9839   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9840   // shuffle.
9841   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9842           DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
9843     return Result;
9844
9845   // Otherwise fall back on generic lowering.
9846   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v16i16, V1, V2, Mask, DAG);
9847 }
9848
9849 /// \brief Handle lowering of 32-lane 8-bit integer shuffles.
9850 ///
9851 /// This routine is only called when we have AVX2 and thus a reasonable
9852 /// instruction set for v32i8 shuffling..
9853 static SDValue lowerV32I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9854                                        const X86Subtarget *Subtarget,
9855                                        SelectionDAG &DAG) {
9856   SDLoc DL(Op);
9857   assert(V1.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
9858   assert(V2.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
9859   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9860   ArrayRef<int> Mask = SVOp->getMask();
9861   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
9862   assert(Subtarget->hasAVX2() && "We can only lower v32i8 with AVX2!");
9863
9864   // Whenever we can lower this as a zext, that instruction is strictly faster
9865   // than any alternative. It also allows us to fold memory operands into the
9866   // shuffle in many cases.
9867   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v32i8, V1, V2,
9868                                                          Mask, Subtarget, DAG))
9869     return ZExt;
9870
9871   // Check for being able to broadcast a single element.
9872   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v32i8, V1,
9873                                                         Mask, Subtarget, DAG))
9874     return Broadcast;
9875
9876   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v32i8, V1, V2, Mask,
9877                                                 Subtarget, DAG))
9878     return Blend;
9879
9880   // Use dedicated unpack instructions for masks that match their pattern.
9881   // Note that these are repeated 128-bit lane unpacks, not unpacks across all
9882   // 256-bit lanes.
9883   if (isShuffleEquivalent(
9884           V1, V2, Mask,
9885           {// First 128-bit lane:
9886            0, 32, 1, 33, 2, 34, 3, 35, 4, 36, 5, 37, 6, 38, 7, 39,
9887            // Second 128-bit lane:
9888            16, 48, 17, 49, 18, 50, 19, 51, 20, 52, 21, 53, 22, 54, 23, 55}))
9889     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v32i8, V1, V2);
9890   if (isShuffleEquivalent(
9891           V1, V2, Mask,
9892           {// First 128-bit lane:
9893            8, 40, 9, 41, 10, 42, 11, 43, 12, 44, 13, 45, 14, 46, 15, 47,
9894            // Second 128-bit lane:
9895            24, 56, 25, 57, 26, 58, 27, 59, 28, 60, 29, 61, 30, 62, 31, 63}))
9896     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v32i8, V1, V2);
9897
9898   // Try to use shift instructions.
9899   if (SDValue Shift =
9900           lowerVectorShuffleAsShift(DL, MVT::v32i8, V1, V2, Mask, DAG))
9901     return Shift;
9902
9903   // Try to use byte rotation instructions.
9904   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9905           DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
9906     return Rotate;
9907
9908   if (isSingleInputShuffleMask(Mask)) {
9909     // There are no generalized cross-lane shuffle operations available on i8
9910     // element types.
9911     if (is128BitLaneCrossingShuffleMask(MVT::v32i8, Mask))
9912       return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v32i8, V1, V2,
9913                                                      Mask, DAG);
9914
9915     SDValue PSHUFBMask[32];
9916     for (int i = 0; i < 32; ++i)
9917       PSHUFBMask[i] =
9918           Mask[i] < 0
9919               ? DAG.getUNDEF(MVT::i8)
9920               : DAG.getConstant(Mask[i] < 16 ? Mask[i] : Mask[i] - 16, DL,
9921                                 MVT::i8);
9922
9923     return DAG.getNode(
9924         X86ISD::PSHUFB, DL, MVT::v32i8, V1,
9925         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, PSHUFBMask));
9926   }
9927
9928   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9929   // shuffle.
9930   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9931           DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
9932     return Result;
9933
9934   // Otherwise fall back on generic lowering.
9935   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v32i8, V1, V2, Mask, DAG);
9936 }
9937
9938 /// \brief High-level routine to lower various 256-bit x86 vector shuffles.
9939 ///
9940 /// This routine either breaks down the specific type of a 256-bit x86 vector
9941 /// shuffle or splits it into two 128-bit shuffles and fuses the results back
9942 /// together based on the available instructions.
9943 static SDValue lower256BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9944                                         MVT VT, const X86Subtarget *Subtarget,
9945                                         SelectionDAG &DAG) {
9946   SDLoc DL(Op);
9947   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9948   ArrayRef<int> Mask = SVOp->getMask();
9949
9950   // If we have a single input to the zero element, insert that into V1 if we
9951   // can do so cheaply.
9952   int NumElts = VT.getVectorNumElements();
9953   int NumV2Elements = std::count_if(Mask.begin(), Mask.end(), [NumElts](int M) {
9954     return M >= NumElts;
9955   });
9956
9957   if (NumV2Elements == 1 && Mask[0] >= NumElts)
9958     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
9959                               DL, VT, V1, V2, Mask, Subtarget, DAG))
9960       return Insertion;
9961
9962   // There is a really nice hard cut-over between AVX1 and AVX2 that means we can
9963   // check for those subtargets here and avoid much of the subtarget querying in
9964   // the per-vector-type lowering routines. With AVX1 we have essentially *zero*
9965   // ability to manipulate a 256-bit vector with integer types. Since we'll use
9966   // floating point types there eventually, just immediately cast everything to
9967   // a float and operate entirely in that domain.
9968   if (VT.isInteger() && !Subtarget->hasAVX2()) {
9969     int ElementBits = VT.getScalarSizeInBits();
9970     if (ElementBits < 32)
9971       // No floating point type available, decompose into 128-bit vectors.
9972       return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9973
9974     MVT FpVT = MVT::getVectorVT(MVT::getFloatingPointVT(ElementBits),
9975                                 VT.getVectorNumElements());
9976     V1 = DAG.getNode(ISD::BITCAST, DL, FpVT, V1);
9977     V2 = DAG.getNode(ISD::BITCAST, DL, FpVT, V2);
9978     return DAG.getNode(ISD::BITCAST, DL, VT,
9979                        DAG.getVectorShuffle(FpVT, DL, V1, V2, Mask));
9980   }
9981
9982   switch (VT.SimpleTy) {
9983   case MVT::v4f64:
9984     return lowerV4F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9985   case MVT::v4i64:
9986     return lowerV4I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9987   case MVT::v8f32:
9988     return lowerV8F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9989   case MVT::v8i32:
9990     return lowerV8I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9991   case MVT::v16i16:
9992     return lowerV16I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
9993   case MVT::v32i8:
9994     return lowerV32I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
9995
9996   default:
9997     llvm_unreachable("Not a valid 256-bit x86 vector type!");
9998   }
9999 }
10000
10001 /// \brief Handle lowering of 8-lane 64-bit floating point shuffles.
10002 static SDValue lowerV8F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10003                                        const X86Subtarget *Subtarget,
10004                                        SelectionDAG &DAG) {
10005   SDLoc DL(Op);
10006   assert(V1.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
10007   assert(V2.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
10008   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10009   ArrayRef<int> Mask = SVOp->getMask();
10010   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10011
10012   // X86 has dedicated unpack instructions that can handle specific blend
10013   // operations: UNPCKH and UNPCKL.
10014   if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 2, 10, 4, 12, 6, 14}))
10015     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f64, V1, V2);
10016   if (isShuffleEquivalent(V1, V2, Mask, {1, 9, 3, 11, 5, 13, 7, 15}))
10017     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f64, V1, V2);
10018
10019   // FIXME: Implement direct support for this type!
10020   return splitAndLowerVectorShuffle(DL, MVT::v8f64, V1, V2, Mask, DAG);
10021 }
10022
10023 /// \brief Handle lowering of 16-lane 32-bit floating point shuffles.
10024 static SDValue lowerV16F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10025                                        const X86Subtarget *Subtarget,
10026                                        SelectionDAG &DAG) {
10027   SDLoc DL(Op);
10028   assert(V1.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
10029   assert(V2.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
10030   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10031   ArrayRef<int> Mask = SVOp->getMask();
10032   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10033
10034   // Use dedicated unpack instructions for masks that match their pattern.
10035   if (isShuffleEquivalent(V1, V2, Mask,
10036                           {// First 128-bit lane.
10037                            0, 16, 1, 17, 4, 20, 5, 21,
10038                            // Second 128-bit lane.
10039                            8, 24, 9, 25, 12, 28, 13, 29}))
10040     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16f32, V1, V2);
10041   if (isShuffleEquivalent(V1, V2, Mask,
10042                           {// First 128-bit lane.
10043                            2, 18, 3, 19, 6, 22, 7, 23,
10044                            // Second 128-bit lane.
10045                            10, 26, 11, 27, 14, 30, 15, 31}))
10046     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16f32, V1, V2);
10047
10048   // FIXME: Implement direct support for this type!
10049   return splitAndLowerVectorShuffle(DL, MVT::v16f32, V1, V2, Mask, DAG);
10050 }
10051
10052 /// \brief Handle lowering of 8-lane 64-bit integer shuffles.
10053 static SDValue lowerV8I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10054                                        const X86Subtarget *Subtarget,
10055                                        SelectionDAG &DAG) {
10056   SDLoc DL(Op);
10057   assert(V1.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
10058   assert(V2.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
10059   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10060   ArrayRef<int> Mask = SVOp->getMask();
10061   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10062
10063   // X86 has dedicated unpack instructions that can handle specific blend
10064   // operations: UNPCKH and UNPCKL.
10065   if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 2, 10, 4, 12, 6, 14}))
10066     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i64, V1, V2);
10067   if (isShuffleEquivalent(V1, V2, Mask, {1, 9, 3, 11, 5, 13, 7, 15}))
10068     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i64, V1, V2);
10069
10070   // FIXME: Implement direct support for this type!
10071   return splitAndLowerVectorShuffle(DL, MVT::v8i64, V1, V2, Mask, DAG);
10072 }
10073
10074 /// \brief Handle lowering of 16-lane 32-bit integer shuffles.
10075 static SDValue lowerV16I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10076                                        const X86Subtarget *Subtarget,
10077                                        SelectionDAG &DAG) {
10078   SDLoc DL(Op);
10079   assert(V1.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
10080   assert(V2.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
10081   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10082   ArrayRef<int> Mask = SVOp->getMask();
10083   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10084
10085   // Use dedicated unpack instructions for masks that match their pattern.
10086   if (isShuffleEquivalent(V1, V2, Mask,
10087                           {// First 128-bit lane.
10088                            0, 16, 1, 17, 4, 20, 5, 21,
10089                            // Second 128-bit lane.
10090                            8, 24, 9, 25, 12, 28, 13, 29}))
10091     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i32, V1, V2);
10092   if (isShuffleEquivalent(V1, V2, Mask,
10093                           {// First 128-bit lane.
10094                            2, 18, 3, 19, 6, 22, 7, 23,
10095                            // Second 128-bit lane.
10096                            10, 26, 11, 27, 14, 30, 15, 31}))
10097     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i32, V1, V2);
10098
10099   // FIXME: Implement direct support for this type!
10100   return splitAndLowerVectorShuffle(DL, MVT::v16i32, V1, V2, Mask, DAG);
10101 }
10102
10103 /// \brief Handle lowering of 32-lane 16-bit integer shuffles.
10104 static SDValue lowerV32I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10105                                         const X86Subtarget *Subtarget,
10106                                         SelectionDAG &DAG) {
10107   SDLoc DL(Op);
10108   assert(V1.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10109   assert(V2.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10110   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10111   ArrayRef<int> Mask = SVOp->getMask();
10112   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
10113   assert(Subtarget->hasBWI() && "We can only lower v32i16 with AVX-512-BWI!");
10114
10115   // FIXME: Implement direct support for this type!
10116   return splitAndLowerVectorShuffle(DL, MVT::v32i16, V1, V2, Mask, DAG);
10117 }
10118
10119 /// \brief Handle lowering of 64-lane 8-bit integer shuffles.
10120 static SDValue lowerV64I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10121                                        const X86Subtarget *Subtarget,
10122                                        SelectionDAG &DAG) {
10123   SDLoc DL(Op);
10124   assert(V1.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10125   assert(V2.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10126   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10127   ArrayRef<int> Mask = SVOp->getMask();
10128   assert(Mask.size() == 64 && "Unexpected mask size for v64 shuffle!");
10129   assert(Subtarget->hasBWI() && "We can only lower v64i8 with AVX-512-BWI!");
10130
10131   // FIXME: Implement direct support for this type!
10132   return splitAndLowerVectorShuffle(DL, MVT::v64i8, V1, V2, Mask, DAG);
10133 }
10134
10135 /// \brief High-level routine to lower various 512-bit x86 vector shuffles.
10136 ///
10137 /// This routine either breaks down the specific type of a 512-bit x86 vector
10138 /// shuffle or splits it into two 256-bit shuffles and fuses the results back
10139 /// together based on the available instructions.
10140 static SDValue lower512BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10141                                         MVT VT, const X86Subtarget *Subtarget,
10142                                         SelectionDAG &DAG) {
10143   SDLoc DL(Op);
10144   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10145   ArrayRef<int> Mask = SVOp->getMask();
10146   assert(Subtarget->hasAVX512() &&
10147          "Cannot lower 512-bit vectors w/ basic ISA!");
10148
10149   // Check for being able to broadcast a single element.
10150   if (SDValue Broadcast =
10151           lowerVectorShuffleAsBroadcast(DL, VT, V1, Mask, Subtarget, DAG))
10152     return Broadcast;
10153
10154   // Dispatch to each element type for lowering. If we don't have supprot for
10155   // specific element type shuffles at 512 bits, immediately split them and
10156   // lower them. Each lowering routine of a given type is allowed to assume that
10157   // the requisite ISA extensions for that element type are available.
10158   switch (VT.SimpleTy) {
10159   case MVT::v8f64:
10160     return lowerV8F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10161   case MVT::v16f32:
10162     return lowerV16F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10163   case MVT::v8i64:
10164     return lowerV8I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10165   case MVT::v16i32:
10166     return lowerV16I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10167   case MVT::v32i16:
10168     if (Subtarget->hasBWI())
10169       return lowerV32I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
10170     break;
10171   case MVT::v64i8:
10172     if (Subtarget->hasBWI())
10173       return lowerV64I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
10174     break;
10175
10176   default:
10177     llvm_unreachable("Not a valid 512-bit x86 vector type!");
10178   }
10179
10180   // Otherwise fall back on splitting.
10181   return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10182 }
10183
10184 /// \brief Top-level lowering for x86 vector shuffles.
10185 ///
10186 /// This handles decomposition, canonicalization, and lowering of all x86
10187 /// vector shuffles. Most of the specific lowering strategies are encapsulated
10188 /// above in helper routines. The canonicalization attempts to widen shuffles
10189 /// to involve fewer lanes of wider elements, consolidate symmetric patterns
10190 /// s.t. only one of the two inputs needs to be tested, etc.
10191 static SDValue lowerVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
10192                                   SelectionDAG &DAG) {
10193   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10194   ArrayRef<int> Mask = SVOp->getMask();
10195   SDValue V1 = Op.getOperand(0);
10196   SDValue V2 = Op.getOperand(1);
10197   MVT VT = Op.getSimpleValueType();
10198   int NumElements = VT.getVectorNumElements();
10199   SDLoc dl(Op);
10200
10201   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
10202
10203   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
10204   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
10205   if (V1IsUndef && V2IsUndef)
10206     return DAG.getUNDEF(VT);
10207
10208   // When we create a shuffle node we put the UNDEF node to second operand,
10209   // but in some cases the first operand may be transformed to UNDEF.
10210   // In this case we should just commute the node.
10211   if (V1IsUndef)
10212     return DAG.getCommutedVectorShuffle(*SVOp);
10213
10214   // Check for non-undef masks pointing at an undef vector and make the masks
10215   // undef as well. This makes it easier to match the shuffle based solely on
10216   // the mask.
10217   if (V2IsUndef)
10218     for (int M : Mask)
10219       if (M >= NumElements) {
10220         SmallVector<int, 8> NewMask(Mask.begin(), Mask.end());
10221         for (int &M : NewMask)
10222           if (M >= NumElements)
10223             M = -1;
10224         return DAG.getVectorShuffle(VT, dl, V1, V2, NewMask);
10225       }
10226
10227   // We actually see shuffles that are entirely re-arrangements of a set of
10228   // zero inputs. This mostly happens while decomposing complex shuffles into
10229   // simple ones. Directly lower these as a buildvector of zeros.
10230   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
10231   if (Zeroable.all())
10232     return getZeroVector(VT, Subtarget, DAG, dl);
10233
10234   // Try to collapse shuffles into using a vector type with fewer elements but
10235   // wider element types. We cap this to not form integers or floating point
10236   // elements wider than 64 bits, but it might be interesting to form i128
10237   // integers to handle flipping the low and high halves of AVX 256-bit vectors.
10238   SmallVector<int, 16> WidenedMask;
10239   if (VT.getScalarSizeInBits() < 64 &&
10240       canWidenShuffleElements(Mask, WidenedMask)) {
10241     MVT NewEltVT = VT.isFloatingPoint()
10242                        ? MVT::getFloatingPointVT(VT.getScalarSizeInBits() * 2)
10243                        : MVT::getIntegerVT(VT.getScalarSizeInBits() * 2);
10244     MVT NewVT = MVT::getVectorVT(NewEltVT, VT.getVectorNumElements() / 2);
10245     // Make sure that the new vector type is legal. For example, v2f64 isn't
10246     // legal on SSE1.
10247     if (DAG.getTargetLoweringInfo().isTypeLegal(NewVT)) {
10248       V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
10249       V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
10250       return DAG.getNode(ISD::BITCAST, dl, VT,
10251                          DAG.getVectorShuffle(NewVT, dl, V1, V2, WidenedMask));
10252     }
10253   }
10254
10255   int NumV1Elements = 0, NumUndefElements = 0, NumV2Elements = 0;
10256   for (int M : SVOp->getMask())
10257     if (M < 0)
10258       ++NumUndefElements;
10259     else if (M < NumElements)
10260       ++NumV1Elements;
10261     else
10262       ++NumV2Elements;
10263
10264   // Commute the shuffle as needed such that more elements come from V1 than
10265   // V2. This allows us to match the shuffle pattern strictly on how many
10266   // elements come from V1 without handling the symmetric cases.
10267   if (NumV2Elements > NumV1Elements)
10268     return DAG.getCommutedVectorShuffle(*SVOp);
10269
10270   // When the number of V1 and V2 elements are the same, try to minimize the
10271   // number of uses of V2 in the low half of the vector. When that is tied,
10272   // ensure that the sum of indices for V1 is equal to or lower than the sum
10273   // indices for V2. When those are equal, try to ensure that the number of odd
10274   // indices for V1 is lower than the number of odd indices for V2.
10275   if (NumV1Elements == NumV2Elements) {
10276     int LowV1Elements = 0, LowV2Elements = 0;
10277     for (int M : SVOp->getMask().slice(0, NumElements / 2))
10278       if (M >= NumElements)
10279         ++LowV2Elements;
10280       else if (M >= 0)
10281         ++LowV1Elements;
10282     if (LowV2Elements > LowV1Elements) {
10283       return DAG.getCommutedVectorShuffle(*SVOp);
10284     } else if (LowV2Elements == LowV1Elements) {
10285       int SumV1Indices = 0, SumV2Indices = 0;
10286       for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
10287         if (SVOp->getMask()[i] >= NumElements)
10288           SumV2Indices += i;
10289         else if (SVOp->getMask()[i] >= 0)
10290           SumV1Indices += i;
10291       if (SumV2Indices < SumV1Indices) {
10292         return DAG.getCommutedVectorShuffle(*SVOp);
10293       } else if (SumV2Indices == SumV1Indices) {
10294         int NumV1OddIndices = 0, NumV2OddIndices = 0;
10295         for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
10296           if (SVOp->getMask()[i] >= NumElements)
10297             NumV2OddIndices += i % 2;
10298           else if (SVOp->getMask()[i] >= 0)
10299             NumV1OddIndices += i % 2;
10300         if (NumV2OddIndices < NumV1OddIndices)
10301           return DAG.getCommutedVectorShuffle(*SVOp);
10302       }
10303     }
10304   }
10305
10306   // For each vector width, delegate to a specialized lowering routine.
10307   if (VT.getSizeInBits() == 128)
10308     return lower128BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10309
10310   if (VT.getSizeInBits() == 256)
10311     return lower256BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10312
10313   // Force AVX-512 vectors to be scalarized for now.
10314   // FIXME: Implement AVX-512 support!
10315   if (VT.getSizeInBits() == 512)
10316     return lower512BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10317
10318   llvm_unreachable("Unimplemented!");
10319 }
10320
10321 // This function assumes its argument is a BUILD_VECTOR of constants or
10322 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
10323 // true.
10324 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
10325                                     unsigned &MaskValue) {
10326   MaskValue = 0;
10327   unsigned NumElems = BuildVector->getNumOperands();
10328   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
10329   unsigned NumLanes = (NumElems - 1) / 8 + 1;
10330   unsigned NumElemsInLane = NumElems / NumLanes;
10331
10332   // Blend for v16i16 should be symetric for the both lanes.
10333   for (unsigned i = 0; i < NumElemsInLane; ++i) {
10334     SDValue EltCond = BuildVector->getOperand(i);
10335     SDValue SndLaneEltCond =
10336         (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
10337
10338     int Lane1Cond = -1, Lane2Cond = -1;
10339     if (isa<ConstantSDNode>(EltCond))
10340       Lane1Cond = !isZero(EltCond);
10341     if (isa<ConstantSDNode>(SndLaneEltCond))
10342       Lane2Cond = !isZero(SndLaneEltCond);
10343
10344     if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
10345       // Lane1Cond != 0, means we want the first argument.
10346       // Lane1Cond == 0, means we want the second argument.
10347       // The encoding of this argument is 0 for the first argument, 1
10348       // for the second. Therefore, invert the condition.
10349       MaskValue |= !Lane1Cond << i;
10350     else if (Lane1Cond < 0)
10351       MaskValue |= !Lane2Cond << i;
10352     else
10353       return false;
10354   }
10355   return true;
10356 }
10357
10358 /// \brief Try to lower a VSELECT instruction to a vector shuffle.
10359 static SDValue lowerVSELECTtoVectorShuffle(SDValue Op,
10360                                            const X86Subtarget *Subtarget,
10361                                            SelectionDAG &DAG) {
10362   SDValue Cond = Op.getOperand(0);
10363   SDValue LHS = Op.getOperand(1);
10364   SDValue RHS = Op.getOperand(2);
10365   SDLoc dl(Op);
10366   MVT VT = Op.getSimpleValueType();
10367
10368   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
10369     return SDValue();
10370   auto *CondBV = cast<BuildVectorSDNode>(Cond);
10371
10372   // Only non-legal VSELECTs reach this lowering, convert those into generic
10373   // shuffles and re-use the shuffle lowering path for blends.
10374   SmallVector<int, 32> Mask;
10375   for (int i = 0, Size = VT.getVectorNumElements(); i < Size; ++i) {
10376     SDValue CondElt = CondBV->getOperand(i);
10377     Mask.push_back(
10378         isa<ConstantSDNode>(CondElt) ? i + (isZero(CondElt) ? Size : 0) : -1);
10379   }
10380   return DAG.getVectorShuffle(VT, dl, LHS, RHS, Mask);
10381 }
10382
10383 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
10384   // A vselect where all conditions and data are constants can be optimized into
10385   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
10386   if (ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(0).getNode()) &&
10387       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(1).getNode()) &&
10388       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(2).getNode()))
10389     return SDValue();
10390
10391   // Try to lower this to a blend-style vector shuffle. This can handle all
10392   // constant condition cases.
10393   if (SDValue BlendOp = lowerVSELECTtoVectorShuffle(Op, Subtarget, DAG))
10394     return BlendOp;
10395
10396   // Variable blends are only legal from SSE4.1 onward.
10397   if (!Subtarget->hasSSE41())
10398     return SDValue();
10399
10400   // Only some types will be legal on some subtargets. If we can emit a legal
10401   // VSELECT-matching blend, return Op, and but if we need to expand, return
10402   // a null value.
10403   switch (Op.getSimpleValueType().SimpleTy) {
10404   default:
10405     // Most of the vector types have blends past SSE4.1.
10406     return Op;
10407
10408   case MVT::v32i8:
10409     // The byte blends for AVX vectors were introduced only in AVX2.
10410     if (Subtarget->hasAVX2())
10411       return Op;
10412
10413     return SDValue();
10414
10415   case MVT::v8i16:
10416   case MVT::v16i16:
10417     // AVX-512 BWI and VLX features support VSELECT with i16 elements.
10418     if (Subtarget->hasBWI() && Subtarget->hasVLX())
10419       return Op;
10420
10421     // FIXME: We should custom lower this by fixing the condition and using i8
10422     // blends.
10423     return SDValue();
10424   }
10425 }
10426
10427 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
10428   MVT VT = Op.getSimpleValueType();
10429   SDLoc dl(Op);
10430
10431   if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
10432     return SDValue();
10433
10434   if (VT.getSizeInBits() == 8) {
10435     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
10436                                   Op.getOperand(0), Op.getOperand(1));
10437     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
10438                                   DAG.getValueType(VT));
10439     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10440   }
10441
10442   if (VT.getSizeInBits() == 16) {
10443     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10444     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
10445     if (Idx == 0)
10446       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
10447                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10448                                      DAG.getNode(ISD::BITCAST, dl,
10449                                                  MVT::v4i32,
10450                                                  Op.getOperand(0)),
10451                                      Op.getOperand(1)));
10452     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
10453                                   Op.getOperand(0), Op.getOperand(1));
10454     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
10455                                   DAG.getValueType(VT));
10456     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10457   }
10458
10459   if (VT == MVT::f32) {
10460     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
10461     // the result back to FR32 register. It's only worth matching if the
10462     // result has a single use which is a store or a bitcast to i32.  And in
10463     // the case of a store, it's not worth it if the index is a constant 0,
10464     // because a MOVSSmr can be used instead, which is smaller and faster.
10465     if (!Op.hasOneUse())
10466       return SDValue();
10467     SDNode *User = *Op.getNode()->use_begin();
10468     if ((User->getOpcode() != ISD::STORE ||
10469          (isa<ConstantSDNode>(Op.getOperand(1)) &&
10470           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
10471         (User->getOpcode() != ISD::BITCAST ||
10472          User->getValueType(0) != MVT::i32))
10473       return SDValue();
10474     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10475                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
10476                                               Op.getOperand(0)),
10477                                               Op.getOperand(1));
10478     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
10479   }
10480
10481   if (VT == MVT::i32 || VT == MVT::i64) {
10482     // ExtractPS/pextrq works with constant index.
10483     if (isa<ConstantSDNode>(Op.getOperand(1)))
10484       return Op;
10485   }
10486   return SDValue();
10487 }
10488
10489 /// Extract one bit from mask vector, like v16i1 or v8i1.
10490 /// AVX-512 feature.
10491 SDValue
10492 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
10493   SDValue Vec = Op.getOperand(0);
10494   SDLoc dl(Vec);
10495   MVT VecVT = Vec.getSimpleValueType();
10496   SDValue Idx = Op.getOperand(1);
10497   MVT EltVT = Op.getSimpleValueType();
10498
10499   assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
10500   assert((VecVT.getVectorNumElements() <= 16 || Subtarget->hasBWI()) &&
10501          "Unexpected vector type in ExtractBitFromMaskVector");
10502
10503   // variable index can't be handled in mask registers,
10504   // extend vector to VR512
10505   if (!isa<ConstantSDNode>(Idx)) {
10506     MVT ExtVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
10507     SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
10508     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
10509                               ExtVT.getVectorElementType(), Ext, Idx);
10510     return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
10511   }
10512
10513   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10514   const TargetRegisterClass* rc = getRegClassFor(VecVT);
10515   if (!Subtarget->hasDQI() && (VecVT.getVectorNumElements() <= 8))
10516     rc = getRegClassFor(MVT::v16i1);
10517   unsigned MaxSift = rc->getSize()*8 - 1;
10518   Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
10519                     DAG.getConstant(MaxSift - IdxVal, dl, MVT::i8));
10520   Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
10521                     DAG.getConstant(MaxSift, dl, MVT::i8));
10522   return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
10523                        DAG.getIntPtrConstant(0, dl));
10524 }
10525
10526 SDValue
10527 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
10528                                            SelectionDAG &DAG) const {
10529   SDLoc dl(Op);
10530   SDValue Vec = Op.getOperand(0);
10531   MVT VecVT = Vec.getSimpleValueType();
10532   SDValue Idx = Op.getOperand(1);
10533
10534   if (Op.getSimpleValueType() == MVT::i1)
10535     return ExtractBitFromMaskVector(Op, DAG);
10536
10537   if (!isa<ConstantSDNode>(Idx)) {
10538     if (VecVT.is512BitVector() ||
10539         (VecVT.is256BitVector() && Subtarget->hasInt256() &&
10540          VecVT.getVectorElementType().getSizeInBits() == 32)) {
10541
10542       MVT MaskEltVT =
10543         MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
10544       MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
10545                                     MaskEltVT.getSizeInBits());
10546
10547       Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
10548       SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
10549                                 getZeroVector(MaskVT, Subtarget, DAG, dl),
10550                                 Idx, DAG.getConstant(0, dl, getPointerTy()));
10551       SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
10552       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(),
10553                         Perm, DAG.getConstant(0, dl, getPointerTy()));
10554     }
10555     return SDValue();
10556   }
10557
10558   // If this is a 256-bit vector result, first extract the 128-bit vector and
10559   // then extract the element from the 128-bit vector.
10560   if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
10561
10562     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10563     // Get the 128-bit vector.
10564     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
10565     MVT EltVT = VecVT.getVectorElementType();
10566
10567     unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
10568
10569     //if (IdxVal >= NumElems/2)
10570     //  IdxVal -= NumElems/2;
10571     IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
10572     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
10573                        DAG.getConstant(IdxVal, dl, MVT::i32));
10574   }
10575
10576   assert(VecVT.is128BitVector() && "Unexpected vector length");
10577
10578   if (Subtarget->hasSSE41()) {
10579     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
10580     if (Res.getNode())
10581       return Res;
10582   }
10583
10584   MVT VT = Op.getSimpleValueType();
10585   // TODO: handle v16i8.
10586   if (VT.getSizeInBits() == 16) {
10587     SDValue Vec = Op.getOperand(0);
10588     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10589     if (Idx == 0)
10590       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
10591                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10592                                      DAG.getNode(ISD::BITCAST, dl,
10593                                                  MVT::v4i32, Vec),
10594                                      Op.getOperand(1)));
10595     // Transform it so it match pextrw which produces a 32-bit result.
10596     MVT EltVT = MVT::i32;
10597     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
10598                                   Op.getOperand(0), Op.getOperand(1));
10599     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
10600                                   DAG.getValueType(VT));
10601     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10602   }
10603
10604   if (VT.getSizeInBits() == 32) {
10605     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10606     if (Idx == 0)
10607       return Op;
10608
10609     // SHUFPS the element to the lowest double word, then movss.
10610     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
10611     MVT VVT = Op.getOperand(0).getSimpleValueType();
10612     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
10613                                        DAG.getUNDEF(VVT), Mask);
10614     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
10615                        DAG.getIntPtrConstant(0, dl));
10616   }
10617
10618   if (VT.getSizeInBits() == 64) {
10619     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
10620     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
10621     //        to match extract_elt for f64.
10622     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10623     if (Idx == 0)
10624       return Op;
10625
10626     // UNPCKHPD the element to the lowest double word, then movsd.
10627     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
10628     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
10629     int Mask[2] = { 1, -1 };
10630     MVT VVT = Op.getOperand(0).getSimpleValueType();
10631     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
10632                                        DAG.getUNDEF(VVT), Mask);
10633     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
10634                        DAG.getIntPtrConstant(0, dl));
10635   }
10636
10637   return SDValue();
10638 }
10639
10640 /// Insert one bit to mask vector, like v16i1 or v8i1.
10641 /// AVX-512 feature.
10642 SDValue
10643 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
10644   SDLoc dl(Op);
10645   SDValue Vec = Op.getOperand(0);
10646   SDValue Elt = Op.getOperand(1);
10647   SDValue Idx = Op.getOperand(2);
10648   MVT VecVT = Vec.getSimpleValueType();
10649
10650   if (!isa<ConstantSDNode>(Idx)) {
10651     // Non constant index. Extend source and destination,
10652     // insert element and then truncate the result.
10653     MVT ExtVecVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
10654     MVT ExtEltVT = (VecVT == MVT::v8i1 ?  MVT::i64 : MVT::i32);
10655     SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT,
10656       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
10657       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
10658     return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
10659   }
10660
10661   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10662   SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
10663   if (Vec.getOpcode() == ISD::UNDEF)
10664     return DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
10665                        DAG.getConstant(IdxVal, dl, MVT::i8));
10666   const TargetRegisterClass* rc = getRegClassFor(VecVT);
10667   unsigned MaxSift = rc->getSize()*8 - 1;
10668   EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
10669                     DAG.getConstant(MaxSift, dl, MVT::i8));
10670   EltInVec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, EltInVec,
10671                     DAG.getConstant(MaxSift - IdxVal, dl, MVT::i8));
10672   return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
10673 }
10674
10675 SDValue X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
10676                                                   SelectionDAG &DAG) const {
10677   MVT VT = Op.getSimpleValueType();
10678   MVT EltVT = VT.getVectorElementType();
10679
10680   if (EltVT == MVT::i1)
10681     return InsertBitToMaskVector(Op, DAG);
10682
10683   SDLoc dl(Op);
10684   SDValue N0 = Op.getOperand(0);
10685   SDValue N1 = Op.getOperand(1);
10686   SDValue N2 = Op.getOperand(2);
10687   if (!isa<ConstantSDNode>(N2))
10688     return SDValue();
10689   auto *N2C = cast<ConstantSDNode>(N2);
10690   unsigned IdxVal = N2C->getZExtValue();
10691
10692   // If the vector is wider than 128 bits, extract the 128-bit subvector, insert
10693   // into that, and then insert the subvector back into the result.
10694   if (VT.is256BitVector() || VT.is512BitVector()) {
10695     // With a 256-bit vector, we can insert into the zero element efficiently
10696     // using a blend if we have AVX or AVX2 and the right data type.
10697     if (VT.is256BitVector() && IdxVal == 0) {
10698       // TODO: It is worthwhile to cast integer to floating point and back
10699       // and incur a domain crossing penalty if that's what we'll end up
10700       // doing anyway after extracting to a 128-bit vector.
10701       if ((Subtarget->hasAVX() && (EltVT == MVT::f64 || EltVT == MVT::f32)) ||
10702           (Subtarget->hasAVX2() && EltVT == MVT::i32)) {
10703         SDValue N1Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, N1);
10704         N2 = DAG.getIntPtrConstant(1, dl);
10705         return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1Vec, N2);
10706       }
10707     }
10708
10709     // Get the desired 128-bit vector chunk.
10710     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
10711
10712     // Insert the element into the desired chunk.
10713     unsigned NumEltsIn128 = 128 / EltVT.getSizeInBits();
10714     unsigned IdxIn128 = IdxVal - (IdxVal / NumEltsIn128) * NumEltsIn128;
10715
10716     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
10717                     DAG.getConstant(IdxIn128, dl, MVT::i32));
10718
10719     // Insert the changed part back into the bigger vector
10720     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
10721   }
10722   assert(VT.is128BitVector() && "Only 128-bit vector types should be left!");
10723
10724   if (Subtarget->hasSSE41()) {
10725     if (EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) {
10726       unsigned Opc;
10727       if (VT == MVT::v8i16) {
10728         Opc = X86ISD::PINSRW;
10729       } else {
10730         assert(VT == MVT::v16i8);
10731         Opc = X86ISD::PINSRB;
10732       }
10733
10734       // Transform it so it match pinsr{b,w} which expects a GR32 as its second
10735       // argument.
10736       if (N1.getValueType() != MVT::i32)
10737         N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
10738       if (N2.getValueType() != MVT::i32)
10739         N2 = DAG.getIntPtrConstant(IdxVal, dl);
10740       return DAG.getNode(Opc, dl, VT, N0, N1, N2);
10741     }
10742
10743     if (EltVT == MVT::f32) {
10744       // Bits [7:6] of the constant are the source select. This will always be
10745       //   zero here. The DAG Combiner may combine an extract_elt index into
10746       //   these bits. For example (insert (extract, 3), 2) could be matched by
10747       //   putting the '3' into bits [7:6] of X86ISD::INSERTPS.
10748       // Bits [5:4] of the constant are the destination select. This is the
10749       //   value of the incoming immediate.
10750       // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
10751       //   combine either bitwise AND or insert of float 0.0 to set these bits.
10752
10753       const Function *F = DAG.getMachineFunction().getFunction();
10754       bool MinSize = F->hasFnAttribute(Attribute::MinSize);
10755       if (IdxVal == 0 && (!MinSize || !MayFoldLoad(N1))) {
10756         // If this is an insertion of 32-bits into the low 32-bits of
10757         // a vector, we prefer to generate a blend with immediate rather
10758         // than an insertps. Blends are simpler operations in hardware and so
10759         // will always have equal or better performance than insertps.
10760         // But if optimizing for size and there's a load folding opportunity,
10761         // generate insertps because blendps does not have a 32-bit memory
10762         // operand form.
10763         N2 = DAG.getIntPtrConstant(1, dl);
10764         N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
10765         return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1, N2);
10766       }
10767       N2 = DAG.getIntPtrConstant(IdxVal << 4, dl);
10768       // Create this as a scalar to vector..
10769       N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
10770       return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
10771     }
10772
10773     if (EltVT == MVT::i32 || EltVT == MVT::i64) {
10774       // PINSR* works with constant index.
10775       return Op;
10776     }
10777   }
10778
10779   if (EltVT == MVT::i8)
10780     return SDValue();
10781
10782   if (EltVT.getSizeInBits() == 16) {
10783     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
10784     // as its second argument.
10785     if (N1.getValueType() != MVT::i32)
10786       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
10787     if (N2.getValueType() != MVT::i32)
10788       N2 = DAG.getIntPtrConstant(IdxVal, dl);
10789     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
10790   }
10791   return SDValue();
10792 }
10793
10794 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
10795   SDLoc dl(Op);
10796   MVT OpVT = Op.getSimpleValueType();
10797
10798   // If this is a 256-bit vector result, first insert into a 128-bit
10799   // vector and then insert into the 256-bit vector.
10800   if (!OpVT.is128BitVector()) {
10801     // Insert into a 128-bit vector.
10802     unsigned SizeFactor = OpVT.getSizeInBits()/128;
10803     MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
10804                                  OpVT.getVectorNumElements() / SizeFactor);
10805
10806     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
10807
10808     // Insert the 128-bit vector.
10809     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
10810   }
10811
10812   if (OpVT == MVT::v1i64 &&
10813       Op.getOperand(0).getValueType() == MVT::i64)
10814     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
10815
10816   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
10817   assert(OpVT.is128BitVector() && "Expected an SSE type!");
10818   return DAG.getNode(ISD::BITCAST, dl, OpVT,
10819                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
10820 }
10821
10822 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
10823 // a simple subregister reference or explicit instructions to grab
10824 // upper bits of a vector.
10825 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
10826                                       SelectionDAG &DAG) {
10827   SDLoc dl(Op);
10828   SDValue In =  Op.getOperand(0);
10829   SDValue Idx = Op.getOperand(1);
10830   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10831   MVT ResVT   = Op.getSimpleValueType();
10832   MVT InVT    = In.getSimpleValueType();
10833
10834   if (Subtarget->hasFp256()) {
10835     if (ResVT.is128BitVector() &&
10836         (InVT.is256BitVector() || InVT.is512BitVector()) &&
10837         isa<ConstantSDNode>(Idx)) {
10838       return Extract128BitVector(In, IdxVal, DAG, dl);
10839     }
10840     if (ResVT.is256BitVector() && InVT.is512BitVector() &&
10841         isa<ConstantSDNode>(Idx)) {
10842       return Extract256BitVector(In, IdxVal, DAG, dl);
10843     }
10844   }
10845   return SDValue();
10846 }
10847
10848 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
10849 // simple superregister reference or explicit instructions to insert
10850 // the upper bits of a vector.
10851 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
10852                                      SelectionDAG &DAG) {
10853   if (!Subtarget->hasAVX())
10854     return SDValue();
10855
10856   SDLoc dl(Op);
10857   SDValue Vec = Op.getOperand(0);
10858   SDValue SubVec = Op.getOperand(1);
10859   SDValue Idx = Op.getOperand(2);
10860
10861   if (!isa<ConstantSDNode>(Idx))
10862     return SDValue();
10863
10864   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10865   MVT OpVT = Op.getSimpleValueType();
10866   MVT SubVecVT = SubVec.getSimpleValueType();
10867
10868   // Fold two 16-byte subvector loads into one 32-byte load:
10869   // (insert_subvector (insert_subvector undef, (load addr), 0),
10870   //                   (load addr + 16), Elts/2)
10871   // --> load32 addr
10872   if ((IdxVal == OpVT.getVectorNumElements() / 2) &&
10873       Vec.getOpcode() == ISD::INSERT_SUBVECTOR &&
10874       OpVT.is256BitVector() && SubVecVT.is128BitVector() &&
10875       !Subtarget->isUnalignedMem32Slow()) {
10876     SDValue SubVec2 = Vec.getOperand(1);
10877     if (auto *Idx2 = dyn_cast<ConstantSDNode>(Vec.getOperand(2))) {
10878       if (Idx2->getZExtValue() == 0) {
10879         SDValue Ops[] = { SubVec2, SubVec };
10880         SDValue LD = EltsFromConsecutiveLoads(OpVT, Ops, dl, DAG, false);
10881         if (LD.getNode())
10882           return LD;
10883       }
10884     }
10885   }
10886
10887   if ((OpVT.is256BitVector() || OpVT.is512BitVector()) &&
10888       SubVecVT.is128BitVector())
10889     return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
10890
10891   if (OpVT.is512BitVector() && SubVecVT.is256BitVector())
10892     return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
10893
10894   if (OpVT.getVectorElementType() == MVT::i1) {
10895     if (IdxVal == 0  && Vec.getOpcode() == ISD::UNDEF) // the operation is legal
10896       return Op;
10897     SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
10898     SDValue Undef = DAG.getUNDEF(OpVT);
10899     unsigned NumElems = OpVT.getVectorNumElements();
10900     SDValue ShiftBits = DAG.getConstant(NumElems/2, dl, MVT::i8);
10901
10902     if (IdxVal == OpVT.getVectorNumElements() / 2) {
10903       // Zero upper bits of the Vec
10904       Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
10905       Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
10906
10907       SDValue Vec2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef,
10908                                  SubVec, ZeroIdx);
10909       Vec2 = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec2, ShiftBits);
10910       return DAG.getNode(ISD::OR, dl, OpVT, Vec, Vec2);
10911     }
10912     if (IdxVal == 0) {
10913       SDValue Vec2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef,
10914                                  SubVec, ZeroIdx);
10915       // Zero upper bits of the Vec2
10916       Vec2 = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec2, ShiftBits);
10917       Vec2 = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec2, ShiftBits);
10918       // Zero lower bits of the Vec
10919       Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
10920       Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
10921       // Merge them together
10922       return DAG.getNode(ISD::OR, dl, OpVT, Vec, Vec2);
10923     }
10924   }
10925   return SDValue();
10926 }
10927
10928 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
10929 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
10930 // one of the above mentioned nodes. It has to be wrapped because otherwise
10931 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
10932 // be used to form addressing mode. These wrapped nodes will be selected
10933 // into MOV32ri.
10934 SDValue
10935 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
10936   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
10937
10938   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10939   // global base reg.
10940   unsigned char OpFlag = 0;
10941   unsigned WrapperKind = X86ISD::Wrapper;
10942   CodeModel::Model M = DAG.getTarget().getCodeModel();
10943
10944   if (Subtarget->isPICStyleRIPRel() &&
10945       (M == CodeModel::Small || M == CodeModel::Kernel))
10946     WrapperKind = X86ISD::WrapperRIP;
10947   else if (Subtarget->isPICStyleGOT())
10948     OpFlag = X86II::MO_GOTOFF;
10949   else if (Subtarget->isPICStyleStubPIC())
10950     OpFlag = X86II::MO_PIC_BASE_OFFSET;
10951
10952   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
10953                                              CP->getAlignment(),
10954                                              CP->getOffset(), OpFlag);
10955   SDLoc DL(CP);
10956   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10957   // With PIC, the address is actually $g + Offset.
10958   if (OpFlag) {
10959     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10960                          DAG.getNode(X86ISD::GlobalBaseReg,
10961                                      SDLoc(), getPointerTy()),
10962                          Result);
10963   }
10964
10965   return Result;
10966 }
10967
10968 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
10969   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
10970
10971   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10972   // global base reg.
10973   unsigned char OpFlag = 0;
10974   unsigned WrapperKind = X86ISD::Wrapper;
10975   CodeModel::Model M = DAG.getTarget().getCodeModel();
10976
10977   if (Subtarget->isPICStyleRIPRel() &&
10978       (M == CodeModel::Small || M == CodeModel::Kernel))
10979     WrapperKind = X86ISD::WrapperRIP;
10980   else if (Subtarget->isPICStyleGOT())
10981     OpFlag = X86II::MO_GOTOFF;
10982   else if (Subtarget->isPICStyleStubPIC())
10983     OpFlag = X86II::MO_PIC_BASE_OFFSET;
10984
10985   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
10986                                           OpFlag);
10987   SDLoc DL(JT);
10988   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10989
10990   // With PIC, the address is actually $g + Offset.
10991   if (OpFlag)
10992     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10993                          DAG.getNode(X86ISD::GlobalBaseReg,
10994                                      SDLoc(), getPointerTy()),
10995                          Result);
10996
10997   return Result;
10998 }
10999
11000 SDValue
11001 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
11002   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
11003
11004   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11005   // global base reg.
11006   unsigned char OpFlag = 0;
11007   unsigned WrapperKind = X86ISD::Wrapper;
11008   CodeModel::Model M = DAG.getTarget().getCodeModel();
11009
11010   if (Subtarget->isPICStyleRIPRel() &&
11011       (M == CodeModel::Small || M == CodeModel::Kernel)) {
11012     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
11013       OpFlag = X86II::MO_GOTPCREL;
11014     WrapperKind = X86ISD::WrapperRIP;
11015   } else if (Subtarget->isPICStyleGOT()) {
11016     OpFlag = X86II::MO_GOT;
11017   } else if (Subtarget->isPICStyleStubPIC()) {
11018     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
11019   } else if (Subtarget->isPICStyleStubNoDynamic()) {
11020     OpFlag = X86II::MO_DARWIN_NONLAZY;
11021   }
11022
11023   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
11024
11025   SDLoc DL(Op);
11026   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
11027
11028   // With PIC, the address is actually $g + Offset.
11029   if (DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
11030       !Subtarget->is64Bit()) {
11031     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11032                          DAG.getNode(X86ISD::GlobalBaseReg,
11033                                      SDLoc(), getPointerTy()),
11034                          Result);
11035   }
11036
11037   // For symbols that require a load from a stub to get the address, emit the
11038   // load.
11039   if (isGlobalStubReference(OpFlag))
11040     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
11041                          MachinePointerInfo::getGOT(), false, false, false, 0);
11042
11043   return Result;
11044 }
11045
11046 SDValue
11047 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
11048   // Create the TargetBlockAddressAddress node.
11049   unsigned char OpFlags =
11050     Subtarget->ClassifyBlockAddressReference();
11051   CodeModel::Model M = DAG.getTarget().getCodeModel();
11052   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
11053   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
11054   SDLoc dl(Op);
11055   SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
11056                                              OpFlags);
11057
11058   if (Subtarget->isPICStyleRIPRel() &&
11059       (M == CodeModel::Small || M == CodeModel::Kernel))
11060     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
11061   else
11062     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
11063
11064   // With PIC, the address is actually $g + Offset.
11065   if (isGlobalRelativeToPICBase(OpFlags)) {
11066     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
11067                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
11068                          Result);
11069   }
11070
11071   return Result;
11072 }
11073
11074 SDValue
11075 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
11076                                       int64_t Offset, SelectionDAG &DAG) const {
11077   // Create the TargetGlobalAddress node, folding in the constant
11078   // offset if it is legal.
11079   unsigned char OpFlags =
11080       Subtarget->ClassifyGlobalReference(GV, DAG.getTarget());
11081   CodeModel::Model M = DAG.getTarget().getCodeModel();
11082   SDValue Result;
11083   if (OpFlags == X86II::MO_NO_FLAG &&
11084       X86::isOffsetSuitableForCodeModel(Offset, M)) {
11085     // A direct static reference to a global.
11086     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
11087     Offset = 0;
11088   } else {
11089     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
11090   }
11091
11092   if (Subtarget->isPICStyleRIPRel() &&
11093       (M == CodeModel::Small || M == CodeModel::Kernel))
11094     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
11095   else
11096     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
11097
11098   // With PIC, the address is actually $g + Offset.
11099   if (isGlobalRelativeToPICBase(OpFlags)) {
11100     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
11101                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
11102                          Result);
11103   }
11104
11105   // For globals that require a load from a stub to get the address, emit the
11106   // load.
11107   if (isGlobalStubReference(OpFlags))
11108     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
11109                          MachinePointerInfo::getGOT(), false, false, false, 0);
11110
11111   // If there was a non-zero offset that we didn't fold, create an explicit
11112   // addition for it.
11113   if (Offset != 0)
11114     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
11115                          DAG.getConstant(Offset, dl, getPointerTy()));
11116
11117   return Result;
11118 }
11119
11120 SDValue
11121 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
11122   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
11123   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
11124   return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
11125 }
11126
11127 static SDValue
11128 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
11129            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
11130            unsigned char OperandFlags, bool LocalDynamic = false) {
11131   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11132   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11133   SDLoc dl(GA);
11134   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11135                                            GA->getValueType(0),
11136                                            GA->getOffset(),
11137                                            OperandFlags);
11138
11139   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
11140                                            : X86ISD::TLSADDR;
11141
11142   if (InFlag) {
11143     SDValue Ops[] = { Chain,  TGA, *InFlag };
11144     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11145   } else {
11146     SDValue Ops[]  = { Chain, TGA };
11147     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11148   }
11149
11150   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
11151   MFI->setAdjustsStack(true);
11152   MFI->setHasCalls(true);
11153
11154   SDValue Flag = Chain.getValue(1);
11155   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
11156 }
11157
11158 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
11159 static SDValue
11160 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11161                                 const EVT PtrVT) {
11162   SDValue InFlag;
11163   SDLoc dl(GA);  // ? function entry point might be better
11164   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
11165                                    DAG.getNode(X86ISD::GlobalBaseReg,
11166                                                SDLoc(), PtrVT), InFlag);
11167   InFlag = Chain.getValue(1);
11168
11169   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
11170 }
11171
11172 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
11173 static SDValue
11174 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11175                                 const EVT PtrVT) {
11176   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
11177                     X86::RAX, X86II::MO_TLSGD);
11178 }
11179
11180 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
11181                                            SelectionDAG &DAG,
11182                                            const EVT PtrVT,
11183                                            bool is64Bit) {
11184   SDLoc dl(GA);
11185
11186   // Get the start address of the TLS block for this module.
11187   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
11188       .getInfo<X86MachineFunctionInfo>();
11189   MFI->incNumLocalDynamicTLSAccesses();
11190
11191   SDValue Base;
11192   if (is64Bit) {
11193     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
11194                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
11195   } else {
11196     SDValue InFlag;
11197     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
11198         DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
11199     InFlag = Chain.getValue(1);
11200     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
11201                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
11202   }
11203
11204   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
11205   // of Base.
11206
11207   // Build x@dtpoff.
11208   unsigned char OperandFlags = X86II::MO_DTPOFF;
11209   unsigned WrapperKind = X86ISD::Wrapper;
11210   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11211                                            GA->getValueType(0),
11212                                            GA->getOffset(), OperandFlags);
11213   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
11214
11215   // Add x@dtpoff with the base.
11216   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
11217 }
11218
11219 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
11220 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11221                                    const EVT PtrVT, TLSModel::Model model,
11222                                    bool is64Bit, bool isPIC) {
11223   SDLoc dl(GA);
11224
11225   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
11226   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
11227                                                          is64Bit ? 257 : 256));
11228
11229   SDValue ThreadPointer =
11230       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0, dl),
11231                   MachinePointerInfo(Ptr), false, false, false, 0);
11232
11233   unsigned char OperandFlags = 0;
11234   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
11235   // initialexec.
11236   unsigned WrapperKind = X86ISD::Wrapper;
11237   if (model == TLSModel::LocalExec) {
11238     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
11239   } else if (model == TLSModel::InitialExec) {
11240     if (is64Bit) {
11241       OperandFlags = X86II::MO_GOTTPOFF;
11242       WrapperKind = X86ISD::WrapperRIP;
11243     } else {
11244       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
11245     }
11246   } else {
11247     llvm_unreachable("Unexpected model");
11248   }
11249
11250   // emit "addl x@ntpoff,%eax" (local exec)
11251   // or "addl x@indntpoff,%eax" (initial exec)
11252   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
11253   SDValue TGA =
11254       DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
11255                                  GA->getOffset(), OperandFlags);
11256   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
11257
11258   if (model == TLSModel::InitialExec) {
11259     if (isPIC && !is64Bit) {
11260       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
11261                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
11262                            Offset);
11263     }
11264
11265     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
11266                          MachinePointerInfo::getGOT(), false, false, false, 0);
11267   }
11268
11269   // The address of the thread local variable is the add of the thread
11270   // pointer with the offset of the variable.
11271   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
11272 }
11273
11274 SDValue
11275 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
11276
11277   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
11278   const GlobalValue *GV = GA->getGlobal();
11279
11280   if (Subtarget->isTargetELF()) {
11281     TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
11282
11283     switch (model) {
11284       case TLSModel::GeneralDynamic:
11285         if (Subtarget->is64Bit())
11286           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
11287         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
11288       case TLSModel::LocalDynamic:
11289         return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
11290                                            Subtarget->is64Bit());
11291       case TLSModel::InitialExec:
11292       case TLSModel::LocalExec:
11293         return LowerToTLSExecModel(
11294             GA, DAG, getPointerTy(), model, Subtarget->is64Bit(),
11295             DAG.getTarget().getRelocationModel() == Reloc::PIC_);
11296     }
11297     llvm_unreachable("Unknown TLS model.");
11298   }
11299
11300   if (Subtarget->isTargetDarwin()) {
11301     // Darwin only has one model of TLS.  Lower to that.
11302     unsigned char OpFlag = 0;
11303     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
11304                            X86ISD::WrapperRIP : X86ISD::Wrapper;
11305
11306     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11307     // global base reg.
11308     bool PIC32 = (DAG.getTarget().getRelocationModel() == Reloc::PIC_) &&
11309                  !Subtarget->is64Bit();
11310     if (PIC32)
11311       OpFlag = X86II::MO_TLVP_PIC_BASE;
11312     else
11313       OpFlag = X86II::MO_TLVP;
11314     SDLoc DL(Op);
11315     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
11316                                                 GA->getValueType(0),
11317                                                 GA->getOffset(), OpFlag);
11318     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
11319
11320     // With PIC32, the address is actually $g + Offset.
11321     if (PIC32)
11322       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11323                            DAG.getNode(X86ISD::GlobalBaseReg,
11324                                        SDLoc(), getPointerTy()),
11325                            Offset);
11326
11327     // Lowering the machine isd will make sure everything is in the right
11328     // location.
11329     SDValue Chain = DAG.getEntryNode();
11330     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11331     SDValue Args[] = { Chain, Offset };
11332     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
11333
11334     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
11335     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11336     MFI->setAdjustsStack(true);
11337
11338     // And our return value (tls address) is in the standard call return value
11339     // location.
11340     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
11341     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
11342                               Chain.getValue(1));
11343   }
11344
11345   if (Subtarget->isTargetKnownWindowsMSVC() ||
11346       Subtarget->isTargetWindowsGNU()) {
11347     // Just use the implicit TLS architecture
11348     // Need to generate someting similar to:
11349     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
11350     //                                  ; from TEB
11351     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
11352     //   mov     rcx, qword [rdx+rcx*8]
11353     //   mov     eax, .tls$:tlsvar
11354     //   [rax+rcx] contains the address
11355     // Windows 64bit: gs:0x58
11356     // Windows 32bit: fs:__tls_array
11357
11358     SDLoc dl(GA);
11359     SDValue Chain = DAG.getEntryNode();
11360
11361     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
11362     // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
11363     // use its literal value of 0x2C.
11364     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
11365                                         ? Type::getInt8PtrTy(*DAG.getContext(),
11366                                                              256)
11367                                         : Type::getInt32PtrTy(*DAG.getContext(),
11368                                                               257));
11369
11370     SDValue TlsArray =
11371         Subtarget->is64Bit()
11372             ? DAG.getIntPtrConstant(0x58, dl)
11373             : (Subtarget->isTargetWindowsGNU()
11374                    ? DAG.getIntPtrConstant(0x2C, dl)
11375                    : DAG.getExternalSymbol("_tls_array", getPointerTy()));
11376
11377     SDValue ThreadPointer =
11378         DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
11379                     MachinePointerInfo(Ptr), false, false, false, 0);
11380
11381     // Load the _tls_index variable
11382     SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
11383     if (Subtarget->is64Bit())
11384       IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
11385                            IDX, MachinePointerInfo(), MVT::i32,
11386                            false, false, false, 0);
11387     else
11388       IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
11389                         false, false, false, 0);
11390
11391     SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()), dl,
11392                                     getPointerTy());
11393     IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
11394
11395     SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
11396     res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
11397                       false, false, false, 0);
11398
11399     // Get the offset of start of .tls section
11400     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11401                                              GA->getValueType(0),
11402                                              GA->getOffset(), X86II::MO_SECREL);
11403     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
11404
11405     // The address of the thread local variable is the add of the thread
11406     // pointer with the offset of the variable.
11407     return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
11408   }
11409
11410   llvm_unreachable("TLS not implemented for this target.");
11411 }
11412
11413 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
11414 /// and take a 2 x i32 value to shift plus a shift amount.
11415 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
11416   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
11417   MVT VT = Op.getSimpleValueType();
11418   unsigned VTBits = VT.getSizeInBits();
11419   SDLoc dl(Op);
11420   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
11421   SDValue ShOpLo = Op.getOperand(0);
11422   SDValue ShOpHi = Op.getOperand(1);
11423   SDValue ShAmt  = Op.getOperand(2);
11424   // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
11425   // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
11426   // during isel.
11427   SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
11428                                   DAG.getConstant(VTBits - 1, dl, MVT::i8));
11429   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
11430                                      DAG.getConstant(VTBits - 1, dl, MVT::i8))
11431                        : DAG.getConstant(0, dl, VT);
11432
11433   SDValue Tmp2, Tmp3;
11434   if (Op.getOpcode() == ISD::SHL_PARTS) {
11435     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
11436     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
11437   } else {
11438     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
11439     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
11440   }
11441
11442   // If the shift amount is larger or equal than the width of a part we can't
11443   // rely on the results of shld/shrd. Insert a test and select the appropriate
11444   // values for large shift amounts.
11445   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
11446                                 DAG.getConstant(VTBits, dl, MVT::i8));
11447   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11448                              AndNode, DAG.getConstant(0, dl, MVT::i8));
11449
11450   SDValue Hi, Lo;
11451   SDValue CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
11452   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
11453   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
11454
11455   if (Op.getOpcode() == ISD::SHL_PARTS) {
11456     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
11457     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
11458   } else {
11459     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
11460     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
11461   }
11462
11463   SDValue Ops[2] = { Lo, Hi };
11464   return DAG.getMergeValues(Ops, dl);
11465 }
11466
11467 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
11468                                            SelectionDAG &DAG) const {
11469   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
11470   SDLoc dl(Op);
11471
11472   if (SrcVT.isVector()) {
11473     if (SrcVT.getVectorElementType() == MVT::i1) {
11474       MVT IntegerVT = MVT::getVectorVT(MVT::i32, SrcVT.getVectorNumElements());
11475       return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
11476                          DAG.getNode(ISD::SIGN_EXTEND, dl, IntegerVT,
11477                                      Op.getOperand(0)));
11478     }
11479     return SDValue();
11480   }
11481
11482   assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
11483          "Unknown SINT_TO_FP to lower!");
11484
11485   // These are really Legal; return the operand so the caller accepts it as
11486   // Legal.
11487   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
11488     return Op;
11489   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
11490       Subtarget->is64Bit()) {
11491     return Op;
11492   }
11493
11494   unsigned Size = SrcVT.getSizeInBits()/8;
11495   MachineFunction &MF = DAG.getMachineFunction();
11496   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
11497   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11498   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11499                                StackSlot,
11500                                MachinePointerInfo::getFixedStack(SSFI),
11501                                false, false, 0);
11502   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
11503 }
11504
11505 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
11506                                      SDValue StackSlot,
11507                                      SelectionDAG &DAG) const {
11508   // Build the FILD
11509   SDLoc DL(Op);
11510   SDVTList Tys;
11511   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
11512   if (useSSE)
11513     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
11514   else
11515     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
11516
11517   unsigned ByteSize = SrcVT.getSizeInBits()/8;
11518
11519   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
11520   MachineMemOperand *MMO;
11521   if (FI) {
11522     int SSFI = FI->getIndex();
11523     MMO =
11524       DAG.getMachineFunction()
11525       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11526                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
11527   } else {
11528     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
11529     StackSlot = StackSlot.getOperand(1);
11530   }
11531   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
11532   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
11533                                            X86ISD::FILD, DL,
11534                                            Tys, Ops, SrcVT, MMO);
11535
11536   if (useSSE) {
11537     Chain = Result.getValue(1);
11538     SDValue InFlag = Result.getValue(2);
11539
11540     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
11541     // shouldn't be necessary except that RFP cannot be live across
11542     // multiple blocks. When stackifier is fixed, they can be uncoupled.
11543     MachineFunction &MF = DAG.getMachineFunction();
11544     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
11545     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
11546     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11547     Tys = DAG.getVTList(MVT::Other);
11548     SDValue Ops[] = {
11549       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
11550     };
11551     MachineMemOperand *MMO =
11552       DAG.getMachineFunction()
11553       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11554                             MachineMemOperand::MOStore, SSFISize, SSFISize);
11555
11556     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
11557                                     Ops, Op.getValueType(), MMO);
11558     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
11559                          MachinePointerInfo::getFixedStack(SSFI),
11560                          false, false, false, 0);
11561   }
11562
11563   return Result;
11564 }
11565
11566 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
11567 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
11568                                                SelectionDAG &DAG) const {
11569   // This algorithm is not obvious. Here it is what we're trying to output:
11570   /*
11571      movq       %rax,  %xmm0
11572      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
11573      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
11574      #ifdef __SSE3__
11575        haddpd   %xmm0, %xmm0
11576      #else
11577        pshufd   $0x4e, %xmm0, %xmm1
11578        addpd    %xmm1, %xmm0
11579      #endif
11580   */
11581
11582   SDLoc dl(Op);
11583   LLVMContext *Context = DAG.getContext();
11584
11585   // Build some magic constants.
11586   static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
11587   Constant *C0 = ConstantDataVector::get(*Context, CV0);
11588   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
11589
11590   SmallVector<Constant*,2> CV1;
11591   CV1.push_back(
11592     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11593                                       APInt(64, 0x4330000000000000ULL))));
11594   CV1.push_back(
11595     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11596                                       APInt(64, 0x4530000000000000ULL))));
11597   Constant *C1 = ConstantVector::get(CV1);
11598   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
11599
11600   // Load the 64-bit value into an XMM register.
11601   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
11602                             Op.getOperand(0));
11603   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
11604                               MachinePointerInfo::getConstantPool(),
11605                               false, false, false, 16);
11606   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
11607                               DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
11608                               CLod0);
11609
11610   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
11611                               MachinePointerInfo::getConstantPool(),
11612                               false, false, false, 16);
11613   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
11614   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
11615   SDValue Result;
11616
11617   if (Subtarget->hasSSE3()) {
11618     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
11619     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
11620   } else {
11621     SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
11622     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
11623                                            S2F, 0x4E, DAG);
11624     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
11625                          DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
11626                          Sub);
11627   }
11628
11629   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
11630                      DAG.getIntPtrConstant(0, dl));
11631 }
11632
11633 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
11634 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
11635                                                SelectionDAG &DAG) const {
11636   SDLoc dl(Op);
11637   // FP constant to bias correct the final result.
11638   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
11639                                    MVT::f64);
11640
11641   // Load the 32-bit value into an XMM register.
11642   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
11643                              Op.getOperand(0));
11644
11645   // Zero out the upper parts of the register.
11646   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
11647
11648   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
11649                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
11650                      DAG.getIntPtrConstant(0, dl));
11651
11652   // Or the load with the bias.
11653   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
11654                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
11655                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
11656                                                    MVT::v2f64, Load)),
11657                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
11658                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
11659                                                    MVT::v2f64, Bias)));
11660   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
11661                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
11662                    DAG.getIntPtrConstant(0, dl));
11663
11664   // Subtract the bias.
11665   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
11666
11667   // Handle final rounding.
11668   EVT DestVT = Op.getValueType();
11669
11670   if (DestVT.bitsLT(MVT::f64))
11671     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
11672                        DAG.getIntPtrConstant(0, dl));
11673   if (DestVT.bitsGT(MVT::f64))
11674     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
11675
11676   // Handle final rounding.
11677   return Sub;
11678 }
11679
11680 static SDValue lowerUINT_TO_FP_vXi32(SDValue Op, SelectionDAG &DAG,
11681                                      const X86Subtarget &Subtarget) {
11682   // The algorithm is the following:
11683   // #ifdef __SSE4_1__
11684   //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
11685   //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
11686   //                                 (uint4) 0x53000000, 0xaa);
11687   // #else
11688   //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
11689   //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
11690   // #endif
11691   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
11692   //     return (float4) lo + fhi;
11693
11694   SDLoc DL(Op);
11695   SDValue V = Op->getOperand(0);
11696   EVT VecIntVT = V.getValueType();
11697   bool Is128 = VecIntVT == MVT::v4i32;
11698   EVT VecFloatVT = Is128 ? MVT::v4f32 : MVT::v8f32;
11699   // If we convert to something else than the supported type, e.g., to v4f64,
11700   // abort early.
11701   if (VecFloatVT != Op->getValueType(0))
11702     return SDValue();
11703
11704   unsigned NumElts = VecIntVT.getVectorNumElements();
11705   assert((VecIntVT == MVT::v4i32 || VecIntVT == MVT::v8i32) &&
11706          "Unsupported custom type");
11707   assert(NumElts <= 8 && "The size of the constant array must be fixed");
11708
11709   // In the #idef/#else code, we have in common:
11710   // - The vector of constants:
11711   // -- 0x4b000000
11712   // -- 0x53000000
11713   // - A shift:
11714   // -- v >> 16
11715
11716   // Create the splat vector for 0x4b000000.
11717   SDValue CstLow = DAG.getConstant(0x4b000000, DL, MVT::i32);
11718   SDValue CstLowArray[] = {CstLow, CstLow, CstLow, CstLow,
11719                            CstLow, CstLow, CstLow, CstLow};
11720   SDValue VecCstLow = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
11721                                   makeArrayRef(&CstLowArray[0], NumElts));
11722   // Create the splat vector for 0x53000000.
11723   SDValue CstHigh = DAG.getConstant(0x53000000, DL, MVT::i32);
11724   SDValue CstHighArray[] = {CstHigh, CstHigh, CstHigh, CstHigh,
11725                             CstHigh, CstHigh, CstHigh, CstHigh};
11726   SDValue VecCstHigh = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
11727                                    makeArrayRef(&CstHighArray[0], NumElts));
11728
11729   // Create the right shift.
11730   SDValue CstShift = DAG.getConstant(16, DL, MVT::i32);
11731   SDValue CstShiftArray[] = {CstShift, CstShift, CstShift, CstShift,
11732                              CstShift, CstShift, CstShift, CstShift};
11733   SDValue VecCstShift = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
11734                                     makeArrayRef(&CstShiftArray[0], NumElts));
11735   SDValue HighShift = DAG.getNode(ISD::SRL, DL, VecIntVT, V, VecCstShift);
11736
11737   SDValue Low, High;
11738   if (Subtarget.hasSSE41()) {
11739     EVT VecI16VT = Is128 ? MVT::v8i16 : MVT::v16i16;
11740     //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
11741     SDValue VecCstLowBitcast =
11742         DAG.getNode(ISD::BITCAST, DL, VecI16VT, VecCstLow);
11743     SDValue VecBitcast = DAG.getNode(ISD::BITCAST, DL, VecI16VT, V);
11744     // Low will be bitcasted right away, so do not bother bitcasting back to its
11745     // original type.
11746     Low = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecBitcast,
11747                       VecCstLowBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
11748     //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
11749     //                                 (uint4) 0x53000000, 0xaa);
11750     SDValue VecCstHighBitcast =
11751         DAG.getNode(ISD::BITCAST, DL, VecI16VT, VecCstHigh);
11752     SDValue VecShiftBitcast =
11753         DAG.getNode(ISD::BITCAST, DL, VecI16VT, HighShift);
11754     // High will be bitcasted right away, so do not bother bitcasting back to
11755     // its original type.
11756     High = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecShiftBitcast,
11757                        VecCstHighBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
11758   } else {
11759     SDValue CstMask = DAG.getConstant(0xffff, DL, MVT::i32);
11760     SDValue VecCstMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT, CstMask,
11761                                      CstMask, CstMask, CstMask);
11762     //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
11763     SDValue LowAnd = DAG.getNode(ISD::AND, DL, VecIntVT, V, VecCstMask);
11764     Low = DAG.getNode(ISD::OR, DL, VecIntVT, LowAnd, VecCstLow);
11765
11766     //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
11767     High = DAG.getNode(ISD::OR, DL, VecIntVT, HighShift, VecCstHigh);
11768   }
11769
11770   // Create the vector constant for -(0x1.0p39f + 0x1.0p23f).
11771   SDValue CstFAdd = DAG.getConstantFP(
11772       APFloat(APFloat::IEEEsingle, APInt(32, 0xD3000080)), DL, MVT::f32);
11773   SDValue CstFAddArray[] = {CstFAdd, CstFAdd, CstFAdd, CstFAdd,
11774                             CstFAdd, CstFAdd, CstFAdd, CstFAdd};
11775   SDValue VecCstFAdd = DAG.getNode(ISD::BUILD_VECTOR, DL, VecFloatVT,
11776                                    makeArrayRef(&CstFAddArray[0], NumElts));
11777
11778   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
11779   SDValue HighBitcast = DAG.getNode(ISD::BITCAST, DL, VecFloatVT, High);
11780   SDValue FHigh =
11781       DAG.getNode(ISD::FADD, DL, VecFloatVT, HighBitcast, VecCstFAdd);
11782   //     return (float4) lo + fhi;
11783   SDValue LowBitcast = DAG.getNode(ISD::BITCAST, DL, VecFloatVT, Low);
11784   return DAG.getNode(ISD::FADD, DL, VecFloatVT, LowBitcast, FHigh);
11785 }
11786
11787 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
11788                                                SelectionDAG &DAG) const {
11789   SDValue N0 = Op.getOperand(0);
11790   MVT SVT = N0.getSimpleValueType();
11791   SDLoc dl(Op);
11792
11793   switch (SVT.SimpleTy) {
11794   default:
11795     llvm_unreachable("Custom UINT_TO_FP is not supported!");
11796   case MVT::v4i8:
11797   case MVT::v4i16:
11798   case MVT::v8i8:
11799   case MVT::v8i16: {
11800     MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
11801     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
11802                        DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
11803   }
11804   case MVT::v4i32:
11805   case MVT::v8i32:
11806     return lowerUINT_TO_FP_vXi32(Op, DAG, *Subtarget);
11807   case MVT::v16i8:
11808   case MVT::v16i16:
11809     if (Subtarget->hasAVX512())
11810       return DAG.getNode(ISD::UINT_TO_FP, dl, Op.getValueType(),
11811                          DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v16i32, N0));
11812   }
11813   llvm_unreachable(nullptr);
11814 }
11815
11816 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
11817                                            SelectionDAG &DAG) const {
11818   SDValue N0 = Op.getOperand(0);
11819   SDLoc dl(Op);
11820
11821   if (Op.getValueType().isVector())
11822     return lowerUINT_TO_FP_vec(Op, DAG);
11823
11824   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
11825   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
11826   // the optimization here.
11827   if (DAG.SignBitIsZero(N0))
11828     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
11829
11830   MVT SrcVT = N0.getSimpleValueType();
11831   MVT DstVT = Op.getSimpleValueType();
11832   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
11833     return LowerUINT_TO_FP_i64(Op, DAG);
11834   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
11835     return LowerUINT_TO_FP_i32(Op, DAG);
11836   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
11837     return SDValue();
11838
11839   // Make a 64-bit buffer, and use it to build an FILD.
11840   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
11841   if (SrcVT == MVT::i32) {
11842     SDValue WordOff = DAG.getConstant(4, dl, getPointerTy());
11843     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
11844                                      getPointerTy(), StackSlot, WordOff);
11845     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11846                                   StackSlot, MachinePointerInfo(),
11847                                   false, false, 0);
11848     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, dl, MVT::i32),
11849                                   OffsetSlot, MachinePointerInfo(),
11850                                   false, false, 0);
11851     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
11852     return Fild;
11853   }
11854
11855   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
11856   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11857                                StackSlot, MachinePointerInfo(),
11858                                false, false, 0);
11859   // For i64 source, we need to add the appropriate power of 2 if the input
11860   // was negative.  This is the same as the optimization in
11861   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
11862   // we must be careful to do the computation in x87 extended precision, not
11863   // in SSE. (The generic code can't know it's OK to do this, or how to.)
11864   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
11865   MachineMemOperand *MMO =
11866     DAG.getMachineFunction()
11867     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11868                           MachineMemOperand::MOLoad, 8, 8);
11869
11870   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
11871   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
11872   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
11873                                          MVT::i64, MMO);
11874
11875   APInt FF(32, 0x5F800000ULL);
11876
11877   // Check whether the sign bit is set.
11878   SDValue SignSet = DAG.getSetCC(dl,
11879                                  getSetCCResultType(*DAG.getContext(), MVT::i64),
11880                                  Op.getOperand(0),
11881                                  DAG.getConstant(0, dl, MVT::i64), ISD::SETLT);
11882
11883   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
11884   SDValue FudgePtr = DAG.getConstantPool(
11885                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
11886                                          getPointerTy());
11887
11888   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
11889   SDValue Zero = DAG.getIntPtrConstant(0, dl);
11890   SDValue Four = DAG.getIntPtrConstant(4, dl);
11891   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
11892                                Zero, Four);
11893   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
11894
11895   // Load the value out, extending it from f32 to f80.
11896   // FIXME: Avoid the extend by constructing the right constant pool?
11897   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
11898                                  FudgePtr, MachinePointerInfo::getConstantPool(),
11899                                  MVT::f32, false, false, false, 4);
11900   // Extend everything to 80 bits to force it to be done on x87.
11901   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
11902   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add,
11903                      DAG.getIntPtrConstant(0, dl));
11904 }
11905
11906 std::pair<SDValue,SDValue>
11907 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
11908                                     bool IsSigned, bool IsReplace) const {
11909   SDLoc DL(Op);
11910
11911   EVT DstTy = Op.getValueType();
11912
11913   if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
11914     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
11915     DstTy = MVT::i64;
11916   }
11917
11918   assert(DstTy.getSimpleVT() <= MVT::i64 &&
11919          DstTy.getSimpleVT() >= MVT::i16 &&
11920          "Unknown FP_TO_INT to lower!");
11921
11922   // These are really Legal.
11923   if (DstTy == MVT::i32 &&
11924       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
11925     return std::make_pair(SDValue(), SDValue());
11926   if (Subtarget->is64Bit() &&
11927       DstTy == MVT::i64 &&
11928       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
11929     return std::make_pair(SDValue(), SDValue());
11930
11931   // We lower FP->int64 either into FISTP64 followed by a load from a temporary
11932   // stack slot, or into the FTOL runtime function.
11933   MachineFunction &MF = DAG.getMachineFunction();
11934   unsigned MemSize = DstTy.getSizeInBits()/8;
11935   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
11936   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11937
11938   unsigned Opc;
11939   if (!IsSigned && isIntegerTypeFTOL(DstTy))
11940     Opc = X86ISD::WIN_FTOL;
11941   else
11942     switch (DstTy.getSimpleVT().SimpleTy) {
11943     default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
11944     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
11945     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
11946     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
11947     }
11948
11949   SDValue Chain = DAG.getEntryNode();
11950   SDValue Value = Op.getOperand(0);
11951   EVT TheVT = Op.getOperand(0).getValueType();
11952   // FIXME This causes a redundant load/store if the SSE-class value is already
11953   // in memory, such as if it is on the callstack.
11954   if (isScalarFPTypeInSSEReg(TheVT)) {
11955     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
11956     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
11957                          MachinePointerInfo::getFixedStack(SSFI),
11958                          false, false, 0);
11959     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
11960     SDValue Ops[] = {
11961       Chain, StackSlot, DAG.getValueType(TheVT)
11962     };
11963
11964     MachineMemOperand *MMO =
11965       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11966                               MachineMemOperand::MOLoad, MemSize, MemSize);
11967     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
11968     Chain = Value.getValue(1);
11969     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
11970     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11971   }
11972
11973   MachineMemOperand *MMO =
11974     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11975                             MachineMemOperand::MOStore, MemSize, MemSize);
11976
11977   if (Opc != X86ISD::WIN_FTOL) {
11978     // Build the FP_TO_INT*_IN_MEM
11979     SDValue Ops[] = { Chain, Value, StackSlot };
11980     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
11981                                            Ops, DstTy, MMO);
11982     return std::make_pair(FIST, StackSlot);
11983   } else {
11984     SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
11985       DAG.getVTList(MVT::Other, MVT::Glue),
11986       Chain, Value);
11987     SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
11988       MVT::i32, ftol.getValue(1));
11989     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
11990       MVT::i32, eax.getValue(2));
11991     SDValue Ops[] = { eax, edx };
11992     SDValue pair = IsReplace
11993       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops)
11994       : DAG.getMergeValues(Ops, DL);
11995     return std::make_pair(pair, SDValue());
11996   }
11997 }
11998
11999 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
12000                               const X86Subtarget *Subtarget) {
12001   MVT VT = Op->getSimpleValueType(0);
12002   SDValue In = Op->getOperand(0);
12003   MVT InVT = In.getSimpleValueType();
12004   SDLoc dl(Op);
12005
12006   if (VT.is512BitVector() || InVT.getScalarType() == MVT::i1)
12007     return DAG.getNode(ISD::ZERO_EXTEND, dl, VT, In);
12008
12009   // Optimize vectors in AVX mode:
12010   //
12011   //   v8i16 -> v8i32
12012   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
12013   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
12014   //   Concat upper and lower parts.
12015   //
12016   //   v4i32 -> v4i64
12017   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
12018   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
12019   //   Concat upper and lower parts.
12020   //
12021
12022   if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
12023       ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
12024       ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
12025     return SDValue();
12026
12027   if (Subtarget->hasInt256())
12028     return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
12029
12030   SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
12031   SDValue Undef = DAG.getUNDEF(InVT);
12032   bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
12033   SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
12034   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
12035
12036   MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
12037                              VT.getVectorNumElements()/2);
12038
12039   OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
12040   OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
12041
12042   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
12043 }
12044
12045 static  SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
12046                                         SelectionDAG &DAG) {
12047   MVT VT = Op->getSimpleValueType(0);
12048   SDValue In = Op->getOperand(0);
12049   MVT InVT = In.getSimpleValueType();
12050   SDLoc DL(Op);
12051   unsigned int NumElts = VT.getVectorNumElements();
12052   if (NumElts != 8 && NumElts != 16)
12053     return SDValue();
12054
12055   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
12056     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
12057
12058   assert(InVT.getVectorElementType() == MVT::i1);
12059   MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
12060   SDValue One =
12061    DAG.getConstant(APInt(ExtVT.getScalarSizeInBits(), 1), DL, ExtVT);
12062   SDValue Zero =
12063    DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), DL, ExtVT);
12064
12065   SDValue V = DAG.getNode(ISD::VSELECT, DL, ExtVT, In, One, Zero);
12066   if (VT.is512BitVector())
12067     return V;
12068   return DAG.getNode(X86ISD::VTRUNC, DL, VT, V);
12069 }
12070
12071 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
12072                                SelectionDAG &DAG) {
12073   if (Subtarget->hasFp256()) {
12074     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
12075     if (Res.getNode())
12076       return Res;
12077   }
12078
12079   return SDValue();
12080 }
12081
12082 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
12083                                 SelectionDAG &DAG) {
12084   SDLoc DL(Op);
12085   MVT VT = Op.getSimpleValueType();
12086   SDValue In = Op.getOperand(0);
12087   MVT SVT = In.getSimpleValueType();
12088
12089   if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
12090     return LowerZERO_EXTEND_AVX512(Op, DAG);
12091
12092   if (Subtarget->hasFp256()) {
12093     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
12094     if (Res.getNode())
12095       return Res;
12096   }
12097
12098   assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
12099          VT.getVectorNumElements() != SVT.getVectorNumElements());
12100   return SDValue();
12101 }
12102
12103 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
12104   SDLoc DL(Op);
12105   MVT VT = Op.getSimpleValueType();
12106   SDValue In = Op.getOperand(0);
12107   MVT InVT = In.getSimpleValueType();
12108
12109   if (VT == MVT::i1) {
12110     assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
12111            "Invalid scalar TRUNCATE operation");
12112     if (InVT.getSizeInBits() >= 32)
12113       return SDValue();
12114     In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
12115     return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
12116   }
12117   assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
12118          "Invalid TRUNCATE operation");
12119
12120   // move vector to mask - truncate solution for SKX
12121   if (VT.getVectorElementType() == MVT::i1) {
12122     if (InVT.is512BitVector() && InVT.getScalarSizeInBits() <= 16 &&
12123         Subtarget->hasBWI())
12124       return Op; // legal, will go to VPMOVB2M, VPMOVW2M
12125     if ((InVT.is256BitVector() || InVT.is128BitVector()) 
12126         && InVT.getScalarSizeInBits() <= 16 &&
12127         Subtarget->hasBWI() && Subtarget->hasVLX())
12128       return Op; // legal, will go to VPMOVB2M, VPMOVW2M
12129     if (InVT.is512BitVector() && InVT.getScalarSizeInBits() >= 32 &&
12130         Subtarget->hasDQI())
12131       return Op; // legal, will go to VPMOVD2M, VPMOVQ2M
12132     if ((InVT.is256BitVector() || InVT.is128BitVector()) 
12133         && InVT.getScalarSizeInBits() >= 32 &&
12134         Subtarget->hasDQI() && Subtarget->hasVLX())
12135       return Op; // legal, will go to VPMOVB2M, VPMOVQ2M
12136   }
12137   if (InVT.is512BitVector() || VT.getVectorElementType() == MVT::i1) {
12138     if (VT.getVectorElementType().getSizeInBits() >=8)
12139       return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
12140
12141     assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
12142     unsigned NumElts = InVT.getVectorNumElements();
12143     assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
12144     if (InVT.getSizeInBits() < 512) {
12145       MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
12146       In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
12147       InVT = ExtVT;
12148     }
12149
12150     SDValue OneV =
12151      DAG.getConstant(APInt::getSignBit(InVT.getScalarSizeInBits()), DL, InVT);
12152     SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
12153     return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
12154   }
12155
12156   if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
12157     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
12158     if (Subtarget->hasInt256()) {
12159       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
12160       In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
12161       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
12162                                 ShufMask);
12163       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
12164                          DAG.getIntPtrConstant(0, DL));
12165     }
12166
12167     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12168                                DAG.getIntPtrConstant(0, DL));
12169     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12170                                DAG.getIntPtrConstant(2, DL));
12171     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
12172     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
12173     static const int ShufMask[] = {0, 2, 4, 6};
12174     return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
12175   }
12176
12177   if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
12178     // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
12179     if (Subtarget->hasInt256()) {
12180       In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
12181
12182       SmallVector<SDValue,32> pshufbMask;
12183       for (unsigned i = 0; i < 2; ++i) {
12184         pshufbMask.push_back(DAG.getConstant(0x0, DL, MVT::i8));
12185         pshufbMask.push_back(DAG.getConstant(0x1, DL, MVT::i8));
12186         pshufbMask.push_back(DAG.getConstant(0x4, DL, MVT::i8));
12187         pshufbMask.push_back(DAG.getConstant(0x5, DL, MVT::i8));
12188         pshufbMask.push_back(DAG.getConstant(0x8, DL, MVT::i8));
12189         pshufbMask.push_back(DAG.getConstant(0x9, DL, MVT::i8));
12190         pshufbMask.push_back(DAG.getConstant(0xc, DL, MVT::i8));
12191         pshufbMask.push_back(DAG.getConstant(0xd, DL, MVT::i8));
12192         for (unsigned j = 0; j < 8; ++j)
12193           pshufbMask.push_back(DAG.getConstant(0x80, DL, MVT::i8));
12194       }
12195       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
12196       In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
12197       In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
12198
12199       static const int ShufMask[] = {0,  2,  -1,  -1};
12200       In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, DAG.getUNDEF(MVT::v4i64),
12201                                 &ShufMask[0]);
12202       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12203                        DAG.getIntPtrConstant(0, DL));
12204       return DAG.getNode(ISD::BITCAST, DL, VT, In);
12205     }
12206
12207     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
12208                                DAG.getIntPtrConstant(0, DL));
12209
12210     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
12211                                DAG.getIntPtrConstant(4, DL));
12212
12213     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
12214     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
12215
12216     // The PSHUFB mask:
12217     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
12218                                    -1, -1, -1, -1, -1, -1, -1, -1};
12219
12220     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
12221     OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
12222     OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
12223
12224     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
12225     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
12226
12227     // The MOVLHPS Mask:
12228     static const int ShufMask2[] = {0, 1, 4, 5};
12229     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
12230     return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
12231   }
12232
12233   // Handle truncation of V256 to V128 using shuffles.
12234   if (!VT.is128BitVector() || !InVT.is256BitVector())
12235     return SDValue();
12236
12237   assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
12238
12239   unsigned NumElems = VT.getVectorNumElements();
12240   MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
12241
12242   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
12243   // Prepare truncation shuffle mask
12244   for (unsigned i = 0; i != NumElems; ++i)
12245     MaskVec[i] = i * 2;
12246   SDValue V = DAG.getVectorShuffle(NVT, DL,
12247                                    DAG.getNode(ISD::BITCAST, DL, NVT, In),
12248                                    DAG.getUNDEF(NVT), &MaskVec[0]);
12249   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
12250                      DAG.getIntPtrConstant(0, DL));
12251 }
12252
12253 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
12254                                            SelectionDAG &DAG) const {
12255   assert(!Op.getSimpleValueType().isVector());
12256
12257   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
12258     /*IsSigned=*/ true, /*IsReplace=*/ false);
12259   SDValue FIST = Vals.first, StackSlot = Vals.second;
12260   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
12261   if (!FIST.getNode()) return Op;
12262
12263   if (StackSlot.getNode())
12264     // Load the result.
12265     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
12266                        FIST, StackSlot, MachinePointerInfo(),
12267                        false, false, false, 0);
12268
12269   // The node is the result.
12270   return FIST;
12271 }
12272
12273 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
12274                                            SelectionDAG &DAG) const {
12275   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
12276     /*IsSigned=*/ false, /*IsReplace=*/ false);
12277   SDValue FIST = Vals.first, StackSlot = Vals.second;
12278   assert(FIST.getNode() && "Unexpected failure");
12279
12280   if (StackSlot.getNode())
12281     // Load the result.
12282     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
12283                        FIST, StackSlot, MachinePointerInfo(),
12284                        false, false, false, 0);
12285
12286   // The node is the result.
12287   return FIST;
12288 }
12289
12290 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
12291   SDLoc DL(Op);
12292   MVT VT = Op.getSimpleValueType();
12293   SDValue In = Op.getOperand(0);
12294   MVT SVT = In.getSimpleValueType();
12295
12296   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
12297
12298   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
12299                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
12300                                  In, DAG.getUNDEF(SVT)));
12301 }
12302
12303 /// The only differences between FABS and FNEG are the mask and the logic op.
12304 /// FNEG also has a folding opportunity for FNEG(FABS(x)).
12305 static SDValue LowerFABSorFNEG(SDValue Op, SelectionDAG &DAG) {
12306   assert((Op.getOpcode() == ISD::FABS || Op.getOpcode() == ISD::FNEG) &&
12307          "Wrong opcode for lowering FABS or FNEG.");
12308
12309   bool IsFABS = (Op.getOpcode() == ISD::FABS);
12310
12311   // If this is a FABS and it has an FNEG user, bail out to fold the combination
12312   // into an FNABS. We'll lower the FABS after that if it is still in use.
12313   if (IsFABS)
12314     for (SDNode *User : Op->uses())
12315       if (User->getOpcode() == ISD::FNEG)
12316         return Op;
12317
12318   SDValue Op0 = Op.getOperand(0);
12319   bool IsFNABS = !IsFABS && (Op0.getOpcode() == ISD::FABS);
12320
12321   SDLoc dl(Op);
12322   MVT VT = Op.getSimpleValueType();
12323   // Assume scalar op for initialization; update for vector if needed.
12324   // Note that there are no scalar bitwise logical SSE/AVX instructions, so we
12325   // generate a 16-byte vector constant and logic op even for the scalar case.
12326   // Using a 16-byte mask allows folding the load of the mask with
12327   // the logic op, so it can save (~4 bytes) on code size.
12328   MVT EltVT = VT;
12329   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
12330   // FIXME: Use function attribute "OptimizeForSize" and/or CodeGenOpt::Level to
12331   // decide if we should generate a 16-byte constant mask when we only need 4 or
12332   // 8 bytes for the scalar case.
12333   if (VT.isVector()) {
12334     EltVT = VT.getVectorElementType();
12335     NumElts = VT.getVectorNumElements();
12336   }
12337
12338   unsigned EltBits = EltVT.getSizeInBits();
12339   LLVMContext *Context = DAG.getContext();
12340   // For FABS, mask is 0x7f...; for FNEG, mask is 0x80...
12341   APInt MaskElt =
12342     IsFABS ? APInt::getSignedMaxValue(EltBits) : APInt::getSignBit(EltBits);
12343   Constant *C = ConstantInt::get(*Context, MaskElt);
12344   C = ConstantVector::getSplat(NumElts, C);
12345   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12346   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
12347   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
12348   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
12349                              MachinePointerInfo::getConstantPool(),
12350                              false, false, false, Alignment);
12351
12352   if (VT.isVector()) {
12353     // For a vector, cast operands to a vector type, perform the logic op,
12354     // and cast the result back to the original value type.
12355     MVT VecVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
12356     SDValue MaskCasted = DAG.getNode(ISD::BITCAST, dl, VecVT, Mask);
12357     SDValue Operand = IsFNABS ?
12358       DAG.getNode(ISD::BITCAST, dl, VecVT, Op0.getOperand(0)) :
12359       DAG.getNode(ISD::BITCAST, dl, VecVT, Op0);
12360     unsigned BitOp = IsFABS ? ISD::AND : IsFNABS ? ISD::OR : ISD::XOR;
12361     return DAG.getNode(ISD::BITCAST, dl, VT,
12362                        DAG.getNode(BitOp, dl, VecVT, Operand, MaskCasted));
12363   }
12364
12365   // If not vector, then scalar.
12366   unsigned BitOp = IsFABS ? X86ISD::FAND : IsFNABS ? X86ISD::FOR : X86ISD::FXOR;
12367   SDValue Operand = IsFNABS ? Op0.getOperand(0) : Op0;
12368   return DAG.getNode(BitOp, dl, VT, Operand, Mask);
12369 }
12370
12371 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
12372   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12373   LLVMContext *Context = DAG.getContext();
12374   SDValue Op0 = Op.getOperand(0);
12375   SDValue Op1 = Op.getOperand(1);
12376   SDLoc dl(Op);
12377   MVT VT = Op.getSimpleValueType();
12378   MVT SrcVT = Op1.getSimpleValueType();
12379
12380   // If second operand is smaller, extend it first.
12381   if (SrcVT.bitsLT(VT)) {
12382     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
12383     SrcVT = VT;
12384   }
12385   // And if it is bigger, shrink it first.
12386   if (SrcVT.bitsGT(VT)) {
12387     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1, dl));
12388     SrcVT = VT;
12389   }
12390
12391   // At this point the operands and the result should have the same
12392   // type, and that won't be f80 since that is not custom lowered.
12393
12394   const fltSemantics &Sem =
12395       VT == MVT::f64 ? APFloat::IEEEdouble : APFloat::IEEEsingle;
12396   const unsigned SizeInBits = VT.getSizeInBits();
12397
12398   SmallVector<Constant *, 4> CV(
12399       VT == MVT::f64 ? 2 : 4,
12400       ConstantFP::get(*Context, APFloat(Sem, APInt(SizeInBits, 0))));
12401
12402   // First, clear all bits but the sign bit from the second operand (sign).
12403   CV[0] = ConstantFP::get(*Context,
12404                           APFloat(Sem, APInt::getHighBitsSet(SizeInBits, 1)));
12405   Constant *C = ConstantVector::get(CV);
12406   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
12407   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
12408                               MachinePointerInfo::getConstantPool(),
12409                               false, false, false, 16);
12410   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
12411
12412   // Next, clear the sign bit from the first operand (magnitude).
12413   // If it's a constant, we can clear it here.
12414   if (ConstantFPSDNode *Op0CN = dyn_cast<ConstantFPSDNode>(Op0)) {
12415     APFloat APF = Op0CN->getValueAPF();
12416     // If the magnitude is a positive zero, the sign bit alone is enough.
12417     if (APF.isPosZero())
12418       return SignBit;
12419     APF.clearSign();
12420     CV[0] = ConstantFP::get(*Context, APF);
12421   } else {
12422     CV[0] = ConstantFP::get(
12423         *Context,
12424         APFloat(Sem, APInt::getLowBitsSet(SizeInBits, SizeInBits - 1)));
12425   }
12426   C = ConstantVector::get(CV);
12427   CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
12428   SDValue Val = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
12429                             MachinePointerInfo::getConstantPool(),
12430                             false, false, false, 16);
12431   // If the magnitude operand wasn't a constant, we need to AND out the sign.
12432   if (!isa<ConstantFPSDNode>(Op0))
12433     Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Val);
12434
12435   // OR the magnitude value with the sign bit.
12436   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
12437 }
12438
12439 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
12440   SDValue N0 = Op.getOperand(0);
12441   SDLoc dl(Op);
12442   MVT VT = Op.getSimpleValueType();
12443
12444   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
12445   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
12446                                   DAG.getConstant(1, dl, VT));
12447   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, dl, VT));
12448 }
12449
12450 // Check whether an OR'd tree is PTEST-able.
12451 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
12452                                       SelectionDAG &DAG) {
12453   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
12454
12455   if (!Subtarget->hasSSE41())
12456     return SDValue();
12457
12458   if (!Op->hasOneUse())
12459     return SDValue();
12460
12461   SDNode *N = Op.getNode();
12462   SDLoc DL(N);
12463
12464   SmallVector<SDValue, 8> Opnds;
12465   DenseMap<SDValue, unsigned> VecInMap;
12466   SmallVector<SDValue, 8> VecIns;
12467   EVT VT = MVT::Other;
12468
12469   // Recognize a special case where a vector is casted into wide integer to
12470   // test all 0s.
12471   Opnds.push_back(N->getOperand(0));
12472   Opnds.push_back(N->getOperand(1));
12473
12474   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
12475     SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
12476     // BFS traverse all OR'd operands.
12477     if (I->getOpcode() == ISD::OR) {
12478       Opnds.push_back(I->getOperand(0));
12479       Opnds.push_back(I->getOperand(1));
12480       // Re-evaluate the number of nodes to be traversed.
12481       e += 2; // 2 more nodes (LHS and RHS) are pushed.
12482       continue;
12483     }
12484
12485     // Quit if a non-EXTRACT_VECTOR_ELT
12486     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
12487       return SDValue();
12488
12489     // Quit if without a constant index.
12490     SDValue Idx = I->getOperand(1);
12491     if (!isa<ConstantSDNode>(Idx))
12492       return SDValue();
12493
12494     SDValue ExtractedFromVec = I->getOperand(0);
12495     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
12496     if (M == VecInMap.end()) {
12497       VT = ExtractedFromVec.getValueType();
12498       // Quit if not 128/256-bit vector.
12499       if (!VT.is128BitVector() && !VT.is256BitVector())
12500         return SDValue();
12501       // Quit if not the same type.
12502       if (VecInMap.begin() != VecInMap.end() &&
12503           VT != VecInMap.begin()->first.getValueType())
12504         return SDValue();
12505       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
12506       VecIns.push_back(ExtractedFromVec);
12507     }
12508     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
12509   }
12510
12511   assert((VT.is128BitVector() || VT.is256BitVector()) &&
12512          "Not extracted from 128-/256-bit vector.");
12513
12514   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
12515
12516   for (DenseMap<SDValue, unsigned>::const_iterator
12517         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
12518     // Quit if not all elements are used.
12519     if (I->second != FullMask)
12520       return SDValue();
12521   }
12522
12523   EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
12524
12525   // Cast all vectors into TestVT for PTEST.
12526   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
12527     VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
12528
12529   // If more than one full vectors are evaluated, OR them first before PTEST.
12530   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
12531     // Each iteration will OR 2 nodes and append the result until there is only
12532     // 1 node left, i.e. the final OR'd value of all vectors.
12533     SDValue LHS = VecIns[Slot];
12534     SDValue RHS = VecIns[Slot + 1];
12535     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
12536   }
12537
12538   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
12539                      VecIns.back(), VecIns.back());
12540 }
12541
12542 /// \brief return true if \c Op has a use that doesn't just read flags.
12543 static bool hasNonFlagsUse(SDValue Op) {
12544   for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
12545        ++UI) {
12546     SDNode *User = *UI;
12547     unsigned UOpNo = UI.getOperandNo();
12548     if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
12549       // Look pass truncate.
12550       UOpNo = User->use_begin().getOperandNo();
12551       User = *User->use_begin();
12552     }
12553
12554     if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
12555         !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
12556       return true;
12557   }
12558   return false;
12559 }
12560
12561 /// Emit nodes that will be selected as "test Op0,Op0", or something
12562 /// equivalent.
12563 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
12564                                     SelectionDAG &DAG) const {
12565   if (Op.getValueType() == MVT::i1) {
12566     SDValue ExtOp = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i8, Op);
12567     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, ExtOp,
12568                        DAG.getConstant(0, dl, MVT::i8));
12569   }
12570   // CF and OF aren't always set the way we want. Determine which
12571   // of these we need.
12572   bool NeedCF = false;
12573   bool NeedOF = false;
12574   switch (X86CC) {
12575   default: break;
12576   case X86::COND_A: case X86::COND_AE:
12577   case X86::COND_B: case X86::COND_BE:
12578     NeedCF = true;
12579     break;
12580   case X86::COND_G: case X86::COND_GE:
12581   case X86::COND_L: case X86::COND_LE:
12582   case X86::COND_O: case X86::COND_NO: {
12583     // Check if we really need to set the
12584     // Overflow flag. If NoSignedWrap is present
12585     // that is not actually needed.
12586     switch (Op->getOpcode()) {
12587     case ISD::ADD:
12588     case ISD::SUB:
12589     case ISD::MUL:
12590     case ISD::SHL: {
12591       const BinaryWithFlagsSDNode *BinNode =
12592           cast<BinaryWithFlagsSDNode>(Op.getNode());
12593       if (BinNode->Flags.hasNoSignedWrap())
12594         break;
12595     }
12596     default:
12597       NeedOF = true;
12598       break;
12599     }
12600     break;
12601   }
12602   }
12603   // See if we can use the EFLAGS value from the operand instead of
12604   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
12605   // we prove that the arithmetic won't overflow, we can't use OF or CF.
12606   if (Op.getResNo() != 0 || NeedOF || NeedCF) {
12607     // Emit a CMP with 0, which is the TEST pattern.
12608     //if (Op.getValueType() == MVT::i1)
12609     //  return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
12610     //                     DAG.getConstant(0, MVT::i1));
12611     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
12612                        DAG.getConstant(0, dl, Op.getValueType()));
12613   }
12614   unsigned Opcode = 0;
12615   unsigned NumOperands = 0;
12616
12617   // Truncate operations may prevent the merge of the SETCC instruction
12618   // and the arithmetic instruction before it. Attempt to truncate the operands
12619   // of the arithmetic instruction and use a reduced bit-width instruction.
12620   bool NeedTruncation = false;
12621   SDValue ArithOp = Op;
12622   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
12623     SDValue Arith = Op->getOperand(0);
12624     // Both the trunc and the arithmetic op need to have one user each.
12625     if (Arith->hasOneUse())
12626       switch (Arith.getOpcode()) {
12627         default: break;
12628         case ISD::ADD:
12629         case ISD::SUB:
12630         case ISD::AND:
12631         case ISD::OR:
12632         case ISD::XOR: {
12633           NeedTruncation = true;
12634           ArithOp = Arith;
12635         }
12636       }
12637   }
12638
12639   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
12640   // which may be the result of a CAST.  We use the variable 'Op', which is the
12641   // non-casted variable when we check for possible users.
12642   switch (ArithOp.getOpcode()) {
12643   case ISD::ADD:
12644     // Due to an isel shortcoming, be conservative if this add is likely to be
12645     // selected as part of a load-modify-store instruction. When the root node
12646     // in a match is a store, isel doesn't know how to remap non-chain non-flag
12647     // uses of other nodes in the match, such as the ADD in this case. This
12648     // leads to the ADD being left around and reselected, with the result being
12649     // two adds in the output.  Alas, even if none our users are stores, that
12650     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
12651     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
12652     // climbing the DAG back to the root, and it doesn't seem to be worth the
12653     // effort.
12654     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
12655          UE = Op.getNode()->use_end(); UI != UE; ++UI)
12656       if (UI->getOpcode() != ISD::CopyToReg &&
12657           UI->getOpcode() != ISD::SETCC &&
12658           UI->getOpcode() != ISD::STORE)
12659         goto default_case;
12660
12661     if (ConstantSDNode *C =
12662         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
12663       // An add of one will be selected as an INC.
12664       if (C->getAPIntValue() == 1 && !Subtarget->slowIncDec()) {
12665         Opcode = X86ISD::INC;
12666         NumOperands = 1;
12667         break;
12668       }
12669
12670       // An add of negative one (subtract of one) will be selected as a DEC.
12671       if (C->getAPIntValue().isAllOnesValue() && !Subtarget->slowIncDec()) {
12672         Opcode = X86ISD::DEC;
12673         NumOperands = 1;
12674         break;
12675       }
12676     }
12677
12678     // Otherwise use a regular EFLAGS-setting add.
12679     Opcode = X86ISD::ADD;
12680     NumOperands = 2;
12681     break;
12682   case ISD::SHL:
12683   case ISD::SRL:
12684     // If we have a constant logical shift that's only used in a comparison
12685     // against zero turn it into an equivalent AND. This allows turning it into
12686     // a TEST instruction later.
12687     if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
12688         isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
12689       EVT VT = Op.getValueType();
12690       unsigned BitWidth = VT.getSizeInBits();
12691       unsigned ShAmt = Op->getConstantOperandVal(1);
12692       if (ShAmt >= BitWidth) // Avoid undefined shifts.
12693         break;
12694       APInt Mask = ArithOp.getOpcode() == ISD::SRL
12695                        ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
12696                        : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
12697       if (!Mask.isSignedIntN(32)) // Avoid large immediates.
12698         break;
12699       SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
12700                                 DAG.getConstant(Mask, dl, VT));
12701       DAG.ReplaceAllUsesWith(Op, New);
12702       Op = New;
12703     }
12704     break;
12705
12706   case ISD::AND:
12707     // If the primary and result isn't used, don't bother using X86ISD::AND,
12708     // because a TEST instruction will be better.
12709     if (!hasNonFlagsUse(Op))
12710       break;
12711     // FALL THROUGH
12712   case ISD::SUB:
12713   case ISD::OR:
12714   case ISD::XOR:
12715     // Due to the ISEL shortcoming noted above, be conservative if this op is
12716     // likely to be selected as part of a load-modify-store instruction.
12717     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
12718            UE = Op.getNode()->use_end(); UI != UE; ++UI)
12719       if (UI->getOpcode() == ISD::STORE)
12720         goto default_case;
12721
12722     // Otherwise use a regular EFLAGS-setting instruction.
12723     switch (ArithOp.getOpcode()) {
12724     default: llvm_unreachable("unexpected operator!");
12725     case ISD::SUB: Opcode = X86ISD::SUB; break;
12726     case ISD::XOR: Opcode = X86ISD::XOR; break;
12727     case ISD::AND: Opcode = X86ISD::AND; break;
12728     case ISD::OR: {
12729       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
12730         SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
12731         if (EFLAGS.getNode())
12732           return EFLAGS;
12733       }
12734       Opcode = X86ISD::OR;
12735       break;
12736     }
12737     }
12738
12739     NumOperands = 2;
12740     break;
12741   case X86ISD::ADD:
12742   case X86ISD::SUB:
12743   case X86ISD::INC:
12744   case X86ISD::DEC:
12745   case X86ISD::OR:
12746   case X86ISD::XOR:
12747   case X86ISD::AND:
12748     return SDValue(Op.getNode(), 1);
12749   default:
12750   default_case:
12751     break;
12752   }
12753
12754   // If we found that truncation is beneficial, perform the truncation and
12755   // update 'Op'.
12756   if (NeedTruncation) {
12757     EVT VT = Op.getValueType();
12758     SDValue WideVal = Op->getOperand(0);
12759     EVT WideVT = WideVal.getValueType();
12760     unsigned ConvertedOp = 0;
12761     // Use a target machine opcode to prevent further DAGCombine
12762     // optimizations that may separate the arithmetic operations
12763     // from the setcc node.
12764     switch (WideVal.getOpcode()) {
12765       default: break;
12766       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
12767       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
12768       case ISD::AND: ConvertedOp = X86ISD::AND; break;
12769       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
12770       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
12771     }
12772
12773     if (ConvertedOp) {
12774       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12775       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
12776         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
12777         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
12778         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
12779       }
12780     }
12781   }
12782
12783   if (Opcode == 0)
12784     // Emit a CMP with 0, which is the TEST pattern.
12785     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
12786                        DAG.getConstant(0, dl, Op.getValueType()));
12787
12788   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
12789   SmallVector<SDValue, 4> Ops(Op->op_begin(), Op->op_begin() + NumOperands);
12790
12791   SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
12792   DAG.ReplaceAllUsesWith(Op, New);
12793   return SDValue(New.getNode(), 1);
12794 }
12795
12796 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
12797 /// equivalent.
12798 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
12799                                    SDLoc dl, SelectionDAG &DAG) const {
12800   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
12801     if (C->getAPIntValue() == 0)
12802       return EmitTest(Op0, X86CC, dl, DAG);
12803
12804      if (Op0.getValueType() == MVT::i1)
12805        llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
12806   }
12807
12808   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
12809        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
12810     // Do the comparison at i32 if it's smaller, besides the Atom case.
12811     // This avoids subregister aliasing issues. Keep the smaller reference
12812     // if we're optimizing for size, however, as that'll allow better folding
12813     // of memory operations.
12814     if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
12815         !DAG.getMachineFunction().getFunction()->hasFnAttribute(
12816             Attribute::MinSize) &&
12817         !Subtarget->isAtom()) {
12818       unsigned ExtendOp =
12819           isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
12820       Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
12821       Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
12822     }
12823     // Use SUB instead of CMP to enable CSE between SUB and CMP.
12824     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
12825     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
12826                               Op0, Op1);
12827     return SDValue(Sub.getNode(), 1);
12828   }
12829   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
12830 }
12831
12832 /// Convert a comparison if required by the subtarget.
12833 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
12834                                                  SelectionDAG &DAG) const {
12835   // If the subtarget does not support the FUCOMI instruction, floating-point
12836   // comparisons have to be converted.
12837   if (Subtarget->hasCMov() ||
12838       Cmp.getOpcode() != X86ISD::CMP ||
12839       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
12840       !Cmp.getOperand(1).getValueType().isFloatingPoint())
12841     return Cmp;
12842
12843   // The instruction selector will select an FUCOM instruction instead of
12844   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
12845   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
12846   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
12847   SDLoc dl(Cmp);
12848   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
12849   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
12850   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
12851                             DAG.getConstant(8, dl, MVT::i8));
12852   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
12853   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
12854 }
12855
12856 /// The minimum architected relative accuracy is 2^-12. We need one
12857 /// Newton-Raphson step to have a good float result (24 bits of precision).
12858 SDValue X86TargetLowering::getRsqrtEstimate(SDValue Op,
12859                                             DAGCombinerInfo &DCI,
12860                                             unsigned &RefinementSteps,
12861                                             bool &UseOneConstNR) const {
12862   // FIXME: We should use instruction latency models to calculate the cost of
12863   // each potential sequence, but this is very hard to do reliably because
12864   // at least Intel's Core* chips have variable timing based on the number of
12865   // significant digits in the divisor and/or sqrt operand.
12866   if (!Subtarget->useSqrtEst())
12867     return SDValue();
12868
12869   EVT VT = Op.getValueType();
12870
12871   // SSE1 has rsqrtss and rsqrtps.
12872   // TODO: Add support for AVX512 (v16f32).
12873   // It is likely not profitable to do this for f64 because a double-precision
12874   // rsqrt estimate with refinement on x86 prior to FMA requires at least 16
12875   // instructions: convert to single, rsqrtss, convert back to double, refine
12876   // (3 steps = at least 13 insts). If an 'rsqrtsd' variant was added to the ISA
12877   // along with FMA, this could be a throughput win.
12878   if ((Subtarget->hasSSE1() && (VT == MVT::f32 || VT == MVT::v4f32)) ||
12879       (Subtarget->hasAVX() && VT == MVT::v8f32)) {
12880     RefinementSteps = 1;
12881     UseOneConstNR = false;
12882     return DCI.DAG.getNode(X86ISD::FRSQRT, SDLoc(Op), VT, Op);
12883   }
12884   return SDValue();
12885 }
12886
12887 /// The minimum architected relative accuracy is 2^-12. We need one
12888 /// Newton-Raphson step to have a good float result (24 bits of precision).
12889 SDValue X86TargetLowering::getRecipEstimate(SDValue Op,
12890                                             DAGCombinerInfo &DCI,
12891                                             unsigned &RefinementSteps) const {
12892   // FIXME: We should use instruction latency models to calculate the cost of
12893   // each potential sequence, but this is very hard to do reliably because
12894   // at least Intel's Core* chips have variable timing based on the number of
12895   // significant digits in the divisor.
12896   if (!Subtarget->useReciprocalEst())
12897     return SDValue();
12898
12899   EVT VT = Op.getValueType();
12900
12901   // SSE1 has rcpss and rcpps. AVX adds a 256-bit variant for rcpps.
12902   // TODO: Add support for AVX512 (v16f32).
12903   // It is likely not profitable to do this for f64 because a double-precision
12904   // reciprocal estimate with refinement on x86 prior to FMA requires
12905   // 15 instructions: convert to single, rcpss, convert back to double, refine
12906   // (3 steps = 12 insts). If an 'rcpsd' variant was added to the ISA
12907   // along with FMA, this could be a throughput win.
12908   if ((Subtarget->hasSSE1() && (VT == MVT::f32 || VT == MVT::v4f32)) ||
12909       (Subtarget->hasAVX() && VT == MVT::v8f32)) {
12910     RefinementSteps = ReciprocalEstimateRefinementSteps;
12911     return DCI.DAG.getNode(X86ISD::FRCP, SDLoc(Op), VT, Op);
12912   }
12913   return SDValue();
12914 }
12915
12916 /// If we have at least two divisions that use the same divisor, convert to
12917 /// multplication by a reciprocal. This may need to be adjusted for a given
12918 /// CPU if a division's cost is not at least twice the cost of a multiplication.
12919 /// This is because we still need one division to calculate the reciprocal and
12920 /// then we need two multiplies by that reciprocal as replacements for the
12921 /// original divisions.
12922 bool X86TargetLowering::combineRepeatedFPDivisors(unsigned NumUsers) const {
12923   return NumUsers > 1;
12924 }
12925
12926 static bool isAllOnes(SDValue V) {
12927   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
12928   return C && C->isAllOnesValue();
12929 }
12930
12931 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
12932 /// if it's possible.
12933 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
12934                                      SDLoc dl, SelectionDAG &DAG) const {
12935   SDValue Op0 = And.getOperand(0);
12936   SDValue Op1 = And.getOperand(1);
12937   if (Op0.getOpcode() == ISD::TRUNCATE)
12938     Op0 = Op0.getOperand(0);
12939   if (Op1.getOpcode() == ISD::TRUNCATE)
12940     Op1 = Op1.getOperand(0);
12941
12942   SDValue LHS, RHS;
12943   if (Op1.getOpcode() == ISD::SHL)
12944     std::swap(Op0, Op1);
12945   if (Op0.getOpcode() == ISD::SHL) {
12946     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
12947       if (And00C->getZExtValue() == 1) {
12948         // If we looked past a truncate, check that it's only truncating away
12949         // known zeros.
12950         unsigned BitWidth = Op0.getValueSizeInBits();
12951         unsigned AndBitWidth = And.getValueSizeInBits();
12952         if (BitWidth > AndBitWidth) {
12953           APInt Zeros, Ones;
12954           DAG.computeKnownBits(Op0, Zeros, Ones);
12955           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
12956             return SDValue();
12957         }
12958         LHS = Op1;
12959         RHS = Op0.getOperand(1);
12960       }
12961   } else if (Op1.getOpcode() == ISD::Constant) {
12962     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
12963     uint64_t AndRHSVal = AndRHS->getZExtValue();
12964     SDValue AndLHS = Op0;
12965
12966     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
12967       LHS = AndLHS.getOperand(0);
12968       RHS = AndLHS.getOperand(1);
12969     }
12970
12971     // Use BT if the immediate can't be encoded in a TEST instruction.
12972     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
12973       LHS = AndLHS;
12974       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), dl, LHS.getValueType());
12975     }
12976   }
12977
12978   if (LHS.getNode()) {
12979     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
12980     // instruction.  Since the shift amount is in-range-or-undefined, we know
12981     // that doing a bittest on the i32 value is ok.  We extend to i32 because
12982     // the encoding for the i16 version is larger than the i32 version.
12983     // Also promote i16 to i32 for performance / code size reason.
12984     if (LHS.getValueType() == MVT::i8 ||
12985         LHS.getValueType() == MVT::i16)
12986       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
12987
12988     // If the operand types disagree, extend the shift amount to match.  Since
12989     // BT ignores high bits (like shifts) we can use anyextend.
12990     if (LHS.getValueType() != RHS.getValueType())
12991       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
12992
12993     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
12994     X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
12995     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12996                        DAG.getConstant(Cond, dl, MVT::i8), BT);
12997   }
12998
12999   return SDValue();
13000 }
13001
13002 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
13003 /// mask CMPs.
13004 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
13005                               SDValue &Op1) {
13006   unsigned SSECC;
13007   bool Swap = false;
13008
13009   // SSE Condition code mapping:
13010   //  0 - EQ
13011   //  1 - LT
13012   //  2 - LE
13013   //  3 - UNORD
13014   //  4 - NEQ
13015   //  5 - NLT
13016   //  6 - NLE
13017   //  7 - ORD
13018   switch (SetCCOpcode) {
13019   default: llvm_unreachable("Unexpected SETCC condition");
13020   case ISD::SETOEQ:
13021   case ISD::SETEQ:  SSECC = 0; break;
13022   case ISD::SETOGT:
13023   case ISD::SETGT:  Swap = true; // Fallthrough
13024   case ISD::SETLT:
13025   case ISD::SETOLT: SSECC = 1; break;
13026   case ISD::SETOGE:
13027   case ISD::SETGE:  Swap = true; // Fallthrough
13028   case ISD::SETLE:
13029   case ISD::SETOLE: SSECC = 2; break;
13030   case ISD::SETUO:  SSECC = 3; break;
13031   case ISD::SETUNE:
13032   case ISD::SETNE:  SSECC = 4; break;
13033   case ISD::SETULE: Swap = true; // Fallthrough
13034   case ISD::SETUGE: SSECC = 5; break;
13035   case ISD::SETULT: Swap = true; // Fallthrough
13036   case ISD::SETUGT: SSECC = 6; break;
13037   case ISD::SETO:   SSECC = 7; break;
13038   case ISD::SETUEQ:
13039   case ISD::SETONE: SSECC = 8; break;
13040   }
13041   if (Swap)
13042     std::swap(Op0, Op1);
13043
13044   return SSECC;
13045 }
13046
13047 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
13048 // ones, and then concatenate the result back.
13049 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
13050   MVT VT = Op.getSimpleValueType();
13051
13052   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
13053          "Unsupported value type for operation");
13054
13055   unsigned NumElems = VT.getVectorNumElements();
13056   SDLoc dl(Op);
13057   SDValue CC = Op.getOperand(2);
13058
13059   // Extract the LHS vectors
13060   SDValue LHS = Op.getOperand(0);
13061   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
13062   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
13063
13064   // Extract the RHS vectors
13065   SDValue RHS = Op.getOperand(1);
13066   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
13067   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
13068
13069   // Issue the operation on the smaller types and concatenate the result back
13070   MVT EltVT = VT.getVectorElementType();
13071   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13072   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
13073                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
13074                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
13075 }
13076
13077 static SDValue LowerBoolVSETCC_AVX512(SDValue Op, SelectionDAG &DAG) {
13078   SDValue Op0 = Op.getOperand(0);
13079   SDValue Op1 = Op.getOperand(1);
13080   SDValue CC = Op.getOperand(2);
13081   MVT VT = Op.getSimpleValueType();
13082   SDLoc dl(Op);
13083
13084   assert(Op0.getValueType().getVectorElementType() == MVT::i1 &&
13085          "Unexpected type for boolean compare operation");
13086   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13087   SDValue NotOp0 = DAG.getNode(ISD::XOR, dl, VT, Op0,
13088                                DAG.getConstant(-1, dl, VT));
13089   SDValue NotOp1 = DAG.getNode(ISD::XOR, dl, VT, Op1,
13090                                DAG.getConstant(-1, dl, VT));
13091   switch (SetCCOpcode) {
13092   default: llvm_unreachable("Unexpected SETCC condition");
13093   case ISD::SETNE:
13094     // (x != y) -> ~(x ^ y)
13095     return DAG.getNode(ISD::XOR, dl, VT,
13096                        DAG.getNode(ISD::XOR, dl, VT, Op0, Op1),
13097                        DAG.getConstant(-1, dl, VT));
13098   case ISD::SETEQ:
13099     // (x == y) -> (x ^ y)
13100     return DAG.getNode(ISD::XOR, dl, VT, Op0, Op1);
13101   case ISD::SETUGT:
13102   case ISD::SETGT:
13103     // (x > y) -> (x & ~y)
13104     return DAG.getNode(ISD::AND, dl, VT, Op0, NotOp1);
13105   case ISD::SETULT:
13106   case ISD::SETLT:
13107     // (x < y) -> (~x & y)
13108     return DAG.getNode(ISD::AND, dl, VT, NotOp0, Op1);
13109   case ISD::SETULE:
13110   case ISD::SETLE:
13111     // (x <= y) -> (~x | y)
13112     return DAG.getNode(ISD::OR, dl, VT, NotOp0, Op1);
13113   case ISD::SETUGE:
13114   case ISD::SETGE:
13115     // (x >=y) -> (x | ~y)
13116     return DAG.getNode(ISD::OR, dl, VT, Op0, NotOp1);
13117   }
13118 }
13119
13120 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
13121                                      const X86Subtarget *Subtarget) {
13122   SDValue Op0 = Op.getOperand(0);
13123   SDValue Op1 = Op.getOperand(1);
13124   SDValue CC = Op.getOperand(2);
13125   MVT VT = Op.getSimpleValueType();
13126   SDLoc dl(Op);
13127
13128   assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 8 &&
13129          Op.getValueType().getScalarType() == MVT::i1 &&
13130          "Cannot set masked compare for this operation");
13131
13132   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13133   unsigned  Opc = 0;
13134   bool Unsigned = false;
13135   bool Swap = false;
13136   unsigned SSECC;
13137   switch (SetCCOpcode) {
13138   default: llvm_unreachable("Unexpected SETCC condition");
13139   case ISD::SETNE:  SSECC = 4; break;
13140   case ISD::SETEQ:  Opc = X86ISD::PCMPEQM; break;
13141   case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
13142   case ISD::SETLT:  Swap = true; //fall-through
13143   case ISD::SETGT:  Opc = X86ISD::PCMPGTM; break;
13144   case ISD::SETULT: SSECC = 1; Unsigned = true; break;
13145   case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
13146   case ISD::SETGE:  Swap = true; SSECC = 2; break; // LE + swap
13147   case ISD::SETULE: Unsigned = true; //fall-through
13148   case ISD::SETLE:  SSECC = 2; break;
13149   }
13150
13151   if (Swap)
13152     std::swap(Op0, Op1);
13153   if (Opc)
13154     return DAG.getNode(Opc, dl, VT, Op0, Op1);
13155   Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
13156   return DAG.getNode(Opc, dl, VT, Op0, Op1,
13157                      DAG.getConstant(SSECC, dl, MVT::i8));
13158 }
13159
13160 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
13161 /// operand \p Op1.  If non-trivial (for example because it's not constant)
13162 /// return an empty value.
13163 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
13164 {
13165   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
13166   if (!BV)
13167     return SDValue();
13168
13169   MVT VT = Op1.getSimpleValueType();
13170   MVT EVT = VT.getVectorElementType();
13171   unsigned n = VT.getVectorNumElements();
13172   SmallVector<SDValue, 8> ULTOp1;
13173
13174   for (unsigned i = 0; i < n; ++i) {
13175     ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
13176     if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
13177       return SDValue();
13178
13179     // Avoid underflow.
13180     APInt Val = Elt->getAPIntValue();
13181     if (Val == 0)
13182       return SDValue();
13183
13184     ULTOp1.push_back(DAG.getConstant(Val - 1, dl, EVT));
13185   }
13186
13187   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
13188 }
13189
13190 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
13191                            SelectionDAG &DAG) {
13192   SDValue Op0 = Op.getOperand(0);
13193   SDValue Op1 = Op.getOperand(1);
13194   SDValue CC = Op.getOperand(2);
13195   MVT VT = Op.getSimpleValueType();
13196   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13197   bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
13198   SDLoc dl(Op);
13199
13200   if (isFP) {
13201 #ifndef NDEBUG
13202     MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
13203     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
13204 #endif
13205
13206     unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
13207     unsigned Opc = X86ISD::CMPP;
13208     if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
13209       assert(VT.getVectorNumElements() <= 16);
13210       Opc = X86ISD::CMPM;
13211     }
13212     // In the two special cases we can't handle, emit two comparisons.
13213     if (SSECC == 8) {
13214       unsigned CC0, CC1;
13215       unsigned CombineOpc;
13216       if (SetCCOpcode == ISD::SETUEQ) {
13217         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
13218       } else {
13219         assert(SetCCOpcode == ISD::SETONE);
13220         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
13221       }
13222
13223       SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
13224                                  DAG.getConstant(CC0, dl, MVT::i8));
13225       SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
13226                                  DAG.getConstant(CC1, dl, MVT::i8));
13227       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
13228     }
13229     // Handle all other FP comparisons here.
13230     return DAG.getNode(Opc, dl, VT, Op0, Op1,
13231                        DAG.getConstant(SSECC, dl, MVT::i8));
13232   }
13233
13234   // Break 256-bit integer vector compare into smaller ones.
13235   if (VT.is256BitVector() && !Subtarget->hasInt256())
13236     return Lower256IntVSETCC(Op, DAG);
13237
13238   EVT OpVT = Op1.getValueType();
13239   if (OpVT.getVectorElementType() == MVT::i1)
13240     return LowerBoolVSETCC_AVX512(Op, DAG);
13241
13242   bool MaskResult = (VT.getVectorElementType() == MVT::i1);
13243   if (Subtarget->hasAVX512()) {
13244     if (Op1.getValueType().is512BitVector() ||
13245         (Subtarget->hasBWI() && Subtarget->hasVLX()) ||
13246         (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
13247       return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
13248
13249     // In AVX-512 architecture setcc returns mask with i1 elements,
13250     // But there is no compare instruction for i8 and i16 elements in KNL.
13251     // We are not talking about 512-bit operands in this case, these
13252     // types are illegal.
13253     if (MaskResult &&
13254         (OpVT.getVectorElementType().getSizeInBits() < 32 &&
13255          OpVT.getVectorElementType().getSizeInBits() >= 8))
13256       return DAG.getNode(ISD::TRUNCATE, dl, VT,
13257                          DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
13258   }
13259
13260   // We are handling one of the integer comparisons here.  Since SSE only has
13261   // GT and EQ comparisons for integer, swapping operands and multiple
13262   // operations may be required for some comparisons.
13263   unsigned Opc;
13264   bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
13265   bool Subus = false;
13266
13267   switch (SetCCOpcode) {
13268   default: llvm_unreachable("Unexpected SETCC condition");
13269   case ISD::SETNE:  Invert = true;
13270   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
13271   case ISD::SETLT:  Swap = true;
13272   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
13273   case ISD::SETGE:  Swap = true;
13274   case ISD::SETLE:  Opc = X86ISD::PCMPGT;
13275                     Invert = true; break;
13276   case ISD::SETULT: Swap = true;
13277   case ISD::SETUGT: Opc = X86ISD::PCMPGT;
13278                     FlipSigns = true; break;
13279   case ISD::SETUGE: Swap = true;
13280   case ISD::SETULE: Opc = X86ISD::PCMPGT;
13281                     FlipSigns = true; Invert = true; break;
13282   }
13283
13284   // Special case: Use min/max operations for SETULE/SETUGE
13285   MVT VET = VT.getVectorElementType();
13286   bool hasMinMax =
13287        (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
13288     || (Subtarget->hasSSE2()  && (VET == MVT::i8));
13289
13290   if (hasMinMax) {
13291     switch (SetCCOpcode) {
13292     default: break;
13293     case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
13294     case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
13295     }
13296
13297     if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
13298   }
13299
13300   bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
13301   if (!MinMax && hasSubus) {
13302     // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
13303     // Op0 u<= Op1:
13304     //   t = psubus Op0, Op1
13305     //   pcmpeq t, <0..0>
13306     switch (SetCCOpcode) {
13307     default: break;
13308     case ISD::SETULT: {
13309       // If the comparison is against a constant we can turn this into a
13310       // setule.  With psubus, setule does not require a swap.  This is
13311       // beneficial because the constant in the register is no longer
13312       // destructed as the destination so it can be hoisted out of a loop.
13313       // Only do this pre-AVX since vpcmp* is no longer destructive.
13314       if (Subtarget->hasAVX())
13315         break;
13316       SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
13317       if (ULEOp1.getNode()) {
13318         Op1 = ULEOp1;
13319         Subus = true; Invert = false; Swap = false;
13320       }
13321       break;
13322     }
13323     // Psubus is better than flip-sign because it requires no inversion.
13324     case ISD::SETUGE: Subus = true; Invert = false; Swap = true;  break;
13325     case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
13326     }
13327
13328     if (Subus) {
13329       Opc = X86ISD::SUBUS;
13330       FlipSigns = false;
13331     }
13332   }
13333
13334   if (Swap)
13335     std::swap(Op0, Op1);
13336
13337   // Check that the operation in question is available (most are plain SSE2,
13338   // but PCMPGTQ and PCMPEQQ have different requirements).
13339   if (VT == MVT::v2i64) {
13340     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
13341       assert(Subtarget->hasSSE2() && "Don't know how to lower!");
13342
13343       // First cast everything to the right type.
13344       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
13345       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
13346
13347       // Since SSE has no unsigned integer comparisons, we need to flip the sign
13348       // bits of the inputs before performing those operations. The lower
13349       // compare is always unsigned.
13350       SDValue SB;
13351       if (FlipSigns) {
13352         SB = DAG.getConstant(0x80000000U, dl, MVT::v4i32);
13353       } else {
13354         SDValue Sign = DAG.getConstant(0x80000000U, dl, MVT::i32);
13355         SDValue Zero = DAG.getConstant(0x00000000U, dl, MVT::i32);
13356         SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
13357                          Sign, Zero, Sign, Zero);
13358       }
13359       Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
13360       Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
13361
13362       // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
13363       SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
13364       SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
13365
13366       // Create masks for only the low parts/high parts of the 64 bit integers.
13367       static const int MaskHi[] = { 1, 1, 3, 3 };
13368       static const int MaskLo[] = { 0, 0, 2, 2 };
13369       SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
13370       SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
13371       SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
13372
13373       SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
13374       Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
13375
13376       if (Invert)
13377         Result = DAG.getNOT(dl, Result, MVT::v4i32);
13378
13379       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
13380     }
13381
13382     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
13383       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
13384       // pcmpeqd + pshufd + pand.
13385       assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
13386
13387       // First cast everything to the right type.
13388       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
13389       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
13390
13391       // Do the compare.
13392       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
13393
13394       // Make sure the lower and upper halves are both all-ones.
13395       static const int Mask[] = { 1, 0, 3, 2 };
13396       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
13397       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
13398
13399       if (Invert)
13400         Result = DAG.getNOT(dl, Result, MVT::v4i32);
13401
13402       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
13403     }
13404   }
13405
13406   // Since SSE has no unsigned integer comparisons, we need to flip the sign
13407   // bits of the inputs before performing those operations.
13408   if (FlipSigns) {
13409     EVT EltVT = VT.getVectorElementType();
13410     SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), dl,
13411                                  VT);
13412     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
13413     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
13414   }
13415
13416   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
13417
13418   // If the logical-not of the result is required, perform that now.
13419   if (Invert)
13420     Result = DAG.getNOT(dl, Result, VT);
13421
13422   if (MinMax)
13423     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
13424
13425   if (Subus)
13426     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
13427                          getZeroVector(VT, Subtarget, DAG, dl));
13428
13429   return Result;
13430 }
13431
13432 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
13433
13434   MVT VT = Op.getSimpleValueType();
13435
13436   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
13437
13438   assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
13439          && "SetCC type must be 8-bit or 1-bit integer");
13440   SDValue Op0 = Op.getOperand(0);
13441   SDValue Op1 = Op.getOperand(1);
13442   SDLoc dl(Op);
13443   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
13444
13445   // Optimize to BT if possible.
13446   // Lower (X & (1 << N)) == 0 to BT(X, N).
13447   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
13448   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
13449   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
13450       Op1.getOpcode() == ISD::Constant &&
13451       cast<ConstantSDNode>(Op1)->isNullValue() &&
13452       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13453     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
13454     if (NewSetCC.getNode()) {
13455       if (VT == MVT::i1)
13456         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewSetCC);
13457       return NewSetCC;
13458     }
13459   }
13460
13461   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
13462   // these.
13463   if (Op1.getOpcode() == ISD::Constant &&
13464       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
13465        cast<ConstantSDNode>(Op1)->isNullValue()) &&
13466       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13467
13468     // If the input is a setcc, then reuse the input setcc or use a new one with
13469     // the inverted condition.
13470     if (Op0.getOpcode() == X86ISD::SETCC) {
13471       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
13472       bool Invert = (CC == ISD::SETNE) ^
13473         cast<ConstantSDNode>(Op1)->isNullValue();
13474       if (!Invert)
13475         return Op0;
13476
13477       CCode = X86::GetOppositeBranchCondition(CCode);
13478       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13479                                   DAG.getConstant(CCode, dl, MVT::i8),
13480                                   Op0.getOperand(1));
13481       if (VT == MVT::i1)
13482         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
13483       return SetCC;
13484     }
13485   }
13486   if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
13487       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
13488       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13489
13490     ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
13491     return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, dl, MVT::i1), NewCC);
13492   }
13493
13494   bool isFP = Op1.getSimpleValueType().isFloatingPoint();
13495   unsigned X86CC = TranslateX86CC(CC, dl, isFP, Op0, Op1, DAG);
13496   if (X86CC == X86::COND_INVALID)
13497     return SDValue();
13498
13499   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
13500   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
13501   SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13502                               DAG.getConstant(X86CC, dl, MVT::i8), EFLAGS);
13503   if (VT == MVT::i1)
13504     return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
13505   return SetCC;
13506 }
13507
13508 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
13509 static bool isX86LogicalCmp(SDValue Op) {
13510   unsigned Opc = Op.getNode()->getOpcode();
13511   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
13512       Opc == X86ISD::SAHF)
13513     return true;
13514   if (Op.getResNo() == 1 &&
13515       (Opc == X86ISD::ADD ||
13516        Opc == X86ISD::SUB ||
13517        Opc == X86ISD::ADC ||
13518        Opc == X86ISD::SBB ||
13519        Opc == X86ISD::SMUL ||
13520        Opc == X86ISD::UMUL ||
13521        Opc == X86ISD::INC ||
13522        Opc == X86ISD::DEC ||
13523        Opc == X86ISD::OR ||
13524        Opc == X86ISD::XOR ||
13525        Opc == X86ISD::AND))
13526     return true;
13527
13528   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
13529     return true;
13530
13531   return false;
13532 }
13533
13534 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
13535   if (V.getOpcode() != ISD::TRUNCATE)
13536     return false;
13537
13538   SDValue VOp0 = V.getOperand(0);
13539   unsigned InBits = VOp0.getValueSizeInBits();
13540   unsigned Bits = V.getValueSizeInBits();
13541   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
13542 }
13543
13544 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
13545   bool addTest = true;
13546   SDValue Cond  = Op.getOperand(0);
13547   SDValue Op1 = Op.getOperand(1);
13548   SDValue Op2 = Op.getOperand(2);
13549   SDLoc DL(Op);
13550   EVT VT = Op1.getValueType();
13551   SDValue CC;
13552
13553   // Lower FP selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
13554   // are available or VBLENDV if AVX is available.
13555   // Otherwise FP cmovs get lowered into a less efficient branch sequence later.
13556   if (Cond.getOpcode() == ISD::SETCC &&
13557       ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
13558        (Subtarget->hasSSE1() && VT == MVT::f32)) &&
13559       VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
13560     SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
13561     int SSECC = translateX86FSETCC(
13562         cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
13563
13564     if (SSECC != 8) {
13565       if (Subtarget->hasAVX512()) {
13566         SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
13567                                   DAG.getConstant(SSECC, DL, MVT::i8));
13568         return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
13569       }
13570
13571       SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
13572                                 DAG.getConstant(SSECC, DL, MVT::i8));
13573
13574       // If we have AVX, we can use a variable vector select (VBLENDV) instead
13575       // of 3 logic instructions for size savings and potentially speed.
13576       // Unfortunately, there is no scalar form of VBLENDV.
13577
13578       // If either operand is a constant, don't try this. We can expect to
13579       // optimize away at least one of the logic instructions later in that
13580       // case, so that sequence would be faster than a variable blend.
13581
13582       // BLENDV was introduced with SSE 4.1, but the 2 register form implicitly
13583       // uses XMM0 as the selection register. That may need just as many
13584       // instructions as the AND/ANDN/OR sequence due to register moves, so
13585       // don't bother.
13586
13587       if (Subtarget->hasAVX() &&
13588           !isa<ConstantFPSDNode>(Op1) && !isa<ConstantFPSDNode>(Op2)) {
13589
13590         // Convert to vectors, do a VSELECT, and convert back to scalar.
13591         // All of the conversions should be optimized away.
13592
13593         EVT VecVT = VT == MVT::f32 ? MVT::v4f32 : MVT::v2f64;
13594         SDValue VOp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op1);
13595         SDValue VOp2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op2);
13596         SDValue VCmp = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Cmp);
13597
13598         EVT VCmpVT = VT == MVT::f32 ? MVT::v4i32 : MVT::v2i64;
13599         VCmp = DAG.getNode(ISD::BITCAST, DL, VCmpVT, VCmp);
13600
13601         SDValue VSel = DAG.getNode(ISD::VSELECT, DL, VecVT, VCmp, VOp1, VOp2);
13602
13603         return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
13604                            VSel, DAG.getIntPtrConstant(0, DL));
13605       }
13606       SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
13607       SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
13608       return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
13609     }
13610   }
13611
13612   if (Cond.getOpcode() == ISD::SETCC) {
13613     SDValue NewCond = LowerSETCC(Cond, DAG);
13614     if (NewCond.getNode())
13615       Cond = NewCond;
13616   }
13617
13618   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
13619   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
13620   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
13621   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
13622   if (Cond.getOpcode() == X86ISD::SETCC &&
13623       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
13624       isZero(Cond.getOperand(1).getOperand(1))) {
13625     SDValue Cmp = Cond.getOperand(1);
13626
13627     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
13628
13629     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
13630         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
13631       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
13632
13633       SDValue CmpOp0 = Cmp.getOperand(0);
13634       // Apply further optimizations for special cases
13635       // (select (x != 0), -1, 0) -> neg & sbb
13636       // (select (x == 0), 0, -1) -> neg & sbb
13637       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
13638         if (YC->isNullValue() &&
13639             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
13640           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
13641           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
13642                                     DAG.getConstant(0, DL,
13643                                                     CmpOp0.getValueType()),
13644                                     CmpOp0);
13645           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
13646                                     DAG.getConstant(X86::COND_B, DL, MVT::i8),
13647                                     SDValue(Neg.getNode(), 1));
13648           return Res;
13649         }
13650
13651       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
13652                         CmpOp0, DAG.getConstant(1, DL, CmpOp0.getValueType()));
13653       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
13654
13655       SDValue Res =   // Res = 0 or -1.
13656         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
13657                     DAG.getConstant(X86::COND_B, DL, MVT::i8), Cmp);
13658
13659       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
13660         Res = DAG.getNOT(DL, Res, Res.getValueType());
13661
13662       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
13663       if (!N2C || !N2C->isNullValue())
13664         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
13665       return Res;
13666     }
13667   }
13668
13669   // Look past (and (setcc_carry (cmp ...)), 1).
13670   if (Cond.getOpcode() == ISD::AND &&
13671       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
13672     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
13673     if (C && C->getAPIntValue() == 1)
13674       Cond = Cond.getOperand(0);
13675   }
13676
13677   // If condition flag is set by a X86ISD::CMP, then use it as the condition
13678   // setting operand in place of the X86ISD::SETCC.
13679   unsigned CondOpcode = Cond.getOpcode();
13680   if (CondOpcode == X86ISD::SETCC ||
13681       CondOpcode == X86ISD::SETCC_CARRY) {
13682     CC = Cond.getOperand(0);
13683
13684     SDValue Cmp = Cond.getOperand(1);
13685     unsigned Opc = Cmp.getOpcode();
13686     MVT VT = Op.getSimpleValueType();
13687
13688     bool IllegalFPCMov = false;
13689     if (VT.isFloatingPoint() && !VT.isVector() &&
13690         !isScalarFPTypeInSSEReg(VT))  // FPStack?
13691       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
13692
13693     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
13694         Opc == X86ISD::BT) { // FIXME
13695       Cond = Cmp;
13696       addTest = false;
13697     }
13698   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
13699              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
13700              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
13701               Cond.getOperand(0).getValueType() != MVT::i8)) {
13702     SDValue LHS = Cond.getOperand(0);
13703     SDValue RHS = Cond.getOperand(1);
13704     unsigned X86Opcode;
13705     unsigned X86Cond;
13706     SDVTList VTs;
13707     switch (CondOpcode) {
13708     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
13709     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
13710     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
13711     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
13712     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
13713     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
13714     default: llvm_unreachable("unexpected overflowing operator");
13715     }
13716     if (CondOpcode == ISD::UMULO)
13717       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
13718                           MVT::i32);
13719     else
13720       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
13721
13722     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
13723
13724     if (CondOpcode == ISD::UMULO)
13725       Cond = X86Op.getValue(2);
13726     else
13727       Cond = X86Op.getValue(1);
13728
13729     CC = DAG.getConstant(X86Cond, DL, MVT::i8);
13730     addTest = false;
13731   }
13732
13733   if (addTest) {
13734     // Look pass the truncate if the high bits are known zero.
13735     if (isTruncWithZeroHighBitsInput(Cond, DAG))
13736         Cond = Cond.getOperand(0);
13737
13738     // We know the result of AND is compared against zero. Try to match
13739     // it to BT.
13740     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
13741       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
13742       if (NewSetCC.getNode()) {
13743         CC = NewSetCC.getOperand(0);
13744         Cond = NewSetCC.getOperand(1);
13745         addTest = false;
13746       }
13747     }
13748   }
13749
13750   if (addTest) {
13751     CC = DAG.getConstant(X86::COND_NE, DL, MVT::i8);
13752     Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
13753   }
13754
13755   // a <  b ? -1 :  0 -> RES = ~setcc_carry
13756   // a <  b ?  0 : -1 -> RES = setcc_carry
13757   // a >= b ? -1 :  0 -> RES = setcc_carry
13758   // a >= b ?  0 : -1 -> RES = ~setcc_carry
13759   if (Cond.getOpcode() == X86ISD::SUB) {
13760     Cond = ConvertCmpIfNecessary(Cond, DAG);
13761     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
13762
13763     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
13764         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
13765       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
13766                                 DAG.getConstant(X86::COND_B, DL, MVT::i8),
13767                                 Cond);
13768       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
13769         return DAG.getNOT(DL, Res, Res.getValueType());
13770       return Res;
13771     }
13772   }
13773
13774   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
13775   // widen the cmov and push the truncate through. This avoids introducing a new
13776   // branch during isel and doesn't add any extensions.
13777   if (Op.getValueType() == MVT::i8 &&
13778       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
13779     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
13780     if (T1.getValueType() == T2.getValueType() &&
13781         // Blacklist CopyFromReg to avoid partial register stalls.
13782         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
13783       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
13784       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
13785       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
13786     }
13787   }
13788
13789   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
13790   // condition is true.
13791   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
13792   SDValue Ops[] = { Op2, Op1, CC, Cond };
13793   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
13794 }
13795
13796 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op, const X86Subtarget *Subtarget,
13797                                        SelectionDAG &DAG) {
13798   MVT VT = Op->getSimpleValueType(0);
13799   SDValue In = Op->getOperand(0);
13800   MVT InVT = In.getSimpleValueType();
13801   MVT VTElt = VT.getVectorElementType();
13802   MVT InVTElt = InVT.getVectorElementType();
13803   SDLoc dl(Op);
13804
13805   // SKX processor
13806   if ((InVTElt == MVT::i1) &&
13807       (((Subtarget->hasBWI() && Subtarget->hasVLX() &&
13808         VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() <= 16)) ||
13809
13810        ((Subtarget->hasBWI() && VT.is512BitVector() &&
13811         VTElt.getSizeInBits() <= 16)) ||
13812
13813        ((Subtarget->hasDQI() && Subtarget->hasVLX() &&
13814         VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() >= 32)) ||
13815
13816        ((Subtarget->hasDQI() && VT.is512BitVector() &&
13817         VTElt.getSizeInBits() >= 32))))
13818     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
13819
13820   unsigned int NumElts = VT.getVectorNumElements();
13821
13822   if (NumElts != 8 && NumElts != 16)
13823     return SDValue();
13824
13825   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1) {
13826     if (In.getOpcode() == X86ISD::VSEXT || In.getOpcode() == X86ISD::VZEXT)
13827       return DAG.getNode(In.getOpcode(), dl, VT, In.getOperand(0));
13828     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
13829   }
13830
13831   assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
13832   MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
13833   SDValue NegOne =
13834    DAG.getConstant(APInt::getAllOnesValue(ExtVT.getScalarSizeInBits()), dl,
13835                    ExtVT);
13836   SDValue Zero =
13837    DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), dl, ExtVT);
13838
13839   SDValue V = DAG.getNode(ISD::VSELECT, dl, ExtVT, In, NegOne, Zero);
13840   if (VT.is512BitVector())
13841     return V;
13842   return DAG.getNode(X86ISD::VTRUNC, dl, VT, V);
13843 }
13844
13845 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
13846                                 SelectionDAG &DAG) {
13847   MVT VT = Op->getSimpleValueType(0);
13848   SDValue In = Op->getOperand(0);
13849   MVT InVT = In.getSimpleValueType();
13850   SDLoc dl(Op);
13851
13852   if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
13853     return LowerSIGN_EXTEND_AVX512(Op, Subtarget, DAG);
13854
13855   if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
13856       (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
13857       (VT != MVT::v16i16 || InVT != MVT::v16i8))
13858     return SDValue();
13859
13860   if (Subtarget->hasInt256())
13861     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
13862
13863   // Optimize vectors in AVX mode
13864   // Sign extend  v8i16 to v8i32 and
13865   //              v4i32 to v4i64
13866   //
13867   // Divide input vector into two parts
13868   // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
13869   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
13870   // concat the vectors to original VT
13871
13872   unsigned NumElems = InVT.getVectorNumElements();
13873   SDValue Undef = DAG.getUNDEF(InVT);
13874
13875   SmallVector<int,8> ShufMask1(NumElems, -1);
13876   for (unsigned i = 0; i != NumElems/2; ++i)
13877     ShufMask1[i] = i;
13878
13879   SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
13880
13881   SmallVector<int,8> ShufMask2(NumElems, -1);
13882   for (unsigned i = 0; i != NumElems/2; ++i)
13883     ShufMask2[i] = i + NumElems/2;
13884
13885   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
13886
13887   MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
13888                                 VT.getVectorNumElements()/2);
13889
13890   OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
13891   OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
13892
13893   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
13894 }
13895
13896 // Lower vector extended loads using a shuffle. If SSSE3 is not available we
13897 // may emit an illegal shuffle but the expansion is still better than scalar
13898 // code. We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise
13899 // we'll emit a shuffle and a arithmetic shift.
13900 // FIXME: Is the expansion actually better than scalar code? It doesn't seem so.
13901 // TODO: It is possible to support ZExt by zeroing the undef values during
13902 // the shuffle phase or after the shuffle.
13903 static SDValue LowerExtendedLoad(SDValue Op, const X86Subtarget *Subtarget,
13904                                  SelectionDAG &DAG) {
13905   MVT RegVT = Op.getSimpleValueType();
13906   assert(RegVT.isVector() && "We only custom lower vector sext loads.");
13907   assert(RegVT.isInteger() &&
13908          "We only custom lower integer vector sext loads.");
13909
13910   // Nothing useful we can do without SSE2 shuffles.
13911   assert(Subtarget->hasSSE2() && "We only custom lower sext loads with SSE2.");
13912
13913   LoadSDNode *Ld = cast<LoadSDNode>(Op.getNode());
13914   SDLoc dl(Ld);
13915   EVT MemVT = Ld->getMemoryVT();
13916   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13917   unsigned RegSz = RegVT.getSizeInBits();
13918
13919   ISD::LoadExtType Ext = Ld->getExtensionType();
13920
13921   assert((Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)
13922          && "Only anyext and sext are currently implemented.");
13923   assert(MemVT != RegVT && "Cannot extend to the same type");
13924   assert(MemVT.isVector() && "Must load a vector from memory");
13925
13926   unsigned NumElems = RegVT.getVectorNumElements();
13927   unsigned MemSz = MemVT.getSizeInBits();
13928   assert(RegSz > MemSz && "Register size must be greater than the mem size");
13929
13930   if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256()) {
13931     // The only way in which we have a legal 256-bit vector result but not the
13932     // integer 256-bit operations needed to directly lower a sextload is if we
13933     // have AVX1 but not AVX2. In that case, we can always emit a sextload to
13934     // a 128-bit vector and a normal sign_extend to 256-bits that should get
13935     // correctly legalized. We do this late to allow the canonical form of
13936     // sextload to persist throughout the rest of the DAG combiner -- it wants
13937     // to fold together any extensions it can, and so will fuse a sign_extend
13938     // of an sextload into a sextload targeting a wider value.
13939     SDValue Load;
13940     if (MemSz == 128) {
13941       // Just switch this to a normal load.
13942       assert(TLI.isTypeLegal(MemVT) && "If the memory type is a 128-bit type, "
13943                                        "it must be a legal 128-bit vector "
13944                                        "type!");
13945       Load = DAG.getLoad(MemVT, dl, Ld->getChain(), Ld->getBasePtr(),
13946                   Ld->getPointerInfo(), Ld->isVolatile(), Ld->isNonTemporal(),
13947                   Ld->isInvariant(), Ld->getAlignment());
13948     } else {
13949       assert(MemSz < 128 &&
13950              "Can't extend a type wider than 128 bits to a 256 bit vector!");
13951       // Do an sext load to a 128-bit vector type. We want to use the same
13952       // number of elements, but elements half as wide. This will end up being
13953       // recursively lowered by this routine, but will succeed as we definitely
13954       // have all the necessary features if we're using AVX1.
13955       EVT HalfEltVT =
13956           EVT::getIntegerVT(*DAG.getContext(), RegVT.getScalarSizeInBits() / 2);
13957       EVT HalfVecVT = EVT::getVectorVT(*DAG.getContext(), HalfEltVT, NumElems);
13958       Load =
13959           DAG.getExtLoad(Ext, dl, HalfVecVT, Ld->getChain(), Ld->getBasePtr(),
13960                          Ld->getPointerInfo(), MemVT, Ld->isVolatile(),
13961                          Ld->isNonTemporal(), Ld->isInvariant(),
13962                          Ld->getAlignment());
13963     }
13964
13965     // Replace chain users with the new chain.
13966     assert(Load->getNumValues() == 2 && "Loads must carry a chain!");
13967     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Load.getValue(1));
13968
13969     // Finally, do a normal sign-extend to the desired register.
13970     return DAG.getSExtOrTrunc(Load, dl, RegVT);
13971   }
13972
13973   // All sizes must be a power of two.
13974   assert(isPowerOf2_32(RegSz * MemSz * NumElems) &&
13975          "Non-power-of-two elements are not custom lowered!");
13976
13977   // Attempt to load the original value using scalar loads.
13978   // Find the largest scalar type that divides the total loaded size.
13979   MVT SclrLoadTy = MVT::i8;
13980   for (MVT Tp : MVT::integer_valuetypes()) {
13981     if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
13982       SclrLoadTy = Tp;
13983     }
13984   }
13985
13986   // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
13987   if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
13988       (64 <= MemSz))
13989     SclrLoadTy = MVT::f64;
13990
13991   // Calculate the number of scalar loads that we need to perform
13992   // in order to load our vector from memory.
13993   unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
13994
13995   assert((Ext != ISD::SEXTLOAD || NumLoads == 1) &&
13996          "Can only lower sext loads with a single scalar load!");
13997
13998   unsigned loadRegZize = RegSz;
13999   if (Ext == ISD::SEXTLOAD && RegSz == 256)
14000     loadRegZize /= 2;
14001
14002   // Represent our vector as a sequence of elements which are the
14003   // largest scalar that we can load.
14004   EVT LoadUnitVecVT = EVT::getVectorVT(
14005       *DAG.getContext(), SclrLoadTy, loadRegZize / SclrLoadTy.getSizeInBits());
14006
14007   // Represent the data using the same element type that is stored in
14008   // memory. In practice, we ''widen'' MemVT.
14009   EVT WideVecVT =
14010       EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
14011                        loadRegZize / MemVT.getScalarType().getSizeInBits());
14012
14013   assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
14014          "Invalid vector type");
14015
14016   // We can't shuffle using an illegal type.
14017   assert(TLI.isTypeLegal(WideVecVT) &&
14018          "We only lower types that form legal widened vector types");
14019
14020   SmallVector<SDValue, 8> Chains;
14021   SDValue Ptr = Ld->getBasePtr();
14022   SDValue Increment =
14023       DAG.getConstant(SclrLoadTy.getSizeInBits() / 8, dl, TLI.getPointerTy());
14024   SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
14025
14026   for (unsigned i = 0; i < NumLoads; ++i) {
14027     // Perform a single load.
14028     SDValue ScalarLoad =
14029         DAG.getLoad(SclrLoadTy, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
14030                     Ld->isVolatile(), Ld->isNonTemporal(), Ld->isInvariant(),
14031                     Ld->getAlignment());
14032     Chains.push_back(ScalarLoad.getValue(1));
14033     // Create the first element type using SCALAR_TO_VECTOR in order to avoid
14034     // another round of DAGCombining.
14035     if (i == 0)
14036       Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
14037     else
14038       Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
14039                         ScalarLoad, DAG.getIntPtrConstant(i, dl));
14040
14041     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
14042   }
14043
14044   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
14045
14046   // Bitcast the loaded value to a vector of the original element type, in
14047   // the size of the target vector type.
14048   SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
14049   unsigned SizeRatio = RegSz / MemSz;
14050
14051   if (Ext == ISD::SEXTLOAD) {
14052     // If we have SSE4.1, we can directly emit a VSEXT node.
14053     if (Subtarget->hasSSE41()) {
14054       SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
14055       DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14056       return Sext;
14057     }
14058
14059     // Otherwise we'll shuffle the small elements in the high bits of the
14060     // larger type and perform an arithmetic shift. If the shift is not legal
14061     // it's better to scalarize.
14062     assert(TLI.isOperationLegalOrCustom(ISD::SRA, RegVT) &&
14063            "We can't implement a sext load without an arithmetic right shift!");
14064
14065     // Redistribute the loaded elements into the different locations.
14066     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
14067     for (unsigned i = 0; i != NumElems; ++i)
14068       ShuffleVec[i * SizeRatio + SizeRatio - 1] = i;
14069
14070     SDValue Shuff = DAG.getVectorShuffle(
14071         WideVecVT, dl, SlicedVec, DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
14072
14073     Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
14074
14075     // Build the arithmetic shift.
14076     unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
14077                    MemVT.getVectorElementType().getSizeInBits();
14078     Shuff =
14079         DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
14080                     DAG.getConstant(Amt, dl, RegVT));
14081
14082     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14083     return Shuff;
14084   }
14085
14086   // Redistribute the loaded elements into the different locations.
14087   SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
14088   for (unsigned i = 0; i != NumElems; ++i)
14089     ShuffleVec[i * SizeRatio] = i;
14090
14091   SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
14092                                        DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
14093
14094   // Bitcast to the requested type.
14095   Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
14096   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14097   return Shuff;
14098 }
14099
14100 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
14101 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
14102 // from the AND / OR.
14103 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
14104   Opc = Op.getOpcode();
14105   if (Opc != ISD::OR && Opc != ISD::AND)
14106     return false;
14107   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
14108           Op.getOperand(0).hasOneUse() &&
14109           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
14110           Op.getOperand(1).hasOneUse());
14111 }
14112
14113 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
14114 // 1 and that the SETCC node has a single use.
14115 static bool isXor1OfSetCC(SDValue Op) {
14116   if (Op.getOpcode() != ISD::XOR)
14117     return false;
14118   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
14119   if (N1C && N1C->getAPIntValue() == 1) {
14120     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
14121       Op.getOperand(0).hasOneUse();
14122   }
14123   return false;
14124 }
14125
14126 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
14127   bool addTest = true;
14128   SDValue Chain = Op.getOperand(0);
14129   SDValue Cond  = Op.getOperand(1);
14130   SDValue Dest  = Op.getOperand(2);
14131   SDLoc dl(Op);
14132   SDValue CC;
14133   bool Inverted = false;
14134
14135   if (Cond.getOpcode() == ISD::SETCC) {
14136     // Check for setcc([su]{add,sub,mul}o == 0).
14137     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
14138         isa<ConstantSDNode>(Cond.getOperand(1)) &&
14139         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
14140         Cond.getOperand(0).getResNo() == 1 &&
14141         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
14142          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
14143          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
14144          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
14145          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
14146          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
14147       Inverted = true;
14148       Cond = Cond.getOperand(0);
14149     } else {
14150       SDValue NewCond = LowerSETCC(Cond, DAG);
14151       if (NewCond.getNode())
14152         Cond = NewCond;
14153     }
14154   }
14155 #if 0
14156   // FIXME: LowerXALUO doesn't handle these!!
14157   else if (Cond.getOpcode() == X86ISD::ADD  ||
14158            Cond.getOpcode() == X86ISD::SUB  ||
14159            Cond.getOpcode() == X86ISD::SMUL ||
14160            Cond.getOpcode() == X86ISD::UMUL)
14161     Cond = LowerXALUO(Cond, DAG);
14162 #endif
14163
14164   // Look pass (and (setcc_carry (cmp ...)), 1).
14165   if (Cond.getOpcode() == ISD::AND &&
14166       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
14167     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
14168     if (C && C->getAPIntValue() == 1)
14169       Cond = Cond.getOperand(0);
14170   }
14171
14172   // If condition flag is set by a X86ISD::CMP, then use it as the condition
14173   // setting operand in place of the X86ISD::SETCC.
14174   unsigned CondOpcode = Cond.getOpcode();
14175   if (CondOpcode == X86ISD::SETCC ||
14176       CondOpcode == X86ISD::SETCC_CARRY) {
14177     CC = Cond.getOperand(0);
14178
14179     SDValue Cmp = Cond.getOperand(1);
14180     unsigned Opc = Cmp.getOpcode();
14181     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
14182     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
14183       Cond = Cmp;
14184       addTest = false;
14185     } else {
14186       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
14187       default: break;
14188       case X86::COND_O:
14189       case X86::COND_B:
14190         // These can only come from an arithmetic instruction with overflow,
14191         // e.g. SADDO, UADDO.
14192         Cond = Cond.getNode()->getOperand(1);
14193         addTest = false;
14194         break;
14195       }
14196     }
14197   }
14198   CondOpcode = Cond.getOpcode();
14199   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
14200       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
14201       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
14202        Cond.getOperand(0).getValueType() != MVT::i8)) {
14203     SDValue LHS = Cond.getOperand(0);
14204     SDValue RHS = Cond.getOperand(1);
14205     unsigned X86Opcode;
14206     unsigned X86Cond;
14207     SDVTList VTs;
14208     // Keep this in sync with LowerXALUO, otherwise we might create redundant
14209     // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
14210     // X86ISD::INC).
14211     switch (CondOpcode) {
14212     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
14213     case ISD::SADDO:
14214       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
14215         if (C->isOne()) {
14216           X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
14217           break;
14218         }
14219       X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
14220     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
14221     case ISD::SSUBO:
14222       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
14223         if (C->isOne()) {
14224           X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
14225           break;
14226         }
14227       X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
14228     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
14229     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
14230     default: llvm_unreachable("unexpected overflowing operator");
14231     }
14232     if (Inverted)
14233       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
14234     if (CondOpcode == ISD::UMULO)
14235       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
14236                           MVT::i32);
14237     else
14238       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
14239
14240     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
14241
14242     if (CondOpcode == ISD::UMULO)
14243       Cond = X86Op.getValue(2);
14244     else
14245       Cond = X86Op.getValue(1);
14246
14247     CC = DAG.getConstant(X86Cond, dl, MVT::i8);
14248     addTest = false;
14249   } else {
14250     unsigned CondOpc;
14251     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
14252       SDValue Cmp = Cond.getOperand(0).getOperand(1);
14253       if (CondOpc == ISD::OR) {
14254         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
14255         // two branches instead of an explicit OR instruction with a
14256         // separate test.
14257         if (Cmp == Cond.getOperand(1).getOperand(1) &&
14258             isX86LogicalCmp(Cmp)) {
14259           CC = Cond.getOperand(0).getOperand(0);
14260           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14261                               Chain, Dest, CC, Cmp);
14262           CC = Cond.getOperand(1).getOperand(0);
14263           Cond = Cmp;
14264           addTest = false;
14265         }
14266       } else { // ISD::AND
14267         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
14268         // two branches instead of an explicit AND instruction with a
14269         // separate test. However, we only do this if this block doesn't
14270         // have a fall-through edge, because this requires an explicit
14271         // jmp when the condition is false.
14272         if (Cmp == Cond.getOperand(1).getOperand(1) &&
14273             isX86LogicalCmp(Cmp) &&
14274             Op.getNode()->hasOneUse()) {
14275           X86::CondCode CCode =
14276             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
14277           CCode = X86::GetOppositeBranchCondition(CCode);
14278           CC = DAG.getConstant(CCode, dl, MVT::i8);
14279           SDNode *User = *Op.getNode()->use_begin();
14280           // Look for an unconditional branch following this conditional branch.
14281           // We need this because we need to reverse the successors in order
14282           // to implement FCMP_OEQ.
14283           if (User->getOpcode() == ISD::BR) {
14284             SDValue FalseBB = User->getOperand(1);
14285             SDNode *NewBR =
14286               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14287             assert(NewBR == User);
14288             (void)NewBR;
14289             Dest = FalseBB;
14290
14291             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14292                                 Chain, Dest, CC, Cmp);
14293             X86::CondCode CCode =
14294               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
14295             CCode = X86::GetOppositeBranchCondition(CCode);
14296             CC = DAG.getConstant(CCode, dl, MVT::i8);
14297             Cond = Cmp;
14298             addTest = false;
14299           }
14300         }
14301       }
14302     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
14303       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
14304       // It should be transformed during dag combiner except when the condition
14305       // is set by a arithmetics with overflow node.
14306       X86::CondCode CCode =
14307         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
14308       CCode = X86::GetOppositeBranchCondition(CCode);
14309       CC = DAG.getConstant(CCode, dl, MVT::i8);
14310       Cond = Cond.getOperand(0).getOperand(1);
14311       addTest = false;
14312     } else if (Cond.getOpcode() == ISD::SETCC &&
14313                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
14314       // For FCMP_OEQ, we can emit
14315       // two branches instead of an explicit AND instruction with a
14316       // separate test. However, we only do this if this block doesn't
14317       // have a fall-through edge, because this requires an explicit
14318       // jmp when the condition is false.
14319       if (Op.getNode()->hasOneUse()) {
14320         SDNode *User = *Op.getNode()->use_begin();
14321         // Look for an unconditional branch following this conditional branch.
14322         // We need this because we need to reverse the successors in order
14323         // to implement FCMP_OEQ.
14324         if (User->getOpcode() == ISD::BR) {
14325           SDValue FalseBB = User->getOperand(1);
14326           SDNode *NewBR =
14327             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14328           assert(NewBR == User);
14329           (void)NewBR;
14330           Dest = FalseBB;
14331
14332           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
14333                                     Cond.getOperand(0), Cond.getOperand(1));
14334           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14335           CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
14336           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14337                               Chain, Dest, CC, Cmp);
14338           CC = DAG.getConstant(X86::COND_P, dl, MVT::i8);
14339           Cond = Cmp;
14340           addTest = false;
14341         }
14342       }
14343     } else if (Cond.getOpcode() == ISD::SETCC &&
14344                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
14345       // For FCMP_UNE, we can emit
14346       // two branches instead of an explicit AND instruction with a
14347       // separate test. However, we only do this if this block doesn't
14348       // have a fall-through edge, because this requires an explicit
14349       // jmp when the condition is false.
14350       if (Op.getNode()->hasOneUse()) {
14351         SDNode *User = *Op.getNode()->use_begin();
14352         // Look for an unconditional branch following this conditional branch.
14353         // We need this because we need to reverse the successors in order
14354         // to implement FCMP_UNE.
14355         if (User->getOpcode() == ISD::BR) {
14356           SDValue FalseBB = User->getOperand(1);
14357           SDNode *NewBR =
14358             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14359           assert(NewBR == User);
14360           (void)NewBR;
14361
14362           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
14363                                     Cond.getOperand(0), Cond.getOperand(1));
14364           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14365           CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
14366           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14367                               Chain, Dest, CC, Cmp);
14368           CC = DAG.getConstant(X86::COND_NP, dl, MVT::i8);
14369           Cond = Cmp;
14370           addTest = false;
14371           Dest = FalseBB;
14372         }
14373       }
14374     }
14375   }
14376
14377   if (addTest) {
14378     // Look pass the truncate if the high bits are known zero.
14379     if (isTruncWithZeroHighBitsInput(Cond, DAG))
14380         Cond = Cond.getOperand(0);
14381
14382     // We know the result of AND is compared against zero. Try to match
14383     // it to BT.
14384     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
14385       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
14386       if (NewSetCC.getNode()) {
14387         CC = NewSetCC.getOperand(0);
14388         Cond = NewSetCC.getOperand(1);
14389         addTest = false;
14390       }
14391     }
14392   }
14393
14394   if (addTest) {
14395     X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
14396     CC = DAG.getConstant(X86Cond, dl, MVT::i8);
14397     Cond = EmitTest(Cond, X86Cond, dl, DAG);
14398   }
14399   Cond = ConvertCmpIfNecessary(Cond, DAG);
14400   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14401                      Chain, Dest, CC, Cond);
14402 }
14403
14404 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
14405 // Calls to _alloca are needed to probe the stack when allocating more than 4k
14406 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
14407 // that the guard pages used by the OS virtual memory manager are allocated in
14408 // correct sequence.
14409 SDValue
14410 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
14411                                            SelectionDAG &DAG) const {
14412   MachineFunction &MF = DAG.getMachineFunction();
14413   bool SplitStack = MF.shouldSplitStack();
14414   bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMachO()) ||
14415                SplitStack;
14416   SDLoc dl(Op);
14417
14418   if (!Lower) {
14419     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14420     SDNode* Node = Op.getNode();
14421
14422     unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
14423     assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
14424         " not tell us which reg is the stack pointer!");
14425     EVT VT = Node->getValueType(0);
14426     SDValue Tmp1 = SDValue(Node, 0);
14427     SDValue Tmp2 = SDValue(Node, 1);
14428     SDValue Tmp3 = Node->getOperand(2);
14429     SDValue Chain = Tmp1.getOperand(0);
14430
14431     // Chain the dynamic stack allocation so that it doesn't modify the stack
14432     // pointer when other instructions are using the stack.
14433     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, dl, true),
14434         SDLoc(Node));
14435
14436     SDValue Size = Tmp2.getOperand(1);
14437     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
14438     Chain = SP.getValue(1);
14439     unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
14440     const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
14441     unsigned StackAlign = TFI.getStackAlignment();
14442     Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
14443     if (Align > StackAlign)
14444       Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
14445           DAG.getConstant(-(uint64_t)Align, dl, VT));
14446     Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
14447
14448     Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, dl, true),
14449         DAG.getIntPtrConstant(0, dl, true), SDValue(),
14450         SDLoc(Node));
14451
14452     SDValue Ops[2] = { Tmp1, Tmp2 };
14453     return DAG.getMergeValues(Ops, dl);
14454   }
14455
14456   // Get the inputs.
14457   SDValue Chain = Op.getOperand(0);
14458   SDValue Size  = Op.getOperand(1);
14459   unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
14460   EVT VT = Op.getNode()->getValueType(0);
14461
14462   bool Is64Bit = Subtarget->is64Bit();
14463   EVT SPTy = getPointerTy();
14464
14465   if (SplitStack) {
14466     MachineRegisterInfo &MRI = MF.getRegInfo();
14467
14468     if (Is64Bit) {
14469       // The 64 bit implementation of segmented stacks needs to clobber both r10
14470       // r11. This makes it impossible to use it along with nested parameters.
14471       const Function *F = MF.getFunction();
14472
14473       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
14474            I != E; ++I)
14475         if (I->hasNestAttr())
14476           report_fatal_error("Cannot use segmented stacks with functions that "
14477                              "have nested arguments.");
14478     }
14479
14480     const TargetRegisterClass *AddrRegClass =
14481       getRegClassFor(getPointerTy());
14482     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
14483     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
14484     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
14485                                 DAG.getRegister(Vreg, SPTy));
14486     SDValue Ops1[2] = { Value, Chain };
14487     return DAG.getMergeValues(Ops1, dl);
14488   } else {
14489     SDValue Flag;
14490     const unsigned Reg = (Subtarget->isTarget64BitLP64() ? X86::RAX : X86::EAX);
14491
14492     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
14493     Flag = Chain.getValue(1);
14494     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
14495
14496     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
14497
14498     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
14499     unsigned SPReg = RegInfo->getStackRegister();
14500     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
14501     Chain = SP.getValue(1);
14502
14503     if (Align) {
14504       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
14505                        DAG.getConstant(-(uint64_t)Align, dl, VT));
14506       Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
14507     }
14508
14509     SDValue Ops1[2] = { SP, Chain };
14510     return DAG.getMergeValues(Ops1, dl);
14511   }
14512 }
14513
14514 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
14515   MachineFunction &MF = DAG.getMachineFunction();
14516   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
14517
14518   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
14519   SDLoc DL(Op);
14520
14521   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
14522     // vastart just stores the address of the VarArgsFrameIndex slot into the
14523     // memory location argument.
14524     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
14525                                    getPointerTy());
14526     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
14527                         MachinePointerInfo(SV), false, false, 0);
14528   }
14529
14530   // __va_list_tag:
14531   //   gp_offset         (0 - 6 * 8)
14532   //   fp_offset         (48 - 48 + 8 * 16)
14533   //   overflow_arg_area (point to parameters coming in memory).
14534   //   reg_save_area
14535   SmallVector<SDValue, 8> MemOps;
14536   SDValue FIN = Op.getOperand(1);
14537   // Store gp_offset
14538   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
14539                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
14540                                                DL, MVT::i32),
14541                                FIN, MachinePointerInfo(SV), false, false, 0);
14542   MemOps.push_back(Store);
14543
14544   // Store fp_offset
14545   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
14546                     FIN, DAG.getIntPtrConstant(4, DL));
14547   Store = DAG.getStore(Op.getOperand(0), DL,
14548                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(), DL,
14549                                        MVT::i32),
14550                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
14551   MemOps.push_back(Store);
14552
14553   // Store ptr to overflow_arg_area
14554   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
14555                     FIN, DAG.getIntPtrConstant(4, DL));
14556   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
14557                                     getPointerTy());
14558   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
14559                        MachinePointerInfo(SV, 8),
14560                        false, false, 0);
14561   MemOps.push_back(Store);
14562
14563   // Store ptr to reg_save_area.
14564   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
14565                     FIN, DAG.getIntPtrConstant(8, DL));
14566   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
14567                                     getPointerTy());
14568   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
14569                        MachinePointerInfo(SV, 16), false, false, 0);
14570   MemOps.push_back(Store);
14571   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
14572 }
14573
14574 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
14575   assert(Subtarget->is64Bit() &&
14576          "LowerVAARG only handles 64-bit va_arg!");
14577   assert((Subtarget->isTargetLinux() ||
14578           Subtarget->isTargetDarwin()) &&
14579           "Unhandled target in LowerVAARG");
14580   assert(Op.getNode()->getNumOperands() == 4);
14581   SDValue Chain = Op.getOperand(0);
14582   SDValue SrcPtr = Op.getOperand(1);
14583   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
14584   unsigned Align = Op.getConstantOperandVal(3);
14585   SDLoc dl(Op);
14586
14587   EVT ArgVT = Op.getNode()->getValueType(0);
14588   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
14589   uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
14590   uint8_t ArgMode;
14591
14592   // Decide which area this value should be read from.
14593   // TODO: Implement the AMD64 ABI in its entirety. This simple
14594   // selection mechanism works only for the basic types.
14595   if (ArgVT == MVT::f80) {
14596     llvm_unreachable("va_arg for f80 not yet implemented");
14597   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
14598     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
14599   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
14600     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
14601   } else {
14602     llvm_unreachable("Unhandled argument type in LowerVAARG");
14603   }
14604
14605   if (ArgMode == 2) {
14606     // Sanity Check: Make sure using fp_offset makes sense.
14607     assert(!Subtarget->useSoftFloat() &&
14608            !(DAG.getMachineFunction().getFunction()->hasFnAttribute(
14609                Attribute::NoImplicitFloat)) &&
14610            Subtarget->hasSSE1());
14611   }
14612
14613   // Insert VAARG_64 node into the DAG
14614   // VAARG_64 returns two values: Variable Argument Address, Chain
14615   SDValue InstOps[] = {Chain, SrcPtr, DAG.getConstant(ArgSize, dl, MVT::i32),
14616                        DAG.getConstant(ArgMode, dl, MVT::i8),
14617                        DAG.getConstant(Align, dl, MVT::i32)};
14618   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
14619   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
14620                                           VTs, InstOps, MVT::i64,
14621                                           MachinePointerInfo(SV),
14622                                           /*Align=*/0,
14623                                           /*Volatile=*/false,
14624                                           /*ReadMem=*/true,
14625                                           /*WriteMem=*/true);
14626   Chain = VAARG.getValue(1);
14627
14628   // Load the next argument and return it
14629   return DAG.getLoad(ArgVT, dl,
14630                      Chain,
14631                      VAARG,
14632                      MachinePointerInfo(),
14633                      false, false, false, 0);
14634 }
14635
14636 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
14637                            SelectionDAG &DAG) {
14638   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
14639   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
14640   SDValue Chain = Op.getOperand(0);
14641   SDValue DstPtr = Op.getOperand(1);
14642   SDValue SrcPtr = Op.getOperand(2);
14643   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
14644   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
14645   SDLoc DL(Op);
14646
14647   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
14648                        DAG.getIntPtrConstant(24, DL), 8, /*isVolatile*/false,
14649                        false, false,
14650                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
14651 }
14652
14653 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
14654 // amount is a constant. Takes immediate version of shift as input.
14655 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
14656                                           SDValue SrcOp, uint64_t ShiftAmt,
14657                                           SelectionDAG &DAG) {
14658   MVT ElementType = VT.getVectorElementType();
14659
14660   // Fold this packed shift into its first operand if ShiftAmt is 0.
14661   if (ShiftAmt == 0)
14662     return SrcOp;
14663
14664   // Check for ShiftAmt >= element width
14665   if (ShiftAmt >= ElementType.getSizeInBits()) {
14666     if (Opc == X86ISD::VSRAI)
14667       ShiftAmt = ElementType.getSizeInBits() - 1;
14668     else
14669       return DAG.getConstant(0, dl, VT);
14670   }
14671
14672   assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
14673          && "Unknown target vector shift-by-constant node");
14674
14675   // Fold this packed vector shift into a build vector if SrcOp is a
14676   // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
14677   if (VT == SrcOp.getSimpleValueType() &&
14678       ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
14679     SmallVector<SDValue, 8> Elts;
14680     unsigned NumElts = SrcOp->getNumOperands();
14681     ConstantSDNode *ND;
14682
14683     switch(Opc) {
14684     default: llvm_unreachable(nullptr);
14685     case X86ISD::VSHLI:
14686       for (unsigned i=0; i!=NumElts; ++i) {
14687         SDValue CurrentOp = SrcOp->getOperand(i);
14688         if (CurrentOp->getOpcode() == ISD::UNDEF) {
14689           Elts.push_back(CurrentOp);
14690           continue;
14691         }
14692         ND = cast<ConstantSDNode>(CurrentOp);
14693         const APInt &C = ND->getAPIntValue();
14694         Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), dl, ElementType));
14695       }
14696       break;
14697     case X86ISD::VSRLI:
14698       for (unsigned i=0; i!=NumElts; ++i) {
14699         SDValue CurrentOp = SrcOp->getOperand(i);
14700         if (CurrentOp->getOpcode() == ISD::UNDEF) {
14701           Elts.push_back(CurrentOp);
14702           continue;
14703         }
14704         ND = cast<ConstantSDNode>(CurrentOp);
14705         const APInt &C = ND->getAPIntValue();
14706         Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), dl, ElementType));
14707       }
14708       break;
14709     case X86ISD::VSRAI:
14710       for (unsigned i=0; i!=NumElts; ++i) {
14711         SDValue CurrentOp = SrcOp->getOperand(i);
14712         if (CurrentOp->getOpcode() == ISD::UNDEF) {
14713           Elts.push_back(CurrentOp);
14714           continue;
14715         }
14716         ND = cast<ConstantSDNode>(CurrentOp);
14717         const APInt &C = ND->getAPIntValue();
14718         Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), dl, ElementType));
14719       }
14720       break;
14721     }
14722
14723     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
14724   }
14725
14726   return DAG.getNode(Opc, dl, VT, SrcOp,
14727                      DAG.getConstant(ShiftAmt, dl, MVT::i8));
14728 }
14729
14730 // getTargetVShiftNode - Handle vector element shifts where the shift amount
14731 // may or may not be a constant. Takes immediate version of shift as input.
14732 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
14733                                    SDValue SrcOp, SDValue ShAmt,
14734                                    SelectionDAG &DAG) {
14735   MVT SVT = ShAmt.getSimpleValueType();
14736   assert((SVT == MVT::i32 || SVT == MVT::i64) && "Unexpected value type!");
14737
14738   // Catch shift-by-constant.
14739   if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
14740     return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
14741                                       CShAmt->getZExtValue(), DAG);
14742
14743   // Change opcode to non-immediate version
14744   switch (Opc) {
14745     default: llvm_unreachable("Unknown target vector shift node");
14746     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
14747     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
14748     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
14749   }
14750
14751   const X86Subtarget &Subtarget =
14752       static_cast<const X86Subtarget &>(DAG.getSubtarget());
14753   if (Subtarget.hasSSE41() && ShAmt.getOpcode() == ISD::ZERO_EXTEND &&
14754       ShAmt.getOperand(0).getSimpleValueType() == MVT::i16) {
14755     // Let the shuffle legalizer expand this shift amount node.
14756     SDValue Op0 = ShAmt.getOperand(0);
14757     Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(Op0), MVT::v8i16, Op0);
14758     ShAmt = getShuffleVectorZeroOrUndef(Op0, 0, true, &Subtarget, DAG);
14759   } else {
14760     // Need to build a vector containing shift amount.
14761     // SSE/AVX packed shifts only use the lower 64-bit of the shift count.
14762     SmallVector<SDValue, 4> ShOps;
14763     ShOps.push_back(ShAmt);
14764     if (SVT == MVT::i32) {
14765       ShOps.push_back(DAG.getConstant(0, dl, SVT));
14766       ShOps.push_back(DAG.getUNDEF(SVT));
14767     }
14768     ShOps.push_back(DAG.getUNDEF(SVT));
14769
14770     MVT BVT = SVT == MVT::i32 ? MVT::v4i32 : MVT::v2i64;
14771     ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, BVT, ShOps);
14772   }
14773
14774   // The return type has to be a 128-bit type with the same element
14775   // type as the input type.
14776   MVT EltVT = VT.getVectorElementType();
14777   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
14778
14779   ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
14780   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
14781 }
14782
14783 /// \brief Return (and \p Op, \p Mask) for compare instructions or
14784 /// (vselect \p Mask, \p Op, \p PreservedSrc) for others along with the
14785 /// necessary casting for \p Mask when lowering masking intrinsics.
14786 static SDValue getVectorMaskingNode(SDValue Op, SDValue Mask,
14787                                     SDValue PreservedSrc,
14788                                     const X86Subtarget *Subtarget,
14789                                     SelectionDAG &DAG) {
14790     EVT VT = Op.getValueType();
14791     EVT MaskVT = EVT::getVectorVT(*DAG.getContext(),
14792                                   MVT::i1, VT.getVectorNumElements());
14793     EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
14794                                      Mask.getValueType().getSizeInBits());
14795     SDLoc dl(Op);
14796
14797     assert(MaskVT.isSimple() && "invalid mask type");
14798
14799     if (isAllOnes(Mask))
14800       return Op;
14801
14802     // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
14803     // are extracted by EXTRACT_SUBVECTOR.
14804     SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
14805                               DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
14806                               DAG.getIntPtrConstant(0, dl));
14807
14808     switch (Op.getOpcode()) {
14809       default: break;
14810       case X86ISD::PCMPEQM:
14811       case X86ISD::PCMPGTM:
14812       case X86ISD::CMPM:
14813       case X86ISD::CMPMU:
14814         return DAG.getNode(ISD::AND, dl, VT, Op, VMask);
14815     }
14816     if (PreservedSrc.getOpcode() == ISD::UNDEF)
14817       PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
14818     return DAG.getNode(ISD::VSELECT, dl, VT, VMask, Op, PreservedSrc);
14819 }
14820
14821 /// \brief Creates an SDNode for a predicated scalar operation.
14822 /// \returns (X86vselect \p Mask, \p Op, \p PreservedSrc).
14823 /// The mask is comming as MVT::i8 and it should be truncated
14824 /// to MVT::i1 while lowering masking intrinsics.
14825 /// The main difference between ScalarMaskingNode and VectorMaskingNode is using
14826 /// "X86select" instead of "vselect". We just can't create the "vselect" node for
14827 /// a scalar instruction.
14828 static SDValue getScalarMaskingNode(SDValue Op, SDValue Mask,
14829                                     SDValue PreservedSrc,
14830                                     const X86Subtarget *Subtarget,
14831                                     SelectionDAG &DAG) {
14832     if (isAllOnes(Mask))
14833       return Op;
14834
14835     EVT VT = Op.getValueType();
14836     SDLoc dl(Op);
14837     // The mask should be of type MVT::i1
14838     SDValue IMask = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Mask);
14839
14840     if (PreservedSrc.getOpcode() == ISD::UNDEF)
14841       PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
14842     return DAG.getNode(X86ISD::SELECT, dl, VT, IMask, Op, PreservedSrc);
14843 }
14844
14845 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
14846                                        SelectionDAG &DAG) {
14847   SDLoc dl(Op);
14848   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
14849   EVT VT = Op.getValueType();
14850   const IntrinsicData* IntrData = getIntrinsicWithoutChain(IntNo);
14851   if (IntrData) {
14852     switch(IntrData->Type) {
14853     case INTR_TYPE_1OP:
14854       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1));
14855     case INTR_TYPE_2OP:
14856       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
14857         Op.getOperand(2));
14858     case INTR_TYPE_3OP:
14859       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
14860         Op.getOperand(2), Op.getOperand(3));
14861     case INTR_TYPE_1OP_MASK_RM: {
14862       SDValue Src = Op.getOperand(1);
14863       SDValue Src0 = Op.getOperand(2);
14864       SDValue Mask = Op.getOperand(3);
14865       SDValue RoundingMode = Op.getOperand(4);
14866       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src,
14867                                               RoundingMode),
14868                                   Mask, Src0, Subtarget, DAG);
14869     }
14870     case INTR_TYPE_SCALAR_MASK_RM: {
14871       SDValue Src1 = Op.getOperand(1);
14872       SDValue Src2 = Op.getOperand(2);
14873       SDValue Src0 = Op.getOperand(3);
14874       SDValue Mask = Op.getOperand(4);
14875       // There are 2 kinds of intrinsics in this group:
14876       // (1) With supress-all-exceptions (sae) - 6 operands
14877       // (2) With rounding mode and sae - 7 operands.
14878       if (Op.getNumOperands() == 6) {
14879         SDValue Sae  = Op.getOperand(5);
14880         return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2,
14881                                                 Sae),
14882                                     Mask, Src0, Subtarget, DAG);
14883       }
14884       assert(Op.getNumOperands() == 7 && "Unexpected intrinsic form");
14885       SDValue RoundingMode  = Op.getOperand(5);
14886       SDValue Sae  = Op.getOperand(6);
14887       return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2,
14888                                               RoundingMode, Sae),
14889                                   Mask, Src0, Subtarget, DAG);
14890     }
14891     case INTR_TYPE_2OP_MASK: {
14892       SDValue Src1 = Op.getOperand(1);
14893       SDValue Src2 = Op.getOperand(2);
14894       SDValue PassThru = Op.getOperand(3);
14895       SDValue Mask = Op.getOperand(4);
14896       // We specify 2 possible opcodes for intrinsics with rounding modes.
14897       // First, we check if the intrinsic may have non-default rounding mode,
14898       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
14899       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
14900       if (IntrWithRoundingModeOpcode != 0) {
14901         SDValue Rnd = Op.getOperand(5);
14902         unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
14903         if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
14904           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
14905                                       dl, Op.getValueType(),
14906                                       Src1, Src2, Rnd),
14907                                       Mask, PassThru, Subtarget, DAG);
14908         }
14909       }
14910       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
14911                                               Src1,Src2),
14912                                   Mask, PassThru, Subtarget, DAG);
14913     }
14914     case FMA_OP_MASK: {
14915       SDValue Src1 = Op.getOperand(1);
14916       SDValue Src2 = Op.getOperand(2);
14917       SDValue Src3 = Op.getOperand(3);
14918       SDValue Mask = Op.getOperand(4);
14919       // We specify 2 possible opcodes for intrinsics with rounding modes.
14920       // First, we check if the intrinsic may have non-default rounding mode,
14921       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
14922       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
14923       if (IntrWithRoundingModeOpcode != 0) {
14924         SDValue Rnd = Op.getOperand(5);
14925         if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
14926             X86::STATIC_ROUNDING::CUR_DIRECTION)
14927           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
14928                                                   dl, Op.getValueType(),
14929                                                   Src1, Src2, Src3, Rnd),
14930                                       Mask, Src1, Subtarget, DAG);
14931       }
14932       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0,
14933                                               dl, Op.getValueType(),
14934                                               Src1, Src2, Src3),
14935                                   Mask, Src1, Subtarget, DAG);
14936     }
14937     case CMP_MASK:
14938     case CMP_MASK_CC: {
14939       // Comparison intrinsics with masks.
14940       // Example of transformation:
14941       // (i8 (int_x86_avx512_mask_pcmpeq_q_128
14942       //             (v2i64 %a), (v2i64 %b), (i8 %mask))) ->
14943       // (i8 (bitcast
14944       //   (v8i1 (insert_subvector undef,
14945       //           (v2i1 (and (PCMPEQM %a, %b),
14946       //                      (extract_subvector
14947       //                         (v8i1 (bitcast %mask)), 0))), 0))))
14948       EVT VT = Op.getOperand(1).getValueType();
14949       EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
14950                                     VT.getVectorNumElements());
14951       SDValue Mask = Op.getOperand((IntrData->Type == CMP_MASK_CC) ? 4 : 3);
14952       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
14953                                        Mask.getValueType().getSizeInBits());
14954       SDValue Cmp;
14955       if (IntrData->Type == CMP_MASK_CC) {
14956         SDValue CC = Op.getOperand(3);
14957         CC = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, CC);
14958         // We specify 2 possible opcodes for intrinsics with rounding modes.
14959         // First, we check if the intrinsic may have non-default rounding mode,
14960         // (IntrData->Opc1 != 0), then we check the rounding mode operand.
14961         if (IntrData->Opc1 != 0) {
14962           SDValue Rnd = Op.getOperand(5);
14963           if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
14964               X86::STATIC_ROUNDING::CUR_DIRECTION)
14965             Cmp = DAG.getNode(IntrData->Opc1, dl, MaskVT, Op.getOperand(1),
14966                               Op.getOperand(2), CC, Rnd);
14967         }
14968         //default rounding mode
14969         if(!Cmp.getNode())
14970             Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
14971                               Op.getOperand(2), CC);
14972
14973       } else {
14974         assert(IntrData->Type == CMP_MASK && "Unexpected intrinsic type!");
14975         Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
14976                           Op.getOperand(2));
14977       }
14978       SDValue CmpMask = getVectorMaskingNode(Cmp, Mask,
14979                                              DAG.getTargetConstant(0, dl,
14980                                                                    MaskVT),
14981                                              Subtarget, DAG);
14982       SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, BitcastVT,
14983                                 DAG.getUNDEF(BitcastVT), CmpMask,
14984                                 DAG.getIntPtrConstant(0, dl));
14985       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
14986     }
14987     case COMI: { // Comparison intrinsics
14988       ISD::CondCode CC = (ISD::CondCode)IntrData->Opc1;
14989       SDValue LHS = Op.getOperand(1);
14990       SDValue RHS = Op.getOperand(2);
14991       unsigned X86CC = TranslateX86CC(CC, dl, true, LHS, RHS, DAG);
14992       assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
14993       SDValue Cond = DAG.getNode(IntrData->Opc0, dl, MVT::i32, LHS, RHS);
14994       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14995                                   DAG.getConstant(X86CC, dl, MVT::i8), Cond);
14996       return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
14997     }
14998     case VSHIFT:
14999       return getTargetVShiftNode(IntrData->Opc0, dl, Op.getSimpleValueType(),
15000                                  Op.getOperand(1), Op.getOperand(2), DAG);
15001     case VSHIFT_MASK:
15002       return getVectorMaskingNode(getTargetVShiftNode(IntrData->Opc0, dl,
15003                                                       Op.getSimpleValueType(),
15004                                                       Op.getOperand(1),
15005                                                       Op.getOperand(2), DAG),
15006                                   Op.getOperand(4), Op.getOperand(3), Subtarget,
15007                                   DAG);
15008     case COMPRESS_EXPAND_IN_REG: {
15009       SDValue Mask = Op.getOperand(3);
15010       SDValue DataToCompress = Op.getOperand(1);
15011       SDValue PassThru = Op.getOperand(2);
15012       if (isAllOnes(Mask)) // return data as is
15013         return Op.getOperand(1);
15014       EVT VT = Op.getValueType();
15015       EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15016                                     VT.getVectorNumElements());
15017       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15018                                        Mask.getValueType().getSizeInBits());
15019       SDLoc dl(Op);
15020       SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15021                                   DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
15022                                   DAG.getIntPtrConstant(0, dl));
15023
15024       return DAG.getNode(IntrData->Opc0, dl, VT, VMask, DataToCompress,
15025                          PassThru);
15026     }
15027     case BLEND: {
15028       SDValue Mask = Op.getOperand(3);
15029       EVT VT = Op.getValueType();
15030       EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15031                                     VT.getVectorNumElements());
15032       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15033                                        Mask.getValueType().getSizeInBits());
15034       SDLoc dl(Op);
15035       SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15036                                   DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
15037                                   DAG.getIntPtrConstant(0, dl));
15038       return DAG.getNode(IntrData->Opc0, dl, VT, VMask, Op.getOperand(1),
15039                          Op.getOperand(2));
15040     }
15041     default:
15042       break;
15043     }
15044   }
15045
15046   switch (IntNo) {
15047   default: return SDValue();    // Don't custom lower most intrinsics.
15048
15049   case Intrinsic::x86_avx2_permd:
15050   case Intrinsic::x86_avx2_permps:
15051     // Operands intentionally swapped. Mask is last operand to intrinsic,
15052     // but second operand for node/instruction.
15053     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
15054                        Op.getOperand(2), Op.getOperand(1));
15055
15056   case Intrinsic::x86_avx512_mask_valign_q_512:
15057   case Intrinsic::x86_avx512_mask_valign_d_512:
15058     // Vector source operands are swapped.
15059     return getVectorMaskingNode(DAG.getNode(X86ISD::VALIGN, dl,
15060                                             Op.getValueType(), Op.getOperand(2),
15061                                             Op.getOperand(1),
15062                                             Op.getOperand(3)),
15063                                 Op.getOperand(5), Op.getOperand(4),
15064                                 Subtarget, DAG);
15065
15066   // ptest and testp intrinsics. The intrinsic these come from are designed to
15067   // return an integer value, not just an instruction so lower it to the ptest
15068   // or testp pattern and a setcc for the result.
15069   case Intrinsic::x86_sse41_ptestz:
15070   case Intrinsic::x86_sse41_ptestc:
15071   case Intrinsic::x86_sse41_ptestnzc:
15072   case Intrinsic::x86_avx_ptestz_256:
15073   case Intrinsic::x86_avx_ptestc_256:
15074   case Intrinsic::x86_avx_ptestnzc_256:
15075   case Intrinsic::x86_avx_vtestz_ps:
15076   case Intrinsic::x86_avx_vtestc_ps:
15077   case Intrinsic::x86_avx_vtestnzc_ps:
15078   case Intrinsic::x86_avx_vtestz_pd:
15079   case Intrinsic::x86_avx_vtestc_pd:
15080   case Intrinsic::x86_avx_vtestnzc_pd:
15081   case Intrinsic::x86_avx_vtestz_ps_256:
15082   case Intrinsic::x86_avx_vtestc_ps_256:
15083   case Intrinsic::x86_avx_vtestnzc_ps_256:
15084   case Intrinsic::x86_avx_vtestz_pd_256:
15085   case Intrinsic::x86_avx_vtestc_pd_256:
15086   case Intrinsic::x86_avx_vtestnzc_pd_256: {
15087     bool IsTestPacked = false;
15088     unsigned X86CC;
15089     switch (IntNo) {
15090     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
15091     case Intrinsic::x86_avx_vtestz_ps:
15092     case Intrinsic::x86_avx_vtestz_pd:
15093     case Intrinsic::x86_avx_vtestz_ps_256:
15094     case Intrinsic::x86_avx_vtestz_pd_256:
15095       IsTestPacked = true; // Fallthrough
15096     case Intrinsic::x86_sse41_ptestz:
15097     case Intrinsic::x86_avx_ptestz_256:
15098       // ZF = 1
15099       X86CC = X86::COND_E;
15100       break;
15101     case Intrinsic::x86_avx_vtestc_ps:
15102     case Intrinsic::x86_avx_vtestc_pd:
15103     case Intrinsic::x86_avx_vtestc_ps_256:
15104     case Intrinsic::x86_avx_vtestc_pd_256:
15105       IsTestPacked = true; // Fallthrough
15106     case Intrinsic::x86_sse41_ptestc:
15107     case Intrinsic::x86_avx_ptestc_256:
15108       // CF = 1
15109       X86CC = X86::COND_B;
15110       break;
15111     case Intrinsic::x86_avx_vtestnzc_ps:
15112     case Intrinsic::x86_avx_vtestnzc_pd:
15113     case Intrinsic::x86_avx_vtestnzc_ps_256:
15114     case Intrinsic::x86_avx_vtestnzc_pd_256:
15115       IsTestPacked = true; // Fallthrough
15116     case Intrinsic::x86_sse41_ptestnzc:
15117     case Intrinsic::x86_avx_ptestnzc_256:
15118       // ZF and CF = 0
15119       X86CC = X86::COND_A;
15120       break;
15121     }
15122
15123     SDValue LHS = Op.getOperand(1);
15124     SDValue RHS = Op.getOperand(2);
15125     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
15126     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
15127     SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
15128     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
15129     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15130   }
15131   case Intrinsic::x86_avx512_kortestz_w:
15132   case Intrinsic::x86_avx512_kortestc_w: {
15133     unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
15134     SDValue LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(1));
15135     SDValue RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(2));
15136     SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
15137     SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
15138     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
15139     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15140   }
15141
15142   case Intrinsic::x86_sse42_pcmpistria128:
15143   case Intrinsic::x86_sse42_pcmpestria128:
15144   case Intrinsic::x86_sse42_pcmpistric128:
15145   case Intrinsic::x86_sse42_pcmpestric128:
15146   case Intrinsic::x86_sse42_pcmpistrio128:
15147   case Intrinsic::x86_sse42_pcmpestrio128:
15148   case Intrinsic::x86_sse42_pcmpistris128:
15149   case Intrinsic::x86_sse42_pcmpestris128:
15150   case Intrinsic::x86_sse42_pcmpistriz128:
15151   case Intrinsic::x86_sse42_pcmpestriz128: {
15152     unsigned Opcode;
15153     unsigned X86CC;
15154     switch (IntNo) {
15155     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
15156     case Intrinsic::x86_sse42_pcmpistria128:
15157       Opcode = X86ISD::PCMPISTRI;
15158       X86CC = X86::COND_A;
15159       break;
15160     case Intrinsic::x86_sse42_pcmpestria128:
15161       Opcode = X86ISD::PCMPESTRI;
15162       X86CC = X86::COND_A;
15163       break;
15164     case Intrinsic::x86_sse42_pcmpistric128:
15165       Opcode = X86ISD::PCMPISTRI;
15166       X86CC = X86::COND_B;
15167       break;
15168     case Intrinsic::x86_sse42_pcmpestric128:
15169       Opcode = X86ISD::PCMPESTRI;
15170       X86CC = X86::COND_B;
15171       break;
15172     case Intrinsic::x86_sse42_pcmpistrio128:
15173       Opcode = X86ISD::PCMPISTRI;
15174       X86CC = X86::COND_O;
15175       break;
15176     case Intrinsic::x86_sse42_pcmpestrio128:
15177       Opcode = X86ISD::PCMPESTRI;
15178       X86CC = X86::COND_O;
15179       break;
15180     case Intrinsic::x86_sse42_pcmpistris128:
15181       Opcode = X86ISD::PCMPISTRI;
15182       X86CC = X86::COND_S;
15183       break;
15184     case Intrinsic::x86_sse42_pcmpestris128:
15185       Opcode = X86ISD::PCMPESTRI;
15186       X86CC = X86::COND_S;
15187       break;
15188     case Intrinsic::x86_sse42_pcmpistriz128:
15189       Opcode = X86ISD::PCMPISTRI;
15190       X86CC = X86::COND_E;
15191       break;
15192     case Intrinsic::x86_sse42_pcmpestriz128:
15193       Opcode = X86ISD::PCMPESTRI;
15194       X86CC = X86::COND_E;
15195       break;
15196     }
15197     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
15198     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
15199     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
15200     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15201                                 DAG.getConstant(X86CC, dl, MVT::i8),
15202                                 SDValue(PCMP.getNode(), 1));
15203     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15204   }
15205
15206   case Intrinsic::x86_sse42_pcmpistri128:
15207   case Intrinsic::x86_sse42_pcmpestri128: {
15208     unsigned Opcode;
15209     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
15210       Opcode = X86ISD::PCMPISTRI;
15211     else
15212       Opcode = X86ISD::PCMPESTRI;
15213
15214     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
15215     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
15216     return DAG.getNode(Opcode, dl, VTs, NewOps);
15217   }
15218   }
15219 }
15220
15221 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15222                               SDValue Src, SDValue Mask, SDValue Base,
15223                               SDValue Index, SDValue ScaleOp, SDValue Chain,
15224                               const X86Subtarget * Subtarget) {
15225   SDLoc dl(Op);
15226   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15227   assert(C && "Invalid scale type");
15228   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
15229   EVT MaskVT = MVT::getVectorVT(MVT::i1,
15230                              Index.getSimpleValueType().getVectorNumElements());
15231   SDValue MaskInReg;
15232   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15233   if (MaskC)
15234     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
15235   else
15236     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
15237   SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
15238   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
15239   SDValue Segment = DAG.getRegister(0, MVT::i32);
15240   if (Src.getOpcode() == ISD::UNDEF)
15241     Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
15242   SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
15243   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
15244   SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
15245   return DAG.getMergeValues(RetOps, dl);
15246 }
15247
15248 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15249                                SDValue Src, SDValue Mask, SDValue Base,
15250                                SDValue Index, SDValue ScaleOp, SDValue Chain) {
15251   SDLoc dl(Op);
15252   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15253   assert(C && "Invalid scale type");
15254   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
15255   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
15256   SDValue Segment = DAG.getRegister(0, MVT::i32);
15257   EVT MaskVT = MVT::getVectorVT(MVT::i1,
15258                              Index.getSimpleValueType().getVectorNumElements());
15259   SDValue MaskInReg;
15260   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15261   if (MaskC)
15262     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
15263   else
15264     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
15265   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
15266   SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
15267   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
15268   return SDValue(Res, 1);
15269 }
15270
15271 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15272                                SDValue Mask, SDValue Base, SDValue Index,
15273                                SDValue ScaleOp, SDValue Chain) {
15274   SDLoc dl(Op);
15275   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15276   assert(C && "Invalid scale type");
15277   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
15278   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
15279   SDValue Segment = DAG.getRegister(0, MVT::i32);
15280   EVT MaskVT =
15281     MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
15282   SDValue MaskInReg;
15283   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15284   if (MaskC)
15285     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
15286   else
15287     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
15288   //SDVTList VTs = DAG.getVTList(MVT::Other);
15289   SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
15290   SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
15291   return SDValue(Res, 0);
15292 }
15293
15294 // getReadPerformanceCounter - Handles the lowering of builtin intrinsics that
15295 // read performance monitor counters (x86_rdpmc).
15296 static void getReadPerformanceCounter(SDNode *N, SDLoc DL,
15297                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
15298                               SmallVectorImpl<SDValue> &Results) {
15299   assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
15300   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
15301   SDValue LO, HI;
15302
15303   // The ECX register is used to select the index of the performance counter
15304   // to read.
15305   SDValue Chain = DAG.getCopyToReg(N->getOperand(0), DL, X86::ECX,
15306                                    N->getOperand(2));
15307   SDValue rd = DAG.getNode(X86ISD::RDPMC_DAG, DL, Tys, Chain);
15308
15309   // Reads the content of a 64-bit performance counter and returns it in the
15310   // registers EDX:EAX.
15311   if (Subtarget->is64Bit()) {
15312     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
15313     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
15314                             LO.getValue(2));
15315   } else {
15316     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
15317     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
15318                             LO.getValue(2));
15319   }
15320   Chain = HI.getValue(1);
15321
15322   if (Subtarget->is64Bit()) {
15323     // The EAX register is loaded with the low-order 32 bits. The EDX register
15324     // is loaded with the supported high-order bits of the counter.
15325     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
15326                               DAG.getConstant(32, DL, MVT::i8));
15327     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
15328     Results.push_back(Chain);
15329     return;
15330   }
15331
15332   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
15333   SDValue Ops[] = { LO, HI };
15334   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
15335   Results.push_back(Pair);
15336   Results.push_back(Chain);
15337 }
15338
15339 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
15340 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
15341 // also used to custom lower READCYCLECOUNTER nodes.
15342 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
15343                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
15344                               SmallVectorImpl<SDValue> &Results) {
15345   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
15346   SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
15347   SDValue LO, HI;
15348
15349   // The processor's time-stamp counter (a 64-bit MSR) is stored into the
15350   // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
15351   // and the EAX register is loaded with the low-order 32 bits.
15352   if (Subtarget->is64Bit()) {
15353     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
15354     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
15355                             LO.getValue(2));
15356   } else {
15357     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
15358     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
15359                             LO.getValue(2));
15360   }
15361   SDValue Chain = HI.getValue(1);
15362
15363   if (Opcode == X86ISD::RDTSCP_DAG) {
15364     assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
15365
15366     // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
15367     // the ECX register. Add 'ecx' explicitly to the chain.
15368     SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
15369                                      HI.getValue(2));
15370     // Explicitly store the content of ECX at the location passed in input
15371     // to the 'rdtscp' intrinsic.
15372     Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
15373                          MachinePointerInfo(), false, false, 0);
15374   }
15375
15376   if (Subtarget->is64Bit()) {
15377     // The EDX register is loaded with the high-order 32 bits of the MSR, and
15378     // the EAX register is loaded with the low-order 32 bits.
15379     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
15380                               DAG.getConstant(32, DL, MVT::i8));
15381     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
15382     Results.push_back(Chain);
15383     return;
15384   }
15385
15386   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
15387   SDValue Ops[] = { LO, HI };
15388   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
15389   Results.push_back(Pair);
15390   Results.push_back(Chain);
15391 }
15392
15393 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
15394                                      SelectionDAG &DAG) {
15395   SmallVector<SDValue, 2> Results;
15396   SDLoc DL(Op);
15397   getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
15398                           Results);
15399   return DAG.getMergeValues(Results, DL);
15400 }
15401
15402
15403 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
15404                                       SelectionDAG &DAG) {
15405   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
15406
15407   const IntrinsicData* IntrData = getIntrinsicWithChain(IntNo);
15408   if (!IntrData)
15409     return SDValue();
15410
15411   SDLoc dl(Op);
15412   switch(IntrData->Type) {
15413   default:
15414     llvm_unreachable("Unknown Intrinsic Type");
15415     break;
15416   case RDSEED:
15417   case RDRAND: {
15418     // Emit the node with the right value type.
15419     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
15420     SDValue Result = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
15421
15422     // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
15423     // Otherwise return the value from Rand, which is always 0, casted to i32.
15424     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
15425                       DAG.getConstant(1, dl, Op->getValueType(1)),
15426                       DAG.getConstant(X86::COND_B, dl, MVT::i32),
15427                       SDValue(Result.getNode(), 1) };
15428     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
15429                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
15430                                   Ops);
15431
15432     // Return { result, isValid, chain }.
15433     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
15434                        SDValue(Result.getNode(), 2));
15435   }
15436   case GATHER: {
15437   //gather(v1, mask, index, base, scale);
15438     SDValue Chain = Op.getOperand(0);
15439     SDValue Src   = Op.getOperand(2);
15440     SDValue Base  = Op.getOperand(3);
15441     SDValue Index = Op.getOperand(4);
15442     SDValue Mask  = Op.getOperand(5);
15443     SDValue Scale = Op.getOperand(6);
15444     return getGatherNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index, Scale,
15445                          Chain, Subtarget);
15446   }
15447   case SCATTER: {
15448   //scatter(base, mask, index, v1, scale);
15449     SDValue Chain = Op.getOperand(0);
15450     SDValue Base  = Op.getOperand(2);
15451     SDValue Mask  = Op.getOperand(3);
15452     SDValue Index = Op.getOperand(4);
15453     SDValue Src   = Op.getOperand(5);
15454     SDValue Scale = Op.getOperand(6);
15455     return getScatterNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index,
15456                           Scale, Chain);
15457   }
15458   case PREFETCH: {
15459     SDValue Hint = Op.getOperand(6);
15460     unsigned HintVal = cast<ConstantSDNode>(Hint)->getZExtValue();
15461     assert(HintVal < 2 && "Wrong prefetch hint in intrinsic: should be 0 or 1");
15462     unsigned Opcode = (HintVal ? IntrData->Opc1 : IntrData->Opc0);
15463     SDValue Chain = Op.getOperand(0);
15464     SDValue Mask  = Op.getOperand(2);
15465     SDValue Index = Op.getOperand(3);
15466     SDValue Base  = Op.getOperand(4);
15467     SDValue Scale = Op.getOperand(5);
15468     return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
15469   }
15470   // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
15471   case RDTSC: {
15472     SmallVector<SDValue, 2> Results;
15473     getReadTimeStampCounter(Op.getNode(), dl, IntrData->Opc0, DAG, Subtarget,
15474                             Results);
15475     return DAG.getMergeValues(Results, dl);
15476   }
15477   // Read Performance Monitoring Counters.
15478   case RDPMC: {
15479     SmallVector<SDValue, 2> Results;
15480     getReadPerformanceCounter(Op.getNode(), dl, DAG, Subtarget, Results);
15481     return DAG.getMergeValues(Results, dl);
15482   }
15483   // XTEST intrinsics.
15484   case XTEST: {
15485     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
15486     SDValue InTrans = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
15487     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15488                                 DAG.getConstant(X86::COND_NE, dl, MVT::i8),
15489                                 InTrans);
15490     SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
15491     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
15492                        Ret, SDValue(InTrans.getNode(), 1));
15493   }
15494   // ADC/ADCX/SBB
15495   case ADX: {
15496     SmallVector<SDValue, 2> Results;
15497     SDVTList CFVTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
15498     SDVTList VTs = DAG.getVTList(Op.getOperand(3)->getValueType(0), MVT::Other);
15499     SDValue GenCF = DAG.getNode(X86ISD::ADD, dl, CFVTs, Op.getOperand(2),
15500                                 DAG.getConstant(-1, dl, MVT::i8));
15501     SDValue Res = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(3),
15502                               Op.getOperand(4), GenCF.getValue(1));
15503     SDValue Store = DAG.getStore(Op.getOperand(0), dl, Res.getValue(0),
15504                                  Op.getOperand(5), MachinePointerInfo(),
15505                                  false, false, 0);
15506     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15507                                 DAG.getConstant(X86::COND_B, dl, MVT::i8),
15508                                 Res.getValue(1));
15509     Results.push_back(SetCC);
15510     Results.push_back(Store);
15511     return DAG.getMergeValues(Results, dl);
15512   }
15513   case COMPRESS_TO_MEM: {
15514     SDLoc dl(Op);
15515     SDValue Mask = Op.getOperand(4);
15516     SDValue DataToCompress = Op.getOperand(3);
15517     SDValue Addr = Op.getOperand(2);
15518     SDValue Chain = Op.getOperand(0);
15519
15520     if (isAllOnes(Mask)) // return just a store
15521       return DAG.getStore(Chain, dl, DataToCompress, Addr,
15522                           MachinePointerInfo(), false, false, 0);
15523
15524     EVT VT = DataToCompress.getValueType();
15525     EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15526                                   VT.getVectorNumElements());
15527     EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15528                                      Mask.getValueType().getSizeInBits());
15529     SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15530                                 DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
15531                                 DAG.getIntPtrConstant(0, dl));
15532
15533     SDValue Compressed =  DAG.getNode(IntrData->Opc0, dl, VT, VMask,
15534                                       DataToCompress, DAG.getUNDEF(VT));
15535     return DAG.getStore(Chain, dl, Compressed, Addr,
15536                         MachinePointerInfo(), false, false, 0);
15537   }
15538   case EXPAND_FROM_MEM: {
15539     SDLoc dl(Op);
15540     SDValue Mask = Op.getOperand(4);
15541     SDValue PathThru = Op.getOperand(3);
15542     SDValue Addr = Op.getOperand(2);
15543     SDValue Chain = Op.getOperand(0);
15544     EVT VT = Op.getValueType();
15545
15546     if (isAllOnes(Mask)) // return just a load
15547       return DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(), false, false,
15548                          false, 0);
15549     EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15550                                   VT.getVectorNumElements());
15551     EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15552                                      Mask.getValueType().getSizeInBits());
15553     SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15554                                 DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
15555                                 DAG.getIntPtrConstant(0, dl));
15556
15557     SDValue DataToExpand = DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(),
15558                                    false, false, false, 0);
15559
15560     SDValue Results[] = {
15561         DAG.getNode(IntrData->Opc0, dl, VT, VMask, DataToExpand, PathThru),
15562         Chain};
15563     return DAG.getMergeValues(Results, dl);
15564   }
15565   }
15566 }
15567
15568 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
15569                                            SelectionDAG &DAG) const {
15570   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
15571   MFI->setReturnAddressIsTaken(true);
15572
15573   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
15574     return SDValue();
15575
15576   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15577   SDLoc dl(Op);
15578   EVT PtrVT = getPointerTy();
15579
15580   if (Depth > 0) {
15581     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
15582     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15583     SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), dl, PtrVT);
15584     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
15585                        DAG.getNode(ISD::ADD, dl, PtrVT,
15586                                    FrameAddr, Offset),
15587                        MachinePointerInfo(), false, false, false, 0);
15588   }
15589
15590   // Just load the return address.
15591   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
15592   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
15593                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
15594 }
15595
15596 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
15597   MachineFunction &MF = DAG.getMachineFunction();
15598   MachineFrameInfo *MFI = MF.getFrameInfo();
15599   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
15600   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15601   EVT VT = Op.getValueType();
15602
15603   MFI->setFrameAddressIsTaken(true);
15604
15605   if (MF.getTarget().getMCAsmInfo()->usesWindowsCFI()) {
15606     // Depth > 0 makes no sense on targets which use Windows unwind codes.  It
15607     // is not possible to crawl up the stack without looking at the unwind codes
15608     // simultaneously.
15609     int FrameAddrIndex = FuncInfo->getFAIndex();
15610     if (!FrameAddrIndex) {
15611       // Set up a frame object for the return address.
15612       unsigned SlotSize = RegInfo->getSlotSize();
15613       FrameAddrIndex = MF.getFrameInfo()->CreateFixedObject(
15614           SlotSize, /*Offset=*/INT64_MIN, /*IsImmutable=*/false);
15615       FuncInfo->setFAIndex(FrameAddrIndex);
15616     }
15617     return DAG.getFrameIndex(FrameAddrIndex, VT);
15618   }
15619
15620   unsigned FrameReg =
15621       RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
15622   SDLoc dl(Op);  // FIXME probably not meaningful
15623   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15624   assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
15625           (FrameReg == X86::EBP && VT == MVT::i32)) &&
15626          "Invalid Frame Register!");
15627   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
15628   while (Depth--)
15629     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
15630                             MachinePointerInfo(),
15631                             false, false, false, 0);
15632   return FrameAddr;
15633 }
15634
15635 // FIXME? Maybe this could be a TableGen attribute on some registers and
15636 // this table could be generated automatically from RegInfo.
15637 unsigned X86TargetLowering::getRegisterByName(const char* RegName,
15638                                               EVT VT) const {
15639   unsigned Reg = StringSwitch<unsigned>(RegName)
15640                        .Case("esp", X86::ESP)
15641                        .Case("rsp", X86::RSP)
15642                        .Default(0);
15643   if (Reg)
15644     return Reg;
15645   report_fatal_error("Invalid register name global variable");
15646 }
15647
15648 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
15649                                                      SelectionDAG &DAG) const {
15650   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15651   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize(), SDLoc(Op));
15652 }
15653
15654 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
15655   SDValue Chain     = Op.getOperand(0);
15656   SDValue Offset    = Op.getOperand(1);
15657   SDValue Handler   = Op.getOperand(2);
15658   SDLoc dl      (Op);
15659
15660   EVT PtrVT = getPointerTy();
15661   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15662   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
15663   assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
15664           (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
15665          "Invalid Frame Register!");
15666   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
15667   unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
15668
15669   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
15670                                  DAG.getIntPtrConstant(RegInfo->getSlotSize(),
15671                                                        dl));
15672   StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
15673   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
15674                        false, false, 0);
15675   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
15676
15677   return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
15678                      DAG.getRegister(StoreAddrReg, PtrVT));
15679 }
15680
15681 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
15682                                                SelectionDAG &DAG) const {
15683   SDLoc DL(Op);
15684   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
15685                      DAG.getVTList(MVT::i32, MVT::Other),
15686                      Op.getOperand(0), Op.getOperand(1));
15687 }
15688
15689 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
15690                                                 SelectionDAG &DAG) const {
15691   SDLoc DL(Op);
15692   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
15693                      Op.getOperand(0), Op.getOperand(1));
15694 }
15695
15696 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
15697   return Op.getOperand(0);
15698 }
15699
15700 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
15701                                                 SelectionDAG &DAG) const {
15702   SDValue Root = Op.getOperand(0);
15703   SDValue Trmp = Op.getOperand(1); // trampoline
15704   SDValue FPtr = Op.getOperand(2); // nested function
15705   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
15706   SDLoc dl (Op);
15707
15708   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
15709   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
15710
15711   if (Subtarget->is64Bit()) {
15712     SDValue OutChains[6];
15713
15714     // Large code-model.
15715     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
15716     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
15717
15718     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
15719     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
15720
15721     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
15722
15723     // Load the pointer to the nested function into R11.
15724     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
15725     SDValue Addr = Trmp;
15726     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
15727                                 Addr, MachinePointerInfo(TrmpAddr),
15728                                 false, false, 0);
15729
15730     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15731                        DAG.getConstant(2, dl, MVT::i64));
15732     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
15733                                 MachinePointerInfo(TrmpAddr, 2),
15734                                 false, false, 2);
15735
15736     // Load the 'nest' parameter value into R10.
15737     // R10 is specified in X86CallingConv.td
15738     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
15739     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15740                        DAG.getConstant(10, dl, MVT::i64));
15741     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
15742                                 Addr, MachinePointerInfo(TrmpAddr, 10),
15743                                 false, false, 0);
15744
15745     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15746                        DAG.getConstant(12, dl, MVT::i64));
15747     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
15748                                 MachinePointerInfo(TrmpAddr, 12),
15749                                 false, false, 2);
15750
15751     // Jump to the nested function.
15752     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
15753     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15754                        DAG.getConstant(20, dl, MVT::i64));
15755     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
15756                                 Addr, MachinePointerInfo(TrmpAddr, 20),
15757                                 false, false, 0);
15758
15759     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
15760     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15761                        DAG.getConstant(22, dl, MVT::i64));
15762     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, dl, MVT::i8),
15763                                 Addr, MachinePointerInfo(TrmpAddr, 22),
15764                                 false, false, 0);
15765
15766     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
15767   } else {
15768     const Function *Func =
15769       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
15770     CallingConv::ID CC = Func->getCallingConv();
15771     unsigned NestReg;
15772
15773     switch (CC) {
15774     default:
15775       llvm_unreachable("Unsupported calling convention");
15776     case CallingConv::C:
15777     case CallingConv::X86_StdCall: {
15778       // Pass 'nest' parameter in ECX.
15779       // Must be kept in sync with X86CallingConv.td
15780       NestReg = X86::ECX;
15781
15782       // Check that ECX wasn't needed by an 'inreg' parameter.
15783       FunctionType *FTy = Func->getFunctionType();
15784       const AttributeSet &Attrs = Func->getAttributes();
15785
15786       if (!Attrs.isEmpty() && !Func->isVarArg()) {
15787         unsigned InRegCount = 0;
15788         unsigned Idx = 1;
15789
15790         for (FunctionType::param_iterator I = FTy->param_begin(),
15791              E = FTy->param_end(); I != E; ++I, ++Idx)
15792           if (Attrs.hasAttribute(Idx, Attribute::InReg))
15793             // FIXME: should only count parameters that are lowered to integers.
15794             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
15795
15796         if (InRegCount > 2) {
15797           report_fatal_error("Nest register in use - reduce number of inreg"
15798                              " parameters!");
15799         }
15800       }
15801       break;
15802     }
15803     case CallingConv::X86_FastCall:
15804     case CallingConv::X86_ThisCall:
15805     case CallingConv::Fast:
15806       // Pass 'nest' parameter in EAX.
15807       // Must be kept in sync with X86CallingConv.td
15808       NestReg = X86::EAX;
15809       break;
15810     }
15811
15812     SDValue OutChains[4];
15813     SDValue Addr, Disp;
15814
15815     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15816                        DAG.getConstant(10, dl, MVT::i32));
15817     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
15818
15819     // This is storing the opcode for MOV32ri.
15820     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
15821     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
15822     OutChains[0] = DAG.getStore(Root, dl,
15823                                 DAG.getConstant(MOV32ri|N86Reg, dl, MVT::i8),
15824                                 Trmp, MachinePointerInfo(TrmpAddr),
15825                                 false, false, 0);
15826
15827     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15828                        DAG.getConstant(1, dl, MVT::i32));
15829     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
15830                                 MachinePointerInfo(TrmpAddr, 1),
15831                                 false, false, 1);
15832
15833     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
15834     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15835                        DAG.getConstant(5, dl, MVT::i32));
15836     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, dl, MVT::i8),
15837                                 Addr, MachinePointerInfo(TrmpAddr, 5),
15838                                 false, false, 1);
15839
15840     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15841                        DAG.getConstant(6, dl, MVT::i32));
15842     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
15843                                 MachinePointerInfo(TrmpAddr, 6),
15844                                 false, false, 1);
15845
15846     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
15847   }
15848 }
15849
15850 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
15851                                             SelectionDAG &DAG) const {
15852   /*
15853    The rounding mode is in bits 11:10 of FPSR, and has the following
15854    settings:
15855      00 Round to nearest
15856      01 Round to -inf
15857      10 Round to +inf
15858      11 Round to 0
15859
15860   FLT_ROUNDS, on the other hand, expects the following:
15861     -1 Undefined
15862      0 Round to 0
15863      1 Round to nearest
15864      2 Round to +inf
15865      3 Round to -inf
15866
15867   To perform the conversion, we do:
15868     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
15869   */
15870
15871   MachineFunction &MF = DAG.getMachineFunction();
15872   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
15873   unsigned StackAlignment = TFI.getStackAlignment();
15874   MVT VT = Op.getSimpleValueType();
15875   SDLoc DL(Op);
15876
15877   // Save FP Control Word to stack slot
15878   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
15879   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
15880
15881   MachineMemOperand *MMO =
15882    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
15883                            MachineMemOperand::MOStore, 2, 2);
15884
15885   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
15886   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
15887                                           DAG.getVTList(MVT::Other),
15888                                           Ops, MVT::i16, MMO);
15889
15890   // Load FP Control Word from stack slot
15891   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
15892                             MachinePointerInfo(), false, false, false, 0);
15893
15894   // Transform as necessary
15895   SDValue CWD1 =
15896     DAG.getNode(ISD::SRL, DL, MVT::i16,
15897                 DAG.getNode(ISD::AND, DL, MVT::i16,
15898                             CWD, DAG.getConstant(0x800, DL, MVT::i16)),
15899                 DAG.getConstant(11, DL, MVT::i8));
15900   SDValue CWD2 =
15901     DAG.getNode(ISD::SRL, DL, MVT::i16,
15902                 DAG.getNode(ISD::AND, DL, MVT::i16,
15903                             CWD, DAG.getConstant(0x400, DL, MVT::i16)),
15904                 DAG.getConstant(9, DL, MVT::i8));
15905
15906   SDValue RetVal =
15907     DAG.getNode(ISD::AND, DL, MVT::i16,
15908                 DAG.getNode(ISD::ADD, DL, MVT::i16,
15909                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
15910                             DAG.getConstant(1, DL, MVT::i16)),
15911                 DAG.getConstant(3, DL, MVT::i16));
15912
15913   return DAG.getNode((VT.getSizeInBits() < 16 ?
15914                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
15915 }
15916
15917 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
15918   MVT VT = Op.getSimpleValueType();
15919   EVT OpVT = VT;
15920   unsigned NumBits = VT.getSizeInBits();
15921   SDLoc dl(Op);
15922
15923   Op = Op.getOperand(0);
15924   if (VT == MVT::i8) {
15925     // Zero extend to i32 since there is not an i8 bsr.
15926     OpVT = MVT::i32;
15927     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
15928   }
15929
15930   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
15931   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
15932   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
15933
15934   // If src is zero (i.e. bsr sets ZF), returns NumBits.
15935   SDValue Ops[] = {
15936     Op,
15937     DAG.getConstant(NumBits + NumBits - 1, dl, OpVT),
15938     DAG.getConstant(X86::COND_E, dl, MVT::i8),
15939     Op.getValue(1)
15940   };
15941   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
15942
15943   // Finally xor with NumBits-1.
15944   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
15945                    DAG.getConstant(NumBits - 1, dl, OpVT));
15946
15947   if (VT == MVT::i8)
15948     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
15949   return Op;
15950 }
15951
15952 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
15953   MVT VT = Op.getSimpleValueType();
15954   EVT OpVT = VT;
15955   unsigned NumBits = VT.getSizeInBits();
15956   SDLoc dl(Op);
15957
15958   Op = Op.getOperand(0);
15959   if (VT == MVT::i8) {
15960     // Zero extend to i32 since there is not an i8 bsr.
15961     OpVT = MVT::i32;
15962     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
15963   }
15964
15965   // Issue a bsr (scan bits in reverse).
15966   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
15967   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
15968
15969   // And xor with NumBits-1.
15970   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
15971                    DAG.getConstant(NumBits - 1, dl, OpVT));
15972
15973   if (VT == MVT::i8)
15974     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
15975   return Op;
15976 }
15977
15978 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
15979   MVT VT = Op.getSimpleValueType();
15980   unsigned NumBits = VT.getSizeInBits();
15981   SDLoc dl(Op);
15982   Op = Op.getOperand(0);
15983
15984   // Issue a bsf (scan bits forward) which also sets EFLAGS.
15985   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
15986   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
15987
15988   // If src is zero (i.e. bsf sets ZF), returns NumBits.
15989   SDValue Ops[] = {
15990     Op,
15991     DAG.getConstant(NumBits, dl, VT),
15992     DAG.getConstant(X86::COND_E, dl, MVT::i8),
15993     Op.getValue(1)
15994   };
15995   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
15996 }
15997
15998 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
15999 // ones, and then concatenate the result back.
16000 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
16001   MVT VT = Op.getSimpleValueType();
16002
16003   assert(VT.is256BitVector() && VT.isInteger() &&
16004          "Unsupported value type for operation");
16005
16006   unsigned NumElems = VT.getVectorNumElements();
16007   SDLoc dl(Op);
16008
16009   // Extract the LHS vectors
16010   SDValue LHS = Op.getOperand(0);
16011   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
16012   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
16013
16014   // Extract the RHS vectors
16015   SDValue RHS = Op.getOperand(1);
16016   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
16017   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
16018
16019   MVT EltVT = VT.getVectorElementType();
16020   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
16021
16022   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
16023                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
16024                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
16025 }
16026
16027 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
16028   assert(Op.getSimpleValueType().is256BitVector() &&
16029          Op.getSimpleValueType().isInteger() &&
16030          "Only handle AVX 256-bit vector integer operation");
16031   return Lower256IntArith(Op, DAG);
16032 }
16033
16034 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
16035   assert(Op.getSimpleValueType().is256BitVector() &&
16036          Op.getSimpleValueType().isInteger() &&
16037          "Only handle AVX 256-bit vector integer operation");
16038   return Lower256IntArith(Op, DAG);
16039 }
16040
16041 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
16042                         SelectionDAG &DAG) {
16043   SDLoc dl(Op);
16044   MVT VT = Op.getSimpleValueType();
16045
16046   // Decompose 256-bit ops into smaller 128-bit ops.
16047   if (VT.is256BitVector() && !Subtarget->hasInt256())
16048     return Lower256IntArith(Op, DAG);
16049
16050   SDValue A = Op.getOperand(0);
16051   SDValue B = Op.getOperand(1);
16052
16053   // Lower v16i8/v32i8 mul as promotion to v8i16/v16i16 vector
16054   // pairs, multiply and truncate.
16055   if (VT == MVT::v16i8 || VT == MVT::v32i8) {
16056     if (Subtarget->hasInt256()) {
16057       if (VT == MVT::v32i8) {
16058         MVT SubVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() / 2);
16059         SDValue Lo = DAG.getIntPtrConstant(0, dl);
16060         SDValue Hi = DAG.getIntPtrConstant(VT.getVectorNumElements() / 2, dl);
16061         SDValue ALo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Lo);
16062         SDValue BLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Lo);
16063         SDValue AHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Hi);
16064         SDValue BHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Hi);
16065         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
16066                            DAG.getNode(ISD::MUL, dl, SubVT, ALo, BLo),
16067                            DAG.getNode(ISD::MUL, dl, SubVT, AHi, BHi));
16068       }
16069
16070       MVT ExVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements());
16071       return DAG.getNode(
16072           ISD::TRUNCATE, dl, VT,
16073           DAG.getNode(ISD::MUL, dl, ExVT,
16074                       DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, A),
16075                       DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, B)));
16076     }
16077
16078     assert(VT == MVT::v16i8 &&
16079            "Pre-AVX2 support only supports v16i8 multiplication");
16080     MVT ExVT = MVT::v8i16;
16081
16082     // Extract the lo parts and sign extend to i16
16083     SDValue ALo, BLo;
16084     if (Subtarget->hasSSE41()) {
16085       ALo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, A);
16086       BLo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, B);
16087     } else {
16088       const int ShufMask[] = {-1, 0, -1, 1, -1, 2, -1, 3,
16089                               -1, 4, -1, 5, -1, 6, -1, 7};
16090       ALo = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
16091       BLo = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
16092       ALo = DAG.getNode(ISD::BITCAST, dl, ExVT, ALo);
16093       BLo = DAG.getNode(ISD::BITCAST, dl, ExVT, BLo);
16094       ALo = DAG.getNode(ISD::SRA, dl, ExVT, ALo, DAG.getConstant(8, dl, ExVT));
16095       BLo = DAG.getNode(ISD::SRA, dl, ExVT, BLo, DAG.getConstant(8, dl, ExVT));
16096     }
16097
16098     // Extract the hi parts and sign extend to i16
16099     SDValue AHi, BHi;
16100     if (Subtarget->hasSSE41()) {
16101       const int ShufMask[] = {8,  9,  10, 11, 12, 13, 14, 15,
16102                               -1, -1, -1, -1, -1, -1, -1, -1};
16103       AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
16104       BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
16105       AHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, AHi);
16106       BHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, BHi);
16107     } else {
16108       const int ShufMask[] = {-1, 8,  -1, 9,  -1, 10, -1, 11,
16109                               -1, 12, -1, 13, -1, 14, -1, 15};
16110       AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
16111       BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
16112       AHi = DAG.getNode(ISD::BITCAST, dl, ExVT, AHi);
16113       BHi = DAG.getNode(ISD::BITCAST, dl, ExVT, BHi);
16114       AHi = DAG.getNode(ISD::SRA, dl, ExVT, AHi, DAG.getConstant(8, dl, ExVT));
16115       BHi = DAG.getNode(ISD::SRA, dl, ExVT, BHi, DAG.getConstant(8, dl, ExVT));
16116     }
16117
16118     // Multiply, mask the lower 8bits of the lo/hi results and pack
16119     SDValue RLo = DAG.getNode(ISD::MUL, dl, ExVT, ALo, BLo);
16120     SDValue RHi = DAG.getNode(ISD::MUL, dl, ExVT, AHi, BHi);
16121     RLo = DAG.getNode(ISD::AND, dl, ExVT, RLo, DAG.getConstant(255, dl, ExVT));
16122     RHi = DAG.getNode(ISD::AND, dl, ExVT, RHi, DAG.getConstant(255, dl, ExVT));
16123     return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
16124   }
16125
16126   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
16127   if (VT == MVT::v4i32) {
16128     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
16129            "Should not custom lower when pmuldq is available!");
16130
16131     // Extract the odd parts.
16132     static const int UnpackMask[] = { 1, -1, 3, -1 };
16133     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
16134     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
16135
16136     // Multiply the even parts.
16137     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
16138     // Now multiply odd parts.
16139     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
16140
16141     Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
16142     Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
16143
16144     // Merge the two vectors back together with a shuffle. This expands into 2
16145     // shuffles.
16146     static const int ShufMask[] = { 0, 4, 2, 6 };
16147     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
16148   }
16149
16150   assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
16151          "Only know how to lower V2I64/V4I64/V8I64 multiply");
16152
16153   //  Ahi = psrlqi(a, 32);
16154   //  Bhi = psrlqi(b, 32);
16155   //
16156   //  AloBlo = pmuludq(a, b);
16157   //  AloBhi = pmuludq(a, Bhi);
16158   //  AhiBlo = pmuludq(Ahi, b);
16159
16160   //  AloBhi = psllqi(AloBhi, 32);
16161   //  AhiBlo = psllqi(AhiBlo, 32);
16162   //  return AloBlo + AloBhi + AhiBlo;
16163
16164   SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
16165   SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
16166
16167   // Bit cast to 32-bit vectors for MULUDQ
16168   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
16169                                   (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
16170   A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
16171   B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
16172   Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
16173   Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
16174
16175   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
16176   SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
16177   SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
16178
16179   AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
16180   AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
16181
16182   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
16183   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
16184 }
16185
16186 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
16187   assert(Subtarget->isTargetWin64() && "Unexpected target");
16188   EVT VT = Op.getValueType();
16189   assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
16190          "Unexpected return type for lowering");
16191
16192   RTLIB::Libcall LC;
16193   bool isSigned;
16194   switch (Op->getOpcode()) {
16195   default: llvm_unreachable("Unexpected request for libcall!");
16196   case ISD::SDIV:      isSigned = true;  LC = RTLIB::SDIV_I128;    break;
16197   case ISD::UDIV:      isSigned = false; LC = RTLIB::UDIV_I128;    break;
16198   case ISD::SREM:      isSigned = true;  LC = RTLIB::SREM_I128;    break;
16199   case ISD::UREM:      isSigned = false; LC = RTLIB::UREM_I128;    break;
16200   case ISD::SDIVREM:   isSigned = true;  LC = RTLIB::SDIVREM_I128; break;
16201   case ISD::UDIVREM:   isSigned = false; LC = RTLIB::UDIVREM_I128; break;
16202   }
16203
16204   SDLoc dl(Op);
16205   SDValue InChain = DAG.getEntryNode();
16206
16207   TargetLowering::ArgListTy Args;
16208   TargetLowering::ArgListEntry Entry;
16209   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
16210     EVT ArgVT = Op->getOperand(i).getValueType();
16211     assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
16212            "Unexpected argument type for lowering");
16213     SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
16214     Entry.Node = StackPtr;
16215     InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
16216                            false, false, 16);
16217     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
16218     Entry.Ty = PointerType::get(ArgTy,0);
16219     Entry.isSExt = false;
16220     Entry.isZExt = false;
16221     Args.push_back(Entry);
16222   }
16223
16224   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
16225                                          getPointerTy());
16226
16227   TargetLowering::CallLoweringInfo CLI(DAG);
16228   CLI.setDebugLoc(dl).setChain(InChain)
16229     .setCallee(getLibcallCallingConv(LC),
16230                static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
16231                Callee, std::move(Args), 0)
16232     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
16233
16234   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
16235   return DAG.getNode(ISD::BITCAST, dl, VT, CallInfo.first);
16236 }
16237
16238 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
16239                              SelectionDAG &DAG) {
16240   SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
16241   EVT VT = Op0.getValueType();
16242   SDLoc dl(Op);
16243
16244   assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
16245          (VT == MVT::v8i32 && Subtarget->hasInt256()));
16246
16247   // PMULxD operations multiply each even value (starting at 0) of LHS with
16248   // the related value of RHS and produce a widen result.
16249   // E.g., PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
16250   // => <2 x i64> <ae|cg>
16251   //
16252   // In other word, to have all the results, we need to perform two PMULxD:
16253   // 1. one with the even values.
16254   // 2. one with the odd values.
16255   // To achieve #2, with need to place the odd values at an even position.
16256   //
16257   // Place the odd value at an even position (basically, shift all values 1
16258   // step to the left):
16259   const int Mask[] = {1, -1, 3, -1, 5, -1, 7, -1};
16260   // <a|b|c|d> => <b|undef|d|undef>
16261   SDValue Odd0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
16262   // <e|f|g|h> => <f|undef|h|undef>
16263   SDValue Odd1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
16264
16265   // Emit two multiplies, one for the lower 2 ints and one for the higher 2
16266   // ints.
16267   MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
16268   bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
16269   unsigned Opcode =
16270       (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
16271   // PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
16272   // => <2 x i64> <ae|cg>
16273   SDValue Mul1 = DAG.getNode(ISD::BITCAST, dl, VT,
16274                              DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
16275   // PMULUDQ <4 x i32> <b|undef|d|undef>, <4 x i32> <f|undef|h|undef>
16276   // => <2 x i64> <bf|dh>
16277   SDValue Mul2 = DAG.getNode(ISD::BITCAST, dl, VT,
16278                              DAG.getNode(Opcode, dl, MulVT, Odd0, Odd1));
16279
16280   // Shuffle it back into the right order.
16281   SDValue Highs, Lows;
16282   if (VT == MVT::v8i32) {
16283     const int HighMask[] = {1, 9, 3, 11, 5, 13, 7, 15};
16284     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
16285     const int LowMask[] = {0, 8, 2, 10, 4, 12, 6, 14};
16286     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
16287   } else {
16288     const int HighMask[] = {1, 5, 3, 7};
16289     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
16290     const int LowMask[] = {0, 4, 2, 6};
16291     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
16292   }
16293
16294   // If we have a signed multiply but no PMULDQ fix up the high parts of a
16295   // unsigned multiply.
16296   if (IsSigned && !Subtarget->hasSSE41()) {
16297     SDValue ShAmt =
16298         DAG.getConstant(31, dl,
16299                         DAG.getTargetLoweringInfo().getShiftAmountTy(VT));
16300     SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
16301                              DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
16302     SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
16303                              DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
16304
16305     SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
16306     Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
16307   }
16308
16309   // The first result of MUL_LOHI is actually the low value, followed by the
16310   // high value.
16311   SDValue Ops[] = {Lows, Highs};
16312   return DAG.getMergeValues(Ops, dl);
16313 }
16314
16315 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
16316                                          const X86Subtarget *Subtarget) {
16317   MVT VT = Op.getSimpleValueType();
16318   SDLoc dl(Op);
16319   SDValue R = Op.getOperand(0);
16320   SDValue Amt = Op.getOperand(1);
16321
16322   // Optimize shl/srl/sra with constant shift amount.
16323   if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
16324     if (auto *ShiftConst = BVAmt->getConstantSplatNode()) {
16325       uint64_t ShiftAmt = ShiftConst->getZExtValue();
16326
16327       if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
16328           (Subtarget->hasInt256() &&
16329            (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16)) ||
16330           (Subtarget->hasAVX512() &&
16331            (VT == MVT::v8i64 || VT == MVT::v16i32))) {
16332         if (Op.getOpcode() == ISD::SHL)
16333           return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
16334                                             DAG);
16335         if (Op.getOpcode() == ISD::SRL)
16336           return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
16337                                             DAG);
16338         if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
16339           return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
16340                                             DAG);
16341       }
16342
16343       if (VT == MVT::v16i8 || (Subtarget->hasInt256() && VT == MVT::v32i8)) {
16344         unsigned NumElts = VT.getVectorNumElements();
16345         MVT ShiftVT = MVT::getVectorVT(MVT::i16, NumElts / 2);
16346
16347         if (Op.getOpcode() == ISD::SHL) {
16348           // Make a large shift.
16349           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, ShiftVT,
16350                                                    R, ShiftAmt, DAG);
16351           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
16352           // Zero out the rightmost bits.
16353           SmallVector<SDValue, 32> V(
16354               NumElts, DAG.getConstant(uint8_t(-1U << ShiftAmt), dl, MVT::i8));
16355           return DAG.getNode(ISD::AND, dl, VT, SHL,
16356                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
16357         }
16358         if (Op.getOpcode() == ISD::SRL) {
16359           // Make a large shift.
16360           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ShiftVT,
16361                                                    R, ShiftAmt, DAG);
16362           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
16363           // Zero out the leftmost bits.
16364           SmallVector<SDValue, 32> V(
16365               NumElts, DAG.getConstant(uint8_t(-1U) >> ShiftAmt, dl, MVT::i8));
16366           return DAG.getNode(ISD::AND, dl, VT, SRL,
16367                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
16368         }
16369         if (Op.getOpcode() == ISD::SRA) {
16370           if (ShiftAmt == 7) {
16371             // R s>> 7  ===  R s< 0
16372             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
16373             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
16374           }
16375
16376           // R s>> a === ((R u>> a) ^ m) - m
16377           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
16378           SmallVector<SDValue, 32> V(NumElts,
16379                                      DAG.getConstant(128 >> ShiftAmt, dl,
16380                                                      MVT::i8));
16381           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
16382           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
16383           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
16384           return Res;
16385         }
16386         llvm_unreachable("Unknown shift opcode.");
16387       }
16388     }
16389   }
16390
16391   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
16392   if (!Subtarget->is64Bit() &&
16393       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
16394       Amt.getOpcode() == ISD::BITCAST &&
16395       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
16396     Amt = Amt.getOperand(0);
16397     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
16398                      VT.getVectorNumElements();
16399     unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
16400     uint64_t ShiftAmt = 0;
16401     for (unsigned i = 0; i != Ratio; ++i) {
16402       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
16403       if (!C)
16404         return SDValue();
16405       // 6 == Log2(64)
16406       ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
16407     }
16408     // Check remaining shift amounts.
16409     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
16410       uint64_t ShAmt = 0;
16411       for (unsigned j = 0; j != Ratio; ++j) {
16412         ConstantSDNode *C =
16413           dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
16414         if (!C)
16415           return SDValue();
16416         // 6 == Log2(64)
16417         ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
16418       }
16419       if (ShAmt != ShiftAmt)
16420         return SDValue();
16421     }
16422     switch (Op.getOpcode()) {
16423     default:
16424       llvm_unreachable("Unknown shift opcode!");
16425     case ISD::SHL:
16426       return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
16427                                         DAG);
16428     case ISD::SRL:
16429       return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
16430                                         DAG);
16431     case ISD::SRA:
16432       return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
16433                                         DAG);
16434     }
16435   }
16436
16437   return SDValue();
16438 }
16439
16440 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
16441                                         const X86Subtarget* Subtarget) {
16442   MVT VT = Op.getSimpleValueType();
16443   SDLoc dl(Op);
16444   SDValue R = Op.getOperand(0);
16445   SDValue Amt = Op.getOperand(1);
16446
16447   if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
16448       VT == MVT::v4i32 || VT == MVT::v8i16 ||
16449       (Subtarget->hasInt256() &&
16450        ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
16451         VT == MVT::v8i32 || VT == MVT::v16i16)) ||
16452        (Subtarget->hasAVX512() && (VT == MVT::v8i64 || VT == MVT::v16i32))) {
16453     SDValue BaseShAmt;
16454     EVT EltVT = VT.getVectorElementType();
16455
16456     if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Amt)) {
16457       // Check if this build_vector node is doing a splat.
16458       // If so, then set BaseShAmt equal to the splat value.
16459       BaseShAmt = BV->getSplatValue();
16460       if (BaseShAmt && BaseShAmt.getOpcode() == ISD::UNDEF)
16461         BaseShAmt = SDValue();
16462     } else {
16463       if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
16464         Amt = Amt.getOperand(0);
16465
16466       ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(Amt);
16467       if (SVN && SVN->isSplat()) {
16468         unsigned SplatIdx = (unsigned)SVN->getSplatIndex();
16469         SDValue InVec = Amt.getOperand(0);
16470         if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
16471           assert((SplatIdx < InVec.getValueType().getVectorNumElements()) &&
16472                  "Unexpected shuffle index found!");
16473           BaseShAmt = InVec.getOperand(SplatIdx);
16474         } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
16475            if (ConstantSDNode *C =
16476                dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
16477              if (C->getZExtValue() == SplatIdx)
16478                BaseShAmt = InVec.getOperand(1);
16479            }
16480         }
16481
16482         if (!BaseShAmt)
16483           // Avoid introducing an extract element from a shuffle.
16484           BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, InVec,
16485                                   DAG.getIntPtrConstant(SplatIdx, dl));
16486       }
16487     }
16488
16489     if (BaseShAmt.getNode()) {
16490       assert(EltVT.bitsLE(MVT::i64) && "Unexpected element type!");
16491       if (EltVT != MVT::i64 && EltVT.bitsGT(MVT::i32))
16492         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, BaseShAmt);
16493       else if (EltVT.bitsLT(MVT::i32))
16494         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
16495
16496       switch (Op.getOpcode()) {
16497       default:
16498         llvm_unreachable("Unknown shift opcode!");
16499       case ISD::SHL:
16500         switch (VT.SimpleTy) {
16501         default: return SDValue();
16502         case MVT::v2i64:
16503         case MVT::v4i32:
16504         case MVT::v8i16:
16505         case MVT::v4i64:
16506         case MVT::v8i32:
16507         case MVT::v16i16:
16508         case MVT::v16i32:
16509         case MVT::v8i64:
16510           return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
16511         }
16512       case ISD::SRA:
16513         switch (VT.SimpleTy) {
16514         default: return SDValue();
16515         case MVT::v4i32:
16516         case MVT::v8i16:
16517         case MVT::v8i32:
16518         case MVT::v16i16:
16519         case MVT::v16i32:
16520         case MVT::v8i64:
16521           return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
16522         }
16523       case ISD::SRL:
16524         switch (VT.SimpleTy) {
16525         default: return SDValue();
16526         case MVT::v2i64:
16527         case MVT::v4i32:
16528         case MVT::v8i16:
16529         case MVT::v4i64:
16530         case MVT::v8i32:
16531         case MVT::v16i16:
16532         case MVT::v16i32:
16533         case MVT::v8i64:
16534           return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
16535         }
16536       }
16537     }
16538   }
16539
16540   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
16541   if (!Subtarget->is64Bit() && VT == MVT::v2i64  &&
16542       Amt.getOpcode() == ISD::BITCAST &&
16543       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
16544     Amt = Amt.getOperand(0);
16545     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
16546                      VT.getVectorNumElements();
16547     std::vector<SDValue> Vals(Ratio);
16548     for (unsigned i = 0; i != Ratio; ++i)
16549       Vals[i] = Amt.getOperand(i);
16550     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
16551       for (unsigned j = 0; j != Ratio; ++j)
16552         if (Vals[j] != Amt.getOperand(i + j))
16553           return SDValue();
16554     }
16555     switch (Op.getOpcode()) {
16556     default:
16557       llvm_unreachable("Unknown shift opcode!");
16558     case ISD::SHL:
16559       return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
16560     case ISD::SRL:
16561       return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
16562     case ISD::SRA:
16563       return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
16564     }
16565   }
16566
16567   return SDValue();
16568 }
16569
16570 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
16571                           SelectionDAG &DAG) {
16572   MVT VT = Op.getSimpleValueType();
16573   SDLoc dl(Op);
16574   SDValue R = Op.getOperand(0);
16575   SDValue Amt = Op.getOperand(1);
16576
16577   assert(VT.isVector() && "Custom lowering only for vector shifts!");
16578   assert(Subtarget->hasSSE2() && "Only custom lower when we have SSE2!");
16579
16580   if (SDValue V = LowerScalarImmediateShift(Op, DAG, Subtarget))
16581     return V;
16582
16583   if (SDValue V = LowerScalarVariableShift(Op, DAG, Subtarget))
16584       return V;
16585
16586   if (Subtarget->hasAVX512() && (VT == MVT::v16i32 || VT == MVT::v8i64))
16587     return Op;
16588
16589   // AVX2 has VPSLLV/VPSRAV/VPSRLV.
16590   if (Subtarget->hasInt256()) {
16591     if (Op.getOpcode() == ISD::SRL &&
16592         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
16593          VT == MVT::v4i64 || VT == MVT::v8i32))
16594       return Op;
16595     if (Op.getOpcode() == ISD::SHL &&
16596         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
16597          VT == MVT::v4i64 || VT == MVT::v8i32))
16598       return Op;
16599     if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
16600       return Op;
16601   }
16602
16603   // 2i64 vector logical shifts can efficiently avoid scalarization - do the
16604   // shifts per-lane and then shuffle the partial results back together.
16605   if (VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) {
16606     // Splat the shift amounts so the scalar shifts above will catch it.
16607     SDValue Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {0, 0});
16608     SDValue Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {1, 1});
16609     SDValue R0 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt0);
16610     SDValue R1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt1);
16611     return DAG.getVectorShuffle(VT, dl, R0, R1, {0, 3});
16612   }
16613
16614   // If possible, lower this packed shift into a vector multiply instead of
16615   // expanding it into a sequence of scalar shifts.
16616   // Do this only if the vector shift count is a constant build_vector.
16617   if (Op.getOpcode() == ISD::SHL &&
16618       (VT == MVT::v8i16 || VT == MVT::v4i32 ||
16619        (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
16620       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
16621     SmallVector<SDValue, 8> Elts;
16622     EVT SVT = VT.getScalarType();
16623     unsigned SVTBits = SVT.getSizeInBits();
16624     const APInt &One = APInt(SVTBits, 1);
16625     unsigned NumElems = VT.getVectorNumElements();
16626
16627     for (unsigned i=0; i !=NumElems; ++i) {
16628       SDValue Op = Amt->getOperand(i);
16629       if (Op->getOpcode() == ISD::UNDEF) {
16630         Elts.push_back(Op);
16631         continue;
16632       }
16633
16634       ConstantSDNode *ND = cast<ConstantSDNode>(Op);
16635       const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
16636       uint64_t ShAmt = C.getZExtValue();
16637       if (ShAmt >= SVTBits) {
16638         Elts.push_back(DAG.getUNDEF(SVT));
16639         continue;
16640       }
16641       Elts.push_back(DAG.getConstant(One.shl(ShAmt), dl, SVT));
16642     }
16643     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
16644     return DAG.getNode(ISD::MUL, dl, VT, R, BV);
16645   }
16646
16647   // Lower SHL with variable shift amount.
16648   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
16649     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, dl, VT));
16650
16651     Op = DAG.getNode(ISD::ADD, dl, VT, Op,
16652                      DAG.getConstant(0x3f800000U, dl, VT));
16653     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
16654     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
16655     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
16656   }
16657
16658   // If possible, lower this shift as a sequence of two shifts by
16659   // constant plus a MOVSS/MOVSD instead of scalarizing it.
16660   // Example:
16661   //   (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
16662   //
16663   // Could be rewritten as:
16664   //   (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
16665   //
16666   // The advantage is that the two shifts from the example would be
16667   // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
16668   // the vector shift into four scalar shifts plus four pairs of vector
16669   // insert/extract.
16670   if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
16671       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
16672     unsigned TargetOpcode = X86ISD::MOVSS;
16673     bool CanBeSimplified;
16674     // The splat value for the first packed shift (the 'X' from the example).
16675     SDValue Amt1 = Amt->getOperand(0);
16676     // The splat value for the second packed shift (the 'Y' from the example).
16677     SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
16678                                         Amt->getOperand(2);
16679
16680     // See if it is possible to replace this node with a sequence of
16681     // two shifts followed by a MOVSS/MOVSD
16682     if (VT == MVT::v4i32) {
16683       // Check if it is legal to use a MOVSS.
16684       CanBeSimplified = Amt2 == Amt->getOperand(2) &&
16685                         Amt2 == Amt->getOperand(3);
16686       if (!CanBeSimplified) {
16687         // Otherwise, check if we can still simplify this node using a MOVSD.
16688         CanBeSimplified = Amt1 == Amt->getOperand(1) &&
16689                           Amt->getOperand(2) == Amt->getOperand(3);
16690         TargetOpcode = X86ISD::MOVSD;
16691         Amt2 = Amt->getOperand(2);
16692       }
16693     } else {
16694       // Do similar checks for the case where the machine value type
16695       // is MVT::v8i16.
16696       CanBeSimplified = Amt1 == Amt->getOperand(1);
16697       for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
16698         CanBeSimplified = Amt2 == Amt->getOperand(i);
16699
16700       if (!CanBeSimplified) {
16701         TargetOpcode = X86ISD::MOVSD;
16702         CanBeSimplified = true;
16703         Amt2 = Amt->getOperand(4);
16704         for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
16705           CanBeSimplified = Amt1 == Amt->getOperand(i);
16706         for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
16707           CanBeSimplified = Amt2 == Amt->getOperand(j);
16708       }
16709     }
16710
16711     if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
16712         isa<ConstantSDNode>(Amt2)) {
16713       // Replace this node with two shifts followed by a MOVSS/MOVSD.
16714       EVT CastVT = MVT::v4i32;
16715       SDValue Splat1 =
16716         DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), dl, VT);
16717       SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
16718       SDValue Splat2 =
16719         DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), dl, VT);
16720       SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
16721       if (TargetOpcode == X86ISD::MOVSD)
16722         CastVT = MVT::v2i64;
16723       SDValue BitCast1 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift1);
16724       SDValue BitCast2 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift2);
16725       SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
16726                                             BitCast1, DAG);
16727       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
16728     }
16729   }
16730
16731   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
16732     // Turn 'a' into a mask suitable for VSELECT: a = a << 5;
16733     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, dl, VT));
16734
16735     SDValue VSelM = DAG.getConstant(0x80, dl, VT);
16736     SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
16737     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
16738
16739     // r = VSELECT(r, shl(r, 4), a);
16740     SDValue M = DAG.getNode(ISD::SHL, dl, VT, R, DAG.getConstant(4, dl, VT));
16741     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
16742
16743     // a += a
16744     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
16745     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
16746     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
16747
16748     // r = VSELECT(r, shl(r, 2), a);
16749     M = DAG.getNode(ISD::SHL, dl, VT, R, DAG.getConstant(2, dl, VT));
16750     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
16751
16752     // a += a
16753     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
16754     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
16755     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
16756
16757     // return VSELECT(r, r+r, a);
16758     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
16759                     DAG.getNode(ISD::ADD, dl, VT, R, R), R);
16760     return R;
16761   }
16762
16763   // It's worth extending once and using the v8i32 shifts for 16-bit types, but
16764   // the extra overheads to get from v16i8 to v8i32 make the existing SSE
16765   // solution better.
16766   if (Subtarget->hasInt256() && VT == MVT::v8i16) {
16767     MVT NewVT = VT == MVT::v8i16 ? MVT::v8i32 : MVT::v16i16;
16768     unsigned ExtOpc =
16769         Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
16770     R = DAG.getNode(ExtOpc, dl, NewVT, R);
16771     Amt = DAG.getNode(ISD::ANY_EXTEND, dl, NewVT, Amt);
16772     return DAG.getNode(ISD::TRUNCATE, dl, VT,
16773                        DAG.getNode(Op.getOpcode(), dl, NewVT, R, Amt));
16774   }
16775
16776   // Decompose 256-bit shifts into smaller 128-bit shifts.
16777   if (VT.is256BitVector()) {
16778     unsigned NumElems = VT.getVectorNumElements();
16779     MVT EltVT = VT.getVectorElementType();
16780     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
16781
16782     // Extract the two vectors
16783     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
16784     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
16785
16786     // Recreate the shift amount vectors
16787     SDValue Amt1, Amt2;
16788     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
16789       // Constant shift amount
16790       SmallVector<SDValue, 8> Ops(Amt->op_begin(), Amt->op_begin() + NumElems);
16791       ArrayRef<SDValue> Amt1Csts = makeArrayRef(Ops).slice(0, NumElems / 2);
16792       ArrayRef<SDValue> Amt2Csts = makeArrayRef(Ops).slice(NumElems / 2);
16793
16794       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
16795       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
16796     } else {
16797       // Variable shift amount
16798       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
16799       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
16800     }
16801
16802     // Issue new vector shifts for the smaller types
16803     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
16804     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
16805
16806     // Concatenate the result back
16807     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
16808   }
16809
16810   return SDValue();
16811 }
16812
16813 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
16814   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
16815   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
16816   // looks for this combo and may remove the "setcc" instruction if the "setcc"
16817   // has only one use.
16818   SDNode *N = Op.getNode();
16819   SDValue LHS = N->getOperand(0);
16820   SDValue RHS = N->getOperand(1);
16821   unsigned BaseOp = 0;
16822   unsigned Cond = 0;
16823   SDLoc DL(Op);
16824   switch (Op.getOpcode()) {
16825   default: llvm_unreachable("Unknown ovf instruction!");
16826   case ISD::SADDO:
16827     // A subtract of one will be selected as a INC. Note that INC doesn't
16828     // set CF, so we can't do this for UADDO.
16829     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
16830       if (C->isOne()) {
16831         BaseOp = X86ISD::INC;
16832         Cond = X86::COND_O;
16833         break;
16834       }
16835     BaseOp = X86ISD::ADD;
16836     Cond = X86::COND_O;
16837     break;
16838   case ISD::UADDO:
16839     BaseOp = X86ISD::ADD;
16840     Cond = X86::COND_B;
16841     break;
16842   case ISD::SSUBO:
16843     // A subtract of one will be selected as a DEC. Note that DEC doesn't
16844     // set CF, so we can't do this for USUBO.
16845     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
16846       if (C->isOne()) {
16847         BaseOp = X86ISD::DEC;
16848         Cond = X86::COND_O;
16849         break;
16850       }
16851     BaseOp = X86ISD::SUB;
16852     Cond = X86::COND_O;
16853     break;
16854   case ISD::USUBO:
16855     BaseOp = X86ISD::SUB;
16856     Cond = X86::COND_B;
16857     break;
16858   case ISD::SMULO:
16859     BaseOp = N->getValueType(0) == MVT::i8 ? X86ISD::SMUL8 : X86ISD::SMUL;
16860     Cond = X86::COND_O;
16861     break;
16862   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
16863     if (N->getValueType(0) == MVT::i8) {
16864       BaseOp = X86ISD::UMUL8;
16865       Cond = X86::COND_O;
16866       break;
16867     }
16868     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
16869                                  MVT::i32);
16870     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
16871
16872     SDValue SetCC =
16873       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
16874                   DAG.getConstant(X86::COND_O, DL, MVT::i32),
16875                   SDValue(Sum.getNode(), 2));
16876
16877     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
16878   }
16879   }
16880
16881   // Also sets EFLAGS.
16882   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
16883   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
16884
16885   SDValue SetCC =
16886     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
16887                 DAG.getConstant(Cond, DL, MVT::i32),
16888                 SDValue(Sum.getNode(), 1));
16889
16890   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
16891 }
16892
16893 /// Returns true if the operand type is exactly twice the native width, and
16894 /// the corresponding cmpxchg8b or cmpxchg16b instruction is available.
16895 /// Used to know whether to use cmpxchg8/16b when expanding atomic operations
16896 /// (otherwise we leave them alone to become __sync_fetch_and_... calls).
16897 bool X86TargetLowering::needsCmpXchgNb(const Type *MemType) const {
16898   unsigned OpWidth = MemType->getPrimitiveSizeInBits();
16899
16900   if (OpWidth == 64)
16901     return !Subtarget->is64Bit(); // FIXME this should be Subtarget.hasCmpxchg8b
16902   else if (OpWidth == 128)
16903     return Subtarget->hasCmpxchg16b();
16904   else
16905     return false;
16906 }
16907
16908 bool X86TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
16909   return needsCmpXchgNb(SI->getValueOperand()->getType());
16910 }
16911
16912 // Note: this turns large loads into lock cmpxchg8b/16b.
16913 // FIXME: On 32 bits x86, fild/movq might be faster than lock cmpxchg8b.
16914 bool X86TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
16915   auto PTy = cast<PointerType>(LI->getPointerOperand()->getType());
16916   return needsCmpXchgNb(PTy->getElementType());
16917 }
16918
16919 TargetLoweringBase::AtomicRMWExpansionKind
16920 X86TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
16921   unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
16922   const Type *MemType = AI->getType();
16923
16924   // If the operand is too big, we must see if cmpxchg8/16b is available
16925   // and default to library calls otherwise.
16926   if (MemType->getPrimitiveSizeInBits() > NativeWidth) {
16927     return needsCmpXchgNb(MemType) ? AtomicRMWExpansionKind::CmpXChg
16928                                    : AtomicRMWExpansionKind::None;
16929   }
16930
16931   AtomicRMWInst::BinOp Op = AI->getOperation();
16932   switch (Op) {
16933   default:
16934     llvm_unreachable("Unknown atomic operation");
16935   case AtomicRMWInst::Xchg:
16936   case AtomicRMWInst::Add:
16937   case AtomicRMWInst::Sub:
16938     // It's better to use xadd, xsub or xchg for these in all cases.
16939     return AtomicRMWExpansionKind::None;
16940   case AtomicRMWInst::Or:
16941   case AtomicRMWInst::And:
16942   case AtomicRMWInst::Xor:
16943     // If the atomicrmw's result isn't actually used, we can just add a "lock"
16944     // prefix to a normal instruction for these operations.
16945     return !AI->use_empty() ? AtomicRMWExpansionKind::CmpXChg
16946                             : AtomicRMWExpansionKind::None;
16947   case AtomicRMWInst::Nand:
16948   case AtomicRMWInst::Max:
16949   case AtomicRMWInst::Min:
16950   case AtomicRMWInst::UMax:
16951   case AtomicRMWInst::UMin:
16952     // These always require a non-trivial set of data operations on x86. We must
16953     // use a cmpxchg loop.
16954     return AtomicRMWExpansionKind::CmpXChg;
16955   }
16956 }
16957
16958 static bool hasMFENCE(const X86Subtarget& Subtarget) {
16959   // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
16960   // no-sse2). There isn't any reason to disable it if the target processor
16961   // supports it.
16962   return Subtarget.hasSSE2() || Subtarget.is64Bit();
16963 }
16964
16965 LoadInst *
16966 X86TargetLowering::lowerIdempotentRMWIntoFencedLoad(AtomicRMWInst *AI) const {
16967   unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
16968   const Type *MemType = AI->getType();
16969   // Accesses larger than the native width are turned into cmpxchg/libcalls, so
16970   // there is no benefit in turning such RMWs into loads, and it is actually
16971   // harmful as it introduces a mfence.
16972   if (MemType->getPrimitiveSizeInBits() > NativeWidth)
16973     return nullptr;
16974
16975   auto Builder = IRBuilder<>(AI);
16976   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
16977   auto SynchScope = AI->getSynchScope();
16978   // We must restrict the ordering to avoid generating loads with Release or
16979   // ReleaseAcquire orderings.
16980   auto Order = AtomicCmpXchgInst::getStrongestFailureOrdering(AI->getOrdering());
16981   auto Ptr = AI->getPointerOperand();
16982
16983   // Before the load we need a fence. Here is an example lifted from
16984   // http://www.hpl.hp.com/techreports/2012/HPL-2012-68.pdf showing why a fence
16985   // is required:
16986   // Thread 0:
16987   //   x.store(1, relaxed);
16988   //   r1 = y.fetch_add(0, release);
16989   // Thread 1:
16990   //   y.fetch_add(42, acquire);
16991   //   r2 = x.load(relaxed);
16992   // r1 = r2 = 0 is impossible, but becomes possible if the idempotent rmw is
16993   // lowered to just a load without a fence. A mfence flushes the store buffer,
16994   // making the optimization clearly correct.
16995   // FIXME: it is required if isAtLeastRelease(Order) but it is not clear
16996   // otherwise, we might be able to be more agressive on relaxed idempotent
16997   // rmw. In practice, they do not look useful, so we don't try to be
16998   // especially clever.
16999   if (SynchScope == SingleThread) {
17000     // FIXME: we could just insert an X86ISD::MEMBARRIER here, except we are at
17001     // the IR level, so we must wrap it in an intrinsic.
17002     return nullptr;
17003   } else if (hasMFENCE(*Subtarget)) {
17004     Function *MFence = llvm::Intrinsic::getDeclaration(M,
17005             Intrinsic::x86_sse2_mfence);
17006     Builder.CreateCall(MFence);
17007   } else {
17008     // FIXME: it might make sense to use a locked operation here but on a
17009     // different cache-line to prevent cache-line bouncing. In practice it
17010     // is probably a small win, and x86 processors without mfence are rare
17011     // enough that we do not bother.
17012     return nullptr;
17013   }
17014
17015   // Finally we can emit the atomic load.
17016   LoadInst *Loaded = Builder.CreateAlignedLoad(Ptr,
17017           AI->getType()->getPrimitiveSizeInBits());
17018   Loaded->setAtomic(Order, SynchScope);
17019   AI->replaceAllUsesWith(Loaded);
17020   AI->eraseFromParent();
17021   return Loaded;
17022 }
17023
17024 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
17025                                  SelectionDAG &DAG) {
17026   SDLoc dl(Op);
17027   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
17028     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
17029   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
17030     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
17031
17032   // The only fence that needs an instruction is a sequentially-consistent
17033   // cross-thread fence.
17034   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
17035     if (hasMFENCE(*Subtarget))
17036       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
17037
17038     SDValue Chain = Op.getOperand(0);
17039     SDValue Zero = DAG.getConstant(0, dl, MVT::i32);
17040     SDValue Ops[] = {
17041       DAG.getRegister(X86::ESP, MVT::i32),     // Base
17042       DAG.getTargetConstant(1, dl, MVT::i8),   // Scale
17043       DAG.getRegister(0, MVT::i32),            // Index
17044       DAG.getTargetConstant(0, dl, MVT::i32),  // Disp
17045       DAG.getRegister(0, MVT::i32),            // Segment.
17046       Zero,
17047       Chain
17048     };
17049     SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
17050     return SDValue(Res, 0);
17051   }
17052
17053   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
17054   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
17055 }
17056
17057 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
17058                              SelectionDAG &DAG) {
17059   MVT T = Op.getSimpleValueType();
17060   SDLoc DL(Op);
17061   unsigned Reg = 0;
17062   unsigned size = 0;
17063   switch(T.SimpleTy) {
17064   default: llvm_unreachable("Invalid value type!");
17065   case MVT::i8:  Reg = X86::AL;  size = 1; break;
17066   case MVT::i16: Reg = X86::AX;  size = 2; break;
17067   case MVT::i32: Reg = X86::EAX; size = 4; break;
17068   case MVT::i64:
17069     assert(Subtarget->is64Bit() && "Node not type legal!");
17070     Reg = X86::RAX; size = 8;
17071     break;
17072   }
17073   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
17074                                   Op.getOperand(2), SDValue());
17075   SDValue Ops[] = { cpIn.getValue(0),
17076                     Op.getOperand(1),
17077                     Op.getOperand(3),
17078                     DAG.getTargetConstant(size, DL, MVT::i8),
17079                     cpIn.getValue(1) };
17080   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
17081   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
17082   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
17083                                            Ops, T, MMO);
17084
17085   SDValue cpOut =
17086     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
17087   SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
17088                                       MVT::i32, cpOut.getValue(2));
17089   SDValue Success = DAG.getNode(X86ISD::SETCC, DL, Op->getValueType(1),
17090                                 DAG.getConstant(X86::COND_E, DL, MVT::i8),
17091                                 EFLAGS);
17092
17093   DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), cpOut);
17094   DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
17095   DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), EFLAGS.getValue(1));
17096   return SDValue();
17097 }
17098
17099 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
17100                             SelectionDAG &DAG) {
17101   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
17102   MVT DstVT = Op.getSimpleValueType();
17103
17104   if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
17105     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
17106     if (DstVT != MVT::f64)
17107       // This conversion needs to be expanded.
17108       return SDValue();
17109
17110     SDValue InVec = Op->getOperand(0);
17111     SDLoc dl(Op);
17112     unsigned NumElts = SrcVT.getVectorNumElements();
17113     EVT SVT = SrcVT.getVectorElementType();
17114
17115     // Widen the vector in input in the case of MVT::v2i32.
17116     // Example: from MVT::v2i32 to MVT::v4i32.
17117     SmallVector<SDValue, 16> Elts;
17118     for (unsigned i = 0, e = NumElts; i != e; ++i)
17119       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
17120                                  DAG.getIntPtrConstant(i, dl)));
17121
17122     // Explicitly mark the extra elements as Undef.
17123     Elts.append(NumElts, DAG.getUNDEF(SVT));
17124
17125     EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
17126     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
17127     SDValue ToV2F64 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, BV);
17128     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
17129                        DAG.getIntPtrConstant(0, dl));
17130   }
17131
17132   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
17133          Subtarget->hasMMX() && "Unexpected custom BITCAST");
17134   assert((DstVT == MVT::i64 ||
17135           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
17136          "Unexpected custom BITCAST");
17137   // i64 <=> MMX conversions are Legal.
17138   if (SrcVT==MVT::i64 && DstVT.isVector())
17139     return Op;
17140   if (DstVT==MVT::i64 && SrcVT.isVector())
17141     return Op;
17142   // MMX <=> MMX conversions are Legal.
17143   if (SrcVT.isVector() && DstVT.isVector())
17144     return Op;
17145   // All other conversions need to be expanded.
17146   return SDValue();
17147 }
17148
17149 static SDValue LowerCTPOP(SDValue Op, const X86Subtarget *Subtarget,
17150                           SelectionDAG &DAG) {
17151   SDNode *Node = Op.getNode();
17152   SDLoc dl(Node);
17153
17154   Op = Op.getOperand(0);
17155   EVT VT = Op.getValueType();
17156   assert((VT.is128BitVector() || VT.is256BitVector()) &&
17157          "CTPOP lowering only implemented for 128/256-bit wide vector types");
17158
17159   unsigned NumElts = VT.getVectorNumElements();
17160   EVT EltVT = VT.getVectorElementType();
17161   unsigned Len = EltVT.getSizeInBits();
17162
17163   // This is the vectorized version of the "best" algorithm from
17164   // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
17165   // with a minor tweak to use a series of adds + shifts instead of vector
17166   // multiplications. Implemented for the v2i64, v4i64, v4i32, v8i32 types:
17167   //
17168   //  v2i64, v4i64, v4i32 => Only profitable w/ popcnt disabled
17169   //  v8i32 => Always profitable
17170   //
17171   // FIXME: There a couple of possible improvements:
17172   //
17173   // 1) Support for i8 and i16 vectors (needs measurements if popcnt enabled).
17174   // 2) Use strategies from http://wm.ite.pl/articles/sse-popcount.html
17175   //
17176   assert(EltVT.isInteger() && (Len == 32 || Len == 64) && Len % 8 == 0 &&
17177          "CTPOP not implemented for this vector element type.");
17178
17179   // X86 canonicalize ANDs to vXi64, generate the appropriate bitcasts to avoid
17180   // extra legalization.
17181   bool NeedsBitcast = EltVT == MVT::i32;
17182   MVT BitcastVT = VT.is256BitVector() ? MVT::v4i64 : MVT::v2i64;
17183
17184   SDValue Cst55 = DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x55)), dl,
17185                                   EltVT);
17186   SDValue Cst33 = DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x33)), dl,
17187                                   EltVT);
17188   SDValue Cst0F = DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x0F)), dl,
17189                                   EltVT);
17190
17191   // v = v - ((v >> 1) & 0x55555555...)
17192   SmallVector<SDValue, 8> Ones(NumElts, DAG.getConstant(1, dl, EltVT));
17193   SDValue OnesV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ones);
17194   SDValue Srl = DAG.getNode(ISD::SRL, dl, VT, Op, OnesV);
17195   if (NeedsBitcast)
17196     Srl = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Srl);
17197
17198   SmallVector<SDValue, 8> Mask55(NumElts, Cst55);
17199   SDValue M55 = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Mask55);
17200   if (NeedsBitcast)
17201     M55 = DAG.getNode(ISD::BITCAST, dl, BitcastVT, M55);
17202
17203   SDValue And = DAG.getNode(ISD::AND, dl, Srl.getValueType(), Srl, M55);
17204   if (VT != And.getValueType())
17205     And = DAG.getNode(ISD::BITCAST, dl, VT, And);
17206   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, Op, And);
17207
17208   // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...)
17209   SmallVector<SDValue, 8> Mask33(NumElts, Cst33);
17210   SDValue M33 = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Mask33);
17211   SmallVector<SDValue, 8> Twos(NumElts, DAG.getConstant(2, dl, EltVT));
17212   SDValue TwosV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Twos);
17213
17214   Srl = DAG.getNode(ISD::SRL, dl, VT, Sub, TwosV);
17215   if (NeedsBitcast) {
17216     Srl = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Srl);
17217     M33 = DAG.getNode(ISD::BITCAST, dl, BitcastVT, M33);
17218     Sub = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Sub);
17219   }
17220
17221   SDValue AndRHS = DAG.getNode(ISD::AND, dl, M33.getValueType(), Srl, M33);
17222   SDValue AndLHS = DAG.getNode(ISD::AND, dl, M33.getValueType(), Sub, M33);
17223   if (VT != AndRHS.getValueType()) {
17224     AndRHS = DAG.getNode(ISD::BITCAST, dl, VT, AndRHS);
17225     AndLHS = DAG.getNode(ISD::BITCAST, dl, VT, AndLHS);
17226   }
17227   SDValue Add = DAG.getNode(ISD::ADD, dl, VT, AndLHS, AndRHS);
17228
17229   // v = (v + (v >> 4)) & 0x0F0F0F0F...
17230   SmallVector<SDValue, 8> Fours(NumElts, DAG.getConstant(4, dl, EltVT));
17231   SDValue FoursV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Fours);
17232   Srl = DAG.getNode(ISD::SRL, dl, VT, Add, FoursV);
17233   Add = DAG.getNode(ISD::ADD, dl, VT, Add, Srl);
17234
17235   SmallVector<SDValue, 8> Mask0F(NumElts, Cst0F);
17236   SDValue M0F = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Mask0F);
17237   if (NeedsBitcast) {
17238     Add = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Add);
17239     M0F = DAG.getNode(ISD::BITCAST, dl, BitcastVT, M0F);
17240   }
17241   And = DAG.getNode(ISD::AND, dl, M0F.getValueType(), Add, M0F);
17242   if (VT != And.getValueType())
17243     And = DAG.getNode(ISD::BITCAST, dl, VT, And);
17244
17245   // The algorithm mentioned above uses:
17246   //    v = (v * 0x01010101...) >> (Len - 8)
17247   //
17248   // Change it to use vector adds + vector shifts which yield faster results on
17249   // Haswell than using vector integer multiplication.
17250   //
17251   // For i32 elements:
17252   //    v = v + (v >> 8)
17253   //    v = v + (v >> 16)
17254   //
17255   // For i64 elements:
17256   //    v = v + (v >> 8)
17257   //    v = v + (v >> 16)
17258   //    v = v + (v >> 32)
17259   //
17260   Add = And;
17261   SmallVector<SDValue, 8> Csts;
17262   for (unsigned i = 8; i <= Len/2; i *= 2) {
17263     Csts.assign(NumElts, DAG.getConstant(i, dl, EltVT));
17264     SDValue CstsV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Csts);
17265     Srl = DAG.getNode(ISD::SRL, dl, VT, Add, CstsV);
17266     Add = DAG.getNode(ISD::ADD, dl, VT, Add, Srl);
17267     Csts.clear();
17268   }
17269
17270   // The result is on the least significant 6-bits on i32 and 7-bits on i64.
17271   SDValue Cst3F = DAG.getConstant(APInt(Len, Len == 32 ? 0x3F : 0x7F), dl,
17272                                   EltVT);
17273   SmallVector<SDValue, 8> Cst3FV(NumElts, Cst3F);
17274   SDValue M3F = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Cst3FV);
17275   if (NeedsBitcast) {
17276     Add = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Add);
17277     M3F = DAG.getNode(ISD::BITCAST, dl, BitcastVT, M3F);
17278   }
17279   And = DAG.getNode(ISD::AND, dl, M3F.getValueType(), Add, M3F);
17280   if (VT != And.getValueType())
17281     And = DAG.getNode(ISD::BITCAST, dl, VT, And);
17282
17283   return And;
17284 }
17285
17286 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
17287   SDNode *Node = Op.getNode();
17288   SDLoc dl(Node);
17289   EVT T = Node->getValueType(0);
17290   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
17291                               DAG.getConstant(0, dl, T), Node->getOperand(2));
17292   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
17293                        cast<AtomicSDNode>(Node)->getMemoryVT(),
17294                        Node->getOperand(0),
17295                        Node->getOperand(1), negOp,
17296                        cast<AtomicSDNode>(Node)->getMemOperand(),
17297                        cast<AtomicSDNode>(Node)->getOrdering(),
17298                        cast<AtomicSDNode>(Node)->getSynchScope());
17299 }
17300
17301 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
17302   SDNode *Node = Op.getNode();
17303   SDLoc dl(Node);
17304   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
17305
17306   // Convert seq_cst store -> xchg
17307   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
17308   // FIXME: On 32-bit, store -> fist or movq would be more efficient
17309   //        (The only way to get a 16-byte store is cmpxchg16b)
17310   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
17311   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
17312       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
17313     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
17314                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
17315                                  Node->getOperand(0),
17316                                  Node->getOperand(1), Node->getOperand(2),
17317                                  cast<AtomicSDNode>(Node)->getMemOperand(),
17318                                  cast<AtomicSDNode>(Node)->getOrdering(),
17319                                  cast<AtomicSDNode>(Node)->getSynchScope());
17320     return Swap.getValue(1);
17321   }
17322   // Other atomic stores have a simple pattern.
17323   return Op;
17324 }
17325
17326 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
17327   EVT VT = Op.getNode()->getSimpleValueType(0);
17328
17329   // Let legalize expand this if it isn't a legal type yet.
17330   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
17331     return SDValue();
17332
17333   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
17334
17335   unsigned Opc;
17336   bool ExtraOp = false;
17337   switch (Op.getOpcode()) {
17338   default: llvm_unreachable("Invalid code");
17339   case ISD::ADDC: Opc = X86ISD::ADD; break;
17340   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
17341   case ISD::SUBC: Opc = X86ISD::SUB; break;
17342   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
17343   }
17344
17345   if (!ExtraOp)
17346     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
17347                        Op.getOperand(1));
17348   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
17349                      Op.getOperand(1), Op.getOperand(2));
17350 }
17351
17352 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
17353                             SelectionDAG &DAG) {
17354   assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
17355
17356   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
17357   // which returns the values as { float, float } (in XMM0) or
17358   // { double, double } (which is returned in XMM0, XMM1).
17359   SDLoc dl(Op);
17360   SDValue Arg = Op.getOperand(0);
17361   EVT ArgVT = Arg.getValueType();
17362   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
17363
17364   TargetLowering::ArgListTy Args;
17365   TargetLowering::ArgListEntry Entry;
17366
17367   Entry.Node = Arg;
17368   Entry.Ty = ArgTy;
17369   Entry.isSExt = false;
17370   Entry.isZExt = false;
17371   Args.push_back(Entry);
17372
17373   bool isF64 = ArgVT == MVT::f64;
17374   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
17375   // the small struct {f32, f32} is returned in (eax, edx). For f64,
17376   // the results are returned via SRet in memory.
17377   const char *LibcallName =  isF64 ? "__sincos_stret" : "__sincosf_stret";
17378   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17379   SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy());
17380
17381   Type *RetTy = isF64
17382     ? (Type*)StructType::get(ArgTy, ArgTy, nullptr)
17383     : (Type*)VectorType::get(ArgTy, 4);
17384
17385   TargetLowering::CallLoweringInfo CLI(DAG);
17386   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
17387     .setCallee(CallingConv::C, RetTy, Callee, std::move(Args), 0);
17388
17389   std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
17390
17391   if (isF64)
17392     // Returned in xmm0 and xmm1.
17393     return CallResult.first;
17394
17395   // Returned in bits 0:31 and 32:64 xmm0.
17396   SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
17397                                CallResult.first, DAG.getIntPtrConstant(0, dl));
17398   SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
17399                                CallResult.first, DAG.getIntPtrConstant(1, dl));
17400   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
17401   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
17402 }
17403
17404 static SDValue LowerMSCATTER(SDValue Op, const X86Subtarget *Subtarget,
17405                              SelectionDAG &DAG) {
17406   assert(Subtarget->hasAVX512() &&
17407          "MGATHER/MSCATTER are supported on AVX-512 arch only");
17408
17409   MaskedScatterSDNode *N = cast<MaskedScatterSDNode>(Op.getNode());
17410   EVT VT = N->getValue().getValueType();
17411   assert(VT.getScalarSizeInBits() >= 32 && "Unsupported scatter op");
17412   SDLoc dl(Op);
17413
17414   // X86 scatter kills mask register, so its type should be added to
17415   // the list of return values
17416   if (N->getNumValues() == 1) {
17417     SDValue Index = N->getIndex();
17418     if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
17419         !Index.getValueType().is512BitVector())
17420       Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
17421
17422     SDVTList VTs = DAG.getVTList(N->getMask().getValueType(), MVT::Other);
17423     SDValue Ops[] = { N->getOperand(0), N->getOperand(1),  N->getOperand(2),
17424                       N->getOperand(3), Index };
17425
17426     SDValue NewScatter = DAG.getMaskedScatter(VTs, VT, dl, Ops, N->getMemOperand());
17427     DAG.ReplaceAllUsesWith(Op, SDValue(NewScatter.getNode(), 1));
17428     return SDValue(NewScatter.getNode(), 0);
17429   }
17430   return Op;
17431 }
17432
17433 static SDValue LowerMGATHER(SDValue Op, const X86Subtarget *Subtarget,
17434                             SelectionDAG &DAG) {
17435   assert(Subtarget->hasAVX512() &&
17436          "MGATHER/MSCATTER are supported on AVX-512 arch only");
17437
17438   MaskedGatherSDNode *N = cast<MaskedGatherSDNode>(Op.getNode());
17439   EVT VT = Op.getValueType();
17440   assert(VT.getScalarSizeInBits() >= 32 && "Unsupported gather op");
17441   SDLoc dl(Op);
17442
17443   SDValue Index = N->getIndex();
17444   if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
17445       !Index.getValueType().is512BitVector()) {
17446     Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
17447     SDValue Ops[] = { N->getOperand(0), N->getOperand(1),  N->getOperand(2),
17448                       N->getOperand(3), Index };
17449     DAG.UpdateNodeOperands(N, Ops);
17450   }
17451   return Op;
17452 }
17453
17454 SDValue X86TargetLowering::LowerGC_TRANSITION_START(SDValue Op,
17455                                                     SelectionDAG &DAG) const {
17456   // TODO: Eventually, the lowering of these nodes should be informed by or
17457   // deferred to the GC strategy for the function in which they appear. For
17458   // now, however, they must be lowered to something. Since they are logically
17459   // no-ops in the case of a null GC strategy (or a GC strategy which does not
17460   // require special handling for these nodes), lower them as literal NOOPs for
17461   // the time being.
17462   SmallVector<SDValue, 2> Ops;
17463
17464   Ops.push_back(Op.getOperand(0));
17465   if (Op->getGluedNode())
17466     Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
17467
17468   SDLoc OpDL(Op);
17469   SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
17470   SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
17471
17472   return NOOP;
17473 }
17474
17475 SDValue X86TargetLowering::LowerGC_TRANSITION_END(SDValue Op,
17476                                                   SelectionDAG &DAG) const {
17477   // TODO: Eventually, the lowering of these nodes should be informed by or
17478   // deferred to the GC strategy for the function in which they appear. For
17479   // now, however, they must be lowered to something. Since they are logically
17480   // no-ops in the case of a null GC strategy (or a GC strategy which does not
17481   // require special handling for these nodes), lower them as literal NOOPs for
17482   // the time being.
17483   SmallVector<SDValue, 2> Ops;
17484
17485   Ops.push_back(Op.getOperand(0));
17486   if (Op->getGluedNode())
17487     Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
17488
17489   SDLoc OpDL(Op);
17490   SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
17491   SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
17492
17493   return NOOP;
17494 }
17495
17496 /// LowerOperation - Provide custom lowering hooks for some operations.
17497 ///
17498 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
17499   switch (Op.getOpcode()) {
17500   default: llvm_unreachable("Should not custom lower this!");
17501   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
17502   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
17503     return LowerCMP_SWAP(Op, Subtarget, DAG);
17504   case ISD::CTPOP:              return LowerCTPOP(Op, Subtarget, DAG);
17505   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
17506   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
17507   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
17508   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, Subtarget, DAG);
17509   case ISD::VECTOR_SHUFFLE:     return lowerVectorShuffle(Op, Subtarget, DAG);
17510   case ISD::VSELECT:            return LowerVSELECT(Op, DAG);
17511   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
17512   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
17513   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
17514   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
17515   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
17516   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
17517   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
17518   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
17519   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
17520   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
17521   case ISD::SHL_PARTS:
17522   case ISD::SRA_PARTS:
17523   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
17524   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
17525   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
17526   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
17527   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, Subtarget, DAG);
17528   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, Subtarget, DAG);
17529   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, Subtarget, DAG);
17530   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
17531   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
17532   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
17533   case ISD::LOAD:               return LowerExtendedLoad(Op, Subtarget, DAG);
17534   case ISD::FABS:
17535   case ISD::FNEG:               return LowerFABSorFNEG(Op, DAG);
17536   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
17537   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
17538   case ISD::SETCC:              return LowerSETCC(Op, DAG);
17539   case ISD::SELECT:             return LowerSELECT(Op, DAG);
17540   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
17541   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
17542   case ISD::VASTART:            return LowerVASTART(Op, DAG);
17543   case ISD::VAARG:              return LowerVAARG(Op, DAG);
17544   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
17545   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, Subtarget, DAG);
17546   case ISD::INTRINSIC_VOID:
17547   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
17548   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
17549   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
17550   case ISD::FRAME_TO_ARGS_OFFSET:
17551                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
17552   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
17553   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
17554   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
17555   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
17556   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
17557   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
17558   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
17559   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
17560   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
17561   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
17562   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
17563   case ISD::UMUL_LOHI:
17564   case ISD::SMUL_LOHI:          return LowerMUL_LOHI(Op, Subtarget, DAG);
17565   case ISD::SRA:
17566   case ISD::SRL:
17567   case ISD::SHL:                return LowerShift(Op, Subtarget, DAG);
17568   case ISD::SADDO:
17569   case ISD::UADDO:
17570   case ISD::SSUBO:
17571   case ISD::USUBO:
17572   case ISD::SMULO:
17573   case ISD::UMULO:              return LowerXALUO(Op, DAG);
17574   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
17575   case ISD::BITCAST:            return LowerBITCAST(Op, Subtarget, DAG);
17576   case ISD::ADDC:
17577   case ISD::ADDE:
17578   case ISD::SUBC:
17579   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
17580   case ISD::ADD:                return LowerADD(Op, DAG);
17581   case ISD::SUB:                return LowerSUB(Op, DAG);
17582   case ISD::FSINCOS:            return LowerFSINCOS(Op, Subtarget, DAG);
17583   case ISD::MGATHER:            return LowerMGATHER(Op, Subtarget, DAG);
17584   case ISD::MSCATTER:           return LowerMSCATTER(Op, Subtarget, DAG);
17585   case ISD::GC_TRANSITION_START:
17586                                 return LowerGC_TRANSITION_START(Op, DAG);
17587   case ISD::GC_TRANSITION_END:  return LowerGC_TRANSITION_END(Op, DAG);
17588   }
17589 }
17590
17591 /// ReplaceNodeResults - Replace a node with an illegal result type
17592 /// with a new node built out of custom code.
17593 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
17594                                            SmallVectorImpl<SDValue>&Results,
17595                                            SelectionDAG &DAG) const {
17596   SDLoc dl(N);
17597   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17598   switch (N->getOpcode()) {
17599   default:
17600     llvm_unreachable("Do not know how to custom type legalize this operation!");
17601   // We might have generated v2f32 FMIN/FMAX operations. Widen them to v4f32.
17602   case X86ISD::FMINC:
17603   case X86ISD::FMIN:
17604   case X86ISD::FMAXC:
17605   case X86ISD::FMAX: {
17606     EVT VT = N->getValueType(0);
17607     if (VT != MVT::v2f32)
17608       llvm_unreachable("Unexpected type (!= v2f32) on FMIN/FMAX.");
17609     SDValue UNDEF = DAG.getUNDEF(VT);
17610     SDValue LHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
17611                               N->getOperand(0), UNDEF);
17612     SDValue RHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
17613                               N->getOperand(1), UNDEF);
17614     Results.push_back(DAG.getNode(N->getOpcode(), dl, MVT::v4f32, LHS, RHS));
17615     return;
17616   }
17617   case ISD::SIGN_EXTEND_INREG:
17618   case ISD::ADDC:
17619   case ISD::ADDE:
17620   case ISD::SUBC:
17621   case ISD::SUBE:
17622     // We don't want to expand or promote these.
17623     return;
17624   case ISD::SDIV:
17625   case ISD::UDIV:
17626   case ISD::SREM:
17627   case ISD::UREM:
17628   case ISD::SDIVREM:
17629   case ISD::UDIVREM: {
17630     SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
17631     Results.push_back(V);
17632     return;
17633   }
17634   case ISD::FP_TO_SINT:
17635     // FP_TO_INT*_IN_MEM is not legal for f16 inputs.  Do not convert
17636     // (FP_TO_SINT (load f16)) to FP_TO_INT*.
17637     if (N->getOperand(0).getValueType() == MVT::f16)
17638       break;
17639     // fallthrough
17640   case ISD::FP_TO_UINT: {
17641     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
17642
17643     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
17644       return;
17645
17646     std::pair<SDValue,SDValue> Vals =
17647         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
17648     SDValue FIST = Vals.first, StackSlot = Vals.second;
17649     if (FIST.getNode()) {
17650       EVT VT = N->getValueType(0);
17651       // Return a load from the stack slot.
17652       if (StackSlot.getNode())
17653         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
17654                                       MachinePointerInfo(),
17655                                       false, false, false, 0));
17656       else
17657         Results.push_back(FIST);
17658     }
17659     return;
17660   }
17661   case ISD::UINT_TO_FP: {
17662     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
17663     if (N->getOperand(0).getValueType() != MVT::v2i32 ||
17664         N->getValueType(0) != MVT::v2f32)
17665       return;
17666     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
17667                                  N->getOperand(0));
17668     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
17669                                      MVT::f64);
17670     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
17671     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
17672                              DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
17673     Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
17674     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
17675     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
17676     return;
17677   }
17678   case ISD::FP_ROUND: {
17679     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
17680         return;
17681     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
17682     Results.push_back(V);
17683     return;
17684   }
17685   case ISD::FP_EXTEND: {
17686     // Right now, only MVT::v2f32 has OperationAction for FP_EXTEND.
17687     // No other ValueType for FP_EXTEND should reach this point.
17688     assert(N->getValueType(0) == MVT::v2f32 &&
17689            "Do not know how to legalize this Node");
17690     return;
17691   }
17692   case ISD::INTRINSIC_W_CHAIN: {
17693     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
17694     switch (IntNo) {
17695     default : llvm_unreachable("Do not know how to custom type "
17696                                "legalize this intrinsic operation!");
17697     case Intrinsic::x86_rdtsc:
17698       return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
17699                                      Results);
17700     case Intrinsic::x86_rdtscp:
17701       return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
17702                                      Results);
17703     case Intrinsic::x86_rdpmc:
17704       return getReadPerformanceCounter(N, dl, DAG, Subtarget, Results);
17705     }
17706   }
17707   case ISD::READCYCLECOUNTER: {
17708     return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
17709                                    Results);
17710   }
17711   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
17712     EVT T = N->getValueType(0);
17713     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
17714     bool Regs64bit = T == MVT::i128;
17715     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
17716     SDValue cpInL, cpInH;
17717     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
17718                         DAG.getConstant(0, dl, HalfT));
17719     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
17720                         DAG.getConstant(1, dl, HalfT));
17721     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
17722                              Regs64bit ? X86::RAX : X86::EAX,
17723                              cpInL, SDValue());
17724     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
17725                              Regs64bit ? X86::RDX : X86::EDX,
17726                              cpInH, cpInL.getValue(1));
17727     SDValue swapInL, swapInH;
17728     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
17729                           DAG.getConstant(0, dl, HalfT));
17730     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
17731                           DAG.getConstant(1, dl, HalfT));
17732     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
17733                                Regs64bit ? X86::RBX : X86::EBX,
17734                                swapInL, cpInH.getValue(1));
17735     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
17736                                Regs64bit ? X86::RCX : X86::ECX,
17737                                swapInH, swapInL.getValue(1));
17738     SDValue Ops[] = { swapInH.getValue(0),
17739                       N->getOperand(1),
17740                       swapInH.getValue(1) };
17741     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
17742     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
17743     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
17744                                   X86ISD::LCMPXCHG8_DAG;
17745     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
17746     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
17747                                         Regs64bit ? X86::RAX : X86::EAX,
17748                                         HalfT, Result.getValue(1));
17749     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
17750                                         Regs64bit ? X86::RDX : X86::EDX,
17751                                         HalfT, cpOutL.getValue(2));
17752     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
17753
17754     SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
17755                                         MVT::i32, cpOutH.getValue(2));
17756     SDValue Success =
17757         DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
17758                     DAG.getConstant(X86::COND_E, dl, MVT::i8), EFLAGS);
17759     Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
17760
17761     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
17762     Results.push_back(Success);
17763     Results.push_back(EFLAGS.getValue(1));
17764     return;
17765   }
17766   case ISD::ATOMIC_SWAP:
17767   case ISD::ATOMIC_LOAD_ADD:
17768   case ISD::ATOMIC_LOAD_SUB:
17769   case ISD::ATOMIC_LOAD_AND:
17770   case ISD::ATOMIC_LOAD_OR:
17771   case ISD::ATOMIC_LOAD_XOR:
17772   case ISD::ATOMIC_LOAD_NAND:
17773   case ISD::ATOMIC_LOAD_MIN:
17774   case ISD::ATOMIC_LOAD_MAX:
17775   case ISD::ATOMIC_LOAD_UMIN:
17776   case ISD::ATOMIC_LOAD_UMAX:
17777   case ISD::ATOMIC_LOAD: {
17778     // Delegate to generic TypeLegalization. Situations we can really handle
17779     // should have already been dealt with by AtomicExpandPass.cpp.
17780     break;
17781   }
17782   case ISD::BITCAST: {
17783     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
17784     EVT DstVT = N->getValueType(0);
17785     EVT SrcVT = N->getOperand(0)->getValueType(0);
17786
17787     if (SrcVT != MVT::f64 ||
17788         (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
17789       return;
17790
17791     unsigned NumElts = DstVT.getVectorNumElements();
17792     EVT SVT = DstVT.getVectorElementType();
17793     EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
17794     SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
17795                                    MVT::v2f64, N->getOperand(0));
17796     SDValue ToVecInt = DAG.getNode(ISD::BITCAST, dl, WiderVT, Expanded);
17797
17798     if (ExperimentalVectorWideningLegalization) {
17799       // If we are legalizing vectors by widening, we already have the desired
17800       // legal vector type, just return it.
17801       Results.push_back(ToVecInt);
17802       return;
17803     }
17804
17805     SmallVector<SDValue, 8> Elts;
17806     for (unsigned i = 0, e = NumElts; i != e; ++i)
17807       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
17808                                    ToVecInt, DAG.getIntPtrConstant(i, dl)));
17809
17810     Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
17811   }
17812   }
17813 }
17814
17815 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
17816   switch ((X86ISD::NodeType)Opcode) {
17817   case X86ISD::FIRST_NUMBER:       break;
17818   case X86ISD::BSF:                return "X86ISD::BSF";
17819   case X86ISD::BSR:                return "X86ISD::BSR";
17820   case X86ISD::SHLD:               return "X86ISD::SHLD";
17821   case X86ISD::SHRD:               return "X86ISD::SHRD";
17822   case X86ISD::FAND:               return "X86ISD::FAND";
17823   case X86ISD::FANDN:              return "X86ISD::FANDN";
17824   case X86ISD::FOR:                return "X86ISD::FOR";
17825   case X86ISD::FXOR:               return "X86ISD::FXOR";
17826   case X86ISD::FSRL:               return "X86ISD::FSRL";
17827   case X86ISD::FILD:               return "X86ISD::FILD";
17828   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
17829   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
17830   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
17831   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
17832   case X86ISD::FLD:                return "X86ISD::FLD";
17833   case X86ISD::FST:                return "X86ISD::FST";
17834   case X86ISD::CALL:               return "X86ISD::CALL";
17835   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
17836   case X86ISD::RDTSCP_DAG:         return "X86ISD::RDTSCP_DAG";
17837   case X86ISD::RDPMC_DAG:          return "X86ISD::RDPMC_DAG";
17838   case X86ISD::BT:                 return "X86ISD::BT";
17839   case X86ISD::CMP:                return "X86ISD::CMP";
17840   case X86ISD::COMI:               return "X86ISD::COMI";
17841   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
17842   case X86ISD::CMPM:               return "X86ISD::CMPM";
17843   case X86ISD::CMPMU:              return "X86ISD::CMPMU";
17844   case X86ISD::CMPM_RND:           return "X86ISD::CMPM_RND";
17845   case X86ISD::SETCC:              return "X86ISD::SETCC";
17846   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
17847   case X86ISD::FSETCC:             return "X86ISD::FSETCC";
17848   case X86ISD::FGETSIGNx86:        return "X86ISD::FGETSIGNx86";
17849   case X86ISD::CMOV:               return "X86ISD::CMOV";
17850   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
17851   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
17852   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
17853   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
17854   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
17855   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
17856   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
17857   case X86ISD::MOVDQ2Q:            return "X86ISD::MOVDQ2Q";
17858   case X86ISD::MMX_MOVD2W:         return "X86ISD::MMX_MOVD2W";
17859   case X86ISD::MMX_MOVW2D:         return "X86ISD::MMX_MOVW2D";
17860   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
17861   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
17862   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
17863   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
17864   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
17865   case X86ISD::MMX_PINSRW:         return "X86ISD::MMX_PINSRW";
17866   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
17867   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
17868   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
17869   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
17870   case X86ISD::SHRUNKBLEND:        return "X86ISD::SHRUNKBLEND";
17871   case X86ISD::ADDUS:              return "X86ISD::ADDUS";
17872   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
17873   case X86ISD::HADD:               return "X86ISD::HADD";
17874   case X86ISD::HSUB:               return "X86ISD::HSUB";
17875   case X86ISD::FHADD:              return "X86ISD::FHADD";
17876   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
17877   case X86ISD::UMAX:               return "X86ISD::UMAX";
17878   case X86ISD::UMIN:               return "X86ISD::UMIN";
17879   case X86ISD::SMAX:               return "X86ISD::SMAX";
17880   case X86ISD::SMIN:               return "X86ISD::SMIN";
17881   case X86ISD::FMAX:               return "X86ISD::FMAX";
17882   case X86ISD::FMAX_RND:           return "X86ISD::FMAX_RND";
17883   case X86ISD::FMIN:               return "X86ISD::FMIN";
17884   case X86ISD::FMIN_RND:           return "X86ISD::FMIN_RND";
17885   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
17886   case X86ISD::FMINC:              return "X86ISD::FMINC";
17887   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
17888   case X86ISD::FRCP:               return "X86ISD::FRCP";
17889   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
17890   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
17891   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
17892   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
17893   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
17894   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
17895   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
17896   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
17897   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
17898   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
17899   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
17900   case X86ISD::LCMPXCHG16_DAG:     return "X86ISD::LCMPXCHG16_DAG";
17901   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
17902   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
17903   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
17904   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
17905   case X86ISD::VTRUNC:             return "X86ISD::VTRUNC";
17906   case X86ISD::VTRUNCM:            return "X86ISD::VTRUNCM";
17907   case X86ISD::VINSERT:            return "X86ISD::VINSERT";
17908   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
17909   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
17910   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
17911   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
17912   case X86ISD::VSHL:               return "X86ISD::VSHL";
17913   case X86ISD::VSRL:               return "X86ISD::VSRL";
17914   case X86ISD::VSRA:               return "X86ISD::VSRA";
17915   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
17916   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
17917   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
17918   case X86ISD::CMPP:               return "X86ISD::CMPP";
17919   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
17920   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
17921   case X86ISD::PCMPEQM:            return "X86ISD::PCMPEQM";
17922   case X86ISD::PCMPGTM:            return "X86ISD::PCMPGTM";
17923   case X86ISD::ADD:                return "X86ISD::ADD";
17924   case X86ISD::SUB:                return "X86ISD::SUB";
17925   case X86ISD::ADC:                return "X86ISD::ADC";
17926   case X86ISD::SBB:                return "X86ISD::SBB";
17927   case X86ISD::SMUL:               return "X86ISD::SMUL";
17928   case X86ISD::UMUL:               return "X86ISD::UMUL";
17929   case X86ISD::SMUL8:              return "X86ISD::SMUL8";
17930   case X86ISD::UMUL8:              return "X86ISD::UMUL8";
17931   case X86ISD::SDIVREM8_SEXT_HREG: return "X86ISD::SDIVREM8_SEXT_HREG";
17932   case X86ISD::UDIVREM8_ZEXT_HREG: return "X86ISD::UDIVREM8_ZEXT_HREG";
17933   case X86ISD::INC:                return "X86ISD::INC";
17934   case X86ISD::DEC:                return "X86ISD::DEC";
17935   case X86ISD::OR:                 return "X86ISD::OR";
17936   case X86ISD::XOR:                return "X86ISD::XOR";
17937   case X86ISD::AND:                return "X86ISD::AND";
17938   case X86ISD::BEXTR:              return "X86ISD::BEXTR";
17939   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
17940   case X86ISD::PTEST:              return "X86ISD::PTEST";
17941   case X86ISD::TESTP:              return "X86ISD::TESTP";
17942   case X86ISD::TESTM:              return "X86ISD::TESTM";
17943   case X86ISD::TESTNM:             return "X86ISD::TESTNM";
17944   case X86ISD::KORTEST:            return "X86ISD::KORTEST";
17945   case X86ISD::PACKSS:             return "X86ISD::PACKSS";
17946   case X86ISD::PACKUS:             return "X86ISD::PACKUS";
17947   case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
17948   case X86ISD::VALIGN:             return "X86ISD::VALIGN";
17949   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
17950   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
17951   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
17952   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
17953   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
17954   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
17955   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
17956   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
17957   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
17958   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
17959   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
17960   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
17961   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
17962   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
17963   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
17964   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
17965   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
17966   case X86ISD::VEXTRACT:           return "X86ISD::VEXTRACT";
17967   case X86ISD::VPERMILPV:          return "X86ISD::VPERMILPV";
17968   case X86ISD::VPERMILPI:          return "X86ISD::VPERMILPI";
17969   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
17970   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
17971   case X86ISD::VPERMV3:            return "X86ISD::VPERMV3";
17972   case X86ISD::VPERMIV3:           return "X86ISD::VPERMIV3";
17973   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
17974   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
17975   case X86ISD::PMULDQ:             return "X86ISD::PMULDQ";
17976   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
17977   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
17978   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
17979   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
17980   case X86ISD::MFENCE:             return "X86ISD::MFENCE";
17981   case X86ISD::SFENCE:             return "X86ISD::SFENCE";
17982   case X86ISD::LFENCE:             return "X86ISD::LFENCE";
17983   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
17984   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
17985   case X86ISD::SAHF:               return "X86ISD::SAHF";
17986   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
17987   case X86ISD::RDSEED:             return "X86ISD::RDSEED";
17988   case X86ISD::FMADD:              return "X86ISD::FMADD";
17989   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
17990   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
17991   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
17992   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
17993   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
17994   case X86ISD::FMADD_RND:          return "X86ISD::FMADD_RND";
17995   case X86ISD::FNMADD_RND:         return "X86ISD::FNMADD_RND";
17996   case X86ISD::FMSUB_RND:          return "X86ISD::FMSUB_RND";
17997   case X86ISD::FNMSUB_RND:         return "X86ISD::FNMSUB_RND";
17998   case X86ISD::FMADDSUB_RND:       return "X86ISD::FMADDSUB_RND";
17999   case X86ISD::FMSUBADD_RND:       return "X86ISD::FMSUBADD_RND";
18000   case X86ISD::RNDSCALE:           return "X86ISD::RNDSCALE";
18001   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
18002   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
18003   case X86ISD::XTEST:              return "X86ISD::XTEST";
18004   case X86ISD::COMPRESS:           return "X86ISD::COMPRESS";
18005   case X86ISD::EXPAND:             return "X86ISD::EXPAND";
18006   case X86ISD::SELECT:             return "X86ISD::SELECT";
18007   case X86ISD::ADDSUB:             return "X86ISD::ADDSUB";
18008   case X86ISD::RCP28:              return "X86ISD::RCP28";
18009   case X86ISD::EXP2:               return "X86ISD::EXP2";
18010   case X86ISD::RSQRT28:            return "X86ISD::RSQRT28";
18011   case X86ISD::FADD_RND:           return "X86ISD::FADD_RND";
18012   case X86ISD::FSUB_RND:           return "X86ISD::FSUB_RND";
18013   case X86ISD::FMUL_RND:           return "X86ISD::FMUL_RND";
18014   case X86ISD::FDIV_RND:           return "X86ISD::FDIV_RND";
18015   case X86ISD::ADDS:               return "X86ISD::ADDS";
18016   case X86ISD::SUBS:               return "X86ISD::SUBS";
18017   }
18018   return nullptr;
18019 }
18020
18021 // isLegalAddressingMode - Return true if the addressing mode represented
18022 // by AM is legal for this target, for a load/store of the specified type.
18023 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
18024                                               Type *Ty) const {
18025   // X86 supports extremely general addressing modes.
18026   CodeModel::Model M = getTargetMachine().getCodeModel();
18027   Reloc::Model R = getTargetMachine().getRelocationModel();
18028
18029   // X86 allows a sign-extended 32-bit immediate field as a displacement.
18030   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
18031     return false;
18032
18033   if (AM.BaseGV) {
18034     unsigned GVFlags =
18035       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
18036
18037     // If a reference to this global requires an extra load, we can't fold it.
18038     if (isGlobalStubReference(GVFlags))
18039       return false;
18040
18041     // If BaseGV requires a register for the PIC base, we cannot also have a
18042     // BaseReg specified.
18043     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
18044       return false;
18045
18046     // If lower 4G is not available, then we must use rip-relative addressing.
18047     if ((M != CodeModel::Small || R != Reloc::Static) &&
18048         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
18049       return false;
18050   }
18051
18052   switch (AM.Scale) {
18053   case 0:
18054   case 1:
18055   case 2:
18056   case 4:
18057   case 8:
18058     // These scales always work.
18059     break;
18060   case 3:
18061   case 5:
18062   case 9:
18063     // These scales are formed with basereg+scalereg.  Only accept if there is
18064     // no basereg yet.
18065     if (AM.HasBaseReg)
18066       return false;
18067     break;
18068   default:  // Other stuff never works.
18069     return false;
18070   }
18071
18072   return true;
18073 }
18074
18075 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
18076   unsigned Bits = Ty->getScalarSizeInBits();
18077
18078   // 8-bit shifts are always expensive, but versions with a scalar amount aren't
18079   // particularly cheaper than those without.
18080   if (Bits == 8)
18081     return false;
18082
18083   // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
18084   // variable shifts just as cheap as scalar ones.
18085   if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
18086     return false;
18087
18088   // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
18089   // fully general vector.
18090   return true;
18091 }
18092
18093 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
18094   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
18095     return false;
18096   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
18097   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
18098   return NumBits1 > NumBits2;
18099 }
18100
18101 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
18102   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
18103     return false;
18104
18105   if (!isTypeLegal(EVT::getEVT(Ty1)))
18106     return false;
18107
18108   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
18109
18110   // Assuming the caller doesn't have a zeroext or signext return parameter,
18111   // truncation all the way down to i1 is valid.
18112   return true;
18113 }
18114
18115 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
18116   return isInt<32>(Imm);
18117 }
18118
18119 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
18120   // Can also use sub to handle negated immediates.
18121   return isInt<32>(Imm);
18122 }
18123
18124 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
18125   if (!VT1.isInteger() || !VT2.isInteger())
18126     return false;
18127   unsigned NumBits1 = VT1.getSizeInBits();
18128   unsigned NumBits2 = VT2.getSizeInBits();
18129   return NumBits1 > NumBits2;
18130 }
18131
18132 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
18133   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
18134   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
18135 }
18136
18137 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
18138   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
18139   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
18140 }
18141
18142 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
18143   EVT VT1 = Val.getValueType();
18144   if (isZExtFree(VT1, VT2))
18145     return true;
18146
18147   if (Val.getOpcode() != ISD::LOAD)
18148     return false;
18149
18150   if (!VT1.isSimple() || !VT1.isInteger() ||
18151       !VT2.isSimple() || !VT2.isInteger())
18152     return false;
18153
18154   switch (VT1.getSimpleVT().SimpleTy) {
18155   default: break;
18156   case MVT::i8:
18157   case MVT::i16:
18158   case MVT::i32:
18159     // X86 has 8, 16, and 32-bit zero-extending loads.
18160     return true;
18161   }
18162
18163   return false;
18164 }
18165
18166 bool X86TargetLowering::isVectorLoadExtDesirable(SDValue) const { return true; }
18167
18168 bool
18169 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
18170   if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
18171     return false;
18172
18173   VT = VT.getScalarType();
18174
18175   if (!VT.isSimple())
18176     return false;
18177
18178   switch (VT.getSimpleVT().SimpleTy) {
18179   case MVT::f32:
18180   case MVT::f64:
18181     return true;
18182   default:
18183     break;
18184   }
18185
18186   return false;
18187 }
18188
18189 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
18190   // i16 instructions are longer (0x66 prefix) and potentially slower.
18191   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
18192 }
18193
18194 /// isShuffleMaskLegal - Targets can use this to indicate that they only
18195 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
18196 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
18197 /// are assumed to be legal.
18198 bool
18199 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
18200                                       EVT VT) const {
18201   if (!VT.isSimple())
18202     return false;
18203
18204   // Not for i1 vectors
18205   if (VT.getScalarType() == MVT::i1)
18206     return false;
18207
18208   // Very little shuffling can be done for 64-bit vectors right now.
18209   if (VT.getSizeInBits() == 64)
18210     return false;
18211
18212   // We only care that the types being shuffled are legal. The lowering can
18213   // handle any possible shuffle mask that results.
18214   return isTypeLegal(VT.getSimpleVT());
18215 }
18216
18217 bool
18218 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
18219                                           EVT VT) const {
18220   // Just delegate to the generic legality, clear masks aren't special.
18221   return isShuffleMaskLegal(Mask, VT);
18222 }
18223
18224 //===----------------------------------------------------------------------===//
18225 //                           X86 Scheduler Hooks
18226 //===----------------------------------------------------------------------===//
18227
18228 /// Utility function to emit xbegin specifying the start of an RTM region.
18229 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
18230                                      const TargetInstrInfo *TII) {
18231   DebugLoc DL = MI->getDebugLoc();
18232
18233   const BasicBlock *BB = MBB->getBasicBlock();
18234   MachineFunction::iterator I = MBB;
18235   ++I;
18236
18237   // For the v = xbegin(), we generate
18238   //
18239   // thisMBB:
18240   //  xbegin sinkMBB
18241   //
18242   // mainMBB:
18243   //  eax = -1
18244   //
18245   // sinkMBB:
18246   //  v = eax
18247
18248   MachineBasicBlock *thisMBB = MBB;
18249   MachineFunction *MF = MBB->getParent();
18250   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
18251   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
18252   MF->insert(I, mainMBB);
18253   MF->insert(I, sinkMBB);
18254
18255   // Transfer the remainder of BB and its successor edges to sinkMBB.
18256   sinkMBB->splice(sinkMBB->begin(), MBB,
18257                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
18258   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
18259
18260   // thisMBB:
18261   //  xbegin sinkMBB
18262   //  # fallthrough to mainMBB
18263   //  # abortion to sinkMBB
18264   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
18265   thisMBB->addSuccessor(mainMBB);
18266   thisMBB->addSuccessor(sinkMBB);
18267
18268   // mainMBB:
18269   //  EAX = -1
18270   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
18271   mainMBB->addSuccessor(sinkMBB);
18272
18273   // sinkMBB:
18274   // EAX is live into the sinkMBB
18275   sinkMBB->addLiveIn(X86::EAX);
18276   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
18277           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
18278     .addReg(X86::EAX);
18279
18280   MI->eraseFromParent();
18281   return sinkMBB;
18282 }
18283
18284 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
18285 // or XMM0_V32I8 in AVX all of this code can be replaced with that
18286 // in the .td file.
18287 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
18288                                        const TargetInstrInfo *TII) {
18289   unsigned Opc;
18290   switch (MI->getOpcode()) {
18291   default: llvm_unreachable("illegal opcode!");
18292   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
18293   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
18294   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
18295   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
18296   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
18297   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
18298   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
18299   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
18300   }
18301
18302   DebugLoc dl = MI->getDebugLoc();
18303   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
18304
18305   unsigned NumArgs = MI->getNumOperands();
18306   for (unsigned i = 1; i < NumArgs; ++i) {
18307     MachineOperand &Op = MI->getOperand(i);
18308     if (!(Op.isReg() && Op.isImplicit()))
18309       MIB.addOperand(Op);
18310   }
18311   if (MI->hasOneMemOperand())
18312     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
18313
18314   BuildMI(*BB, MI, dl,
18315     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
18316     .addReg(X86::XMM0);
18317
18318   MI->eraseFromParent();
18319   return BB;
18320 }
18321
18322 // FIXME: Custom handling because TableGen doesn't support multiple implicit
18323 // defs in an instruction pattern
18324 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
18325                                        const TargetInstrInfo *TII) {
18326   unsigned Opc;
18327   switch (MI->getOpcode()) {
18328   default: llvm_unreachable("illegal opcode!");
18329   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
18330   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
18331   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
18332   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
18333   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
18334   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
18335   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
18336   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
18337   }
18338
18339   DebugLoc dl = MI->getDebugLoc();
18340   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
18341
18342   unsigned NumArgs = MI->getNumOperands(); // remove the results
18343   for (unsigned i = 1; i < NumArgs; ++i) {
18344     MachineOperand &Op = MI->getOperand(i);
18345     if (!(Op.isReg() && Op.isImplicit()))
18346       MIB.addOperand(Op);
18347   }
18348   if (MI->hasOneMemOperand())
18349     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
18350
18351   BuildMI(*BB, MI, dl,
18352     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
18353     .addReg(X86::ECX);
18354
18355   MI->eraseFromParent();
18356   return BB;
18357 }
18358
18359 static MachineBasicBlock *EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
18360                                       const X86Subtarget *Subtarget) {
18361   DebugLoc dl = MI->getDebugLoc();
18362   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18363   // Address into RAX/EAX, other two args into ECX, EDX.
18364   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
18365   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
18366   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
18367   for (int i = 0; i < X86::AddrNumOperands; ++i)
18368     MIB.addOperand(MI->getOperand(i));
18369
18370   unsigned ValOps = X86::AddrNumOperands;
18371   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
18372     .addReg(MI->getOperand(ValOps).getReg());
18373   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
18374     .addReg(MI->getOperand(ValOps+1).getReg());
18375
18376   // The instruction doesn't actually take any operands though.
18377   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
18378
18379   MI->eraseFromParent(); // The pseudo is gone now.
18380   return BB;
18381 }
18382
18383 MachineBasicBlock *
18384 X86TargetLowering::EmitVAARG64WithCustomInserter(MachineInstr *MI,
18385                                                  MachineBasicBlock *MBB) const {
18386   // Emit va_arg instruction on X86-64.
18387
18388   // Operands to this pseudo-instruction:
18389   // 0  ) Output        : destination address (reg)
18390   // 1-5) Input         : va_list address (addr, i64mem)
18391   // 6  ) ArgSize       : Size (in bytes) of vararg type
18392   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
18393   // 8  ) Align         : Alignment of type
18394   // 9  ) EFLAGS (implicit-def)
18395
18396   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
18397   static_assert(X86::AddrNumOperands == 5,
18398                 "VAARG_64 assumes 5 address operands");
18399
18400   unsigned DestReg = MI->getOperand(0).getReg();
18401   MachineOperand &Base = MI->getOperand(1);
18402   MachineOperand &Scale = MI->getOperand(2);
18403   MachineOperand &Index = MI->getOperand(3);
18404   MachineOperand &Disp = MI->getOperand(4);
18405   MachineOperand &Segment = MI->getOperand(5);
18406   unsigned ArgSize = MI->getOperand(6).getImm();
18407   unsigned ArgMode = MI->getOperand(7).getImm();
18408   unsigned Align = MI->getOperand(8).getImm();
18409
18410   // Memory Reference
18411   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
18412   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
18413   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
18414
18415   // Machine Information
18416   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18417   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
18418   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
18419   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
18420   DebugLoc DL = MI->getDebugLoc();
18421
18422   // struct va_list {
18423   //   i32   gp_offset
18424   //   i32   fp_offset
18425   //   i64   overflow_area (address)
18426   //   i64   reg_save_area (address)
18427   // }
18428   // sizeof(va_list) = 24
18429   // alignment(va_list) = 8
18430
18431   unsigned TotalNumIntRegs = 6;
18432   unsigned TotalNumXMMRegs = 8;
18433   bool UseGPOffset = (ArgMode == 1);
18434   bool UseFPOffset = (ArgMode == 2);
18435   unsigned MaxOffset = TotalNumIntRegs * 8 +
18436                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
18437
18438   /* Align ArgSize to a multiple of 8 */
18439   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
18440   bool NeedsAlign = (Align > 8);
18441
18442   MachineBasicBlock *thisMBB = MBB;
18443   MachineBasicBlock *overflowMBB;
18444   MachineBasicBlock *offsetMBB;
18445   MachineBasicBlock *endMBB;
18446
18447   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
18448   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
18449   unsigned OffsetReg = 0;
18450
18451   if (!UseGPOffset && !UseFPOffset) {
18452     // If we only pull from the overflow region, we don't create a branch.
18453     // We don't need to alter control flow.
18454     OffsetDestReg = 0; // unused
18455     OverflowDestReg = DestReg;
18456
18457     offsetMBB = nullptr;
18458     overflowMBB = thisMBB;
18459     endMBB = thisMBB;
18460   } else {
18461     // First emit code to check if gp_offset (or fp_offset) is below the bound.
18462     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
18463     // If not, pull from overflow_area. (branch to overflowMBB)
18464     //
18465     //       thisMBB
18466     //         |     .
18467     //         |        .
18468     //     offsetMBB   overflowMBB
18469     //         |        .
18470     //         |     .
18471     //        endMBB
18472
18473     // Registers for the PHI in endMBB
18474     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
18475     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
18476
18477     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
18478     MachineFunction *MF = MBB->getParent();
18479     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18480     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18481     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18482
18483     MachineFunction::iterator MBBIter = MBB;
18484     ++MBBIter;
18485
18486     // Insert the new basic blocks
18487     MF->insert(MBBIter, offsetMBB);
18488     MF->insert(MBBIter, overflowMBB);
18489     MF->insert(MBBIter, endMBB);
18490
18491     // Transfer the remainder of MBB and its successor edges to endMBB.
18492     endMBB->splice(endMBB->begin(), thisMBB,
18493                    std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
18494     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
18495
18496     // Make offsetMBB and overflowMBB successors of thisMBB
18497     thisMBB->addSuccessor(offsetMBB);
18498     thisMBB->addSuccessor(overflowMBB);
18499
18500     // endMBB is a successor of both offsetMBB and overflowMBB
18501     offsetMBB->addSuccessor(endMBB);
18502     overflowMBB->addSuccessor(endMBB);
18503
18504     // Load the offset value into a register
18505     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
18506     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
18507       .addOperand(Base)
18508       .addOperand(Scale)
18509       .addOperand(Index)
18510       .addDisp(Disp, UseFPOffset ? 4 : 0)
18511       .addOperand(Segment)
18512       .setMemRefs(MMOBegin, MMOEnd);
18513
18514     // Check if there is enough room left to pull this argument.
18515     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
18516       .addReg(OffsetReg)
18517       .addImm(MaxOffset + 8 - ArgSizeA8);
18518
18519     // Branch to "overflowMBB" if offset >= max
18520     // Fall through to "offsetMBB" otherwise
18521     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
18522       .addMBB(overflowMBB);
18523   }
18524
18525   // In offsetMBB, emit code to use the reg_save_area.
18526   if (offsetMBB) {
18527     assert(OffsetReg != 0);
18528
18529     // Read the reg_save_area address.
18530     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
18531     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
18532       .addOperand(Base)
18533       .addOperand(Scale)
18534       .addOperand(Index)
18535       .addDisp(Disp, 16)
18536       .addOperand(Segment)
18537       .setMemRefs(MMOBegin, MMOEnd);
18538
18539     // Zero-extend the offset
18540     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
18541       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
18542         .addImm(0)
18543         .addReg(OffsetReg)
18544         .addImm(X86::sub_32bit);
18545
18546     // Add the offset to the reg_save_area to get the final address.
18547     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
18548       .addReg(OffsetReg64)
18549       .addReg(RegSaveReg);
18550
18551     // Compute the offset for the next argument
18552     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
18553     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
18554       .addReg(OffsetReg)
18555       .addImm(UseFPOffset ? 16 : 8);
18556
18557     // Store it back into the va_list.
18558     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
18559       .addOperand(Base)
18560       .addOperand(Scale)
18561       .addOperand(Index)
18562       .addDisp(Disp, UseFPOffset ? 4 : 0)
18563       .addOperand(Segment)
18564       .addReg(NextOffsetReg)
18565       .setMemRefs(MMOBegin, MMOEnd);
18566
18567     // Jump to endMBB
18568     BuildMI(offsetMBB, DL, TII->get(X86::JMP_1))
18569       .addMBB(endMBB);
18570   }
18571
18572   //
18573   // Emit code to use overflow area
18574   //
18575
18576   // Load the overflow_area address into a register.
18577   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
18578   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
18579     .addOperand(Base)
18580     .addOperand(Scale)
18581     .addOperand(Index)
18582     .addDisp(Disp, 8)
18583     .addOperand(Segment)
18584     .setMemRefs(MMOBegin, MMOEnd);
18585
18586   // If we need to align it, do so. Otherwise, just copy the address
18587   // to OverflowDestReg.
18588   if (NeedsAlign) {
18589     // Align the overflow address
18590     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
18591     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
18592
18593     // aligned_addr = (addr + (align-1)) & ~(align-1)
18594     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
18595       .addReg(OverflowAddrReg)
18596       .addImm(Align-1);
18597
18598     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
18599       .addReg(TmpReg)
18600       .addImm(~(uint64_t)(Align-1));
18601   } else {
18602     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
18603       .addReg(OverflowAddrReg);
18604   }
18605
18606   // Compute the next overflow address after this argument.
18607   // (the overflow address should be kept 8-byte aligned)
18608   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
18609   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
18610     .addReg(OverflowDestReg)
18611     .addImm(ArgSizeA8);
18612
18613   // Store the new overflow address.
18614   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
18615     .addOperand(Base)
18616     .addOperand(Scale)
18617     .addOperand(Index)
18618     .addDisp(Disp, 8)
18619     .addOperand(Segment)
18620     .addReg(NextAddrReg)
18621     .setMemRefs(MMOBegin, MMOEnd);
18622
18623   // If we branched, emit the PHI to the front of endMBB.
18624   if (offsetMBB) {
18625     BuildMI(*endMBB, endMBB->begin(), DL,
18626             TII->get(X86::PHI), DestReg)
18627       .addReg(OffsetDestReg).addMBB(offsetMBB)
18628       .addReg(OverflowDestReg).addMBB(overflowMBB);
18629   }
18630
18631   // Erase the pseudo instruction
18632   MI->eraseFromParent();
18633
18634   return endMBB;
18635 }
18636
18637 MachineBasicBlock *
18638 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
18639                                                  MachineInstr *MI,
18640                                                  MachineBasicBlock *MBB) const {
18641   // Emit code to save XMM registers to the stack. The ABI says that the
18642   // number of registers to save is given in %al, so it's theoretically
18643   // possible to do an indirect jump trick to avoid saving all of them,
18644   // however this code takes a simpler approach and just executes all
18645   // of the stores if %al is non-zero. It's less code, and it's probably
18646   // easier on the hardware branch predictor, and stores aren't all that
18647   // expensive anyway.
18648
18649   // Create the new basic blocks. One block contains all the XMM stores,
18650   // and one block is the final destination regardless of whether any
18651   // stores were performed.
18652   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
18653   MachineFunction *F = MBB->getParent();
18654   MachineFunction::iterator MBBIter = MBB;
18655   ++MBBIter;
18656   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
18657   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
18658   F->insert(MBBIter, XMMSaveMBB);
18659   F->insert(MBBIter, EndMBB);
18660
18661   // Transfer the remainder of MBB and its successor edges to EndMBB.
18662   EndMBB->splice(EndMBB->begin(), MBB,
18663                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
18664   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
18665
18666   // The original block will now fall through to the XMM save block.
18667   MBB->addSuccessor(XMMSaveMBB);
18668   // The XMMSaveMBB will fall through to the end block.
18669   XMMSaveMBB->addSuccessor(EndMBB);
18670
18671   // Now add the instructions.
18672   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18673   DebugLoc DL = MI->getDebugLoc();
18674
18675   unsigned CountReg = MI->getOperand(0).getReg();
18676   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
18677   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
18678
18679   if (!Subtarget->isTargetWin64()) {
18680     // If %al is 0, branch around the XMM save block.
18681     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
18682     BuildMI(MBB, DL, TII->get(X86::JE_1)).addMBB(EndMBB);
18683     MBB->addSuccessor(EndMBB);
18684   }
18685
18686   // Make sure the last operand is EFLAGS, which gets clobbered by the branch
18687   // that was just emitted, but clearly shouldn't be "saved".
18688   assert((MI->getNumOperands() <= 3 ||
18689           !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
18690           MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
18691          && "Expected last argument to be EFLAGS");
18692   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
18693   // In the XMM save block, save all the XMM argument registers.
18694   for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
18695     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
18696     MachineMemOperand *MMO =
18697       F->getMachineMemOperand(
18698           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
18699         MachineMemOperand::MOStore,
18700         /*Size=*/16, /*Align=*/16);
18701     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
18702       .addFrameIndex(RegSaveFrameIndex)
18703       .addImm(/*Scale=*/1)
18704       .addReg(/*IndexReg=*/0)
18705       .addImm(/*Disp=*/Offset)
18706       .addReg(/*Segment=*/0)
18707       .addReg(MI->getOperand(i).getReg())
18708       .addMemOperand(MMO);
18709   }
18710
18711   MI->eraseFromParent();   // The pseudo instruction is gone now.
18712
18713   return EndMBB;
18714 }
18715
18716 // The EFLAGS operand of SelectItr might be missing a kill marker
18717 // because there were multiple uses of EFLAGS, and ISel didn't know
18718 // which to mark. Figure out whether SelectItr should have had a
18719 // kill marker, and set it if it should. Returns the correct kill
18720 // marker value.
18721 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
18722                                      MachineBasicBlock* BB,
18723                                      const TargetRegisterInfo* TRI) {
18724   // Scan forward through BB for a use/def of EFLAGS.
18725   MachineBasicBlock::iterator miI(std::next(SelectItr));
18726   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
18727     const MachineInstr& mi = *miI;
18728     if (mi.readsRegister(X86::EFLAGS))
18729       return false;
18730     if (mi.definesRegister(X86::EFLAGS))
18731       break; // Should have kill-flag - update below.
18732   }
18733
18734   // If we hit the end of the block, check whether EFLAGS is live into a
18735   // successor.
18736   if (miI == BB->end()) {
18737     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
18738                                           sEnd = BB->succ_end();
18739          sItr != sEnd; ++sItr) {
18740       MachineBasicBlock* succ = *sItr;
18741       if (succ->isLiveIn(X86::EFLAGS))
18742         return false;
18743     }
18744   }
18745
18746   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
18747   // out. SelectMI should have a kill flag on EFLAGS.
18748   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
18749   return true;
18750 }
18751
18752 MachineBasicBlock *
18753 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
18754                                      MachineBasicBlock *BB) const {
18755   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18756   DebugLoc DL = MI->getDebugLoc();
18757
18758   // To "insert" a SELECT_CC instruction, we actually have to insert the
18759   // diamond control-flow pattern.  The incoming instruction knows the
18760   // destination vreg to set, the condition code register to branch on, the
18761   // true/false values to select between, and a branch opcode to use.
18762   const BasicBlock *LLVM_BB = BB->getBasicBlock();
18763   MachineFunction::iterator It = BB;
18764   ++It;
18765
18766   //  thisMBB:
18767   //  ...
18768   //   TrueVal = ...
18769   //   cmpTY ccX, r1, r2
18770   //   bCC copy1MBB
18771   //   fallthrough --> copy0MBB
18772   MachineBasicBlock *thisMBB = BB;
18773   MachineFunction *F = BB->getParent();
18774
18775   // We also lower double CMOVs:
18776   //   (CMOV (CMOV F, T, cc1), T, cc2)
18777   // to two successives branches.  For that, we look for another CMOV as the
18778   // following instruction.
18779   //
18780   // Without this, we would add a PHI between the two jumps, which ends up
18781   // creating a few copies all around. For instance, for
18782   //
18783   //    (sitofp (zext (fcmp une)))
18784   //
18785   // we would generate:
18786   //
18787   //         ucomiss %xmm1, %xmm0
18788   //         movss  <1.0f>, %xmm0
18789   //         movaps  %xmm0, %xmm1
18790   //         jne     .LBB5_2
18791   //         xorps   %xmm1, %xmm1
18792   // .LBB5_2:
18793   //         jp      .LBB5_4
18794   //         movaps  %xmm1, %xmm0
18795   // .LBB5_4:
18796   //         retq
18797   //
18798   // because this custom-inserter would have generated:
18799   //
18800   //   A
18801   //   | \
18802   //   |  B
18803   //   | /
18804   //   C
18805   //   | \
18806   //   |  D
18807   //   | /
18808   //   E
18809   //
18810   // A: X = ...; Y = ...
18811   // B: empty
18812   // C: Z = PHI [X, A], [Y, B]
18813   // D: empty
18814   // E: PHI [X, C], [Z, D]
18815   //
18816   // If we lower both CMOVs in a single step, we can instead generate:
18817   //
18818   //   A
18819   //   | \
18820   //   |  C
18821   //   | /|
18822   //   |/ |
18823   //   |  |
18824   //   |  D
18825   //   | /
18826   //   E
18827   //
18828   // A: X = ...; Y = ...
18829   // D: empty
18830   // E: PHI [X, A], [X, C], [Y, D]
18831   //
18832   // Which, in our sitofp/fcmp example, gives us something like:
18833   //
18834   //         ucomiss %xmm1, %xmm0
18835   //         movss  <1.0f>, %xmm0
18836   //         jne     .LBB5_4
18837   //         jp      .LBB5_4
18838   //         xorps   %xmm0, %xmm0
18839   // .LBB5_4:
18840   //         retq
18841   //
18842   MachineInstr *NextCMOV = nullptr;
18843   MachineBasicBlock::iterator NextMIIt =
18844       std::next(MachineBasicBlock::iterator(MI));
18845   if (NextMIIt != BB->end() && NextMIIt->getOpcode() == MI->getOpcode() &&
18846       NextMIIt->getOperand(2).getReg() == MI->getOperand(2).getReg() &&
18847       NextMIIt->getOperand(1).getReg() == MI->getOperand(0).getReg())
18848     NextCMOV = &*NextMIIt;
18849
18850   MachineBasicBlock *jcc1MBB = nullptr;
18851
18852   // If we have a double CMOV, we lower it to two successive branches to
18853   // the same block.  EFLAGS is used by both, so mark it as live in the second.
18854   if (NextCMOV) {
18855     jcc1MBB = F->CreateMachineBasicBlock(LLVM_BB);
18856     F->insert(It, jcc1MBB);
18857     jcc1MBB->addLiveIn(X86::EFLAGS);
18858   }
18859
18860   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
18861   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
18862   F->insert(It, copy0MBB);
18863   F->insert(It, sinkMBB);
18864
18865   // If the EFLAGS register isn't dead in the terminator, then claim that it's
18866   // live into the sink and copy blocks.
18867   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
18868
18869   MachineInstr *LastEFLAGSUser = NextCMOV ? NextCMOV : MI;
18870   if (!LastEFLAGSUser->killsRegister(X86::EFLAGS) &&
18871       !checkAndUpdateEFLAGSKill(LastEFLAGSUser, BB, TRI)) {
18872     copy0MBB->addLiveIn(X86::EFLAGS);
18873     sinkMBB->addLiveIn(X86::EFLAGS);
18874   }
18875
18876   // Transfer the remainder of BB and its successor edges to sinkMBB.
18877   sinkMBB->splice(sinkMBB->begin(), BB,
18878                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
18879   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
18880
18881   // Add the true and fallthrough blocks as its successors.
18882   if (NextCMOV) {
18883     // The fallthrough block may be jcc1MBB, if we have a double CMOV.
18884     BB->addSuccessor(jcc1MBB);
18885
18886     // In that case, jcc1MBB will itself fallthrough the copy0MBB, and
18887     // jump to the sinkMBB.
18888     jcc1MBB->addSuccessor(copy0MBB);
18889     jcc1MBB->addSuccessor(sinkMBB);
18890   } else {
18891     BB->addSuccessor(copy0MBB);
18892   }
18893
18894   // The true block target of the first (or only) branch is always sinkMBB.
18895   BB->addSuccessor(sinkMBB);
18896
18897   // Create the conditional branch instruction.
18898   unsigned Opc =
18899     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
18900   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
18901
18902   if (NextCMOV) {
18903     unsigned Opc2 = X86::GetCondBranchFromCond(
18904         (X86::CondCode)NextCMOV->getOperand(3).getImm());
18905     BuildMI(jcc1MBB, DL, TII->get(Opc2)).addMBB(sinkMBB);
18906   }
18907
18908   //  copy0MBB:
18909   //   %FalseValue = ...
18910   //   # fallthrough to sinkMBB
18911   copy0MBB->addSuccessor(sinkMBB);
18912
18913   //  sinkMBB:
18914   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
18915   //  ...
18916   MachineInstrBuilder MIB =
18917       BuildMI(*sinkMBB, sinkMBB->begin(), DL, TII->get(X86::PHI),
18918               MI->getOperand(0).getReg())
18919           .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
18920           .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
18921
18922   // If we have a double CMOV, the second Jcc provides the same incoming
18923   // value as the first Jcc (the True operand of the SELECT_CC/CMOV nodes).
18924   if (NextCMOV) {
18925     MIB.addReg(MI->getOperand(2).getReg()).addMBB(jcc1MBB);
18926     // Copy the PHI result to the register defined by the second CMOV.
18927     BuildMI(*sinkMBB, std::next(MachineBasicBlock::iterator(MIB.getInstr())),
18928             DL, TII->get(TargetOpcode::COPY), NextCMOV->getOperand(0).getReg())
18929         .addReg(MI->getOperand(0).getReg());
18930     NextCMOV->eraseFromParent();
18931   }
18932
18933   MI->eraseFromParent();   // The pseudo instruction is gone now.
18934   return sinkMBB;
18935 }
18936
18937 MachineBasicBlock *
18938 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI,
18939                                         MachineBasicBlock *BB) const {
18940   MachineFunction *MF = BB->getParent();
18941   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18942   DebugLoc DL = MI->getDebugLoc();
18943   const BasicBlock *LLVM_BB = BB->getBasicBlock();
18944
18945   assert(MF->shouldSplitStack());
18946
18947   const bool Is64Bit = Subtarget->is64Bit();
18948   const bool IsLP64 = Subtarget->isTarget64BitLP64();
18949
18950   const unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
18951   const unsigned TlsOffset = IsLP64 ? 0x70 : Is64Bit ? 0x40 : 0x30;
18952
18953   // BB:
18954   //  ... [Till the alloca]
18955   // If stacklet is not large enough, jump to mallocMBB
18956   //
18957   // bumpMBB:
18958   //  Allocate by subtracting from RSP
18959   //  Jump to continueMBB
18960   //
18961   // mallocMBB:
18962   //  Allocate by call to runtime
18963   //
18964   // continueMBB:
18965   //  ...
18966   //  [rest of original BB]
18967   //
18968
18969   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18970   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18971   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18972
18973   MachineRegisterInfo &MRI = MF->getRegInfo();
18974   const TargetRegisterClass *AddrRegClass =
18975     getRegClassFor(getPointerTy());
18976
18977   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
18978     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
18979     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
18980     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
18981     sizeVReg = MI->getOperand(1).getReg(),
18982     physSPReg = IsLP64 || Subtarget->isTargetNaCl64() ? X86::RSP : X86::ESP;
18983
18984   MachineFunction::iterator MBBIter = BB;
18985   ++MBBIter;
18986
18987   MF->insert(MBBIter, bumpMBB);
18988   MF->insert(MBBIter, mallocMBB);
18989   MF->insert(MBBIter, continueMBB);
18990
18991   continueMBB->splice(continueMBB->begin(), BB,
18992                       std::next(MachineBasicBlock::iterator(MI)), BB->end());
18993   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
18994
18995   // Add code to the main basic block to check if the stack limit has been hit,
18996   // and if so, jump to mallocMBB otherwise to bumpMBB.
18997   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
18998   BuildMI(BB, DL, TII->get(IsLP64 ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
18999     .addReg(tmpSPVReg).addReg(sizeVReg);
19000   BuildMI(BB, DL, TII->get(IsLP64 ? X86::CMP64mr:X86::CMP32mr))
19001     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
19002     .addReg(SPLimitVReg);
19003   BuildMI(BB, DL, TII->get(X86::JG_1)).addMBB(mallocMBB);
19004
19005   // bumpMBB simply decreases the stack pointer, since we know the current
19006   // stacklet has enough space.
19007   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
19008     .addReg(SPLimitVReg);
19009   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
19010     .addReg(SPLimitVReg);
19011   BuildMI(bumpMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
19012
19013   // Calls into a routine in libgcc to allocate more space from the heap.
19014   const uint32_t *RegMask =
19015       Subtarget->getRegisterInfo()->getCallPreservedMask(*MF, CallingConv::C);
19016   if (IsLP64) {
19017     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
19018       .addReg(sizeVReg);
19019     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
19020       .addExternalSymbol("__morestack_allocate_stack_space")
19021       .addRegMask(RegMask)
19022       .addReg(X86::RDI, RegState::Implicit)
19023       .addReg(X86::RAX, RegState::ImplicitDefine);
19024   } else if (Is64Bit) {
19025     BuildMI(mallocMBB, DL, TII->get(X86::MOV32rr), X86::EDI)
19026       .addReg(sizeVReg);
19027     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
19028       .addExternalSymbol("__morestack_allocate_stack_space")
19029       .addRegMask(RegMask)
19030       .addReg(X86::EDI, RegState::Implicit)
19031       .addReg(X86::EAX, RegState::ImplicitDefine);
19032   } else {
19033     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
19034       .addImm(12);
19035     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
19036     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
19037       .addExternalSymbol("__morestack_allocate_stack_space")
19038       .addRegMask(RegMask)
19039       .addReg(X86::EAX, RegState::ImplicitDefine);
19040   }
19041
19042   if (!Is64Bit)
19043     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
19044       .addImm(16);
19045
19046   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
19047     .addReg(IsLP64 ? X86::RAX : X86::EAX);
19048   BuildMI(mallocMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
19049
19050   // Set up the CFG correctly.
19051   BB->addSuccessor(bumpMBB);
19052   BB->addSuccessor(mallocMBB);
19053   mallocMBB->addSuccessor(continueMBB);
19054   bumpMBB->addSuccessor(continueMBB);
19055
19056   // Take care of the PHI nodes.
19057   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
19058           MI->getOperand(0).getReg())
19059     .addReg(mallocPtrVReg).addMBB(mallocMBB)
19060     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
19061
19062   // Delete the original pseudo instruction.
19063   MI->eraseFromParent();
19064
19065   // And we're done.
19066   return continueMBB;
19067 }
19068
19069 MachineBasicBlock *
19070 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
19071                                         MachineBasicBlock *BB) const {
19072   DebugLoc DL = MI->getDebugLoc();
19073
19074   assert(!Subtarget->isTargetMachO());
19075
19076   X86FrameLowering::emitStackProbeCall(*BB->getParent(), *BB, MI, DL);
19077
19078   MI->eraseFromParent();   // The pseudo instruction is gone now.
19079   return BB;
19080 }
19081
19082 MachineBasicBlock *
19083 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
19084                                       MachineBasicBlock *BB) const {
19085   // This is pretty easy.  We're taking the value that we received from
19086   // our load from the relocation, sticking it in either RDI (x86-64)
19087   // or EAX and doing an indirect call.  The return value will then
19088   // be in the normal return register.
19089   MachineFunction *F = BB->getParent();
19090   const X86InstrInfo *TII = Subtarget->getInstrInfo();
19091   DebugLoc DL = MI->getDebugLoc();
19092
19093   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
19094   assert(MI->getOperand(3).isGlobal() && "This should be a global");
19095
19096   // Get a register mask for the lowered call.
19097   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
19098   // proper register mask.
19099   const uint32_t *RegMask =
19100       Subtarget->getRegisterInfo()->getCallPreservedMask(*F, CallingConv::C);
19101   if (Subtarget->is64Bit()) {
19102     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
19103                                       TII->get(X86::MOV64rm), X86::RDI)
19104     .addReg(X86::RIP)
19105     .addImm(0).addReg(0)
19106     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
19107                       MI->getOperand(3).getTargetFlags())
19108     .addReg(0);
19109     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
19110     addDirectMem(MIB, X86::RDI);
19111     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
19112   } else if (F->getTarget().getRelocationModel() != Reloc::PIC_) {
19113     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
19114                                       TII->get(X86::MOV32rm), X86::EAX)
19115     .addReg(0)
19116     .addImm(0).addReg(0)
19117     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
19118                       MI->getOperand(3).getTargetFlags())
19119     .addReg(0);
19120     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
19121     addDirectMem(MIB, X86::EAX);
19122     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
19123   } else {
19124     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
19125                                       TII->get(X86::MOV32rm), X86::EAX)
19126     .addReg(TII->getGlobalBaseReg(F))
19127     .addImm(0).addReg(0)
19128     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
19129                       MI->getOperand(3).getTargetFlags())
19130     .addReg(0);
19131     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
19132     addDirectMem(MIB, X86::EAX);
19133     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
19134   }
19135
19136   MI->eraseFromParent(); // The pseudo instruction is gone now.
19137   return BB;
19138 }
19139
19140 MachineBasicBlock *
19141 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
19142                                     MachineBasicBlock *MBB) const {
19143   DebugLoc DL = MI->getDebugLoc();
19144   MachineFunction *MF = MBB->getParent();
19145   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19146   MachineRegisterInfo &MRI = MF->getRegInfo();
19147
19148   const BasicBlock *BB = MBB->getBasicBlock();
19149   MachineFunction::iterator I = MBB;
19150   ++I;
19151
19152   // Memory Reference
19153   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
19154   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
19155
19156   unsigned DstReg;
19157   unsigned MemOpndSlot = 0;
19158
19159   unsigned CurOp = 0;
19160
19161   DstReg = MI->getOperand(CurOp++).getReg();
19162   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
19163   assert(RC->hasType(MVT::i32) && "Invalid destination!");
19164   unsigned mainDstReg = MRI.createVirtualRegister(RC);
19165   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
19166
19167   MemOpndSlot = CurOp;
19168
19169   MVT PVT = getPointerTy();
19170   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
19171          "Invalid Pointer Size!");
19172
19173   // For v = setjmp(buf), we generate
19174   //
19175   // thisMBB:
19176   //  buf[LabelOffset] = restoreMBB
19177   //  SjLjSetup restoreMBB
19178   //
19179   // mainMBB:
19180   //  v_main = 0
19181   //
19182   // sinkMBB:
19183   //  v = phi(main, restore)
19184   //
19185   // restoreMBB:
19186   //  if base pointer being used, load it from frame
19187   //  v_restore = 1
19188
19189   MachineBasicBlock *thisMBB = MBB;
19190   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
19191   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
19192   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
19193   MF->insert(I, mainMBB);
19194   MF->insert(I, sinkMBB);
19195   MF->push_back(restoreMBB);
19196
19197   MachineInstrBuilder MIB;
19198
19199   // Transfer the remainder of BB and its successor edges to sinkMBB.
19200   sinkMBB->splice(sinkMBB->begin(), MBB,
19201                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
19202   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
19203
19204   // thisMBB:
19205   unsigned PtrStoreOpc = 0;
19206   unsigned LabelReg = 0;
19207   const int64_t LabelOffset = 1 * PVT.getStoreSize();
19208   Reloc::Model RM = MF->getTarget().getRelocationModel();
19209   bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
19210                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
19211
19212   // Prepare IP either in reg or imm.
19213   if (!UseImmLabel) {
19214     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
19215     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
19216     LabelReg = MRI.createVirtualRegister(PtrRC);
19217     if (Subtarget->is64Bit()) {
19218       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
19219               .addReg(X86::RIP)
19220               .addImm(0)
19221               .addReg(0)
19222               .addMBB(restoreMBB)
19223               .addReg(0);
19224     } else {
19225       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
19226       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
19227               .addReg(XII->getGlobalBaseReg(MF))
19228               .addImm(0)
19229               .addReg(0)
19230               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
19231               .addReg(0);
19232     }
19233   } else
19234     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
19235   // Store IP
19236   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
19237   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
19238     if (i == X86::AddrDisp)
19239       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
19240     else
19241       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
19242   }
19243   if (!UseImmLabel)
19244     MIB.addReg(LabelReg);
19245   else
19246     MIB.addMBB(restoreMBB);
19247   MIB.setMemRefs(MMOBegin, MMOEnd);
19248   // Setup
19249   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
19250           .addMBB(restoreMBB);
19251
19252   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
19253   MIB.addRegMask(RegInfo->getNoPreservedMask());
19254   thisMBB->addSuccessor(mainMBB);
19255   thisMBB->addSuccessor(restoreMBB);
19256
19257   // mainMBB:
19258   //  EAX = 0
19259   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
19260   mainMBB->addSuccessor(sinkMBB);
19261
19262   // sinkMBB:
19263   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
19264           TII->get(X86::PHI), DstReg)
19265     .addReg(mainDstReg).addMBB(mainMBB)
19266     .addReg(restoreDstReg).addMBB(restoreMBB);
19267
19268   // restoreMBB:
19269   if (RegInfo->hasBasePointer(*MF)) {
19270     const bool Uses64BitFramePtr =
19271         Subtarget->isTarget64BitLP64() || Subtarget->isTargetNaCl64();
19272     X86MachineFunctionInfo *X86FI = MF->getInfo<X86MachineFunctionInfo>();
19273     X86FI->setRestoreBasePointer(MF);
19274     unsigned FramePtr = RegInfo->getFrameRegister(*MF);
19275     unsigned BasePtr = RegInfo->getBaseRegister();
19276     unsigned Opm = Uses64BitFramePtr ? X86::MOV64rm : X86::MOV32rm;
19277     addRegOffset(BuildMI(restoreMBB, DL, TII->get(Opm), BasePtr),
19278                  FramePtr, true, X86FI->getRestoreBasePointerOffset())
19279       .setMIFlag(MachineInstr::FrameSetup);
19280   }
19281   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
19282   BuildMI(restoreMBB, DL, TII->get(X86::JMP_1)).addMBB(sinkMBB);
19283   restoreMBB->addSuccessor(sinkMBB);
19284
19285   MI->eraseFromParent();
19286   return sinkMBB;
19287 }
19288
19289 MachineBasicBlock *
19290 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
19291                                      MachineBasicBlock *MBB) const {
19292   DebugLoc DL = MI->getDebugLoc();
19293   MachineFunction *MF = MBB->getParent();
19294   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19295   MachineRegisterInfo &MRI = MF->getRegInfo();
19296
19297   // Memory Reference
19298   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
19299   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
19300
19301   MVT PVT = getPointerTy();
19302   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
19303          "Invalid Pointer Size!");
19304
19305   const TargetRegisterClass *RC =
19306     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
19307   unsigned Tmp = MRI.createVirtualRegister(RC);
19308   // Since FP is only updated here but NOT referenced, it's treated as GPR.
19309   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
19310   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
19311   unsigned SP = RegInfo->getStackRegister();
19312
19313   MachineInstrBuilder MIB;
19314
19315   const int64_t LabelOffset = 1 * PVT.getStoreSize();
19316   const int64_t SPOffset = 2 * PVT.getStoreSize();
19317
19318   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
19319   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
19320
19321   // Reload FP
19322   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
19323   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
19324     MIB.addOperand(MI->getOperand(i));
19325   MIB.setMemRefs(MMOBegin, MMOEnd);
19326   // Reload IP
19327   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
19328   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
19329     if (i == X86::AddrDisp)
19330       MIB.addDisp(MI->getOperand(i), LabelOffset);
19331     else
19332       MIB.addOperand(MI->getOperand(i));
19333   }
19334   MIB.setMemRefs(MMOBegin, MMOEnd);
19335   // Reload SP
19336   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
19337   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
19338     if (i == X86::AddrDisp)
19339       MIB.addDisp(MI->getOperand(i), SPOffset);
19340     else
19341       MIB.addOperand(MI->getOperand(i));
19342   }
19343   MIB.setMemRefs(MMOBegin, MMOEnd);
19344   // Jump
19345   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
19346
19347   MI->eraseFromParent();
19348   return MBB;
19349 }
19350
19351 // Replace 213-type (isel default) FMA3 instructions with 231-type for
19352 // accumulator loops. Writing back to the accumulator allows the coalescer
19353 // to remove extra copies in the loop.
19354 MachineBasicBlock *
19355 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
19356                                  MachineBasicBlock *MBB) const {
19357   MachineOperand &AddendOp = MI->getOperand(3);
19358
19359   // Bail out early if the addend isn't a register - we can't switch these.
19360   if (!AddendOp.isReg())
19361     return MBB;
19362
19363   MachineFunction &MF = *MBB->getParent();
19364   MachineRegisterInfo &MRI = MF.getRegInfo();
19365
19366   // Check whether the addend is defined by a PHI:
19367   assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
19368   MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
19369   if (!AddendDef.isPHI())
19370     return MBB;
19371
19372   // Look for the following pattern:
19373   // loop:
19374   //   %addend = phi [%entry, 0], [%loop, %result]
19375   //   ...
19376   //   %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
19377
19378   // Replace with:
19379   //   loop:
19380   //   %addend = phi [%entry, 0], [%loop, %result]
19381   //   ...
19382   //   %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
19383
19384   for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
19385     assert(AddendDef.getOperand(i).isReg());
19386     MachineOperand PHISrcOp = AddendDef.getOperand(i);
19387     MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
19388     if (&PHISrcInst == MI) {
19389       // Found a matching instruction.
19390       unsigned NewFMAOpc = 0;
19391       switch (MI->getOpcode()) {
19392         case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
19393         case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
19394         case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
19395         case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
19396         case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
19397         case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
19398         case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
19399         case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
19400         case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
19401         case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
19402         case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
19403         case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
19404         case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
19405         case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
19406         case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
19407         case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
19408         case X86::VFMADDSUBPDr213r: NewFMAOpc = X86::VFMADDSUBPDr231r; break;
19409         case X86::VFMADDSUBPSr213r: NewFMAOpc = X86::VFMADDSUBPSr231r; break;
19410         case X86::VFMSUBADDPDr213r: NewFMAOpc = X86::VFMSUBADDPDr231r; break;
19411         case X86::VFMSUBADDPSr213r: NewFMAOpc = X86::VFMSUBADDPSr231r; break;
19412
19413         case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
19414         case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
19415         case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
19416         case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
19417         case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
19418         case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
19419         case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
19420         case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
19421         case X86::VFMADDSUBPDr213rY: NewFMAOpc = X86::VFMADDSUBPDr231rY; break;
19422         case X86::VFMADDSUBPSr213rY: NewFMAOpc = X86::VFMADDSUBPSr231rY; break;
19423         case X86::VFMSUBADDPDr213rY: NewFMAOpc = X86::VFMSUBADDPDr231rY; break;
19424         case X86::VFMSUBADDPSr213rY: NewFMAOpc = X86::VFMSUBADDPSr231rY; break;
19425         default: llvm_unreachable("Unrecognized FMA variant.");
19426       }
19427
19428       const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
19429       MachineInstrBuilder MIB =
19430         BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
19431         .addOperand(MI->getOperand(0))
19432         .addOperand(MI->getOperand(3))
19433         .addOperand(MI->getOperand(2))
19434         .addOperand(MI->getOperand(1));
19435       MBB->insert(MachineBasicBlock::iterator(MI), MIB);
19436       MI->eraseFromParent();
19437     }
19438   }
19439
19440   return MBB;
19441 }
19442
19443 MachineBasicBlock *
19444 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
19445                                                MachineBasicBlock *BB) const {
19446   switch (MI->getOpcode()) {
19447   default: llvm_unreachable("Unexpected instr type to insert");
19448   case X86::TAILJMPd64:
19449   case X86::TAILJMPr64:
19450   case X86::TAILJMPm64:
19451   case X86::TAILJMPd64_REX:
19452   case X86::TAILJMPr64_REX:
19453   case X86::TAILJMPm64_REX:
19454     llvm_unreachable("TAILJMP64 would not be touched here.");
19455   case X86::TCRETURNdi64:
19456   case X86::TCRETURNri64:
19457   case X86::TCRETURNmi64:
19458     return BB;
19459   case X86::WIN_ALLOCA:
19460     return EmitLoweredWinAlloca(MI, BB);
19461   case X86::SEG_ALLOCA_32:
19462   case X86::SEG_ALLOCA_64:
19463     return EmitLoweredSegAlloca(MI, BB);
19464   case X86::TLSCall_32:
19465   case X86::TLSCall_64:
19466     return EmitLoweredTLSCall(MI, BB);
19467   case X86::CMOV_GR8:
19468   case X86::CMOV_FR32:
19469   case X86::CMOV_FR64:
19470   case X86::CMOV_V4F32:
19471   case X86::CMOV_V2F64:
19472   case X86::CMOV_V2I64:
19473   case X86::CMOV_V8F32:
19474   case X86::CMOV_V4F64:
19475   case X86::CMOV_V4I64:
19476   case X86::CMOV_V16F32:
19477   case X86::CMOV_V8F64:
19478   case X86::CMOV_V8I64:
19479   case X86::CMOV_GR16:
19480   case X86::CMOV_GR32:
19481   case X86::CMOV_RFP32:
19482   case X86::CMOV_RFP64:
19483   case X86::CMOV_RFP80:
19484     return EmitLoweredSelect(MI, BB);
19485
19486   case X86::FP32_TO_INT16_IN_MEM:
19487   case X86::FP32_TO_INT32_IN_MEM:
19488   case X86::FP32_TO_INT64_IN_MEM:
19489   case X86::FP64_TO_INT16_IN_MEM:
19490   case X86::FP64_TO_INT32_IN_MEM:
19491   case X86::FP64_TO_INT64_IN_MEM:
19492   case X86::FP80_TO_INT16_IN_MEM:
19493   case X86::FP80_TO_INT32_IN_MEM:
19494   case X86::FP80_TO_INT64_IN_MEM: {
19495     MachineFunction *F = BB->getParent();
19496     const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19497     DebugLoc DL = MI->getDebugLoc();
19498
19499     // Change the floating point control register to use "round towards zero"
19500     // mode when truncating to an integer value.
19501     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
19502     addFrameReference(BuildMI(*BB, MI, DL,
19503                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
19504
19505     // Load the old value of the high byte of the control word...
19506     unsigned OldCW =
19507       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
19508     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
19509                       CWFrameIdx);
19510
19511     // Set the high part to be round to zero...
19512     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
19513       .addImm(0xC7F);
19514
19515     // Reload the modified control word now...
19516     addFrameReference(BuildMI(*BB, MI, DL,
19517                               TII->get(X86::FLDCW16m)), CWFrameIdx);
19518
19519     // Restore the memory image of control word to original value
19520     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
19521       .addReg(OldCW);
19522
19523     // Get the X86 opcode to use.
19524     unsigned Opc;
19525     switch (MI->getOpcode()) {
19526     default: llvm_unreachable("illegal opcode!");
19527     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
19528     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
19529     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
19530     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
19531     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
19532     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
19533     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
19534     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
19535     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
19536     }
19537
19538     X86AddressMode AM;
19539     MachineOperand &Op = MI->getOperand(0);
19540     if (Op.isReg()) {
19541       AM.BaseType = X86AddressMode::RegBase;
19542       AM.Base.Reg = Op.getReg();
19543     } else {
19544       AM.BaseType = X86AddressMode::FrameIndexBase;
19545       AM.Base.FrameIndex = Op.getIndex();
19546     }
19547     Op = MI->getOperand(1);
19548     if (Op.isImm())
19549       AM.Scale = Op.getImm();
19550     Op = MI->getOperand(2);
19551     if (Op.isImm())
19552       AM.IndexReg = Op.getImm();
19553     Op = MI->getOperand(3);
19554     if (Op.isGlobal()) {
19555       AM.GV = Op.getGlobal();
19556     } else {
19557       AM.Disp = Op.getImm();
19558     }
19559     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
19560                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
19561
19562     // Reload the original control word now.
19563     addFrameReference(BuildMI(*BB, MI, DL,
19564                               TII->get(X86::FLDCW16m)), CWFrameIdx);
19565
19566     MI->eraseFromParent();   // The pseudo instruction is gone now.
19567     return BB;
19568   }
19569     // String/text processing lowering.
19570   case X86::PCMPISTRM128REG:
19571   case X86::VPCMPISTRM128REG:
19572   case X86::PCMPISTRM128MEM:
19573   case X86::VPCMPISTRM128MEM:
19574   case X86::PCMPESTRM128REG:
19575   case X86::VPCMPESTRM128REG:
19576   case X86::PCMPESTRM128MEM:
19577   case X86::VPCMPESTRM128MEM:
19578     assert(Subtarget->hasSSE42() &&
19579            "Target must have SSE4.2 or AVX features enabled");
19580     return EmitPCMPSTRM(MI, BB, Subtarget->getInstrInfo());
19581
19582   // String/text processing lowering.
19583   case X86::PCMPISTRIREG:
19584   case X86::VPCMPISTRIREG:
19585   case X86::PCMPISTRIMEM:
19586   case X86::VPCMPISTRIMEM:
19587   case X86::PCMPESTRIREG:
19588   case X86::VPCMPESTRIREG:
19589   case X86::PCMPESTRIMEM:
19590   case X86::VPCMPESTRIMEM:
19591     assert(Subtarget->hasSSE42() &&
19592            "Target must have SSE4.2 or AVX features enabled");
19593     return EmitPCMPSTRI(MI, BB, Subtarget->getInstrInfo());
19594
19595   // Thread synchronization.
19596   case X86::MONITOR:
19597     return EmitMonitor(MI, BB, Subtarget);
19598
19599   // xbegin
19600   case X86::XBEGIN:
19601     return EmitXBegin(MI, BB, Subtarget->getInstrInfo());
19602
19603   case X86::VASTART_SAVE_XMM_REGS:
19604     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
19605
19606   case X86::VAARG_64:
19607     return EmitVAARG64WithCustomInserter(MI, BB);
19608
19609   case X86::EH_SjLj_SetJmp32:
19610   case X86::EH_SjLj_SetJmp64:
19611     return emitEHSjLjSetJmp(MI, BB);
19612
19613   case X86::EH_SjLj_LongJmp32:
19614   case X86::EH_SjLj_LongJmp64:
19615     return emitEHSjLjLongJmp(MI, BB);
19616
19617   case TargetOpcode::STATEPOINT:
19618     // As an implementation detail, STATEPOINT shares the STACKMAP format at
19619     // this point in the process.  We diverge later.
19620     return emitPatchPoint(MI, BB);
19621
19622   case TargetOpcode::STACKMAP:
19623   case TargetOpcode::PATCHPOINT:
19624     return emitPatchPoint(MI, BB);
19625
19626   case X86::VFMADDPDr213r:
19627   case X86::VFMADDPSr213r:
19628   case X86::VFMADDSDr213r:
19629   case X86::VFMADDSSr213r:
19630   case X86::VFMSUBPDr213r:
19631   case X86::VFMSUBPSr213r:
19632   case X86::VFMSUBSDr213r:
19633   case X86::VFMSUBSSr213r:
19634   case X86::VFNMADDPDr213r:
19635   case X86::VFNMADDPSr213r:
19636   case X86::VFNMADDSDr213r:
19637   case X86::VFNMADDSSr213r:
19638   case X86::VFNMSUBPDr213r:
19639   case X86::VFNMSUBPSr213r:
19640   case X86::VFNMSUBSDr213r:
19641   case X86::VFNMSUBSSr213r:
19642   case X86::VFMADDSUBPDr213r:
19643   case X86::VFMADDSUBPSr213r:
19644   case X86::VFMSUBADDPDr213r:
19645   case X86::VFMSUBADDPSr213r:
19646   case X86::VFMADDPDr213rY:
19647   case X86::VFMADDPSr213rY:
19648   case X86::VFMSUBPDr213rY:
19649   case X86::VFMSUBPSr213rY:
19650   case X86::VFNMADDPDr213rY:
19651   case X86::VFNMADDPSr213rY:
19652   case X86::VFNMSUBPDr213rY:
19653   case X86::VFNMSUBPSr213rY:
19654   case X86::VFMADDSUBPDr213rY:
19655   case X86::VFMADDSUBPSr213rY:
19656   case X86::VFMSUBADDPDr213rY:
19657   case X86::VFMSUBADDPSr213rY:
19658     return emitFMA3Instr(MI, BB);
19659   }
19660 }
19661
19662 //===----------------------------------------------------------------------===//
19663 //                           X86 Optimization Hooks
19664 //===----------------------------------------------------------------------===//
19665
19666 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
19667                                                       APInt &KnownZero,
19668                                                       APInt &KnownOne,
19669                                                       const SelectionDAG &DAG,
19670                                                       unsigned Depth) const {
19671   unsigned BitWidth = KnownZero.getBitWidth();
19672   unsigned Opc = Op.getOpcode();
19673   assert((Opc >= ISD::BUILTIN_OP_END ||
19674           Opc == ISD::INTRINSIC_WO_CHAIN ||
19675           Opc == ISD::INTRINSIC_W_CHAIN ||
19676           Opc == ISD::INTRINSIC_VOID) &&
19677          "Should use MaskedValueIsZero if you don't know whether Op"
19678          " is a target node!");
19679
19680   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
19681   switch (Opc) {
19682   default: break;
19683   case X86ISD::ADD:
19684   case X86ISD::SUB:
19685   case X86ISD::ADC:
19686   case X86ISD::SBB:
19687   case X86ISD::SMUL:
19688   case X86ISD::UMUL:
19689   case X86ISD::INC:
19690   case X86ISD::DEC:
19691   case X86ISD::OR:
19692   case X86ISD::XOR:
19693   case X86ISD::AND:
19694     // These nodes' second result is a boolean.
19695     if (Op.getResNo() == 0)
19696       break;
19697     // Fallthrough
19698   case X86ISD::SETCC:
19699     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
19700     break;
19701   case ISD::INTRINSIC_WO_CHAIN: {
19702     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
19703     unsigned NumLoBits = 0;
19704     switch (IntId) {
19705     default: break;
19706     case Intrinsic::x86_sse_movmsk_ps:
19707     case Intrinsic::x86_avx_movmsk_ps_256:
19708     case Intrinsic::x86_sse2_movmsk_pd:
19709     case Intrinsic::x86_avx_movmsk_pd_256:
19710     case Intrinsic::x86_mmx_pmovmskb:
19711     case Intrinsic::x86_sse2_pmovmskb_128:
19712     case Intrinsic::x86_avx2_pmovmskb: {
19713       // High bits of movmskp{s|d}, pmovmskb are known zero.
19714       switch (IntId) {
19715         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
19716         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
19717         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
19718         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
19719         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
19720         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
19721         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
19722         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
19723       }
19724       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
19725       break;
19726     }
19727     }
19728     break;
19729   }
19730   }
19731 }
19732
19733 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
19734   SDValue Op,
19735   const SelectionDAG &,
19736   unsigned Depth) const {
19737   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
19738   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
19739     return Op.getValueType().getScalarType().getSizeInBits();
19740
19741   // Fallback case.
19742   return 1;
19743 }
19744
19745 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
19746 /// node is a GlobalAddress + offset.
19747 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
19748                                        const GlobalValue* &GA,
19749                                        int64_t &Offset) const {
19750   if (N->getOpcode() == X86ISD::Wrapper) {
19751     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
19752       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
19753       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
19754       return true;
19755     }
19756   }
19757   return TargetLowering::isGAPlusOffset(N, GA, Offset);
19758 }
19759
19760 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
19761 /// same as extracting the high 128-bit part of 256-bit vector and then
19762 /// inserting the result into the low part of a new 256-bit vector
19763 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
19764   EVT VT = SVOp->getValueType(0);
19765   unsigned NumElems = VT.getVectorNumElements();
19766
19767   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
19768   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
19769     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
19770         SVOp->getMaskElt(j) >= 0)
19771       return false;
19772
19773   return true;
19774 }
19775
19776 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
19777 /// same as extracting the low 128-bit part of 256-bit vector and then
19778 /// inserting the result into the high part of a new 256-bit vector
19779 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
19780   EVT VT = SVOp->getValueType(0);
19781   unsigned NumElems = VT.getVectorNumElements();
19782
19783   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
19784   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
19785     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
19786         SVOp->getMaskElt(j) >= 0)
19787       return false;
19788
19789   return true;
19790 }
19791
19792 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
19793 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
19794                                         TargetLowering::DAGCombinerInfo &DCI,
19795                                         const X86Subtarget* Subtarget) {
19796   SDLoc dl(N);
19797   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
19798   SDValue V1 = SVOp->getOperand(0);
19799   SDValue V2 = SVOp->getOperand(1);
19800   EVT VT = SVOp->getValueType(0);
19801   unsigned NumElems = VT.getVectorNumElements();
19802
19803   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
19804       V2.getOpcode() == ISD::CONCAT_VECTORS) {
19805     //
19806     //                   0,0,0,...
19807     //                      |
19808     //    V      UNDEF    BUILD_VECTOR    UNDEF
19809     //     \      /           \           /
19810     //  CONCAT_VECTOR         CONCAT_VECTOR
19811     //         \                  /
19812     //          \                /
19813     //          RESULT: V + zero extended
19814     //
19815     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
19816         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
19817         V1.getOperand(1).getOpcode() != ISD::UNDEF)
19818       return SDValue();
19819
19820     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
19821       return SDValue();
19822
19823     // To match the shuffle mask, the first half of the mask should
19824     // be exactly the first vector, and all the rest a splat with the
19825     // first element of the second one.
19826     for (unsigned i = 0; i != NumElems/2; ++i)
19827       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
19828           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
19829         return SDValue();
19830
19831     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
19832     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
19833       if (Ld->hasNUsesOfValue(1, 0)) {
19834         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
19835         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
19836         SDValue ResNode =
19837           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
19838                                   Ld->getMemoryVT(),
19839                                   Ld->getPointerInfo(),
19840                                   Ld->getAlignment(),
19841                                   false/*isVolatile*/, true/*ReadMem*/,
19842                                   false/*WriteMem*/);
19843
19844         // Make sure the newly-created LOAD is in the same position as Ld in
19845         // terms of dependency. We create a TokenFactor for Ld and ResNode,
19846         // and update uses of Ld's output chain to use the TokenFactor.
19847         if (Ld->hasAnyUseOfValue(1)) {
19848           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
19849                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
19850           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
19851           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
19852                                  SDValue(ResNode.getNode(), 1));
19853         }
19854
19855         return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
19856       }
19857     }
19858
19859     // Emit a zeroed vector and insert the desired subvector on its
19860     // first half.
19861     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
19862     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
19863     return DCI.CombineTo(N, InsV);
19864   }
19865
19866   //===--------------------------------------------------------------------===//
19867   // Combine some shuffles into subvector extracts and inserts:
19868   //
19869
19870   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
19871   if (isShuffleHigh128VectorInsertLow(SVOp)) {
19872     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
19873     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
19874     return DCI.CombineTo(N, InsV);
19875   }
19876
19877   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
19878   if (isShuffleLow128VectorInsertHigh(SVOp)) {
19879     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
19880     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
19881     return DCI.CombineTo(N, InsV);
19882   }
19883
19884   return SDValue();
19885 }
19886
19887 /// \brief Combine an arbitrary chain of shuffles into a single instruction if
19888 /// possible.
19889 ///
19890 /// This is the leaf of the recursive combinine below. When we have found some
19891 /// chain of single-use x86 shuffle instructions and accumulated the combined
19892 /// shuffle mask represented by them, this will try to pattern match that mask
19893 /// into either a single instruction if there is a special purpose instruction
19894 /// for this operation, or into a PSHUFB instruction which is a fully general
19895 /// instruction but should only be used to replace chains over a certain depth.
19896 static bool combineX86ShuffleChain(SDValue Op, SDValue Root, ArrayRef<int> Mask,
19897                                    int Depth, bool HasPSHUFB, SelectionDAG &DAG,
19898                                    TargetLowering::DAGCombinerInfo &DCI,
19899                                    const X86Subtarget *Subtarget) {
19900   assert(!Mask.empty() && "Cannot combine an empty shuffle mask!");
19901
19902   // Find the operand that enters the chain. Note that multiple uses are OK
19903   // here, we're not going to remove the operand we find.
19904   SDValue Input = Op.getOperand(0);
19905   while (Input.getOpcode() == ISD::BITCAST)
19906     Input = Input.getOperand(0);
19907
19908   MVT VT = Input.getSimpleValueType();
19909   MVT RootVT = Root.getSimpleValueType();
19910   SDLoc DL(Root);
19911
19912   // Just remove no-op shuffle masks.
19913   if (Mask.size() == 1) {
19914     DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Input),
19915                   /*AddTo*/ true);
19916     return true;
19917   }
19918
19919   // Use the float domain if the operand type is a floating point type.
19920   bool FloatDomain = VT.isFloatingPoint();
19921
19922   // For floating point shuffles, we don't have free copies in the shuffle
19923   // instructions or the ability to load as part of the instruction, so
19924   // canonicalize their shuffles to UNPCK or MOV variants.
19925   //
19926   // Note that even with AVX we prefer the PSHUFD form of shuffle for integer
19927   // vectors because it can have a load folded into it that UNPCK cannot. This
19928   // doesn't preclude something switching to the shorter encoding post-RA.
19929   //
19930   // FIXME: Should teach these routines about AVX vector widths.
19931   if (FloatDomain && VT.getSizeInBits() == 128) {
19932     if (Mask.equals({0, 0}) || Mask.equals({1, 1})) {
19933       bool Lo = Mask.equals({0, 0});
19934       unsigned Shuffle;
19935       MVT ShuffleVT;
19936       // Check if we have SSE3 which will let us use MOVDDUP. That instruction
19937       // is no slower than UNPCKLPD but has the option to fold the input operand
19938       // into even an unaligned memory load.
19939       if (Lo && Subtarget->hasSSE3()) {
19940         Shuffle = X86ISD::MOVDDUP;
19941         ShuffleVT = MVT::v2f64;
19942       } else {
19943         // We have MOVLHPS and MOVHLPS throughout SSE and they encode smaller
19944         // than the UNPCK variants.
19945         Shuffle = Lo ? X86ISD::MOVLHPS : X86ISD::MOVHLPS;
19946         ShuffleVT = MVT::v4f32;
19947       }
19948       if (Depth == 1 && Root->getOpcode() == Shuffle)
19949         return false; // Nothing to do!
19950       Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
19951       DCI.AddToWorklist(Op.getNode());
19952       if (Shuffle == X86ISD::MOVDDUP)
19953         Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
19954       else
19955         Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
19956       DCI.AddToWorklist(Op.getNode());
19957       DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
19958                     /*AddTo*/ true);
19959       return true;
19960     }
19961     if (Subtarget->hasSSE3() &&
19962         (Mask.equals({0, 0, 2, 2}) || Mask.equals({1, 1, 3, 3}))) {
19963       bool Lo = Mask.equals({0, 0, 2, 2});
19964       unsigned Shuffle = Lo ? X86ISD::MOVSLDUP : X86ISD::MOVSHDUP;
19965       MVT ShuffleVT = MVT::v4f32;
19966       if (Depth == 1 && Root->getOpcode() == Shuffle)
19967         return false; // Nothing to do!
19968       Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
19969       DCI.AddToWorklist(Op.getNode());
19970       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
19971       DCI.AddToWorklist(Op.getNode());
19972       DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
19973                     /*AddTo*/ true);
19974       return true;
19975     }
19976     if (Mask.equals({0, 0, 1, 1}) || Mask.equals({2, 2, 3, 3})) {
19977       bool Lo = Mask.equals({0, 0, 1, 1});
19978       unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
19979       MVT ShuffleVT = MVT::v4f32;
19980       if (Depth == 1 && Root->getOpcode() == Shuffle)
19981         return false; // Nothing to do!
19982       Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
19983       DCI.AddToWorklist(Op.getNode());
19984       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
19985       DCI.AddToWorklist(Op.getNode());
19986       DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
19987                     /*AddTo*/ true);
19988       return true;
19989     }
19990   }
19991
19992   // We always canonicalize the 8 x i16 and 16 x i8 shuffles into their UNPCK
19993   // variants as none of these have single-instruction variants that are
19994   // superior to the UNPCK formulation.
19995   if (!FloatDomain && VT.getSizeInBits() == 128 &&
19996       (Mask.equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
19997        Mask.equals({4, 4, 5, 5, 6, 6, 7, 7}) ||
19998        Mask.equals({0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7}) ||
19999        Mask.equals(
20000            {8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15, 15}))) {
20001     bool Lo = Mask[0] == 0;
20002     unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
20003     if (Depth == 1 && Root->getOpcode() == Shuffle)
20004       return false; // Nothing to do!
20005     MVT ShuffleVT;
20006     switch (Mask.size()) {
20007     case 8:
20008       ShuffleVT = MVT::v8i16;
20009       break;
20010     case 16:
20011       ShuffleVT = MVT::v16i8;
20012       break;
20013     default:
20014       llvm_unreachable("Impossible mask size!");
20015     };
20016     Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
20017     DCI.AddToWorklist(Op.getNode());
20018     Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
20019     DCI.AddToWorklist(Op.getNode());
20020     DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
20021                   /*AddTo*/ true);
20022     return true;
20023   }
20024
20025   // Don't try to re-form single instruction chains under any circumstances now
20026   // that we've done encoding canonicalization for them.
20027   if (Depth < 2)
20028     return false;
20029
20030   // If we have 3 or more shuffle instructions or a chain involving PSHUFB, we
20031   // can replace them with a single PSHUFB instruction profitably. Intel's
20032   // manuals suggest only using PSHUFB if doing so replacing 5 instructions, but
20033   // in practice PSHUFB tends to be *very* fast so we're more aggressive.
20034   if ((Depth >= 3 || HasPSHUFB) && Subtarget->hasSSSE3()) {
20035     SmallVector<SDValue, 16> PSHUFBMask;
20036     int NumBytes = VT.getSizeInBits() / 8;
20037     int Ratio = NumBytes / Mask.size();
20038     for (int i = 0; i < NumBytes; ++i) {
20039       if (Mask[i / Ratio] == SM_SentinelUndef) {
20040         PSHUFBMask.push_back(DAG.getUNDEF(MVT::i8));
20041         continue;
20042       }
20043       int M = Mask[i / Ratio] != SM_SentinelZero
20044                   ? Ratio * Mask[i / Ratio] + i % Ratio
20045                   : 255;
20046       PSHUFBMask.push_back(DAG.getConstant(M, DL, MVT::i8));
20047     }
20048     MVT ByteVT = MVT::getVectorVT(MVT::i8, NumBytes);
20049     Op = DAG.getNode(ISD::BITCAST, DL, ByteVT, Input);
20050     DCI.AddToWorklist(Op.getNode());
20051     SDValue PSHUFBMaskOp =
20052         DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVT, PSHUFBMask);
20053     DCI.AddToWorklist(PSHUFBMaskOp.getNode());
20054     Op = DAG.getNode(X86ISD::PSHUFB, DL, ByteVT, Op, PSHUFBMaskOp);
20055     DCI.AddToWorklist(Op.getNode());
20056     DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
20057                   /*AddTo*/ true);
20058     return true;
20059   }
20060
20061   // Failed to find any combines.
20062   return false;
20063 }
20064
20065 /// \brief Fully generic combining of x86 shuffle instructions.
20066 ///
20067 /// This should be the last combine run over the x86 shuffle instructions. Once
20068 /// they have been fully optimized, this will recursively consider all chains
20069 /// of single-use shuffle instructions, build a generic model of the cumulative
20070 /// shuffle operation, and check for simpler instructions which implement this
20071 /// operation. We use this primarily for two purposes:
20072 ///
20073 /// 1) Collapse generic shuffles to specialized single instructions when
20074 ///    equivalent. In most cases, this is just an encoding size win, but
20075 ///    sometimes we will collapse multiple generic shuffles into a single
20076 ///    special-purpose shuffle.
20077 /// 2) Look for sequences of shuffle instructions with 3 or more total
20078 ///    instructions, and replace them with the slightly more expensive SSSE3
20079 ///    PSHUFB instruction if available. We do this as the last combining step
20080 ///    to ensure we avoid using PSHUFB if we can implement the shuffle with
20081 ///    a suitable short sequence of other instructions. The PHUFB will either
20082 ///    use a register or have to read from memory and so is slightly (but only
20083 ///    slightly) more expensive than the other shuffle instructions.
20084 ///
20085 /// Because this is inherently a quadratic operation (for each shuffle in
20086 /// a chain, we recurse up the chain), the depth is limited to 8 instructions.
20087 /// This should never be an issue in practice as the shuffle lowering doesn't
20088 /// produce sequences of more than 8 instructions.
20089 ///
20090 /// FIXME: We will currently miss some cases where the redundant shuffling
20091 /// would simplify under the threshold for PSHUFB formation because of
20092 /// combine-ordering. To fix this, we should do the redundant instruction
20093 /// combining in this recursive walk.
20094 static bool combineX86ShufflesRecursively(SDValue Op, SDValue Root,
20095                                           ArrayRef<int> RootMask,
20096                                           int Depth, bool HasPSHUFB,
20097                                           SelectionDAG &DAG,
20098                                           TargetLowering::DAGCombinerInfo &DCI,
20099                                           const X86Subtarget *Subtarget) {
20100   // Bound the depth of our recursive combine because this is ultimately
20101   // quadratic in nature.
20102   if (Depth > 8)
20103     return false;
20104
20105   // Directly rip through bitcasts to find the underlying operand.
20106   while (Op.getOpcode() == ISD::BITCAST && Op.getOperand(0).hasOneUse())
20107     Op = Op.getOperand(0);
20108
20109   MVT VT = Op.getSimpleValueType();
20110   if (!VT.isVector())
20111     return false; // Bail if we hit a non-vector.
20112
20113   assert(Root.getSimpleValueType().isVector() &&
20114          "Shuffles operate on vector types!");
20115   assert(VT.getSizeInBits() == Root.getSimpleValueType().getSizeInBits() &&
20116          "Can only combine shuffles of the same vector register size.");
20117
20118   if (!isTargetShuffle(Op.getOpcode()))
20119     return false;
20120   SmallVector<int, 16> OpMask;
20121   bool IsUnary;
20122   bool HaveMask = getTargetShuffleMask(Op.getNode(), VT, OpMask, IsUnary);
20123   // We only can combine unary shuffles which we can decode the mask for.
20124   if (!HaveMask || !IsUnary)
20125     return false;
20126
20127   assert(VT.getVectorNumElements() == OpMask.size() &&
20128          "Different mask size from vector size!");
20129   assert(((RootMask.size() > OpMask.size() &&
20130            RootMask.size() % OpMask.size() == 0) ||
20131           (OpMask.size() > RootMask.size() &&
20132            OpMask.size() % RootMask.size() == 0) ||
20133           OpMask.size() == RootMask.size()) &&
20134          "The smaller number of elements must divide the larger.");
20135   int RootRatio = std::max<int>(1, OpMask.size() / RootMask.size());
20136   int OpRatio = std::max<int>(1, RootMask.size() / OpMask.size());
20137   assert(((RootRatio == 1 && OpRatio == 1) ||
20138           (RootRatio == 1) != (OpRatio == 1)) &&
20139          "Must not have a ratio for both incoming and op masks!");
20140
20141   SmallVector<int, 16> Mask;
20142   Mask.reserve(std::max(OpMask.size(), RootMask.size()));
20143
20144   // Merge this shuffle operation's mask into our accumulated mask. Note that
20145   // this shuffle's mask will be the first applied to the input, followed by the
20146   // root mask to get us all the way to the root value arrangement. The reason
20147   // for this order is that we are recursing up the operation chain.
20148   for (int i = 0, e = std::max(OpMask.size(), RootMask.size()); i < e; ++i) {
20149     int RootIdx = i / RootRatio;
20150     if (RootMask[RootIdx] < 0) {
20151       // This is a zero or undef lane, we're done.
20152       Mask.push_back(RootMask[RootIdx]);
20153       continue;
20154     }
20155
20156     int RootMaskedIdx = RootMask[RootIdx] * RootRatio + i % RootRatio;
20157     int OpIdx = RootMaskedIdx / OpRatio;
20158     if (OpMask[OpIdx] < 0) {
20159       // The incoming lanes are zero or undef, it doesn't matter which ones we
20160       // are using.
20161       Mask.push_back(OpMask[OpIdx]);
20162       continue;
20163     }
20164
20165     // Ok, we have non-zero lanes, map them through.
20166     Mask.push_back(OpMask[OpIdx] * OpRatio +
20167                    RootMaskedIdx % OpRatio);
20168   }
20169
20170   // See if we can recurse into the operand to combine more things.
20171   switch (Op.getOpcode()) {
20172     case X86ISD::PSHUFB:
20173       HasPSHUFB = true;
20174     case X86ISD::PSHUFD:
20175     case X86ISD::PSHUFHW:
20176     case X86ISD::PSHUFLW:
20177       if (Op.getOperand(0).hasOneUse() &&
20178           combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
20179                                         HasPSHUFB, DAG, DCI, Subtarget))
20180         return true;
20181       break;
20182
20183     case X86ISD::UNPCKL:
20184     case X86ISD::UNPCKH:
20185       assert(Op.getOperand(0) == Op.getOperand(1) && "We only combine unary shuffles!");
20186       // We can't check for single use, we have to check that this shuffle is the only user.
20187       if (Op->isOnlyUserOf(Op.getOperand(0).getNode()) &&
20188           combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
20189                                         HasPSHUFB, DAG, DCI, Subtarget))
20190           return true;
20191       break;
20192   }
20193
20194   // Minor canonicalization of the accumulated shuffle mask to make it easier
20195   // to match below. All this does is detect masks with squential pairs of
20196   // elements, and shrink them to the half-width mask. It does this in a loop
20197   // so it will reduce the size of the mask to the minimal width mask which
20198   // performs an equivalent shuffle.
20199   SmallVector<int, 16> WidenedMask;
20200   while (Mask.size() > 1 && canWidenShuffleElements(Mask, WidenedMask)) {
20201     Mask = std::move(WidenedMask);
20202     WidenedMask.clear();
20203   }
20204
20205   return combineX86ShuffleChain(Op, Root, Mask, Depth, HasPSHUFB, DAG, DCI,
20206                                 Subtarget);
20207 }
20208
20209 /// \brief Get the PSHUF-style mask from PSHUF node.
20210 ///
20211 /// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
20212 /// PSHUF-style masks that can be reused with such instructions.
20213 static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
20214   MVT VT = N.getSimpleValueType();
20215   SmallVector<int, 4> Mask;
20216   bool IsUnary;
20217   bool HaveMask = getTargetShuffleMask(N.getNode(), VT, Mask, IsUnary);
20218   (void)HaveMask;
20219   assert(HaveMask);
20220
20221   // If we have more than 128-bits, only the low 128-bits of shuffle mask
20222   // matter. Check that the upper masks are repeats and remove them.
20223   if (VT.getSizeInBits() > 128) {
20224     int LaneElts = 128 / VT.getScalarSizeInBits();
20225 #ifndef NDEBUG
20226     for (int i = 1, NumLanes = VT.getSizeInBits() / 128; i < NumLanes; ++i)
20227       for (int j = 0; j < LaneElts; ++j)
20228         assert(Mask[j] == Mask[i * LaneElts + j] - LaneElts &&
20229                "Mask doesn't repeat in high 128-bit lanes!");
20230 #endif
20231     Mask.resize(LaneElts);
20232   }
20233
20234   switch (N.getOpcode()) {
20235   case X86ISD::PSHUFD:
20236     return Mask;
20237   case X86ISD::PSHUFLW:
20238     Mask.resize(4);
20239     return Mask;
20240   case X86ISD::PSHUFHW:
20241     Mask.erase(Mask.begin(), Mask.begin() + 4);
20242     for (int &M : Mask)
20243       M -= 4;
20244     return Mask;
20245   default:
20246     llvm_unreachable("No valid shuffle instruction found!");
20247   }
20248 }
20249
20250 /// \brief Search for a combinable shuffle across a chain ending in pshufd.
20251 ///
20252 /// We walk up the chain and look for a combinable shuffle, skipping over
20253 /// shuffles that we could hoist this shuffle's transformation past without
20254 /// altering anything.
20255 static SDValue
20256 combineRedundantDWordShuffle(SDValue N, MutableArrayRef<int> Mask,
20257                              SelectionDAG &DAG,
20258                              TargetLowering::DAGCombinerInfo &DCI) {
20259   assert(N.getOpcode() == X86ISD::PSHUFD &&
20260          "Called with something other than an x86 128-bit half shuffle!");
20261   SDLoc DL(N);
20262
20263   // Walk up a single-use chain looking for a combinable shuffle. Keep a stack
20264   // of the shuffles in the chain so that we can form a fresh chain to replace
20265   // this one.
20266   SmallVector<SDValue, 8> Chain;
20267   SDValue V = N.getOperand(0);
20268   for (; V.hasOneUse(); V = V.getOperand(0)) {
20269     switch (V.getOpcode()) {
20270     default:
20271       return SDValue(); // Nothing combined!
20272
20273     case ISD::BITCAST:
20274       // Skip bitcasts as we always know the type for the target specific
20275       // instructions.
20276       continue;
20277
20278     case X86ISD::PSHUFD:
20279       // Found another dword shuffle.
20280       break;
20281
20282     case X86ISD::PSHUFLW:
20283       // Check that the low words (being shuffled) are the identity in the
20284       // dword shuffle, and the high words are self-contained.
20285       if (Mask[0] != 0 || Mask[1] != 1 ||
20286           !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
20287         return SDValue();
20288
20289       Chain.push_back(V);
20290       continue;
20291
20292     case X86ISD::PSHUFHW:
20293       // Check that the high words (being shuffled) are the identity in the
20294       // dword shuffle, and the low words are self-contained.
20295       if (Mask[2] != 2 || Mask[3] != 3 ||
20296           !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
20297         return SDValue();
20298
20299       Chain.push_back(V);
20300       continue;
20301
20302     case X86ISD::UNPCKL:
20303     case X86ISD::UNPCKH:
20304       // For either i8 -> i16 or i16 -> i32 unpacks, we can combine a dword
20305       // shuffle into a preceding word shuffle.
20306       if (V.getSimpleValueType().getScalarType() != MVT::i8 &&
20307           V.getSimpleValueType().getScalarType() != MVT::i16)
20308         return SDValue();
20309
20310       // Search for a half-shuffle which we can combine with.
20311       unsigned CombineOp =
20312           V.getOpcode() == X86ISD::UNPCKL ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
20313       if (V.getOperand(0) != V.getOperand(1) ||
20314           !V->isOnlyUserOf(V.getOperand(0).getNode()))
20315         return SDValue();
20316       Chain.push_back(V);
20317       V = V.getOperand(0);
20318       do {
20319         switch (V.getOpcode()) {
20320         default:
20321           return SDValue(); // Nothing to combine.
20322
20323         case X86ISD::PSHUFLW:
20324         case X86ISD::PSHUFHW:
20325           if (V.getOpcode() == CombineOp)
20326             break;
20327
20328           Chain.push_back(V);
20329
20330           // Fallthrough!
20331         case ISD::BITCAST:
20332           V = V.getOperand(0);
20333           continue;
20334         }
20335         break;
20336       } while (V.hasOneUse());
20337       break;
20338     }
20339     // Break out of the loop if we break out of the switch.
20340     break;
20341   }
20342
20343   if (!V.hasOneUse())
20344     // We fell out of the loop without finding a viable combining instruction.
20345     return SDValue();
20346
20347   // Merge this node's mask and our incoming mask.
20348   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
20349   for (int &M : Mask)
20350     M = VMask[M];
20351   V = DAG.getNode(V.getOpcode(), DL, V.getValueType(), V.getOperand(0),
20352                   getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
20353
20354   // Rebuild the chain around this new shuffle.
20355   while (!Chain.empty()) {
20356     SDValue W = Chain.pop_back_val();
20357
20358     if (V.getValueType() != W.getOperand(0).getValueType())
20359       V = DAG.getNode(ISD::BITCAST, DL, W.getOperand(0).getValueType(), V);
20360
20361     switch (W.getOpcode()) {
20362     default:
20363       llvm_unreachable("Only PSHUF and UNPCK instructions get here!");
20364
20365     case X86ISD::UNPCKL:
20366     case X86ISD::UNPCKH:
20367       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, V);
20368       break;
20369
20370     case X86ISD::PSHUFD:
20371     case X86ISD::PSHUFLW:
20372     case X86ISD::PSHUFHW:
20373       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, W.getOperand(1));
20374       break;
20375     }
20376   }
20377   if (V.getValueType() != N.getValueType())
20378     V = DAG.getNode(ISD::BITCAST, DL, N.getValueType(), V);
20379
20380   // Return the new chain to replace N.
20381   return V;
20382 }
20383
20384 /// \brief Search for a combinable shuffle across a chain ending in pshuflw or pshufhw.
20385 ///
20386 /// We walk up the chain, skipping shuffles of the other half and looking
20387 /// through shuffles which switch halves trying to find a shuffle of the same
20388 /// pair of dwords.
20389 static bool combineRedundantHalfShuffle(SDValue N, MutableArrayRef<int> Mask,
20390                                         SelectionDAG &DAG,
20391                                         TargetLowering::DAGCombinerInfo &DCI) {
20392   assert(
20393       (N.getOpcode() == X86ISD::PSHUFLW || N.getOpcode() == X86ISD::PSHUFHW) &&
20394       "Called with something other than an x86 128-bit half shuffle!");
20395   SDLoc DL(N);
20396   unsigned CombineOpcode = N.getOpcode();
20397
20398   // Walk up a single-use chain looking for a combinable shuffle.
20399   SDValue V = N.getOperand(0);
20400   for (; V.hasOneUse(); V = V.getOperand(0)) {
20401     switch (V.getOpcode()) {
20402     default:
20403       return false; // Nothing combined!
20404
20405     case ISD::BITCAST:
20406       // Skip bitcasts as we always know the type for the target specific
20407       // instructions.
20408       continue;
20409
20410     case X86ISD::PSHUFLW:
20411     case X86ISD::PSHUFHW:
20412       if (V.getOpcode() == CombineOpcode)
20413         break;
20414
20415       // Other-half shuffles are no-ops.
20416       continue;
20417     }
20418     // Break out of the loop if we break out of the switch.
20419     break;
20420   }
20421
20422   if (!V.hasOneUse())
20423     // We fell out of the loop without finding a viable combining instruction.
20424     return false;
20425
20426   // Combine away the bottom node as its shuffle will be accumulated into
20427   // a preceding shuffle.
20428   DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
20429
20430   // Record the old value.
20431   SDValue Old = V;
20432
20433   // Merge this node's mask and our incoming mask (adjusted to account for all
20434   // the pshufd instructions encountered).
20435   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
20436   for (int &M : Mask)
20437     M = VMask[M];
20438   V = DAG.getNode(V.getOpcode(), DL, MVT::v8i16, V.getOperand(0),
20439                   getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
20440
20441   // Check that the shuffles didn't cancel each other out. If not, we need to
20442   // combine to the new one.
20443   if (Old != V)
20444     // Replace the combinable shuffle with the combined one, updating all users
20445     // so that we re-evaluate the chain here.
20446     DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
20447
20448   return true;
20449 }
20450
20451 /// \brief Try to combine x86 target specific shuffles.
20452 static SDValue PerformTargetShuffleCombine(SDValue N, SelectionDAG &DAG,
20453                                            TargetLowering::DAGCombinerInfo &DCI,
20454                                            const X86Subtarget *Subtarget) {
20455   SDLoc DL(N);
20456   MVT VT = N.getSimpleValueType();
20457   SmallVector<int, 4> Mask;
20458
20459   switch (N.getOpcode()) {
20460   case X86ISD::PSHUFD:
20461   case X86ISD::PSHUFLW:
20462   case X86ISD::PSHUFHW:
20463     Mask = getPSHUFShuffleMask(N);
20464     assert(Mask.size() == 4);
20465     break;
20466   default:
20467     return SDValue();
20468   }
20469
20470   // Nuke no-op shuffles that show up after combining.
20471   if (isNoopShuffleMask(Mask))
20472     return DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
20473
20474   // Look for simplifications involving one or two shuffle instructions.
20475   SDValue V = N.getOperand(0);
20476   switch (N.getOpcode()) {
20477   default:
20478     break;
20479   case X86ISD::PSHUFLW:
20480   case X86ISD::PSHUFHW:
20481     assert(VT.getScalarType() == MVT::i16 && "Bad word shuffle type!");
20482
20483     if (combineRedundantHalfShuffle(N, Mask, DAG, DCI))
20484       return SDValue(); // We combined away this shuffle, so we're done.
20485
20486     // See if this reduces to a PSHUFD which is no more expensive and can
20487     // combine with more operations. Note that it has to at least flip the
20488     // dwords as otherwise it would have been removed as a no-op.
20489     if (makeArrayRef(Mask).equals({2, 3, 0, 1})) {
20490       int DMask[] = {0, 1, 2, 3};
20491       int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
20492       DMask[DOffset + 0] = DOffset + 1;
20493       DMask[DOffset + 1] = DOffset + 0;
20494       MVT DVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
20495       V = DAG.getNode(ISD::BITCAST, DL, DVT, V);
20496       DCI.AddToWorklist(V.getNode());
20497       V = DAG.getNode(X86ISD::PSHUFD, DL, DVT, V,
20498                       getV4X86ShuffleImm8ForMask(DMask, DL, DAG));
20499       DCI.AddToWorklist(V.getNode());
20500       return DAG.getNode(ISD::BITCAST, DL, VT, V);
20501     }
20502
20503     // Look for shuffle patterns which can be implemented as a single unpack.
20504     // FIXME: This doesn't handle the location of the PSHUFD generically, and
20505     // only works when we have a PSHUFD followed by two half-shuffles.
20506     if (Mask[0] == Mask[1] && Mask[2] == Mask[3] &&
20507         (V.getOpcode() == X86ISD::PSHUFLW ||
20508          V.getOpcode() == X86ISD::PSHUFHW) &&
20509         V.getOpcode() != N.getOpcode() &&
20510         V.hasOneUse()) {
20511       SDValue D = V.getOperand(0);
20512       while (D.getOpcode() == ISD::BITCAST && D.hasOneUse())
20513         D = D.getOperand(0);
20514       if (D.getOpcode() == X86ISD::PSHUFD && D.hasOneUse()) {
20515         SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
20516         SmallVector<int, 4> DMask = getPSHUFShuffleMask(D);
20517         int NOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
20518         int VOffset = V.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
20519         int WordMask[8];
20520         for (int i = 0; i < 4; ++i) {
20521           WordMask[i + NOffset] = Mask[i] + NOffset;
20522           WordMask[i + VOffset] = VMask[i] + VOffset;
20523         }
20524         // Map the word mask through the DWord mask.
20525         int MappedMask[8];
20526         for (int i = 0; i < 8; ++i)
20527           MappedMask[i] = 2 * DMask[WordMask[i] / 2] + WordMask[i] % 2;
20528         if (makeArrayRef(MappedMask).equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
20529             makeArrayRef(MappedMask).equals({4, 4, 5, 5, 6, 6, 7, 7})) {
20530           // We can replace all three shuffles with an unpack.
20531           V = DAG.getNode(ISD::BITCAST, DL, VT, D.getOperand(0));
20532           DCI.AddToWorklist(V.getNode());
20533           return DAG.getNode(MappedMask[0] == 0 ? X86ISD::UNPCKL
20534                                                 : X86ISD::UNPCKH,
20535                              DL, VT, V, V);
20536         }
20537       }
20538     }
20539
20540     break;
20541
20542   case X86ISD::PSHUFD:
20543     if (SDValue NewN = combineRedundantDWordShuffle(N, Mask, DAG, DCI))
20544       return NewN;
20545
20546     break;
20547   }
20548
20549   return SDValue();
20550 }
20551
20552 /// \brief Try to combine a shuffle into a target-specific add-sub node.
20553 ///
20554 /// We combine this directly on the abstract vector shuffle nodes so it is
20555 /// easier to generically match. We also insert dummy vector shuffle nodes for
20556 /// the operands which explicitly discard the lanes which are unused by this
20557 /// operation to try to flow through the rest of the combiner the fact that
20558 /// they're unused.
20559 static SDValue combineShuffleToAddSub(SDNode *N, SelectionDAG &DAG) {
20560   SDLoc DL(N);
20561   EVT VT = N->getValueType(0);
20562
20563   // We only handle target-independent shuffles.
20564   // FIXME: It would be easy and harmless to use the target shuffle mask
20565   // extraction tool to support more.
20566   if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
20567     return SDValue();
20568
20569   auto *SVN = cast<ShuffleVectorSDNode>(N);
20570   ArrayRef<int> Mask = SVN->getMask();
20571   SDValue V1 = N->getOperand(0);
20572   SDValue V2 = N->getOperand(1);
20573
20574   // We require the first shuffle operand to be the SUB node, and the second to
20575   // be the ADD node.
20576   // FIXME: We should support the commuted patterns.
20577   if (V1->getOpcode() != ISD::FSUB || V2->getOpcode() != ISD::FADD)
20578     return SDValue();
20579
20580   // If there are other uses of these operations we can't fold them.
20581   if (!V1->hasOneUse() || !V2->hasOneUse())
20582     return SDValue();
20583
20584   // Ensure that both operations have the same operands. Note that we can
20585   // commute the FADD operands.
20586   SDValue LHS = V1->getOperand(0), RHS = V1->getOperand(1);
20587   if ((V2->getOperand(0) != LHS || V2->getOperand(1) != RHS) &&
20588       (V2->getOperand(0) != RHS || V2->getOperand(1) != LHS))
20589     return SDValue();
20590
20591   // We're looking for blends between FADD and FSUB nodes. We insist on these
20592   // nodes being lined up in a specific expected pattern.
20593   if (!(isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
20594         isShuffleEquivalent(V1, V2, Mask, {0, 5, 2, 7}) ||
20595         isShuffleEquivalent(V1, V2, Mask, {0, 9, 2, 11, 4, 13, 6, 15})))
20596     return SDValue();
20597
20598   // Only specific types are legal at this point, assert so we notice if and
20599   // when these change.
20600   assert((VT == MVT::v4f32 || VT == MVT::v2f64 || VT == MVT::v8f32 ||
20601           VT == MVT::v4f64) &&
20602          "Unknown vector type encountered!");
20603
20604   return DAG.getNode(X86ISD::ADDSUB, DL, VT, LHS, RHS);
20605 }
20606
20607 /// PerformShuffleCombine - Performs several different shuffle combines.
20608 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
20609                                      TargetLowering::DAGCombinerInfo &DCI,
20610                                      const X86Subtarget *Subtarget) {
20611   SDLoc dl(N);
20612   SDValue N0 = N->getOperand(0);
20613   SDValue N1 = N->getOperand(1);
20614   EVT VT = N->getValueType(0);
20615
20616   // Don't create instructions with illegal types after legalize types has run.
20617   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20618   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
20619     return SDValue();
20620
20621   // If we have legalized the vector types, look for blends of FADD and FSUB
20622   // nodes that we can fuse into an ADDSUB node.
20623   if (TLI.isTypeLegal(VT) && Subtarget->hasSSE3())
20624     if (SDValue AddSub = combineShuffleToAddSub(N, DAG))
20625       return AddSub;
20626
20627   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
20628   if (Subtarget->hasFp256() && VT.is256BitVector() &&
20629       N->getOpcode() == ISD::VECTOR_SHUFFLE)
20630     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
20631
20632   // During Type Legalization, when promoting illegal vector types,
20633   // the backend might introduce new shuffle dag nodes and bitcasts.
20634   //
20635   // This code performs the following transformation:
20636   // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
20637   //       (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
20638   //
20639   // We do this only if both the bitcast and the BINOP dag nodes have
20640   // one use. Also, perform this transformation only if the new binary
20641   // operation is legal. This is to avoid introducing dag nodes that
20642   // potentially need to be further expanded (or custom lowered) into a
20643   // less optimal sequence of dag nodes.
20644   if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
20645       N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
20646       N0.getOpcode() == ISD::BITCAST) {
20647     SDValue BC0 = N0.getOperand(0);
20648     EVT SVT = BC0.getValueType();
20649     unsigned Opcode = BC0.getOpcode();
20650     unsigned NumElts = VT.getVectorNumElements();
20651
20652     if (BC0.hasOneUse() && SVT.isVector() &&
20653         SVT.getVectorNumElements() * 2 == NumElts &&
20654         TLI.isOperationLegal(Opcode, VT)) {
20655       bool CanFold = false;
20656       switch (Opcode) {
20657       default : break;
20658       case ISD::ADD :
20659       case ISD::FADD :
20660       case ISD::SUB :
20661       case ISD::FSUB :
20662       case ISD::MUL :
20663       case ISD::FMUL :
20664         CanFold = true;
20665       }
20666
20667       unsigned SVTNumElts = SVT.getVectorNumElements();
20668       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
20669       for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
20670         CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
20671       for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
20672         CanFold = SVOp->getMaskElt(i) < 0;
20673
20674       if (CanFold) {
20675         SDValue BC00 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(0));
20676         SDValue BC01 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(1));
20677         SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
20678         return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
20679       }
20680     }
20681   }
20682
20683   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
20684   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
20685   // consecutive, non-overlapping, and in the right order.
20686   SmallVector<SDValue, 16> Elts;
20687   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
20688     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
20689
20690   SDValue LD = EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true);
20691   if (LD.getNode())
20692     return LD;
20693
20694   if (isTargetShuffle(N->getOpcode())) {
20695     SDValue Shuffle =
20696         PerformTargetShuffleCombine(SDValue(N, 0), DAG, DCI, Subtarget);
20697     if (Shuffle.getNode())
20698       return Shuffle;
20699
20700     // Try recursively combining arbitrary sequences of x86 shuffle
20701     // instructions into higher-order shuffles. We do this after combining
20702     // specific PSHUF instruction sequences into their minimal form so that we
20703     // can evaluate how many specialized shuffle instructions are involved in
20704     // a particular chain.
20705     SmallVector<int, 1> NonceMask; // Just a placeholder.
20706     NonceMask.push_back(0);
20707     if (combineX86ShufflesRecursively(SDValue(N, 0), SDValue(N, 0), NonceMask,
20708                                       /*Depth*/ 1, /*HasPSHUFB*/ false, DAG,
20709                                       DCI, Subtarget))
20710       return SDValue(); // This routine will use CombineTo to replace N.
20711   }
20712
20713   return SDValue();
20714 }
20715
20716 /// PerformTruncateCombine - Converts truncate operation to
20717 /// a sequence of vector shuffle operations.
20718 /// It is possible when we truncate 256-bit vector to 128-bit vector
20719 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
20720                                       TargetLowering::DAGCombinerInfo &DCI,
20721                                       const X86Subtarget *Subtarget)  {
20722   return SDValue();
20723 }
20724
20725 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
20726 /// specific shuffle of a load can be folded into a single element load.
20727 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
20728 /// shuffles have been custom lowered so we need to handle those here.
20729 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
20730                                          TargetLowering::DAGCombinerInfo &DCI) {
20731   if (DCI.isBeforeLegalizeOps())
20732     return SDValue();
20733
20734   SDValue InVec = N->getOperand(0);
20735   SDValue EltNo = N->getOperand(1);
20736
20737   if (!isa<ConstantSDNode>(EltNo))
20738     return SDValue();
20739
20740   EVT OriginalVT = InVec.getValueType();
20741
20742   if (InVec.getOpcode() == ISD::BITCAST) {
20743     // Don't duplicate a load with other uses.
20744     if (!InVec.hasOneUse())
20745       return SDValue();
20746     EVT BCVT = InVec.getOperand(0).getValueType();
20747     if (BCVT.getVectorNumElements() != OriginalVT.getVectorNumElements())
20748       return SDValue();
20749     InVec = InVec.getOperand(0);
20750   }
20751
20752   EVT CurrentVT = InVec.getValueType();
20753
20754   if (!isTargetShuffle(InVec.getOpcode()))
20755     return SDValue();
20756
20757   // Don't duplicate a load with other uses.
20758   if (!InVec.hasOneUse())
20759     return SDValue();
20760
20761   SmallVector<int, 16> ShuffleMask;
20762   bool UnaryShuffle;
20763   if (!getTargetShuffleMask(InVec.getNode(), CurrentVT.getSimpleVT(),
20764                             ShuffleMask, UnaryShuffle))
20765     return SDValue();
20766
20767   // Select the input vector, guarding against out of range extract vector.
20768   unsigned NumElems = CurrentVT.getVectorNumElements();
20769   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
20770   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
20771   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
20772                                          : InVec.getOperand(1);
20773
20774   // If inputs to shuffle are the same for both ops, then allow 2 uses
20775   unsigned AllowedUses = InVec.getNumOperands() > 1 &&
20776                          InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
20777
20778   if (LdNode.getOpcode() == ISD::BITCAST) {
20779     // Don't duplicate a load with other uses.
20780     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
20781       return SDValue();
20782
20783     AllowedUses = 1; // only allow 1 load use if we have a bitcast
20784     LdNode = LdNode.getOperand(0);
20785   }
20786
20787   if (!ISD::isNormalLoad(LdNode.getNode()))
20788     return SDValue();
20789
20790   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
20791
20792   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
20793     return SDValue();
20794
20795   EVT EltVT = N->getValueType(0);
20796   // If there's a bitcast before the shuffle, check if the load type and
20797   // alignment is valid.
20798   unsigned Align = LN0->getAlignment();
20799   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20800   unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment(
20801       EltVT.getTypeForEVT(*DAG.getContext()));
20802
20803   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, EltVT))
20804     return SDValue();
20805
20806   // All checks match so transform back to vector_shuffle so that DAG combiner
20807   // can finish the job
20808   SDLoc dl(N);
20809
20810   // Create shuffle node taking into account the case that its a unary shuffle
20811   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(CurrentVT)
20812                                    : InVec.getOperand(1);
20813   Shuffle = DAG.getVectorShuffle(CurrentVT, dl,
20814                                  InVec.getOperand(0), Shuffle,
20815                                  &ShuffleMask[0]);
20816   Shuffle = DAG.getNode(ISD::BITCAST, dl, OriginalVT, Shuffle);
20817   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
20818                      EltNo);
20819 }
20820
20821 /// \brief Detect bitcasts between i32 to x86mmx low word. Since MMX types are
20822 /// special and don't usually play with other vector types, it's better to
20823 /// handle them early to be sure we emit efficient code by avoiding
20824 /// store-load conversions.
20825 static SDValue PerformBITCASTCombine(SDNode *N, SelectionDAG &DAG) {
20826   if (N->getValueType(0) != MVT::x86mmx ||
20827       N->getOperand(0)->getOpcode() != ISD::BUILD_VECTOR ||
20828       N->getOperand(0)->getValueType(0) != MVT::v2i32)
20829     return SDValue();
20830
20831   SDValue V = N->getOperand(0);
20832   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V.getOperand(1));
20833   if (C && C->getZExtValue() == 0 && V.getOperand(0).getValueType() == MVT::i32)
20834     return DAG.getNode(X86ISD::MMX_MOVW2D, SDLoc(V.getOperand(0)),
20835                        N->getValueType(0), V.getOperand(0));
20836
20837   return SDValue();
20838 }
20839
20840 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
20841 /// generation and convert it from being a bunch of shuffles and extracts
20842 /// into a somewhat faster sequence. For i686, the best sequence is apparently
20843 /// storing the value and loading scalars back, while for x64 we should
20844 /// use 64-bit extracts and shifts.
20845 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
20846                                          TargetLowering::DAGCombinerInfo &DCI) {
20847   SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
20848   if (NewOp.getNode())
20849     return NewOp;
20850
20851   SDValue InputVector = N->getOperand(0);
20852
20853   // Detect mmx to i32 conversion through a v2i32 elt extract.
20854   if (InputVector.getOpcode() == ISD::BITCAST && InputVector.hasOneUse() &&
20855       N->getValueType(0) == MVT::i32 &&
20856       InputVector.getValueType() == MVT::v2i32) {
20857
20858     // The bitcast source is a direct mmx result.
20859     SDValue MMXSrc = InputVector.getNode()->getOperand(0);
20860     if (MMXSrc.getValueType() == MVT::x86mmx)
20861       return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
20862                          N->getValueType(0),
20863                          InputVector.getNode()->getOperand(0));
20864
20865     // The mmx is indirect: (i64 extract_elt (v1i64 bitcast (x86mmx ...))).
20866     SDValue MMXSrcOp = MMXSrc.getOperand(0);
20867     if (MMXSrc.getOpcode() == ISD::EXTRACT_VECTOR_ELT && MMXSrc.hasOneUse() &&
20868         MMXSrc.getValueType() == MVT::i64 && MMXSrcOp.hasOneUse() &&
20869         MMXSrcOp.getOpcode() == ISD::BITCAST &&
20870         MMXSrcOp.getValueType() == MVT::v1i64 &&
20871         MMXSrcOp.getOperand(0).getValueType() == MVT::x86mmx)
20872       return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
20873                          N->getValueType(0),
20874                          MMXSrcOp.getOperand(0));
20875   }
20876
20877   // Only operate on vectors of 4 elements, where the alternative shuffling
20878   // gets to be more expensive.
20879   if (InputVector.getValueType() != MVT::v4i32)
20880     return SDValue();
20881
20882   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
20883   // single use which is a sign-extend or zero-extend, and all elements are
20884   // used.
20885   SmallVector<SDNode *, 4> Uses;
20886   unsigned ExtractedElements = 0;
20887   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
20888        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
20889     if (UI.getUse().getResNo() != InputVector.getResNo())
20890       return SDValue();
20891
20892     SDNode *Extract = *UI;
20893     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
20894       return SDValue();
20895
20896     if (Extract->getValueType(0) != MVT::i32)
20897       return SDValue();
20898     if (!Extract->hasOneUse())
20899       return SDValue();
20900     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
20901         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
20902       return SDValue();
20903     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
20904       return SDValue();
20905
20906     // Record which element was extracted.
20907     ExtractedElements |=
20908       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
20909
20910     Uses.push_back(Extract);
20911   }
20912
20913   // If not all the elements were used, this may not be worthwhile.
20914   if (ExtractedElements != 15)
20915     return SDValue();
20916
20917   // Ok, we've now decided to do the transformation.
20918   // If 64-bit shifts are legal, use the extract-shift sequence,
20919   // otherwise bounce the vector off the cache.
20920   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20921   SDValue Vals[4];
20922   SDLoc dl(InputVector);
20923
20924   if (TLI.isOperationLegal(ISD::SRA, MVT::i64)) {
20925     SDValue Cst = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, InputVector);
20926     EVT VecIdxTy = DAG.getTargetLoweringInfo().getVectorIdxTy();
20927     SDValue BottomHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
20928       DAG.getConstant(0, dl, VecIdxTy));
20929     SDValue TopHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
20930       DAG.getConstant(1, dl, VecIdxTy));
20931
20932     SDValue ShAmt = DAG.getConstant(32, dl,
20933       DAG.getTargetLoweringInfo().getShiftAmountTy(MVT::i64));
20934     Vals[0] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BottomHalf);
20935     Vals[1] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
20936       DAG.getNode(ISD::SRA, dl, MVT::i64, BottomHalf, ShAmt));
20937     Vals[2] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, TopHalf);
20938     Vals[3] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
20939       DAG.getNode(ISD::SRA, dl, MVT::i64, TopHalf, ShAmt));
20940   } else {
20941     // Store the value to a temporary stack slot.
20942     SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
20943     SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
20944       MachinePointerInfo(), false, false, 0);
20945
20946     EVT ElementType = InputVector.getValueType().getVectorElementType();
20947     unsigned EltSize = ElementType.getSizeInBits() / 8;
20948
20949     // Replace each use (extract) with a load of the appropriate element.
20950     for (unsigned i = 0; i < 4; ++i) {
20951       uint64_t Offset = EltSize * i;
20952       SDValue OffsetVal = DAG.getConstant(Offset, dl, TLI.getPointerTy());
20953
20954       SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
20955                                        StackPtr, OffsetVal);
20956
20957       // Load the scalar.
20958       Vals[i] = DAG.getLoad(ElementType, dl, Ch,
20959                             ScalarAddr, MachinePointerInfo(),
20960                             false, false, false, 0);
20961
20962     }
20963   }
20964
20965   // Replace the extracts
20966   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
20967     UE = Uses.end(); UI != UE; ++UI) {
20968     SDNode *Extract = *UI;
20969
20970     SDValue Idx = Extract->getOperand(1);
20971     uint64_t IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
20972     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), Vals[IdxVal]);
20973   }
20974
20975   // The replacement was made in place; don't return anything.
20976   return SDValue();
20977 }
20978
20979 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
20980 static std::pair<unsigned, bool>
20981 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
20982                    SelectionDAG &DAG, const X86Subtarget *Subtarget) {
20983   if (!VT.isVector())
20984     return std::make_pair(0, false);
20985
20986   bool NeedSplit = false;
20987   switch (VT.getSimpleVT().SimpleTy) {
20988   default: return std::make_pair(0, false);
20989   case MVT::v4i64:
20990   case MVT::v2i64:
20991     if (!Subtarget->hasVLX())
20992       return std::make_pair(0, false);
20993     break;
20994   case MVT::v64i8:
20995   case MVT::v32i16:
20996     if (!Subtarget->hasBWI())
20997       return std::make_pair(0, false);
20998     break;
20999   case MVT::v16i32:
21000   case MVT::v8i64:
21001     if (!Subtarget->hasAVX512())
21002       return std::make_pair(0, false);
21003     break;
21004   case MVT::v32i8:
21005   case MVT::v16i16:
21006   case MVT::v8i32:
21007     if (!Subtarget->hasAVX2())
21008       NeedSplit = true;
21009     if (!Subtarget->hasAVX())
21010       return std::make_pair(0, false);
21011     break;
21012   case MVT::v16i8:
21013   case MVT::v8i16:
21014   case MVT::v4i32:
21015     if (!Subtarget->hasSSE2())
21016       return std::make_pair(0, false);
21017   }
21018
21019   // SSE2 has only a small subset of the operations.
21020   bool hasUnsigned = Subtarget->hasSSE41() ||
21021                      (Subtarget->hasSSE2() && VT == MVT::v16i8);
21022   bool hasSigned = Subtarget->hasSSE41() ||
21023                    (Subtarget->hasSSE2() && VT == MVT::v8i16);
21024
21025   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
21026
21027   unsigned Opc = 0;
21028   // Check for x CC y ? x : y.
21029   if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
21030       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
21031     switch (CC) {
21032     default: break;
21033     case ISD::SETULT:
21034     case ISD::SETULE:
21035       Opc = hasUnsigned ? X86ISD::UMIN : 0u; break;
21036     case ISD::SETUGT:
21037     case ISD::SETUGE:
21038       Opc = hasUnsigned ? X86ISD::UMAX : 0u; break;
21039     case ISD::SETLT:
21040     case ISD::SETLE:
21041       Opc = hasSigned ? X86ISD::SMIN : 0u; break;
21042     case ISD::SETGT:
21043     case ISD::SETGE:
21044       Opc = hasSigned ? X86ISD::SMAX : 0u; break;
21045     }
21046   // Check for x CC y ? y : x -- a min/max with reversed arms.
21047   } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
21048              DAG.isEqualTo(RHS, Cond.getOperand(0))) {
21049     switch (CC) {
21050     default: break;
21051     case ISD::SETULT:
21052     case ISD::SETULE:
21053       Opc = hasUnsigned ? X86ISD::UMAX : 0u; break;
21054     case ISD::SETUGT:
21055     case ISD::SETUGE:
21056       Opc = hasUnsigned ? X86ISD::UMIN : 0u; break;
21057     case ISD::SETLT:
21058     case ISD::SETLE:
21059       Opc = hasSigned ? X86ISD::SMAX : 0u; break;
21060     case ISD::SETGT:
21061     case ISD::SETGE:
21062       Opc = hasSigned ? X86ISD::SMIN : 0u; break;
21063     }
21064   }
21065
21066   return std::make_pair(Opc, NeedSplit);
21067 }
21068
21069 static SDValue
21070 transformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
21071                                       const X86Subtarget *Subtarget) {
21072   SDLoc dl(N);
21073   SDValue Cond = N->getOperand(0);
21074   SDValue LHS = N->getOperand(1);
21075   SDValue RHS = N->getOperand(2);
21076
21077   if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
21078     SDValue CondSrc = Cond->getOperand(0);
21079     if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
21080       Cond = CondSrc->getOperand(0);
21081   }
21082
21083   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
21084     return SDValue();
21085
21086   // A vselect where all conditions and data are constants can be optimized into
21087   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
21088   if (ISD::isBuildVectorOfConstantSDNodes(LHS.getNode()) &&
21089       ISD::isBuildVectorOfConstantSDNodes(RHS.getNode()))
21090     return SDValue();
21091
21092   unsigned MaskValue = 0;
21093   if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
21094     return SDValue();
21095
21096   MVT VT = N->getSimpleValueType(0);
21097   unsigned NumElems = VT.getVectorNumElements();
21098   SmallVector<int, 8> ShuffleMask(NumElems, -1);
21099   for (unsigned i = 0; i < NumElems; ++i) {
21100     // Be sure we emit undef where we can.
21101     if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
21102       ShuffleMask[i] = -1;
21103     else
21104       ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
21105   }
21106
21107   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21108   if (!TLI.isShuffleMaskLegal(ShuffleMask, VT))
21109     return SDValue();
21110   return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
21111 }
21112
21113 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
21114 /// nodes.
21115 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
21116                                     TargetLowering::DAGCombinerInfo &DCI,
21117                                     const X86Subtarget *Subtarget) {
21118   SDLoc DL(N);
21119   SDValue Cond = N->getOperand(0);
21120   // Get the LHS/RHS of the select.
21121   SDValue LHS = N->getOperand(1);
21122   SDValue RHS = N->getOperand(2);
21123   EVT VT = LHS.getValueType();
21124   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21125
21126   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
21127   // instructions match the semantics of the common C idiom x<y?x:y but not
21128   // x<=y?x:y, because of how they handle negative zero (which can be
21129   // ignored in unsafe-math mode).
21130   // We also try to create v2f32 min/max nodes, which we later widen to v4f32.
21131   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
21132       VT != MVT::f80 && (TLI.isTypeLegal(VT) || VT == MVT::v2f32) &&
21133       (Subtarget->hasSSE2() ||
21134        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
21135     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
21136
21137     unsigned Opcode = 0;
21138     // Check for x CC y ? x : y.
21139     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
21140         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
21141       switch (CC) {
21142       default: break;
21143       case ISD::SETULT:
21144         // Converting this to a min would handle NaNs incorrectly, and swapping
21145         // the operands would cause it to handle comparisons between positive
21146         // and negative zero incorrectly.
21147         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
21148           if (!DAG.getTarget().Options.UnsafeFPMath &&
21149               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
21150             break;
21151           std::swap(LHS, RHS);
21152         }
21153         Opcode = X86ISD::FMIN;
21154         break;
21155       case ISD::SETOLE:
21156         // Converting this to a min would handle comparisons between positive
21157         // and negative zero incorrectly.
21158         if (!DAG.getTarget().Options.UnsafeFPMath &&
21159             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
21160           break;
21161         Opcode = X86ISD::FMIN;
21162         break;
21163       case ISD::SETULE:
21164         // Converting this to a min would handle both negative zeros and NaNs
21165         // incorrectly, but we can swap the operands to fix both.
21166         std::swap(LHS, RHS);
21167       case ISD::SETOLT:
21168       case ISD::SETLT:
21169       case ISD::SETLE:
21170         Opcode = X86ISD::FMIN;
21171         break;
21172
21173       case ISD::SETOGE:
21174         // Converting this to a max would handle comparisons between positive
21175         // and negative zero incorrectly.
21176         if (!DAG.getTarget().Options.UnsafeFPMath &&
21177             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
21178           break;
21179         Opcode = X86ISD::FMAX;
21180         break;
21181       case ISD::SETUGT:
21182         // Converting this to a max would handle NaNs incorrectly, and swapping
21183         // the operands would cause it to handle comparisons between positive
21184         // and negative zero incorrectly.
21185         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
21186           if (!DAG.getTarget().Options.UnsafeFPMath &&
21187               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
21188             break;
21189           std::swap(LHS, RHS);
21190         }
21191         Opcode = X86ISD::FMAX;
21192         break;
21193       case ISD::SETUGE:
21194         // Converting this to a max would handle both negative zeros and NaNs
21195         // incorrectly, but we can swap the operands to fix both.
21196         std::swap(LHS, RHS);
21197       case ISD::SETOGT:
21198       case ISD::SETGT:
21199       case ISD::SETGE:
21200         Opcode = X86ISD::FMAX;
21201         break;
21202       }
21203     // Check for x CC y ? y : x -- a min/max with reversed arms.
21204     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
21205                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
21206       switch (CC) {
21207       default: break;
21208       case ISD::SETOGE:
21209         // Converting this to a min would handle comparisons between positive
21210         // and negative zero incorrectly, and swapping the operands would
21211         // cause it to handle NaNs incorrectly.
21212         if (!DAG.getTarget().Options.UnsafeFPMath &&
21213             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
21214           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
21215             break;
21216           std::swap(LHS, RHS);
21217         }
21218         Opcode = X86ISD::FMIN;
21219         break;
21220       case ISD::SETUGT:
21221         // Converting this to a min would handle NaNs incorrectly.
21222         if (!DAG.getTarget().Options.UnsafeFPMath &&
21223             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
21224           break;
21225         Opcode = X86ISD::FMIN;
21226         break;
21227       case ISD::SETUGE:
21228         // Converting this to a min would handle both negative zeros and NaNs
21229         // incorrectly, but we can swap the operands to fix both.
21230         std::swap(LHS, RHS);
21231       case ISD::SETOGT:
21232       case ISD::SETGT:
21233       case ISD::SETGE:
21234         Opcode = X86ISD::FMIN;
21235         break;
21236
21237       case ISD::SETULT:
21238         // Converting this to a max would handle NaNs incorrectly.
21239         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
21240           break;
21241         Opcode = X86ISD::FMAX;
21242         break;
21243       case ISD::SETOLE:
21244         // Converting this to a max would handle comparisons between positive
21245         // and negative zero incorrectly, and swapping the operands would
21246         // cause it to handle NaNs incorrectly.
21247         if (!DAG.getTarget().Options.UnsafeFPMath &&
21248             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
21249           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
21250             break;
21251           std::swap(LHS, RHS);
21252         }
21253         Opcode = X86ISD::FMAX;
21254         break;
21255       case ISD::SETULE:
21256         // Converting this to a max would handle both negative zeros and NaNs
21257         // incorrectly, but we can swap the operands to fix both.
21258         std::swap(LHS, RHS);
21259       case ISD::SETOLT:
21260       case ISD::SETLT:
21261       case ISD::SETLE:
21262         Opcode = X86ISD::FMAX;
21263         break;
21264       }
21265     }
21266
21267     if (Opcode)
21268       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
21269   }
21270
21271   EVT CondVT = Cond.getValueType();
21272   if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
21273       CondVT.getVectorElementType() == MVT::i1) {
21274     // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
21275     // lowering on KNL. In this case we convert it to
21276     // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
21277     // The same situation for all 128 and 256-bit vectors of i8 and i16.
21278     // Since SKX these selects have a proper lowering.
21279     EVT OpVT = LHS.getValueType();
21280     if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
21281         (OpVT.getVectorElementType() == MVT::i8 ||
21282          OpVT.getVectorElementType() == MVT::i16) &&
21283         !(Subtarget->hasBWI() && Subtarget->hasVLX())) {
21284       Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
21285       DCI.AddToWorklist(Cond.getNode());
21286       return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
21287     }
21288   }
21289   // If this is a select between two integer constants, try to do some
21290   // optimizations.
21291   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
21292     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
21293       // Don't do this for crazy integer types.
21294       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
21295         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
21296         // so that TrueC (the true value) is larger than FalseC.
21297         bool NeedsCondInvert = false;
21298
21299         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
21300             // Efficiently invertible.
21301             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
21302              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
21303               isa<ConstantSDNode>(Cond.getOperand(1))))) {
21304           NeedsCondInvert = true;
21305           std::swap(TrueC, FalseC);
21306         }
21307
21308         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
21309         if (FalseC->getAPIntValue() == 0 &&
21310             TrueC->getAPIntValue().isPowerOf2()) {
21311           if (NeedsCondInvert) // Invert the condition if needed.
21312             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
21313                                DAG.getConstant(1, DL, Cond.getValueType()));
21314
21315           // Zero extend the condition if needed.
21316           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
21317
21318           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
21319           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
21320                              DAG.getConstant(ShAmt, DL, MVT::i8));
21321         }
21322
21323         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
21324         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
21325           if (NeedsCondInvert) // Invert the condition if needed.
21326             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
21327                                DAG.getConstant(1, DL, Cond.getValueType()));
21328
21329           // Zero extend the condition if needed.
21330           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
21331                              FalseC->getValueType(0), Cond);
21332           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
21333                              SDValue(FalseC, 0));
21334         }
21335
21336         // Optimize cases that will turn into an LEA instruction.  This requires
21337         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
21338         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
21339           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
21340           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
21341
21342           bool isFastMultiplier = false;
21343           if (Diff < 10) {
21344             switch ((unsigned char)Diff) {
21345               default: break;
21346               case 1:  // result = add base, cond
21347               case 2:  // result = lea base(    , cond*2)
21348               case 3:  // result = lea base(cond, cond*2)
21349               case 4:  // result = lea base(    , cond*4)
21350               case 5:  // result = lea base(cond, cond*4)
21351               case 8:  // result = lea base(    , cond*8)
21352               case 9:  // result = lea base(cond, cond*8)
21353                 isFastMultiplier = true;
21354                 break;
21355             }
21356           }
21357
21358           if (isFastMultiplier) {
21359             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
21360             if (NeedsCondInvert) // Invert the condition if needed.
21361               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
21362                                  DAG.getConstant(1, DL, Cond.getValueType()));
21363
21364             // Zero extend the condition if needed.
21365             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
21366                                Cond);
21367             // Scale the condition by the difference.
21368             if (Diff != 1)
21369               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
21370                                  DAG.getConstant(Diff, DL,
21371                                                  Cond.getValueType()));
21372
21373             // Add the base if non-zero.
21374             if (FalseC->getAPIntValue() != 0)
21375               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
21376                                  SDValue(FalseC, 0));
21377             return Cond;
21378           }
21379         }
21380       }
21381   }
21382
21383   // Canonicalize max and min:
21384   // (x > y) ? x : y -> (x >= y) ? x : y
21385   // (x < y) ? x : y -> (x <= y) ? x : y
21386   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
21387   // the need for an extra compare
21388   // against zero. e.g.
21389   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
21390   // subl   %esi, %edi
21391   // testl  %edi, %edi
21392   // movl   $0, %eax
21393   // cmovgl %edi, %eax
21394   // =>
21395   // xorl   %eax, %eax
21396   // subl   %esi, $edi
21397   // cmovsl %eax, %edi
21398   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
21399       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
21400       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
21401     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
21402     switch (CC) {
21403     default: break;
21404     case ISD::SETLT:
21405     case ISD::SETGT: {
21406       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
21407       Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
21408                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
21409       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
21410     }
21411     }
21412   }
21413
21414   // Early exit check
21415   if (!TLI.isTypeLegal(VT))
21416     return SDValue();
21417
21418   // Match VSELECTs into subs with unsigned saturation.
21419   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
21420       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
21421       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
21422        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
21423     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
21424
21425     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
21426     // left side invert the predicate to simplify logic below.
21427     SDValue Other;
21428     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
21429       Other = RHS;
21430       CC = ISD::getSetCCInverse(CC, true);
21431     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
21432       Other = LHS;
21433     }
21434
21435     if (Other.getNode() && Other->getNumOperands() == 2 &&
21436         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
21437       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
21438       SDValue CondRHS = Cond->getOperand(1);
21439
21440       // Look for a general sub with unsigned saturation first.
21441       // x >= y ? x-y : 0 --> subus x, y
21442       // x >  y ? x-y : 0 --> subus x, y
21443       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
21444           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
21445         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
21446
21447       if (auto *OpRHSBV = dyn_cast<BuildVectorSDNode>(OpRHS))
21448         if (auto *OpRHSConst = OpRHSBV->getConstantSplatNode()) {
21449           if (auto *CondRHSBV = dyn_cast<BuildVectorSDNode>(CondRHS))
21450             if (auto *CondRHSConst = CondRHSBV->getConstantSplatNode())
21451               // If the RHS is a constant we have to reverse the const
21452               // canonicalization.
21453               // x > C-1 ? x+-C : 0 --> subus x, C
21454               if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
21455                   CondRHSConst->getAPIntValue() ==
21456                       (-OpRHSConst->getAPIntValue() - 1))
21457                 return DAG.getNode(
21458                     X86ISD::SUBUS, DL, VT, OpLHS,
21459                     DAG.getConstant(-OpRHSConst->getAPIntValue(), DL, VT));
21460
21461           // Another special case: If C was a sign bit, the sub has been
21462           // canonicalized into a xor.
21463           // FIXME: Would it be better to use computeKnownBits to determine
21464           //        whether it's safe to decanonicalize the xor?
21465           // x s< 0 ? x^C : 0 --> subus x, C
21466           if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
21467               ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
21468               OpRHSConst->getAPIntValue().isSignBit())
21469             // Note that we have to rebuild the RHS constant here to ensure we
21470             // don't rely on particular values of undef lanes.
21471             return DAG.getNode(
21472                 X86ISD::SUBUS, DL, VT, OpLHS,
21473                 DAG.getConstant(OpRHSConst->getAPIntValue(), DL, VT));
21474         }
21475     }
21476   }
21477
21478   // Try to match a min/max vector operation.
21479   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
21480     std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
21481     unsigned Opc = ret.first;
21482     bool NeedSplit = ret.second;
21483
21484     if (Opc && NeedSplit) {
21485       unsigned NumElems = VT.getVectorNumElements();
21486       // Extract the LHS vectors
21487       SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
21488       SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
21489
21490       // Extract the RHS vectors
21491       SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
21492       SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
21493
21494       // Create min/max for each subvector
21495       LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
21496       RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
21497
21498       // Merge the result
21499       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
21500     } else if (Opc)
21501       return DAG.getNode(Opc, DL, VT, LHS, RHS);
21502   }
21503
21504   // Simplify vector selection if condition value type matches vselect
21505   // operand type
21506   if (N->getOpcode() == ISD::VSELECT && CondVT == VT) {
21507     assert(Cond.getValueType().isVector() &&
21508            "vector select expects a vector selector!");
21509
21510     bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
21511     bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
21512
21513     // Try invert the condition if true value is not all 1s and false value
21514     // is not all 0s.
21515     if (!TValIsAllOnes && !FValIsAllZeros &&
21516         // Check if the selector will be produced by CMPP*/PCMP*
21517         Cond.getOpcode() == ISD::SETCC &&
21518         // Check if SETCC has already been promoted
21519         TLI.getSetCCResultType(*DAG.getContext(), VT) == CondVT) {
21520       bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
21521       bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
21522
21523       if (TValIsAllZeros || FValIsAllOnes) {
21524         SDValue CC = Cond.getOperand(2);
21525         ISD::CondCode NewCC =
21526           ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
21527                                Cond.getOperand(0).getValueType().isInteger());
21528         Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
21529         std::swap(LHS, RHS);
21530         TValIsAllOnes = FValIsAllOnes;
21531         FValIsAllZeros = TValIsAllZeros;
21532       }
21533     }
21534
21535     if (TValIsAllOnes || FValIsAllZeros) {
21536       SDValue Ret;
21537
21538       if (TValIsAllOnes && FValIsAllZeros)
21539         Ret = Cond;
21540       else if (TValIsAllOnes)
21541         Ret = DAG.getNode(ISD::OR, DL, CondVT, Cond,
21542                           DAG.getNode(ISD::BITCAST, DL, CondVT, RHS));
21543       else if (FValIsAllZeros)
21544         Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
21545                           DAG.getNode(ISD::BITCAST, DL, CondVT, LHS));
21546
21547       return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
21548     }
21549   }
21550
21551   // We should generate an X86ISD::BLENDI from a vselect if its argument
21552   // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
21553   // constants. This specific pattern gets generated when we split a
21554   // selector for a 512 bit vector in a machine without AVX512 (but with
21555   // 256-bit vectors), during legalization:
21556   //
21557   // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
21558   //
21559   // Iff we find this pattern and the build_vectors are built from
21560   // constants, we translate the vselect into a shuffle_vector that we
21561   // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
21562   if ((N->getOpcode() == ISD::VSELECT ||
21563        N->getOpcode() == X86ISD::SHRUNKBLEND) &&
21564       !DCI.isBeforeLegalize()) {
21565     SDValue Shuffle = transformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
21566     if (Shuffle.getNode())
21567       return Shuffle;
21568   }
21569
21570   // If this is a *dynamic* select (non-constant condition) and we can match
21571   // this node with one of the variable blend instructions, restructure the
21572   // condition so that the blends can use the high bit of each element and use
21573   // SimplifyDemandedBits to simplify the condition operand.
21574   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
21575       !DCI.isBeforeLegalize() &&
21576       !ISD::isBuildVectorOfConstantSDNodes(Cond.getNode())) {
21577     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
21578
21579     // Don't optimize vector selects that map to mask-registers.
21580     if (BitWidth == 1)
21581       return SDValue();
21582
21583     // We can only handle the cases where VSELECT is directly legal on the
21584     // subtarget. We custom lower VSELECT nodes with constant conditions and
21585     // this makes it hard to see whether a dynamic VSELECT will correctly
21586     // lower, so we both check the operation's status and explicitly handle the
21587     // cases where a *dynamic* blend will fail even though a constant-condition
21588     // blend could be custom lowered.
21589     // FIXME: We should find a better way to handle this class of problems.
21590     // Potentially, we should combine constant-condition vselect nodes
21591     // pre-legalization into shuffles and not mark as many types as custom
21592     // lowered.
21593     if (!TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
21594       return SDValue();
21595     // FIXME: We don't support i16-element blends currently. We could and
21596     // should support them by making *all* the bits in the condition be set
21597     // rather than just the high bit and using an i8-element blend.
21598     if (VT.getScalarType() == MVT::i16)
21599       return SDValue();
21600     // Dynamic blending was only available from SSE4.1 onward.
21601     if (VT.getSizeInBits() == 128 && !Subtarget->hasSSE41())
21602       return SDValue();
21603     // Byte blends are only available in AVX2
21604     if (VT.getSizeInBits() == 256 && VT.getScalarType() == MVT::i8 &&
21605         !Subtarget->hasAVX2())
21606       return SDValue();
21607
21608     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
21609     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
21610
21611     APInt KnownZero, KnownOne;
21612     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
21613                                           DCI.isBeforeLegalizeOps());
21614     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
21615         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne,
21616                                  TLO)) {
21617       // If we changed the computation somewhere in the DAG, this change
21618       // will affect all users of Cond.
21619       // Make sure it is fine and update all the nodes so that we do not
21620       // use the generic VSELECT anymore. Otherwise, we may perform
21621       // wrong optimizations as we messed up with the actual expectation
21622       // for the vector boolean values.
21623       if (Cond != TLO.Old) {
21624         // Check all uses of that condition operand to check whether it will be
21625         // consumed by non-BLEND instructions, which may depend on all bits are
21626         // set properly.
21627         for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
21628              I != E; ++I)
21629           if (I->getOpcode() != ISD::VSELECT)
21630             // TODO: Add other opcodes eventually lowered into BLEND.
21631             return SDValue();
21632
21633         // Update all the users of the condition, before committing the change,
21634         // so that the VSELECT optimizations that expect the correct vector
21635         // boolean value will not be triggered.
21636         for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
21637              I != E; ++I)
21638           DAG.ReplaceAllUsesOfValueWith(
21639               SDValue(*I, 0),
21640               DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(*I), I->getValueType(0),
21641                           Cond, I->getOperand(1), I->getOperand(2)));
21642         DCI.CommitTargetLoweringOpt(TLO);
21643         return SDValue();
21644       }
21645       // At this point, only Cond is changed. Change the condition
21646       // just for N to keep the opportunity to optimize all other
21647       // users their own way.
21648       DAG.ReplaceAllUsesOfValueWith(
21649           SDValue(N, 0),
21650           DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(N), N->getValueType(0),
21651                       TLO.New, N->getOperand(1), N->getOperand(2)));
21652       return SDValue();
21653     }
21654   }
21655
21656   return SDValue();
21657 }
21658
21659 // Check whether a boolean test is testing a boolean value generated by
21660 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
21661 // code.
21662 //
21663 // Simplify the following patterns:
21664 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
21665 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
21666 // to (Op EFLAGS Cond)
21667 //
21668 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
21669 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
21670 // to (Op EFLAGS !Cond)
21671 //
21672 // where Op could be BRCOND or CMOV.
21673 //
21674 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
21675   // Quit if not CMP and SUB with its value result used.
21676   if (Cmp.getOpcode() != X86ISD::CMP &&
21677       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
21678       return SDValue();
21679
21680   // Quit if not used as a boolean value.
21681   if (CC != X86::COND_E && CC != X86::COND_NE)
21682     return SDValue();
21683
21684   // Check CMP operands. One of them should be 0 or 1 and the other should be
21685   // an SetCC or extended from it.
21686   SDValue Op1 = Cmp.getOperand(0);
21687   SDValue Op2 = Cmp.getOperand(1);
21688
21689   SDValue SetCC;
21690   const ConstantSDNode* C = nullptr;
21691   bool needOppositeCond = (CC == X86::COND_E);
21692   bool checkAgainstTrue = false; // Is it a comparison against 1?
21693
21694   if ((C = dyn_cast<ConstantSDNode>(Op1)))
21695     SetCC = Op2;
21696   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
21697     SetCC = Op1;
21698   else // Quit if all operands are not constants.
21699     return SDValue();
21700
21701   if (C->getZExtValue() == 1) {
21702     needOppositeCond = !needOppositeCond;
21703     checkAgainstTrue = true;
21704   } else if (C->getZExtValue() != 0)
21705     // Quit if the constant is neither 0 or 1.
21706     return SDValue();
21707
21708   bool truncatedToBoolWithAnd = false;
21709   // Skip (zext $x), (trunc $x), or (and $x, 1) node.
21710   while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
21711          SetCC.getOpcode() == ISD::TRUNCATE ||
21712          SetCC.getOpcode() == ISD::AND) {
21713     if (SetCC.getOpcode() == ISD::AND) {
21714       int OpIdx = -1;
21715       ConstantSDNode *CS;
21716       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
21717           CS->getZExtValue() == 1)
21718         OpIdx = 1;
21719       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
21720           CS->getZExtValue() == 1)
21721         OpIdx = 0;
21722       if (OpIdx == -1)
21723         break;
21724       SetCC = SetCC.getOperand(OpIdx);
21725       truncatedToBoolWithAnd = true;
21726     } else
21727       SetCC = SetCC.getOperand(0);
21728   }
21729
21730   switch (SetCC.getOpcode()) {
21731   case X86ISD::SETCC_CARRY:
21732     // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
21733     // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
21734     // i.e. it's a comparison against true but the result of SETCC_CARRY is not
21735     // truncated to i1 using 'and'.
21736     if (checkAgainstTrue && !truncatedToBoolWithAnd)
21737       break;
21738     assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
21739            "Invalid use of SETCC_CARRY!");
21740     // FALL THROUGH
21741   case X86ISD::SETCC:
21742     // Set the condition code or opposite one if necessary.
21743     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
21744     if (needOppositeCond)
21745       CC = X86::GetOppositeBranchCondition(CC);
21746     return SetCC.getOperand(1);
21747   case X86ISD::CMOV: {
21748     // Check whether false/true value has canonical one, i.e. 0 or 1.
21749     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
21750     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
21751     // Quit if true value is not a constant.
21752     if (!TVal)
21753       return SDValue();
21754     // Quit if false value is not a constant.
21755     if (!FVal) {
21756       SDValue Op = SetCC.getOperand(0);
21757       // Skip 'zext' or 'trunc' node.
21758       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
21759           Op.getOpcode() == ISD::TRUNCATE)
21760         Op = Op.getOperand(0);
21761       // A special case for rdrand/rdseed, where 0 is set if false cond is
21762       // found.
21763       if ((Op.getOpcode() != X86ISD::RDRAND &&
21764            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
21765         return SDValue();
21766     }
21767     // Quit if false value is not the constant 0 or 1.
21768     bool FValIsFalse = true;
21769     if (FVal && FVal->getZExtValue() != 0) {
21770       if (FVal->getZExtValue() != 1)
21771         return SDValue();
21772       // If FVal is 1, opposite cond is needed.
21773       needOppositeCond = !needOppositeCond;
21774       FValIsFalse = false;
21775     }
21776     // Quit if TVal is not the constant opposite of FVal.
21777     if (FValIsFalse && TVal->getZExtValue() != 1)
21778       return SDValue();
21779     if (!FValIsFalse && TVal->getZExtValue() != 0)
21780       return SDValue();
21781     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
21782     if (needOppositeCond)
21783       CC = X86::GetOppositeBranchCondition(CC);
21784     return SetCC.getOperand(3);
21785   }
21786   }
21787
21788   return SDValue();
21789 }
21790
21791 /// Check whether Cond is an AND/OR of SETCCs off of the same EFLAGS.
21792 /// Match:
21793 ///   (X86or (X86setcc) (X86setcc))
21794 ///   (X86cmp (and (X86setcc) (X86setcc)), 0)
21795 static bool checkBoolTestAndOrSetCCCombine(SDValue Cond, X86::CondCode &CC0,
21796                                            X86::CondCode &CC1, SDValue &Flags,
21797                                            bool &isAnd) {
21798   if (Cond->getOpcode() == X86ISD::CMP) {
21799     ConstantSDNode *CondOp1C = dyn_cast<ConstantSDNode>(Cond->getOperand(1));
21800     if (!CondOp1C || !CondOp1C->isNullValue())
21801       return false;
21802
21803     Cond = Cond->getOperand(0);
21804   }
21805
21806   isAnd = false;
21807
21808   SDValue SetCC0, SetCC1;
21809   switch (Cond->getOpcode()) {
21810   default: return false;
21811   case ISD::AND:
21812   case X86ISD::AND:
21813     isAnd = true;
21814     // fallthru
21815   case ISD::OR:
21816   case X86ISD::OR:
21817     SetCC0 = Cond->getOperand(0);
21818     SetCC1 = Cond->getOperand(1);
21819     break;
21820   };
21821
21822   // Make sure we have SETCC nodes, using the same flags value.
21823   if (SetCC0.getOpcode() != X86ISD::SETCC ||
21824       SetCC1.getOpcode() != X86ISD::SETCC ||
21825       SetCC0->getOperand(1) != SetCC1->getOperand(1))
21826     return false;
21827
21828   CC0 = (X86::CondCode)SetCC0->getConstantOperandVal(0);
21829   CC1 = (X86::CondCode)SetCC1->getConstantOperandVal(0);
21830   Flags = SetCC0->getOperand(1);
21831   return true;
21832 }
21833
21834 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
21835 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
21836                                   TargetLowering::DAGCombinerInfo &DCI,
21837                                   const X86Subtarget *Subtarget) {
21838   SDLoc DL(N);
21839
21840   // If the flag operand isn't dead, don't touch this CMOV.
21841   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
21842     return SDValue();
21843
21844   SDValue FalseOp = N->getOperand(0);
21845   SDValue TrueOp = N->getOperand(1);
21846   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
21847   SDValue Cond = N->getOperand(3);
21848
21849   if (CC == X86::COND_E || CC == X86::COND_NE) {
21850     switch (Cond.getOpcode()) {
21851     default: break;
21852     case X86ISD::BSR:
21853     case X86ISD::BSF:
21854       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
21855       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
21856         return (CC == X86::COND_E) ? FalseOp : TrueOp;
21857     }
21858   }
21859
21860   SDValue Flags;
21861
21862   Flags = checkBoolTestSetCCCombine(Cond, CC);
21863   if (Flags.getNode() &&
21864       // Extra check as FCMOV only supports a subset of X86 cond.
21865       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
21866     SDValue Ops[] = { FalseOp, TrueOp,
21867                       DAG.getConstant(CC, DL, MVT::i8), Flags };
21868     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
21869   }
21870
21871   // If this is a select between two integer constants, try to do some
21872   // optimizations.  Note that the operands are ordered the opposite of SELECT
21873   // operands.
21874   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
21875     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
21876       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
21877       // larger than FalseC (the false value).
21878       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
21879         CC = X86::GetOppositeBranchCondition(CC);
21880         std::swap(TrueC, FalseC);
21881         std::swap(TrueOp, FalseOp);
21882       }
21883
21884       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
21885       // This is efficient for any integer data type (including i8/i16) and
21886       // shift amount.
21887       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
21888         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
21889                            DAG.getConstant(CC, DL, MVT::i8), Cond);
21890
21891         // Zero extend the condition if needed.
21892         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
21893
21894         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
21895         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
21896                            DAG.getConstant(ShAmt, DL, MVT::i8));
21897         if (N->getNumValues() == 2)  // Dead flag value?
21898           return DCI.CombineTo(N, Cond, SDValue());
21899         return Cond;
21900       }
21901
21902       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
21903       // for any integer data type, including i8/i16.
21904       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
21905         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
21906                            DAG.getConstant(CC, DL, MVT::i8), Cond);
21907
21908         // Zero extend the condition if needed.
21909         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
21910                            FalseC->getValueType(0), Cond);
21911         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
21912                            SDValue(FalseC, 0));
21913
21914         if (N->getNumValues() == 2)  // Dead flag value?
21915           return DCI.CombineTo(N, Cond, SDValue());
21916         return Cond;
21917       }
21918
21919       // Optimize cases that will turn into an LEA instruction.  This requires
21920       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
21921       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
21922         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
21923         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
21924
21925         bool isFastMultiplier = false;
21926         if (Diff < 10) {
21927           switch ((unsigned char)Diff) {
21928           default: break;
21929           case 1:  // result = add base, cond
21930           case 2:  // result = lea base(    , cond*2)
21931           case 3:  // result = lea base(cond, cond*2)
21932           case 4:  // result = lea base(    , cond*4)
21933           case 5:  // result = lea base(cond, cond*4)
21934           case 8:  // result = lea base(    , cond*8)
21935           case 9:  // result = lea base(cond, cond*8)
21936             isFastMultiplier = true;
21937             break;
21938           }
21939         }
21940
21941         if (isFastMultiplier) {
21942           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
21943           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
21944                              DAG.getConstant(CC, DL, MVT::i8), Cond);
21945           // Zero extend the condition if needed.
21946           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
21947                              Cond);
21948           // Scale the condition by the difference.
21949           if (Diff != 1)
21950             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
21951                                DAG.getConstant(Diff, DL, Cond.getValueType()));
21952
21953           // Add the base if non-zero.
21954           if (FalseC->getAPIntValue() != 0)
21955             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
21956                                SDValue(FalseC, 0));
21957           if (N->getNumValues() == 2)  // Dead flag value?
21958             return DCI.CombineTo(N, Cond, SDValue());
21959           return Cond;
21960         }
21961       }
21962     }
21963   }
21964
21965   // Handle these cases:
21966   //   (select (x != c), e, c) -> select (x != c), e, x),
21967   //   (select (x == c), c, e) -> select (x == c), x, e)
21968   // where the c is an integer constant, and the "select" is the combination
21969   // of CMOV and CMP.
21970   //
21971   // The rationale for this change is that the conditional-move from a constant
21972   // needs two instructions, however, conditional-move from a register needs
21973   // only one instruction.
21974   //
21975   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
21976   //  some instruction-combining opportunities. This opt needs to be
21977   //  postponed as late as possible.
21978   //
21979   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
21980     // the DCI.xxxx conditions are provided to postpone the optimization as
21981     // late as possible.
21982
21983     ConstantSDNode *CmpAgainst = nullptr;
21984     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
21985         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
21986         !isa<ConstantSDNode>(Cond.getOperand(0))) {
21987
21988       if (CC == X86::COND_NE &&
21989           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
21990         CC = X86::GetOppositeBranchCondition(CC);
21991         std::swap(TrueOp, FalseOp);
21992       }
21993
21994       if (CC == X86::COND_E &&
21995           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
21996         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
21997                           DAG.getConstant(CC, DL, MVT::i8), Cond };
21998         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
21999       }
22000     }
22001   }
22002
22003   // Fold and/or of setcc's to double CMOV:
22004   //   (CMOV F, T, ((cc1 | cc2) != 0)) -> (CMOV (CMOV F, T, cc1), T, cc2)
22005   //   (CMOV F, T, ((cc1 & cc2) != 0)) -> (CMOV (CMOV T, F, !cc1), F, !cc2)
22006   //
22007   // This combine lets us generate:
22008   //   cmovcc1 (jcc1 if we don't have CMOV)
22009   //   cmovcc2 (same)
22010   // instead of:
22011   //   setcc1
22012   //   setcc2
22013   //   and/or
22014   //   cmovne (jne if we don't have CMOV)
22015   // When we can't use the CMOV instruction, it might increase branch
22016   // mispredicts.
22017   // When we can use CMOV, or when there is no mispredict, this improves
22018   // throughput and reduces register pressure.
22019   //
22020   if (CC == X86::COND_NE) {
22021     SDValue Flags;
22022     X86::CondCode CC0, CC1;
22023     bool isAndSetCC;
22024     if (checkBoolTestAndOrSetCCCombine(Cond, CC0, CC1, Flags, isAndSetCC)) {
22025       if (isAndSetCC) {
22026         std::swap(FalseOp, TrueOp);
22027         CC0 = X86::GetOppositeBranchCondition(CC0);
22028         CC1 = X86::GetOppositeBranchCondition(CC1);
22029       }
22030
22031       SDValue LOps[] = {FalseOp, TrueOp, DAG.getConstant(CC0, DL, MVT::i8),
22032         Flags};
22033       SDValue LCMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), LOps);
22034       SDValue Ops[] = {LCMOV, TrueOp, DAG.getConstant(CC1, DL, MVT::i8), Flags};
22035       SDValue CMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
22036       DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SDValue(CMOV.getNode(), 1));
22037       return CMOV;
22038     }
22039   }
22040
22041   return SDValue();
22042 }
22043
22044 static SDValue PerformINTRINSIC_WO_CHAINCombine(SDNode *N, SelectionDAG &DAG,
22045                                                 const X86Subtarget *Subtarget) {
22046   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
22047   switch (IntNo) {
22048   default: return SDValue();
22049   // SSE/AVX/AVX2 blend intrinsics.
22050   case Intrinsic::x86_avx2_pblendvb:
22051     // Don't try to simplify this intrinsic if we don't have AVX2.
22052     if (!Subtarget->hasAVX2())
22053       return SDValue();
22054     // FALL-THROUGH
22055   case Intrinsic::x86_avx_blendv_pd_256:
22056   case Intrinsic::x86_avx_blendv_ps_256:
22057     // Don't try to simplify this intrinsic if we don't have AVX.
22058     if (!Subtarget->hasAVX())
22059       return SDValue();
22060     // FALL-THROUGH
22061   case Intrinsic::x86_sse41_blendvps:
22062   case Intrinsic::x86_sse41_blendvpd:
22063   case Intrinsic::x86_sse41_pblendvb: {
22064     SDValue Op0 = N->getOperand(1);
22065     SDValue Op1 = N->getOperand(2);
22066     SDValue Mask = N->getOperand(3);
22067
22068     // Don't try to simplify this intrinsic if we don't have SSE4.1.
22069     if (!Subtarget->hasSSE41())
22070       return SDValue();
22071
22072     // fold (blend A, A, Mask) -> A
22073     if (Op0 == Op1)
22074       return Op0;
22075     // fold (blend A, B, allZeros) -> A
22076     if (ISD::isBuildVectorAllZeros(Mask.getNode()))
22077       return Op0;
22078     // fold (blend A, B, allOnes) -> B
22079     if (ISD::isBuildVectorAllOnes(Mask.getNode()))
22080       return Op1;
22081
22082     // Simplify the case where the mask is a constant i32 value.
22083     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Mask)) {
22084       if (C->isNullValue())
22085         return Op0;
22086       if (C->isAllOnesValue())
22087         return Op1;
22088     }
22089
22090     return SDValue();
22091   }
22092
22093   // Packed SSE2/AVX2 arithmetic shift immediate intrinsics.
22094   case Intrinsic::x86_sse2_psrai_w:
22095   case Intrinsic::x86_sse2_psrai_d:
22096   case Intrinsic::x86_avx2_psrai_w:
22097   case Intrinsic::x86_avx2_psrai_d:
22098   case Intrinsic::x86_sse2_psra_w:
22099   case Intrinsic::x86_sse2_psra_d:
22100   case Intrinsic::x86_avx2_psra_w:
22101   case Intrinsic::x86_avx2_psra_d: {
22102     SDValue Op0 = N->getOperand(1);
22103     SDValue Op1 = N->getOperand(2);
22104     EVT VT = Op0.getValueType();
22105     assert(VT.isVector() && "Expected a vector type!");
22106
22107     if (isa<BuildVectorSDNode>(Op1))
22108       Op1 = Op1.getOperand(0);
22109
22110     if (!isa<ConstantSDNode>(Op1))
22111       return SDValue();
22112
22113     EVT SVT = VT.getVectorElementType();
22114     unsigned SVTBits = SVT.getSizeInBits();
22115
22116     ConstantSDNode *CND = cast<ConstantSDNode>(Op1);
22117     const APInt &C = APInt(SVTBits, CND->getAPIntValue().getZExtValue());
22118     uint64_t ShAmt = C.getZExtValue();
22119
22120     // Don't try to convert this shift into a ISD::SRA if the shift
22121     // count is bigger than or equal to the element size.
22122     if (ShAmt >= SVTBits)
22123       return SDValue();
22124
22125     // Trivial case: if the shift count is zero, then fold this
22126     // into the first operand.
22127     if (ShAmt == 0)
22128       return Op0;
22129
22130     // Replace this packed shift intrinsic with a target independent
22131     // shift dag node.
22132     SDLoc DL(N);
22133     SDValue Splat = DAG.getConstant(C, DL, VT);
22134     return DAG.getNode(ISD::SRA, DL, VT, Op0, Splat);
22135   }
22136   }
22137 }
22138
22139 /// PerformMulCombine - Optimize a single multiply with constant into two
22140 /// in order to implement it with two cheaper instructions, e.g.
22141 /// LEA + SHL, LEA + LEA.
22142 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
22143                                  TargetLowering::DAGCombinerInfo &DCI) {
22144   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
22145     return SDValue();
22146
22147   EVT VT = N->getValueType(0);
22148   if (VT != MVT::i64 && VT != MVT::i32)
22149     return SDValue();
22150
22151   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
22152   if (!C)
22153     return SDValue();
22154   uint64_t MulAmt = C->getZExtValue();
22155   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
22156     return SDValue();
22157
22158   uint64_t MulAmt1 = 0;
22159   uint64_t MulAmt2 = 0;
22160   if ((MulAmt % 9) == 0) {
22161     MulAmt1 = 9;
22162     MulAmt2 = MulAmt / 9;
22163   } else if ((MulAmt % 5) == 0) {
22164     MulAmt1 = 5;
22165     MulAmt2 = MulAmt / 5;
22166   } else if ((MulAmt % 3) == 0) {
22167     MulAmt1 = 3;
22168     MulAmt2 = MulAmt / 3;
22169   }
22170   if (MulAmt2 &&
22171       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
22172     SDLoc DL(N);
22173
22174     if (isPowerOf2_64(MulAmt2) &&
22175         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
22176       // If second multiplifer is pow2, issue it first. We want the multiply by
22177       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
22178       // is an add.
22179       std::swap(MulAmt1, MulAmt2);
22180
22181     SDValue NewMul;
22182     if (isPowerOf2_64(MulAmt1))
22183       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
22184                            DAG.getConstant(Log2_64(MulAmt1), DL, MVT::i8));
22185     else
22186       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
22187                            DAG.getConstant(MulAmt1, DL, VT));
22188
22189     if (isPowerOf2_64(MulAmt2))
22190       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
22191                            DAG.getConstant(Log2_64(MulAmt2), DL, MVT::i8));
22192     else
22193       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
22194                            DAG.getConstant(MulAmt2, DL, VT));
22195
22196     // Do not add new nodes to DAG combiner worklist.
22197     DCI.CombineTo(N, NewMul, false);
22198   }
22199   return SDValue();
22200 }
22201
22202 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
22203   SDValue N0 = N->getOperand(0);
22204   SDValue N1 = N->getOperand(1);
22205   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
22206   EVT VT = N0.getValueType();
22207
22208   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
22209   // since the result of setcc_c is all zero's or all ones.
22210   if (VT.isInteger() && !VT.isVector() &&
22211       N1C && N0.getOpcode() == ISD::AND &&
22212       N0.getOperand(1).getOpcode() == ISD::Constant) {
22213     SDValue N00 = N0.getOperand(0);
22214     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
22215         ((N00.getOpcode() == ISD::ANY_EXTEND ||
22216           N00.getOpcode() == ISD::ZERO_EXTEND) &&
22217          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
22218       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
22219       APInt ShAmt = N1C->getAPIntValue();
22220       Mask = Mask.shl(ShAmt);
22221       if (Mask != 0) {
22222         SDLoc DL(N);
22223         return DAG.getNode(ISD::AND, DL, VT,
22224                            N00, DAG.getConstant(Mask, DL, VT));
22225       }
22226     }
22227   }
22228
22229   // Hardware support for vector shifts is sparse which makes us scalarize the
22230   // vector operations in many cases. Also, on sandybridge ADD is faster than
22231   // shl.
22232   // (shl V, 1) -> add V,V
22233   if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
22234     if (auto *N1SplatC = N1BV->getConstantSplatNode()) {
22235       assert(N0.getValueType().isVector() && "Invalid vector shift type");
22236       // We shift all of the values by one. In many cases we do not have
22237       // hardware support for this operation. This is better expressed as an ADD
22238       // of two values.
22239       if (N1SplatC->getZExtValue() == 1)
22240         return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
22241     }
22242
22243   return SDValue();
22244 }
22245
22246 /// \brief Returns a vector of 0s if the node in input is a vector logical
22247 /// shift by a constant amount which is known to be bigger than or equal
22248 /// to the vector element size in bits.
22249 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
22250                                       const X86Subtarget *Subtarget) {
22251   EVT VT = N->getValueType(0);
22252
22253   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
22254       (!Subtarget->hasInt256() ||
22255        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
22256     return SDValue();
22257
22258   SDValue Amt = N->getOperand(1);
22259   SDLoc DL(N);
22260   if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Amt))
22261     if (auto *AmtSplat = AmtBV->getConstantSplatNode()) {
22262       APInt ShiftAmt = AmtSplat->getAPIntValue();
22263       unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
22264
22265       // SSE2/AVX2 logical shifts always return a vector of 0s
22266       // if the shift amount is bigger than or equal to
22267       // the element size. The constant shift amount will be
22268       // encoded as a 8-bit immediate.
22269       if (ShiftAmt.trunc(8).uge(MaxAmount))
22270         return getZeroVector(VT, Subtarget, DAG, DL);
22271     }
22272
22273   return SDValue();
22274 }
22275
22276 /// PerformShiftCombine - Combine shifts.
22277 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
22278                                    TargetLowering::DAGCombinerInfo &DCI,
22279                                    const X86Subtarget *Subtarget) {
22280   if (N->getOpcode() == ISD::SHL) {
22281     SDValue V = PerformSHLCombine(N, DAG);
22282     if (V.getNode()) return V;
22283   }
22284
22285   if (N->getOpcode() != ISD::SRA) {
22286     // Try to fold this logical shift into a zero vector.
22287     SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
22288     if (V.getNode()) return V;
22289   }
22290
22291   return SDValue();
22292 }
22293
22294 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
22295 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
22296 // and friends.  Likewise for OR -> CMPNEQSS.
22297 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
22298                             TargetLowering::DAGCombinerInfo &DCI,
22299                             const X86Subtarget *Subtarget) {
22300   unsigned opcode;
22301
22302   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
22303   // we're requiring SSE2 for both.
22304   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
22305     SDValue N0 = N->getOperand(0);
22306     SDValue N1 = N->getOperand(1);
22307     SDValue CMP0 = N0->getOperand(1);
22308     SDValue CMP1 = N1->getOperand(1);
22309     SDLoc DL(N);
22310
22311     // The SETCCs should both refer to the same CMP.
22312     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
22313       return SDValue();
22314
22315     SDValue CMP00 = CMP0->getOperand(0);
22316     SDValue CMP01 = CMP0->getOperand(1);
22317     EVT     VT    = CMP00.getValueType();
22318
22319     if (VT == MVT::f32 || VT == MVT::f64) {
22320       bool ExpectingFlags = false;
22321       // Check for any users that want flags:
22322       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
22323            !ExpectingFlags && UI != UE; ++UI)
22324         switch (UI->getOpcode()) {
22325         default:
22326         case ISD::BR_CC:
22327         case ISD::BRCOND:
22328         case ISD::SELECT:
22329           ExpectingFlags = true;
22330           break;
22331         case ISD::CopyToReg:
22332         case ISD::SIGN_EXTEND:
22333         case ISD::ZERO_EXTEND:
22334         case ISD::ANY_EXTEND:
22335           break;
22336         }
22337
22338       if (!ExpectingFlags) {
22339         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
22340         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
22341
22342         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
22343           X86::CondCode tmp = cc0;
22344           cc0 = cc1;
22345           cc1 = tmp;
22346         }
22347
22348         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
22349             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
22350           // FIXME: need symbolic constants for these magic numbers.
22351           // See X86ATTInstPrinter.cpp:printSSECC().
22352           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
22353           if (Subtarget->hasAVX512()) {
22354             SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
22355                                          CMP01,
22356                                          DAG.getConstant(x86cc, DL, MVT::i8));
22357             if (N->getValueType(0) != MVT::i1)
22358               return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
22359                                  FSetCC);
22360             return FSetCC;
22361           }
22362           SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
22363                                               CMP00.getValueType(), CMP00, CMP01,
22364                                               DAG.getConstant(x86cc, DL,
22365                                                               MVT::i8));
22366
22367           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
22368           MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
22369
22370           if (is64BitFP && !Subtarget->is64Bit()) {
22371             // On a 32-bit target, we cannot bitcast the 64-bit float to a
22372             // 64-bit integer, since that's not a legal type. Since
22373             // OnesOrZeroesF is all ones of all zeroes, we don't need all the
22374             // bits, but can do this little dance to extract the lowest 32 bits
22375             // and work with those going forward.
22376             SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
22377                                            OnesOrZeroesF);
22378             SDValue Vector32 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f32,
22379                                            Vector64);
22380             OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
22381                                         Vector32, DAG.getIntPtrConstant(0, DL));
22382             IntVT = MVT::i32;
22383           }
22384
22385           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, IntVT,
22386                                               OnesOrZeroesF);
22387           SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
22388                                       DAG.getConstant(1, DL, IntVT));
22389           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8,
22390                                               ANDed);
22391           return OneBitOfTruth;
22392         }
22393       }
22394     }
22395   }
22396   return SDValue();
22397 }
22398
22399 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
22400 /// so it can be folded inside ANDNP.
22401 static bool CanFoldXORWithAllOnes(const SDNode *N) {
22402   EVT VT = N->getValueType(0);
22403
22404   // Match direct AllOnes for 128 and 256-bit vectors
22405   if (ISD::isBuildVectorAllOnes(N))
22406     return true;
22407
22408   // Look through a bit convert.
22409   if (N->getOpcode() == ISD::BITCAST)
22410     N = N->getOperand(0).getNode();
22411
22412   // Sometimes the operand may come from a insert_subvector building a 256-bit
22413   // allones vector
22414   if (VT.is256BitVector() &&
22415       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
22416     SDValue V1 = N->getOperand(0);
22417     SDValue V2 = N->getOperand(1);
22418
22419     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
22420         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
22421         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
22422         ISD::isBuildVectorAllOnes(V2.getNode()))
22423       return true;
22424   }
22425
22426   return false;
22427 }
22428
22429 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
22430 // register. In most cases we actually compare or select YMM-sized registers
22431 // and mixing the two types creates horrible code. This method optimizes
22432 // some of the transition sequences.
22433 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
22434                                  TargetLowering::DAGCombinerInfo &DCI,
22435                                  const X86Subtarget *Subtarget) {
22436   EVT VT = N->getValueType(0);
22437   if (!VT.is256BitVector())
22438     return SDValue();
22439
22440   assert((N->getOpcode() == ISD::ANY_EXTEND ||
22441           N->getOpcode() == ISD::ZERO_EXTEND ||
22442           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
22443
22444   SDValue Narrow = N->getOperand(0);
22445   EVT NarrowVT = Narrow->getValueType(0);
22446   if (!NarrowVT.is128BitVector())
22447     return SDValue();
22448
22449   if (Narrow->getOpcode() != ISD::XOR &&
22450       Narrow->getOpcode() != ISD::AND &&
22451       Narrow->getOpcode() != ISD::OR)
22452     return SDValue();
22453
22454   SDValue N0  = Narrow->getOperand(0);
22455   SDValue N1  = Narrow->getOperand(1);
22456   SDLoc DL(Narrow);
22457
22458   // The Left side has to be a trunc.
22459   if (N0.getOpcode() != ISD::TRUNCATE)
22460     return SDValue();
22461
22462   // The type of the truncated inputs.
22463   EVT WideVT = N0->getOperand(0)->getValueType(0);
22464   if (WideVT != VT)
22465     return SDValue();
22466
22467   // The right side has to be a 'trunc' or a constant vector.
22468   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
22469   ConstantSDNode *RHSConstSplat = nullptr;
22470   if (auto *RHSBV = dyn_cast<BuildVectorSDNode>(N1))
22471     RHSConstSplat = RHSBV->getConstantSplatNode();
22472   if (!RHSTrunc && !RHSConstSplat)
22473     return SDValue();
22474
22475   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22476
22477   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
22478     return SDValue();
22479
22480   // Set N0 and N1 to hold the inputs to the new wide operation.
22481   N0 = N0->getOperand(0);
22482   if (RHSConstSplat) {
22483     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
22484                      SDValue(RHSConstSplat, 0));
22485     SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
22486     N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
22487   } else if (RHSTrunc) {
22488     N1 = N1->getOperand(0);
22489   }
22490
22491   // Generate the wide operation.
22492   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
22493   unsigned Opcode = N->getOpcode();
22494   switch (Opcode) {
22495   case ISD::ANY_EXTEND:
22496     return Op;
22497   case ISD::ZERO_EXTEND: {
22498     unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
22499     APInt Mask = APInt::getAllOnesValue(InBits);
22500     Mask = Mask.zext(VT.getScalarType().getSizeInBits());
22501     return DAG.getNode(ISD::AND, DL, VT,
22502                        Op, DAG.getConstant(Mask, DL, VT));
22503   }
22504   case ISD::SIGN_EXTEND:
22505     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
22506                        Op, DAG.getValueType(NarrowVT));
22507   default:
22508     llvm_unreachable("Unexpected opcode");
22509   }
22510 }
22511
22512 static SDValue VectorZextCombine(SDNode *N, SelectionDAG &DAG,
22513                                  TargetLowering::DAGCombinerInfo &DCI,
22514                                  const X86Subtarget *Subtarget) {
22515   SDValue N0 = N->getOperand(0);
22516   SDValue N1 = N->getOperand(1);
22517   SDLoc DL(N);
22518
22519   // A vector zext_in_reg may be represented as a shuffle,
22520   // feeding into a bitcast (this represents anyext) feeding into
22521   // an and with a mask.
22522   // We'd like to try to combine that into a shuffle with zero
22523   // plus a bitcast, removing the and.
22524   if (N0.getOpcode() != ISD::BITCAST ||
22525       N0.getOperand(0).getOpcode() != ISD::VECTOR_SHUFFLE)
22526     return SDValue();
22527
22528   // The other side of the AND should be a splat of 2^C, where C
22529   // is the number of bits in the source type.
22530   if (N1.getOpcode() == ISD::BITCAST)
22531     N1 = N1.getOperand(0);
22532   if (N1.getOpcode() != ISD::BUILD_VECTOR)
22533     return SDValue();
22534   BuildVectorSDNode *Vector = cast<BuildVectorSDNode>(N1);
22535
22536   ShuffleVectorSDNode *Shuffle = cast<ShuffleVectorSDNode>(N0.getOperand(0));
22537   EVT SrcType = Shuffle->getValueType(0);
22538
22539   // We expect a single-source shuffle
22540   if (Shuffle->getOperand(1)->getOpcode() != ISD::UNDEF)
22541     return SDValue();
22542
22543   unsigned SrcSize = SrcType.getScalarSizeInBits();
22544
22545   APInt SplatValue, SplatUndef;
22546   unsigned SplatBitSize;
22547   bool HasAnyUndefs;
22548   if (!Vector->isConstantSplat(SplatValue, SplatUndef,
22549                                 SplatBitSize, HasAnyUndefs))
22550     return SDValue();
22551
22552   unsigned ResSize = N1.getValueType().getScalarSizeInBits();
22553   // Make sure the splat matches the mask we expect
22554   if (SplatBitSize > ResSize ||
22555       (SplatValue + 1).exactLogBase2() != (int)SrcSize)
22556     return SDValue();
22557
22558   // Make sure the input and output size make sense
22559   if (SrcSize >= ResSize || ResSize % SrcSize)
22560     return SDValue();
22561
22562   // We expect a shuffle of the form <0, u, u, u, 1, u, u, u...>
22563   // The number of u's between each two values depends on the ratio between
22564   // the source and dest type.
22565   unsigned ZextRatio = ResSize / SrcSize;
22566   bool IsZext = true;
22567   for (unsigned i = 0; i < SrcType.getVectorNumElements(); ++i) {
22568     if (i % ZextRatio) {
22569       if (Shuffle->getMaskElt(i) > 0) {
22570         // Expected undef
22571         IsZext = false;
22572         break;
22573       }
22574     } else {
22575       if (Shuffle->getMaskElt(i) != (int)(i / ZextRatio)) {
22576         // Expected element number
22577         IsZext = false;
22578         break;
22579       }
22580     }
22581   }
22582
22583   if (!IsZext)
22584     return SDValue();
22585
22586   // Ok, perform the transformation - replace the shuffle with
22587   // a shuffle of the form <0, k, k, k, 1, k, k, k> with zero
22588   // (instead of undef) where the k elements come from the zero vector.
22589   SmallVector<int, 8> Mask;
22590   unsigned NumElems = SrcType.getVectorNumElements();
22591   for (unsigned i = 0; i < NumElems; ++i)
22592     if (i % ZextRatio)
22593       Mask.push_back(NumElems);
22594     else
22595       Mask.push_back(i / ZextRatio);
22596
22597   SDValue NewShuffle = DAG.getVectorShuffle(Shuffle->getValueType(0), DL,
22598     Shuffle->getOperand(0), DAG.getConstant(0, DL, SrcType), Mask);
22599   return DAG.getNode(ISD::BITCAST, DL, N0.getValueType(), NewShuffle);
22600 }
22601
22602 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
22603                                  TargetLowering::DAGCombinerInfo &DCI,
22604                                  const X86Subtarget *Subtarget) {
22605   if (DCI.isBeforeLegalizeOps())
22606     return SDValue();
22607
22608   if (SDValue Zext = VectorZextCombine(N, DAG, DCI, Subtarget))
22609     return Zext;
22610
22611   if (SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget))
22612     return R;
22613
22614   EVT VT = N->getValueType(0);
22615   SDValue N0 = N->getOperand(0);
22616   SDValue N1 = N->getOperand(1);
22617   SDLoc DL(N);
22618
22619   // Create BEXTR instructions
22620   // BEXTR is ((X >> imm) & (2**size-1))
22621   if (VT == MVT::i32 || VT == MVT::i64) {
22622     // Check for BEXTR.
22623     if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
22624         (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
22625       ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
22626       ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
22627       if (MaskNode && ShiftNode) {
22628         uint64_t Mask = MaskNode->getZExtValue();
22629         uint64_t Shift = ShiftNode->getZExtValue();
22630         if (isMask_64(Mask)) {
22631           uint64_t MaskSize = countPopulation(Mask);
22632           if (Shift + MaskSize <= VT.getSizeInBits())
22633             return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
22634                                DAG.getConstant(Shift | (MaskSize << 8), DL,
22635                                                VT));
22636         }
22637       }
22638     } // BEXTR
22639
22640     return SDValue();
22641   }
22642
22643   // Want to form ANDNP nodes:
22644   // 1) In the hopes of then easily combining them with OR and AND nodes
22645   //    to form PBLEND/PSIGN.
22646   // 2) To match ANDN packed intrinsics
22647   if (VT != MVT::v2i64 && VT != MVT::v4i64)
22648     return SDValue();
22649
22650   // Check LHS for vnot
22651   if (N0.getOpcode() == ISD::XOR &&
22652       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
22653       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
22654     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
22655
22656   // Check RHS for vnot
22657   if (N1.getOpcode() == ISD::XOR &&
22658       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
22659       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
22660     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
22661
22662   return SDValue();
22663 }
22664
22665 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
22666                                 TargetLowering::DAGCombinerInfo &DCI,
22667                                 const X86Subtarget *Subtarget) {
22668   if (DCI.isBeforeLegalizeOps())
22669     return SDValue();
22670
22671   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
22672   if (R.getNode())
22673     return R;
22674
22675   SDValue N0 = N->getOperand(0);
22676   SDValue N1 = N->getOperand(1);
22677   EVT VT = N->getValueType(0);
22678
22679   // look for psign/blend
22680   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
22681     if (!Subtarget->hasSSSE3() ||
22682         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
22683       return SDValue();
22684
22685     // Canonicalize pandn to RHS
22686     if (N0.getOpcode() == X86ISD::ANDNP)
22687       std::swap(N0, N1);
22688     // or (and (m, y), (pandn m, x))
22689     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
22690       SDValue Mask = N1.getOperand(0);
22691       SDValue X    = N1.getOperand(1);
22692       SDValue Y;
22693       if (N0.getOperand(0) == Mask)
22694         Y = N0.getOperand(1);
22695       if (N0.getOperand(1) == Mask)
22696         Y = N0.getOperand(0);
22697
22698       // Check to see if the mask appeared in both the AND and ANDNP and
22699       if (!Y.getNode())
22700         return SDValue();
22701
22702       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
22703       // Look through mask bitcast.
22704       if (Mask.getOpcode() == ISD::BITCAST)
22705         Mask = Mask.getOperand(0);
22706       if (X.getOpcode() == ISD::BITCAST)
22707         X = X.getOperand(0);
22708       if (Y.getOpcode() == ISD::BITCAST)
22709         Y = Y.getOperand(0);
22710
22711       EVT MaskVT = Mask.getValueType();
22712
22713       // Validate that the Mask operand is a vector sra node.
22714       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
22715       // there is no psrai.b
22716       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
22717       unsigned SraAmt = ~0;
22718       if (Mask.getOpcode() == ISD::SRA) {
22719         if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Mask.getOperand(1)))
22720           if (auto *AmtConst = AmtBV->getConstantSplatNode())
22721             SraAmt = AmtConst->getZExtValue();
22722       } else if (Mask.getOpcode() == X86ISD::VSRAI) {
22723         SDValue SraC = Mask.getOperand(1);
22724         SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
22725       }
22726       if ((SraAmt + 1) != EltBits)
22727         return SDValue();
22728
22729       SDLoc DL(N);
22730
22731       // Now we know we at least have a plendvb with the mask val.  See if
22732       // we can form a psignb/w/d.
22733       // psign = x.type == y.type == mask.type && y = sub(0, x);
22734       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
22735           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
22736           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
22737         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
22738                "Unsupported VT for PSIGN");
22739         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
22740         return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
22741       }
22742       // PBLENDVB only available on SSE 4.1
22743       if (!Subtarget->hasSSE41())
22744         return SDValue();
22745
22746       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
22747
22748       X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
22749       Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
22750       Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
22751       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
22752       return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
22753     }
22754   }
22755
22756   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
22757     return SDValue();
22758
22759   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
22760   MachineFunction &MF = DAG.getMachineFunction();
22761   bool OptForSize =
22762       MF.getFunction()->hasFnAttribute(Attribute::OptimizeForSize);
22763
22764   // SHLD/SHRD instructions have lower register pressure, but on some
22765   // platforms they have higher latency than the equivalent
22766   // series of shifts/or that would otherwise be generated.
22767   // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
22768   // have higher latencies and we are not optimizing for size.
22769   if (!OptForSize && Subtarget->isSHLDSlow())
22770     return SDValue();
22771
22772   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
22773     std::swap(N0, N1);
22774   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
22775     return SDValue();
22776   if (!N0.hasOneUse() || !N1.hasOneUse())
22777     return SDValue();
22778
22779   SDValue ShAmt0 = N0.getOperand(1);
22780   if (ShAmt0.getValueType() != MVT::i8)
22781     return SDValue();
22782   SDValue ShAmt1 = N1.getOperand(1);
22783   if (ShAmt1.getValueType() != MVT::i8)
22784     return SDValue();
22785   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
22786     ShAmt0 = ShAmt0.getOperand(0);
22787   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
22788     ShAmt1 = ShAmt1.getOperand(0);
22789
22790   SDLoc DL(N);
22791   unsigned Opc = X86ISD::SHLD;
22792   SDValue Op0 = N0.getOperand(0);
22793   SDValue Op1 = N1.getOperand(0);
22794   if (ShAmt0.getOpcode() == ISD::SUB) {
22795     Opc = X86ISD::SHRD;
22796     std::swap(Op0, Op1);
22797     std::swap(ShAmt0, ShAmt1);
22798   }
22799
22800   unsigned Bits = VT.getSizeInBits();
22801   if (ShAmt1.getOpcode() == ISD::SUB) {
22802     SDValue Sum = ShAmt1.getOperand(0);
22803     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
22804       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
22805       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
22806         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
22807       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
22808         return DAG.getNode(Opc, DL, VT,
22809                            Op0, Op1,
22810                            DAG.getNode(ISD::TRUNCATE, DL,
22811                                        MVT::i8, ShAmt0));
22812     }
22813   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
22814     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
22815     if (ShAmt0C &&
22816         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
22817       return DAG.getNode(Opc, DL, VT,
22818                          N0.getOperand(0), N1.getOperand(0),
22819                          DAG.getNode(ISD::TRUNCATE, DL,
22820                                        MVT::i8, ShAmt0));
22821   }
22822
22823   return SDValue();
22824 }
22825
22826 // Generate NEG and CMOV for integer abs.
22827 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
22828   EVT VT = N->getValueType(0);
22829
22830   // Since X86 does not have CMOV for 8-bit integer, we don't convert
22831   // 8-bit integer abs to NEG and CMOV.
22832   if (VT.isInteger() && VT.getSizeInBits() == 8)
22833     return SDValue();
22834
22835   SDValue N0 = N->getOperand(0);
22836   SDValue N1 = N->getOperand(1);
22837   SDLoc DL(N);
22838
22839   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
22840   // and change it to SUB and CMOV.
22841   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
22842       N0.getOpcode() == ISD::ADD &&
22843       N0.getOperand(1) == N1 &&
22844       N1.getOpcode() == ISD::SRA &&
22845       N1.getOperand(0) == N0.getOperand(0))
22846     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
22847       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
22848         // Generate SUB & CMOV.
22849         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
22850                                   DAG.getConstant(0, DL, VT), N0.getOperand(0));
22851
22852         SDValue Ops[] = { N0.getOperand(0), Neg,
22853                           DAG.getConstant(X86::COND_GE, DL, MVT::i8),
22854                           SDValue(Neg.getNode(), 1) };
22855         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
22856       }
22857   return SDValue();
22858 }
22859
22860 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
22861 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
22862                                  TargetLowering::DAGCombinerInfo &DCI,
22863                                  const X86Subtarget *Subtarget) {
22864   if (DCI.isBeforeLegalizeOps())
22865     return SDValue();
22866
22867   if (Subtarget->hasCMov()) {
22868     SDValue RV = performIntegerAbsCombine(N, DAG);
22869     if (RV.getNode())
22870       return RV;
22871   }
22872
22873   return SDValue();
22874 }
22875
22876 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
22877 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
22878                                   TargetLowering::DAGCombinerInfo &DCI,
22879                                   const X86Subtarget *Subtarget) {
22880   LoadSDNode *Ld = cast<LoadSDNode>(N);
22881   EVT RegVT = Ld->getValueType(0);
22882   EVT MemVT = Ld->getMemoryVT();
22883   SDLoc dl(Ld);
22884   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22885
22886   // For chips with slow 32-byte unaligned loads, break the 32-byte operation
22887   // into two 16-byte operations.
22888   ISD::LoadExtType Ext = Ld->getExtensionType();
22889   unsigned Alignment = Ld->getAlignment();
22890   bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
22891   if (RegVT.is256BitVector() && Subtarget->isUnalignedMem32Slow() &&
22892       !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
22893     unsigned NumElems = RegVT.getVectorNumElements();
22894     if (NumElems < 2)
22895       return SDValue();
22896
22897     SDValue Ptr = Ld->getBasePtr();
22898     SDValue Increment = DAG.getConstant(16, dl, TLI.getPointerTy());
22899
22900     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
22901                                   NumElems/2);
22902     SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
22903                                 Ld->getPointerInfo(), Ld->isVolatile(),
22904                                 Ld->isNonTemporal(), Ld->isInvariant(),
22905                                 Alignment);
22906     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
22907     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
22908                                 Ld->getPointerInfo(), Ld->isVolatile(),
22909                                 Ld->isNonTemporal(), Ld->isInvariant(),
22910                                 std::min(16U, Alignment));
22911     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
22912                              Load1.getValue(1),
22913                              Load2.getValue(1));
22914
22915     SDValue NewVec = DAG.getUNDEF(RegVT);
22916     NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
22917     NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
22918     return DCI.CombineTo(N, NewVec, TF, true);
22919   }
22920
22921   return SDValue();
22922 }
22923
22924 /// PerformMLOADCombine - Resolve extending loads
22925 static SDValue PerformMLOADCombine(SDNode *N, SelectionDAG &DAG,
22926                                    TargetLowering::DAGCombinerInfo &DCI,
22927                                    const X86Subtarget *Subtarget) {
22928   MaskedLoadSDNode *Mld = cast<MaskedLoadSDNode>(N);
22929   if (Mld->getExtensionType() != ISD::SEXTLOAD)
22930     return SDValue();
22931
22932   EVT VT = Mld->getValueType(0);
22933   unsigned NumElems = VT.getVectorNumElements();
22934   EVT LdVT = Mld->getMemoryVT();
22935   SDLoc dl(Mld);
22936
22937   assert(LdVT != VT && "Cannot extend to the same type");
22938   unsigned ToSz = VT.getVectorElementType().getSizeInBits();
22939   unsigned FromSz = LdVT.getVectorElementType().getSizeInBits();
22940   // From, To sizes and ElemCount must be pow of two
22941   assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
22942     "Unexpected size for extending masked load");
22943
22944   unsigned SizeRatio  = ToSz / FromSz;
22945   assert(SizeRatio * NumElems * FromSz == VT.getSizeInBits());
22946
22947   // Create a type on which we perform the shuffle
22948   EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
22949           LdVT.getScalarType(), NumElems*SizeRatio);
22950   assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
22951
22952   // Convert Src0 value
22953   SDValue WideSrc0 = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Mld->getSrc0());
22954   if (Mld->getSrc0().getOpcode() != ISD::UNDEF) {
22955     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
22956     for (unsigned i = 0; i != NumElems; ++i)
22957       ShuffleVec[i] = i * SizeRatio;
22958
22959     // Can't shuffle using an illegal type.
22960     assert (DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT)
22961             && "WideVecVT should be legal");
22962     WideSrc0 = DAG.getVectorShuffle(WideVecVT, dl, WideSrc0,
22963                                     DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
22964   }
22965   // Prepare the new mask
22966   SDValue NewMask;
22967   SDValue Mask = Mld->getMask();
22968   if (Mask.getValueType() == VT) {
22969     // Mask and original value have the same type
22970     NewMask = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Mask);
22971     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
22972     for (unsigned i = 0; i != NumElems; ++i)
22973       ShuffleVec[i] = i * SizeRatio;
22974     for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
22975       ShuffleVec[i] = NumElems*SizeRatio;
22976     NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
22977                                    DAG.getConstant(0, dl, WideVecVT),
22978                                    &ShuffleVec[0]);
22979   }
22980   else {
22981     assert(Mask.getValueType().getVectorElementType() == MVT::i1);
22982     unsigned WidenNumElts = NumElems*SizeRatio;
22983     unsigned MaskNumElts = VT.getVectorNumElements();
22984     EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(),  MVT::i1,
22985                                      WidenNumElts);
22986
22987     unsigned NumConcat = WidenNumElts / MaskNumElts;
22988     SmallVector<SDValue, 16> Ops(NumConcat);
22989     SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
22990     Ops[0] = Mask;
22991     for (unsigned i = 1; i != NumConcat; ++i)
22992       Ops[i] = ZeroVal;
22993
22994     NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
22995   }
22996
22997   SDValue WideLd = DAG.getMaskedLoad(WideVecVT, dl, Mld->getChain(),
22998                                      Mld->getBasePtr(), NewMask, WideSrc0,
22999                                      Mld->getMemoryVT(), Mld->getMemOperand(),
23000                                      ISD::NON_EXTLOAD);
23001   SDValue NewVec = DAG.getNode(X86ISD::VSEXT, dl, VT, WideLd);
23002   return DCI.CombineTo(N, NewVec, WideLd.getValue(1), true);
23003
23004 }
23005 /// PerformMSTORECombine - Resolve truncating stores
23006 static SDValue PerformMSTORECombine(SDNode *N, SelectionDAG &DAG,
23007                                     const X86Subtarget *Subtarget) {
23008   MaskedStoreSDNode *Mst = cast<MaskedStoreSDNode>(N);
23009   if (!Mst->isTruncatingStore())
23010     return SDValue();
23011
23012   EVT VT = Mst->getValue().getValueType();
23013   unsigned NumElems = VT.getVectorNumElements();
23014   EVT StVT = Mst->getMemoryVT();
23015   SDLoc dl(Mst);
23016
23017   assert(StVT != VT && "Cannot truncate to the same type");
23018   unsigned FromSz = VT.getVectorElementType().getSizeInBits();
23019   unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
23020
23021   // From, To sizes and ElemCount must be pow of two
23022   assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
23023     "Unexpected size for truncating masked store");
23024   // We are going to use the original vector elt for storing.
23025   // Accumulated smaller vector elements must be a multiple of the store size.
23026   assert (((NumElems * FromSz) % ToSz) == 0 &&
23027           "Unexpected ratio for truncating masked store");
23028
23029   unsigned SizeRatio  = FromSz / ToSz;
23030   assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
23031
23032   // Create a type on which we perform the shuffle
23033   EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
23034           StVT.getScalarType(), NumElems*SizeRatio);
23035
23036   assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
23037
23038   SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Mst->getValue());
23039   SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
23040   for (unsigned i = 0; i != NumElems; ++i)
23041     ShuffleVec[i] = i * SizeRatio;
23042
23043   // Can't shuffle using an illegal type.
23044   assert (DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT)
23045           && "WideVecVT should be legal");
23046
23047   SDValue TruncatedVal = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
23048                                         DAG.getUNDEF(WideVecVT),
23049                                         &ShuffleVec[0]);
23050
23051   SDValue NewMask;
23052   SDValue Mask = Mst->getMask();
23053   if (Mask.getValueType() == VT) {
23054     // Mask and original value have the same type
23055     NewMask = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Mask);
23056     for (unsigned i = 0; i != NumElems; ++i)
23057       ShuffleVec[i] = i * SizeRatio;
23058     for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
23059       ShuffleVec[i] = NumElems*SizeRatio;
23060     NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
23061                                    DAG.getConstant(0, dl, WideVecVT),
23062                                    &ShuffleVec[0]);
23063   }
23064   else {
23065     assert(Mask.getValueType().getVectorElementType() == MVT::i1);
23066     unsigned WidenNumElts = NumElems*SizeRatio;
23067     unsigned MaskNumElts = VT.getVectorNumElements();
23068     EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(),  MVT::i1,
23069                                      WidenNumElts);
23070
23071     unsigned NumConcat = WidenNumElts / MaskNumElts;
23072     SmallVector<SDValue, 16> Ops(NumConcat);
23073     SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
23074     Ops[0] = Mask;
23075     for (unsigned i = 1; i != NumConcat; ++i)
23076       Ops[i] = ZeroVal;
23077
23078     NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
23079   }
23080
23081   return DAG.getMaskedStore(Mst->getChain(), dl, TruncatedVal, Mst->getBasePtr(),
23082                             NewMask, StVT, Mst->getMemOperand(), false);
23083 }
23084 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
23085 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
23086                                    const X86Subtarget *Subtarget) {
23087   StoreSDNode *St = cast<StoreSDNode>(N);
23088   EVT VT = St->getValue().getValueType();
23089   EVT StVT = St->getMemoryVT();
23090   SDLoc dl(St);
23091   SDValue StoredVal = St->getOperand(1);
23092   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23093
23094   // If we are saving a concatenation of two XMM registers and 32-byte stores
23095   // are slow, such as on Sandy Bridge, perform two 16-byte stores.
23096   unsigned Alignment = St->getAlignment();
23097   bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
23098   if (VT.is256BitVector() && Subtarget->isUnalignedMem32Slow() &&
23099       StVT == VT && !IsAligned) {
23100     unsigned NumElems = VT.getVectorNumElements();
23101     if (NumElems < 2)
23102       return SDValue();
23103
23104     SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
23105     SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
23106
23107     SDValue Stride = DAG.getConstant(16, dl, TLI.getPointerTy());
23108     SDValue Ptr0 = St->getBasePtr();
23109     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
23110
23111     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
23112                                 St->getPointerInfo(), St->isVolatile(),
23113                                 St->isNonTemporal(), Alignment);
23114     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
23115                                 St->getPointerInfo(), St->isVolatile(),
23116                                 St->isNonTemporal(),
23117                                 std::min(16U, Alignment));
23118     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
23119   }
23120
23121   // Optimize trunc store (of multiple scalars) to shuffle and store.
23122   // First, pack all of the elements in one place. Next, store to memory
23123   // in fewer chunks.
23124   if (St->isTruncatingStore() && VT.isVector()) {
23125     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23126     unsigned NumElems = VT.getVectorNumElements();
23127     assert(StVT != VT && "Cannot truncate to the same type");
23128     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
23129     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
23130
23131     // From, To sizes and ElemCount must be pow of two
23132     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
23133     // We are going to use the original vector elt for storing.
23134     // Accumulated smaller vector elements must be a multiple of the store size.
23135     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
23136
23137     unsigned SizeRatio  = FromSz / ToSz;
23138
23139     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
23140
23141     // Create a type on which we perform the shuffle
23142     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
23143             StVT.getScalarType(), NumElems*SizeRatio);
23144
23145     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
23146
23147     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
23148     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
23149     for (unsigned i = 0; i != NumElems; ++i)
23150       ShuffleVec[i] = i * SizeRatio;
23151
23152     // Can't shuffle using an illegal type.
23153     if (!TLI.isTypeLegal(WideVecVT))
23154       return SDValue();
23155
23156     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
23157                                          DAG.getUNDEF(WideVecVT),
23158                                          &ShuffleVec[0]);
23159     // At this point all of the data is stored at the bottom of the
23160     // register. We now need to save it to mem.
23161
23162     // Find the largest store unit
23163     MVT StoreType = MVT::i8;
23164     for (MVT Tp : MVT::integer_valuetypes()) {
23165       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
23166         StoreType = Tp;
23167     }
23168
23169     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
23170     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
23171         (64 <= NumElems * ToSz))
23172       StoreType = MVT::f64;
23173
23174     // Bitcast the original vector into a vector of store-size units
23175     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
23176             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
23177     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
23178     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
23179     SmallVector<SDValue, 8> Chains;
23180     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8, dl,
23181                                         TLI.getPointerTy());
23182     SDValue Ptr = St->getBasePtr();
23183
23184     // Perform one or more big stores into memory.
23185     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
23186       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
23187                                    StoreType, ShuffWide,
23188                                    DAG.getIntPtrConstant(i, dl));
23189       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
23190                                 St->getPointerInfo(), St->isVolatile(),
23191                                 St->isNonTemporal(), St->getAlignment());
23192       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
23193       Chains.push_back(Ch);
23194     }
23195
23196     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
23197   }
23198
23199   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
23200   // the FP state in cases where an emms may be missing.
23201   // A preferable solution to the general problem is to figure out the right
23202   // places to insert EMMS.  This qualifies as a quick hack.
23203
23204   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
23205   if (VT.getSizeInBits() != 64)
23206     return SDValue();
23207
23208   const Function *F = DAG.getMachineFunction().getFunction();
23209   bool NoImplicitFloatOps = F->hasFnAttribute(Attribute::NoImplicitFloat);
23210   bool F64IsLegal =
23211       !Subtarget->useSoftFloat() && !NoImplicitFloatOps && Subtarget->hasSSE2();
23212   if ((VT.isVector() ||
23213        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
23214       isa<LoadSDNode>(St->getValue()) &&
23215       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
23216       St->getChain().hasOneUse() && !St->isVolatile()) {
23217     SDNode* LdVal = St->getValue().getNode();
23218     LoadSDNode *Ld = nullptr;
23219     int TokenFactorIndex = -1;
23220     SmallVector<SDValue, 8> Ops;
23221     SDNode* ChainVal = St->getChain().getNode();
23222     // Must be a store of a load.  We currently handle two cases:  the load
23223     // is a direct child, and it's under an intervening TokenFactor.  It is
23224     // possible to dig deeper under nested TokenFactors.
23225     if (ChainVal == LdVal)
23226       Ld = cast<LoadSDNode>(St->getChain());
23227     else if (St->getValue().hasOneUse() &&
23228              ChainVal->getOpcode() == ISD::TokenFactor) {
23229       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
23230         if (ChainVal->getOperand(i).getNode() == LdVal) {
23231           TokenFactorIndex = i;
23232           Ld = cast<LoadSDNode>(St->getValue());
23233         } else
23234           Ops.push_back(ChainVal->getOperand(i));
23235       }
23236     }
23237
23238     if (!Ld || !ISD::isNormalLoad(Ld))
23239       return SDValue();
23240
23241     // If this is not the MMX case, i.e. we are just turning i64 load/store
23242     // into f64 load/store, avoid the transformation if there are multiple
23243     // uses of the loaded value.
23244     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
23245       return SDValue();
23246
23247     SDLoc LdDL(Ld);
23248     SDLoc StDL(N);
23249     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
23250     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
23251     // pair instead.
23252     if (Subtarget->is64Bit() || F64IsLegal) {
23253       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
23254       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
23255                                   Ld->getPointerInfo(), Ld->isVolatile(),
23256                                   Ld->isNonTemporal(), Ld->isInvariant(),
23257                                   Ld->getAlignment());
23258       SDValue NewChain = NewLd.getValue(1);
23259       if (TokenFactorIndex != -1) {
23260         Ops.push_back(NewChain);
23261         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
23262       }
23263       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
23264                           St->getPointerInfo(),
23265                           St->isVolatile(), St->isNonTemporal(),
23266                           St->getAlignment());
23267     }
23268
23269     // Otherwise, lower to two pairs of 32-bit loads / stores.
23270     SDValue LoAddr = Ld->getBasePtr();
23271     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
23272                                  DAG.getConstant(4, LdDL, MVT::i32));
23273
23274     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
23275                                Ld->getPointerInfo(),
23276                                Ld->isVolatile(), Ld->isNonTemporal(),
23277                                Ld->isInvariant(), Ld->getAlignment());
23278     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
23279                                Ld->getPointerInfo().getWithOffset(4),
23280                                Ld->isVolatile(), Ld->isNonTemporal(),
23281                                Ld->isInvariant(),
23282                                MinAlign(Ld->getAlignment(), 4));
23283
23284     SDValue NewChain = LoLd.getValue(1);
23285     if (TokenFactorIndex != -1) {
23286       Ops.push_back(LoLd);
23287       Ops.push_back(HiLd);
23288       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
23289     }
23290
23291     LoAddr = St->getBasePtr();
23292     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
23293                          DAG.getConstant(4, StDL, MVT::i32));
23294
23295     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
23296                                 St->getPointerInfo(),
23297                                 St->isVolatile(), St->isNonTemporal(),
23298                                 St->getAlignment());
23299     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
23300                                 St->getPointerInfo().getWithOffset(4),
23301                                 St->isVolatile(),
23302                                 St->isNonTemporal(),
23303                                 MinAlign(St->getAlignment(), 4));
23304     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
23305   }
23306
23307   // This is similar to the above case, but here we handle a scalar 64-bit
23308   // integer store that is extracted from a vector on a 32-bit target.
23309   // If we have SSE2, then we can treat it like a floating-point double
23310   // to get past legalization. The execution dependencies fixup pass will
23311   // choose the optimal machine instruction for the store if this really is
23312   // an integer or v2f32 rather than an f64.
23313   if (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit() &&
23314       St->getOperand(1).getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
23315     SDValue OldExtract = St->getOperand(1);
23316     SDValue ExtOp0 = OldExtract.getOperand(0);
23317     unsigned VecSize = ExtOp0.getValueSizeInBits();
23318     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, VecSize / 64);
23319     SDValue BitCast = DAG.getNode(ISD::BITCAST, dl, VecVT, ExtOp0);
23320     SDValue NewExtract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
23321                                      BitCast, OldExtract.getOperand(1));
23322     return DAG.getStore(St->getChain(), dl, NewExtract, St->getBasePtr(),
23323                         St->getPointerInfo(), St->isVolatile(),
23324                         St->isNonTemporal(), St->getAlignment());
23325   }
23326
23327   return SDValue();
23328 }
23329
23330 /// Return 'true' if this vector operation is "horizontal"
23331 /// and return the operands for the horizontal operation in LHS and RHS.  A
23332 /// horizontal operation performs the binary operation on successive elements
23333 /// of its first operand, then on successive elements of its second operand,
23334 /// returning the resulting values in a vector.  For example, if
23335 ///   A = < float a0, float a1, float a2, float a3 >
23336 /// and
23337 ///   B = < float b0, float b1, float b2, float b3 >
23338 /// then the result of doing a horizontal operation on A and B is
23339 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
23340 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
23341 /// A horizontal-op B, for some already available A and B, and if so then LHS is
23342 /// set to A, RHS to B, and the routine returns 'true'.
23343 /// Note that the binary operation should have the property that if one of the
23344 /// operands is UNDEF then the result is UNDEF.
23345 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
23346   // Look for the following pattern: if
23347   //   A = < float a0, float a1, float a2, float a3 >
23348   //   B = < float b0, float b1, float b2, float b3 >
23349   // and
23350   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
23351   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
23352   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
23353   // which is A horizontal-op B.
23354
23355   // At least one of the operands should be a vector shuffle.
23356   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
23357       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
23358     return false;
23359
23360   MVT VT = LHS.getSimpleValueType();
23361
23362   assert((VT.is128BitVector() || VT.is256BitVector()) &&
23363          "Unsupported vector type for horizontal add/sub");
23364
23365   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
23366   // operate independently on 128-bit lanes.
23367   unsigned NumElts = VT.getVectorNumElements();
23368   unsigned NumLanes = VT.getSizeInBits()/128;
23369   unsigned NumLaneElts = NumElts / NumLanes;
23370   assert((NumLaneElts % 2 == 0) &&
23371          "Vector type should have an even number of elements in each lane");
23372   unsigned HalfLaneElts = NumLaneElts/2;
23373
23374   // View LHS in the form
23375   //   LHS = VECTOR_SHUFFLE A, B, LMask
23376   // If LHS is not a shuffle then pretend it is the shuffle
23377   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
23378   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
23379   // type VT.
23380   SDValue A, B;
23381   SmallVector<int, 16> LMask(NumElts);
23382   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
23383     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
23384       A = LHS.getOperand(0);
23385     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
23386       B = LHS.getOperand(1);
23387     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
23388     std::copy(Mask.begin(), Mask.end(), LMask.begin());
23389   } else {
23390     if (LHS.getOpcode() != ISD::UNDEF)
23391       A = LHS;
23392     for (unsigned i = 0; i != NumElts; ++i)
23393       LMask[i] = i;
23394   }
23395
23396   // Likewise, view RHS in the form
23397   //   RHS = VECTOR_SHUFFLE C, D, RMask
23398   SDValue C, D;
23399   SmallVector<int, 16> RMask(NumElts);
23400   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
23401     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
23402       C = RHS.getOperand(0);
23403     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
23404       D = RHS.getOperand(1);
23405     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
23406     std::copy(Mask.begin(), Mask.end(), RMask.begin());
23407   } else {
23408     if (RHS.getOpcode() != ISD::UNDEF)
23409       C = RHS;
23410     for (unsigned i = 0; i != NumElts; ++i)
23411       RMask[i] = i;
23412   }
23413
23414   // Check that the shuffles are both shuffling the same vectors.
23415   if (!(A == C && B == D) && !(A == D && B == C))
23416     return false;
23417
23418   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
23419   if (!A.getNode() && !B.getNode())
23420     return false;
23421
23422   // If A and B occur in reverse order in RHS, then "swap" them (which means
23423   // rewriting the mask).
23424   if (A != C)
23425     ShuffleVectorSDNode::commuteMask(RMask);
23426
23427   // At this point LHS and RHS are equivalent to
23428   //   LHS = VECTOR_SHUFFLE A, B, LMask
23429   //   RHS = VECTOR_SHUFFLE A, B, RMask
23430   // Check that the masks correspond to performing a horizontal operation.
23431   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
23432     for (unsigned i = 0; i != NumLaneElts; ++i) {
23433       int LIdx = LMask[i+l], RIdx = RMask[i+l];
23434
23435       // Ignore any UNDEF components.
23436       if (LIdx < 0 || RIdx < 0 ||
23437           (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
23438           (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
23439         continue;
23440
23441       // Check that successive elements are being operated on.  If not, this is
23442       // not a horizontal operation.
23443       unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
23444       int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
23445       if (!(LIdx == Index && RIdx == Index + 1) &&
23446           !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
23447         return false;
23448     }
23449   }
23450
23451   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
23452   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
23453   return true;
23454 }
23455
23456 /// Do target-specific dag combines on floating point adds.
23457 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
23458                                   const X86Subtarget *Subtarget) {
23459   EVT VT = N->getValueType(0);
23460   SDValue LHS = N->getOperand(0);
23461   SDValue RHS = N->getOperand(1);
23462
23463   // Try to synthesize horizontal adds from adds of shuffles.
23464   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
23465        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
23466       isHorizontalBinOp(LHS, RHS, true))
23467     return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
23468   return SDValue();
23469 }
23470
23471 /// Do target-specific dag combines on floating point subs.
23472 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
23473                                   const X86Subtarget *Subtarget) {
23474   EVT VT = N->getValueType(0);
23475   SDValue LHS = N->getOperand(0);
23476   SDValue RHS = N->getOperand(1);
23477
23478   // Try to synthesize horizontal subs from subs of shuffles.
23479   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
23480        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
23481       isHorizontalBinOp(LHS, RHS, false))
23482     return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
23483   return SDValue();
23484 }
23485
23486 /// Do target-specific dag combines on X86ISD::FOR and X86ISD::FXOR nodes.
23487 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
23488   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
23489
23490   // F[X]OR(0.0, x) -> x
23491   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
23492     if (C->getValueAPF().isPosZero())
23493       return N->getOperand(1);
23494
23495   // F[X]OR(x, 0.0) -> x
23496   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
23497     if (C->getValueAPF().isPosZero())
23498       return N->getOperand(0);
23499   return SDValue();
23500 }
23501
23502 /// Do target-specific dag combines on X86ISD::FMIN and X86ISD::FMAX nodes.
23503 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
23504   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
23505
23506   // Only perform optimizations if UnsafeMath is used.
23507   if (!DAG.getTarget().Options.UnsafeFPMath)
23508     return SDValue();
23509
23510   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
23511   // into FMINC and FMAXC, which are Commutative operations.
23512   unsigned NewOp = 0;
23513   switch (N->getOpcode()) {
23514     default: llvm_unreachable("unknown opcode");
23515     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
23516     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
23517   }
23518
23519   return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
23520                      N->getOperand(0), N->getOperand(1));
23521 }
23522
23523 /// Do target-specific dag combines on X86ISD::FAND nodes.
23524 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
23525   // FAND(0.0, x) -> 0.0
23526   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
23527     if (C->getValueAPF().isPosZero())
23528       return N->getOperand(0);
23529
23530   // FAND(x, 0.0) -> 0.0
23531   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
23532     if (C->getValueAPF().isPosZero())
23533       return N->getOperand(1);
23534
23535   return SDValue();
23536 }
23537
23538 /// Do target-specific dag combines on X86ISD::FANDN nodes
23539 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
23540   // FANDN(0.0, x) -> x
23541   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
23542     if (C->getValueAPF().isPosZero())
23543       return N->getOperand(1);
23544
23545   // FANDN(x, 0.0) -> 0.0
23546   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
23547     if (C->getValueAPF().isPosZero())
23548       return N->getOperand(1);
23549
23550   return SDValue();
23551 }
23552
23553 static SDValue PerformBTCombine(SDNode *N,
23554                                 SelectionDAG &DAG,
23555                                 TargetLowering::DAGCombinerInfo &DCI) {
23556   // BT ignores high bits in the bit index operand.
23557   SDValue Op1 = N->getOperand(1);
23558   if (Op1.hasOneUse()) {
23559     unsigned BitWidth = Op1.getValueSizeInBits();
23560     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
23561     APInt KnownZero, KnownOne;
23562     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
23563                                           !DCI.isBeforeLegalizeOps());
23564     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23565     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
23566         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
23567       DCI.CommitTargetLoweringOpt(TLO);
23568   }
23569   return SDValue();
23570 }
23571
23572 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
23573   SDValue Op = N->getOperand(0);
23574   if (Op.getOpcode() == ISD::BITCAST)
23575     Op = Op.getOperand(0);
23576   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
23577   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
23578       VT.getVectorElementType().getSizeInBits() ==
23579       OpVT.getVectorElementType().getSizeInBits()) {
23580     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
23581   }
23582   return SDValue();
23583 }
23584
23585 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
23586                                                const X86Subtarget *Subtarget) {
23587   EVT VT = N->getValueType(0);
23588   if (!VT.isVector())
23589     return SDValue();
23590
23591   SDValue N0 = N->getOperand(0);
23592   SDValue N1 = N->getOperand(1);
23593   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
23594   SDLoc dl(N);
23595
23596   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
23597   // both SSE and AVX2 since there is no sign-extended shift right
23598   // operation on a vector with 64-bit elements.
23599   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
23600   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
23601   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
23602       N0.getOpcode() == ISD::SIGN_EXTEND)) {
23603     SDValue N00 = N0.getOperand(0);
23604
23605     // EXTLOAD has a better solution on AVX2,
23606     // it may be replaced with X86ISD::VSEXT node.
23607     if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
23608       if (!ISD::isNormalLoad(N00.getNode()))
23609         return SDValue();
23610
23611     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
23612         SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
23613                                   N00, N1);
23614       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
23615     }
23616   }
23617   return SDValue();
23618 }
23619
23620 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
23621                                   TargetLowering::DAGCombinerInfo &DCI,
23622                                   const X86Subtarget *Subtarget) {
23623   SDValue N0 = N->getOperand(0);
23624   EVT VT = N->getValueType(0);
23625
23626   // (i8,i32 sext (sdivrem (i8 x, i8 y)) ->
23627   // (i8,i32 (sdivrem_sext_hreg (i8 x, i8 y)
23628   // This exposes the sext to the sdivrem lowering, so that it directly extends
23629   // from AH (which we otherwise need to do contortions to access).
23630   if (N0.getOpcode() == ISD::SDIVREM && N0.getResNo() == 1 &&
23631       N0.getValueType() == MVT::i8 && VT == MVT::i32) {
23632     SDLoc dl(N);
23633     SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
23634     SDValue R = DAG.getNode(X86ISD::SDIVREM8_SEXT_HREG, dl, NodeTys,
23635                             N0.getOperand(0), N0.getOperand(1));
23636     DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
23637     return R.getValue(1);
23638   }
23639
23640   if (!DCI.isBeforeLegalizeOps())
23641     return SDValue();
23642
23643   if (!Subtarget->hasFp256())
23644     return SDValue();
23645
23646   if (VT.isVector() && VT.getSizeInBits() == 256) {
23647     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
23648     if (R.getNode())
23649       return R;
23650   }
23651
23652   return SDValue();
23653 }
23654
23655 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
23656                                  const X86Subtarget* Subtarget) {
23657   SDLoc dl(N);
23658   EVT VT = N->getValueType(0);
23659
23660   // Let legalize expand this if it isn't a legal type yet.
23661   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
23662     return SDValue();
23663
23664   EVT ScalarVT = VT.getScalarType();
23665   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
23666       (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
23667     return SDValue();
23668
23669   SDValue A = N->getOperand(0);
23670   SDValue B = N->getOperand(1);
23671   SDValue C = N->getOperand(2);
23672
23673   bool NegA = (A.getOpcode() == ISD::FNEG);
23674   bool NegB = (B.getOpcode() == ISD::FNEG);
23675   bool NegC = (C.getOpcode() == ISD::FNEG);
23676
23677   // Negative multiplication when NegA xor NegB
23678   bool NegMul = (NegA != NegB);
23679   if (NegA)
23680     A = A.getOperand(0);
23681   if (NegB)
23682     B = B.getOperand(0);
23683   if (NegC)
23684     C = C.getOperand(0);
23685
23686   unsigned Opcode;
23687   if (!NegMul)
23688     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
23689   else
23690     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
23691
23692   return DAG.getNode(Opcode, dl, VT, A, B, C);
23693 }
23694
23695 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
23696                                   TargetLowering::DAGCombinerInfo &DCI,
23697                                   const X86Subtarget *Subtarget) {
23698   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
23699   //           (and (i32 x86isd::setcc_carry), 1)
23700   // This eliminates the zext. This transformation is necessary because
23701   // ISD::SETCC is always legalized to i8.
23702   SDLoc dl(N);
23703   SDValue N0 = N->getOperand(0);
23704   EVT VT = N->getValueType(0);
23705
23706   if (N0.getOpcode() == ISD::AND &&
23707       N0.hasOneUse() &&
23708       N0.getOperand(0).hasOneUse()) {
23709     SDValue N00 = N0.getOperand(0);
23710     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
23711       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
23712       if (!C || C->getZExtValue() != 1)
23713         return SDValue();
23714       return DAG.getNode(ISD::AND, dl, VT,
23715                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
23716                                      N00.getOperand(0), N00.getOperand(1)),
23717                          DAG.getConstant(1, dl, VT));
23718     }
23719   }
23720
23721   if (N0.getOpcode() == ISD::TRUNCATE &&
23722       N0.hasOneUse() &&
23723       N0.getOperand(0).hasOneUse()) {
23724     SDValue N00 = N0.getOperand(0);
23725     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
23726       return DAG.getNode(ISD::AND, dl, VT,
23727                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
23728                                      N00.getOperand(0), N00.getOperand(1)),
23729                          DAG.getConstant(1, dl, VT));
23730     }
23731   }
23732   if (VT.is256BitVector()) {
23733     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
23734     if (R.getNode())
23735       return R;
23736   }
23737
23738   // (i8,i32 zext (udivrem (i8 x, i8 y)) ->
23739   // (i8,i32 (udivrem_zext_hreg (i8 x, i8 y)
23740   // This exposes the zext to the udivrem lowering, so that it directly extends
23741   // from AH (which we otherwise need to do contortions to access).
23742   if (N0.getOpcode() == ISD::UDIVREM &&
23743       N0.getResNo() == 1 && N0.getValueType() == MVT::i8 &&
23744       (VT == MVT::i32 || VT == MVT::i64)) {
23745     SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
23746     SDValue R = DAG.getNode(X86ISD::UDIVREM8_ZEXT_HREG, dl, NodeTys,
23747                             N0.getOperand(0), N0.getOperand(1));
23748     DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
23749     return R.getValue(1);
23750   }
23751
23752   return SDValue();
23753 }
23754
23755 // Optimize x == -y --> x+y == 0
23756 //          x != -y --> x+y != 0
23757 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
23758                                       const X86Subtarget* Subtarget) {
23759   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
23760   SDValue LHS = N->getOperand(0);
23761   SDValue RHS = N->getOperand(1);
23762   EVT VT = N->getValueType(0);
23763   SDLoc DL(N);
23764
23765   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
23766     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
23767       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
23768         SDValue addV = DAG.getNode(ISD::ADD, DL, LHS.getValueType(), RHS,
23769                                    LHS.getOperand(1));
23770         return DAG.getSetCC(DL, N->getValueType(0), addV,
23771                             DAG.getConstant(0, DL, addV.getValueType()), CC);
23772       }
23773   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
23774     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
23775       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
23776         SDValue addV = DAG.getNode(ISD::ADD, DL, RHS.getValueType(), LHS,
23777                                    RHS.getOperand(1));
23778         return DAG.getSetCC(DL, N->getValueType(0), addV,
23779                             DAG.getConstant(0, DL, addV.getValueType()), CC);
23780       }
23781
23782   if (VT.getScalarType() == MVT::i1 &&
23783       (CC == ISD::SETNE || CC == ISD::SETEQ || ISD::isSignedIntSetCC(CC))) {
23784     bool IsSEXT0 =
23785         (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
23786         (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
23787     bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
23788
23789     if (!IsSEXT0 || !IsVZero1) {
23790       // Swap the operands and update the condition code.
23791       std::swap(LHS, RHS);
23792       CC = ISD::getSetCCSwappedOperands(CC);
23793
23794       IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
23795                 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
23796       IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
23797     }
23798
23799     if (IsSEXT0 && IsVZero1) {
23800       assert(VT == LHS.getOperand(0).getValueType() &&
23801              "Uexpected operand type");
23802       if (CC == ISD::SETGT)
23803         return DAG.getConstant(0, DL, VT);
23804       if (CC == ISD::SETLE)
23805         return DAG.getConstant(1, DL, VT);
23806       if (CC == ISD::SETEQ || CC == ISD::SETGE)
23807         return DAG.getNOT(DL, LHS.getOperand(0), VT);
23808
23809       assert((CC == ISD::SETNE || CC == ISD::SETLT) &&
23810              "Unexpected condition code!");
23811       return LHS.getOperand(0);
23812     }
23813   }
23814
23815   return SDValue();
23816 }
23817
23818 static SDValue NarrowVectorLoadToElement(LoadSDNode *Load, unsigned Index,
23819                                          SelectionDAG &DAG) {
23820   SDLoc dl(Load);
23821   MVT VT = Load->getSimpleValueType(0);
23822   MVT EVT = VT.getVectorElementType();
23823   SDValue Addr = Load->getOperand(1);
23824   SDValue NewAddr = DAG.getNode(
23825       ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
23826       DAG.getConstant(Index * EVT.getStoreSize(), dl,
23827                       Addr.getSimpleValueType()));
23828
23829   SDValue NewLoad =
23830       DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
23831                   DAG.getMachineFunction().getMachineMemOperand(
23832                       Load->getMemOperand(), 0, EVT.getStoreSize()));
23833   return NewLoad;
23834 }
23835
23836 static SDValue PerformINSERTPSCombine(SDNode *N, SelectionDAG &DAG,
23837                                       const X86Subtarget *Subtarget) {
23838   SDLoc dl(N);
23839   MVT VT = N->getOperand(1)->getSimpleValueType(0);
23840   assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
23841          "X86insertps is only defined for v4x32");
23842
23843   SDValue Ld = N->getOperand(1);
23844   if (MayFoldLoad(Ld)) {
23845     // Extract the countS bits from the immediate so we can get the proper
23846     // address when narrowing the vector load to a specific element.
23847     // When the second source op is a memory address, insertps doesn't use
23848     // countS and just gets an f32 from that address.
23849     unsigned DestIndex =
23850         cast<ConstantSDNode>(N->getOperand(2))->getZExtValue() >> 6;
23851
23852     Ld = NarrowVectorLoadToElement(cast<LoadSDNode>(Ld), DestIndex, DAG);
23853
23854     // Create this as a scalar to vector to match the instruction pattern.
23855     SDValue LoadScalarToVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Ld);
23856     // countS bits are ignored when loading from memory on insertps, which
23857     // means we don't need to explicitly set them to 0.
23858     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N->getOperand(0),
23859                        LoadScalarToVector, N->getOperand(2));
23860   }
23861   return SDValue();
23862 }
23863
23864 static SDValue PerformBLENDICombine(SDNode *N, SelectionDAG &DAG) {
23865   SDValue V0 = N->getOperand(0);
23866   SDValue V1 = N->getOperand(1);
23867   SDLoc DL(N);
23868   EVT VT = N->getValueType(0);
23869
23870   // Canonicalize a v2f64 blend with a mask of 2 by swapping the vector
23871   // operands and changing the mask to 1. This saves us a bunch of
23872   // pattern-matching possibilities related to scalar math ops in SSE/AVX.
23873   // x86InstrInfo knows how to commute this back after instruction selection
23874   // if it would help register allocation.
23875
23876   // TODO: If optimizing for size or a processor that doesn't suffer from
23877   // partial register update stalls, this should be transformed into a MOVSD
23878   // instruction because a MOVSD is 1-2 bytes smaller than a BLENDPD.
23879
23880   if (VT == MVT::v2f64)
23881     if (auto *Mask = dyn_cast<ConstantSDNode>(N->getOperand(2)))
23882       if (Mask->getZExtValue() == 2 && !isShuffleFoldableLoad(V0)) {
23883         SDValue NewMask = DAG.getConstant(1, DL, MVT::i8);
23884         return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V0, NewMask);
23885       }
23886
23887   return SDValue();
23888 }
23889
23890 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
23891 // as "sbb reg,reg", since it can be extended without zext and produces
23892 // an all-ones bit which is more useful than 0/1 in some cases.
23893 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
23894                                MVT VT) {
23895   if (VT == MVT::i8)
23896     return DAG.getNode(ISD::AND, DL, VT,
23897                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
23898                                    DAG.getConstant(X86::COND_B, DL, MVT::i8),
23899                                    EFLAGS),
23900                        DAG.getConstant(1, DL, VT));
23901   assert (VT == MVT::i1 && "Unexpected type for SECCC node");
23902   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
23903                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
23904                                  DAG.getConstant(X86::COND_B, DL, MVT::i8),
23905                                  EFLAGS));
23906 }
23907
23908 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
23909 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
23910                                    TargetLowering::DAGCombinerInfo &DCI,
23911                                    const X86Subtarget *Subtarget) {
23912   SDLoc DL(N);
23913   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
23914   SDValue EFLAGS = N->getOperand(1);
23915
23916   if (CC == X86::COND_A) {
23917     // Try to convert COND_A into COND_B in an attempt to facilitate
23918     // materializing "setb reg".
23919     //
23920     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
23921     // cannot take an immediate as its first operand.
23922     //
23923     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
23924         EFLAGS.getValueType().isInteger() &&
23925         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
23926       SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
23927                                    EFLAGS.getNode()->getVTList(),
23928                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
23929       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
23930       return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
23931     }
23932   }
23933
23934   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
23935   // a zext and produces an all-ones bit which is more useful than 0/1 in some
23936   // cases.
23937   if (CC == X86::COND_B)
23938     return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
23939
23940   SDValue Flags;
23941
23942   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
23943   if (Flags.getNode()) {
23944     SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
23945     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
23946   }
23947
23948   return SDValue();
23949 }
23950
23951 // Optimize branch condition evaluation.
23952 //
23953 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
23954                                     TargetLowering::DAGCombinerInfo &DCI,
23955                                     const X86Subtarget *Subtarget) {
23956   SDLoc DL(N);
23957   SDValue Chain = N->getOperand(0);
23958   SDValue Dest = N->getOperand(1);
23959   SDValue EFLAGS = N->getOperand(3);
23960   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
23961
23962   SDValue Flags;
23963
23964   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
23965   if (Flags.getNode()) {
23966     SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
23967     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
23968                        Flags);
23969   }
23970
23971   return SDValue();
23972 }
23973
23974 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
23975                                                          SelectionDAG &DAG) {
23976   // Take advantage of vector comparisons producing 0 or -1 in each lane to
23977   // optimize away operation when it's from a constant.
23978   //
23979   // The general transformation is:
23980   //    UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
23981   //       AND(VECTOR_CMP(x,y), constant2)
23982   //    constant2 = UNARYOP(constant)
23983
23984   // Early exit if this isn't a vector operation, the operand of the
23985   // unary operation isn't a bitwise AND, or if the sizes of the operations
23986   // aren't the same.
23987   EVT VT = N->getValueType(0);
23988   if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
23989       N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
23990       VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
23991     return SDValue();
23992
23993   // Now check that the other operand of the AND is a constant. We could
23994   // make the transformation for non-constant splats as well, but it's unclear
23995   // that would be a benefit as it would not eliminate any operations, just
23996   // perform one more step in scalar code before moving to the vector unit.
23997   if (BuildVectorSDNode *BV =
23998           dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
23999     // Bail out if the vector isn't a constant.
24000     if (!BV->isConstant())
24001       return SDValue();
24002
24003     // Everything checks out. Build up the new and improved node.
24004     SDLoc DL(N);
24005     EVT IntVT = BV->getValueType(0);
24006     // Create a new constant of the appropriate type for the transformed
24007     // DAG.
24008     SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
24009     // The AND node needs bitcasts to/from an integer vector type around it.
24010     SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
24011     SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
24012                                  N->getOperand(0)->getOperand(0), MaskConst);
24013     SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
24014     return Res;
24015   }
24016
24017   return SDValue();
24018 }
24019
24020 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
24021                                         const X86Subtarget *Subtarget) {
24022   // First try to optimize away the conversion entirely when it's
24023   // conditionally from a constant. Vectors only.
24024   SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG);
24025   if (Res != SDValue())
24026     return Res;
24027
24028   // Now move on to more general possibilities.
24029   SDValue Op0 = N->getOperand(0);
24030   EVT InVT = Op0->getValueType(0);
24031
24032   // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
24033   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
24034     SDLoc dl(N);
24035     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
24036     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
24037     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
24038   }
24039
24040   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
24041   // a 32-bit target where SSE doesn't support i64->FP operations.
24042   if (Op0.getOpcode() == ISD::LOAD) {
24043     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
24044     EVT VT = Ld->getValueType(0);
24045
24046     // This transformation is not supported if the result type is f16
24047     if (N->getValueType(0) == MVT::f16)
24048       return SDValue();
24049
24050     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
24051         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
24052         !Subtarget->is64Bit() && VT == MVT::i64) {
24053       SDValue FILDChain = Subtarget->getTargetLowering()->BuildFILD(
24054           SDValue(N, 0), Ld->getValueType(0), Ld->getChain(), Op0, DAG);
24055       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
24056       return FILDChain;
24057     }
24058   }
24059   return SDValue();
24060 }
24061
24062 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
24063 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
24064                                  X86TargetLowering::DAGCombinerInfo &DCI) {
24065   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
24066   // the result is either zero or one (depending on the input carry bit).
24067   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
24068   if (X86::isZeroNode(N->getOperand(0)) &&
24069       X86::isZeroNode(N->getOperand(1)) &&
24070       // We don't have a good way to replace an EFLAGS use, so only do this when
24071       // dead right now.
24072       SDValue(N, 1).use_empty()) {
24073     SDLoc DL(N);
24074     EVT VT = N->getValueType(0);
24075     SDValue CarryOut = DAG.getConstant(0, DL, N->getValueType(1));
24076     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
24077                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
24078                                            DAG.getConstant(X86::COND_B, DL,
24079                                                            MVT::i8),
24080                                            N->getOperand(2)),
24081                                DAG.getConstant(1, DL, VT));
24082     return DCI.CombineTo(N, Res1, CarryOut);
24083   }
24084
24085   return SDValue();
24086 }
24087
24088 // fold (add Y, (sete  X, 0)) -> adc  0, Y
24089 //      (add Y, (setne X, 0)) -> sbb -1, Y
24090 //      (sub (sete  X, 0), Y) -> sbb  0, Y
24091 //      (sub (setne X, 0), Y) -> adc -1, Y
24092 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
24093   SDLoc DL(N);
24094
24095   // Look through ZExts.
24096   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
24097   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
24098     return SDValue();
24099
24100   SDValue SetCC = Ext.getOperand(0);
24101   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
24102     return SDValue();
24103
24104   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
24105   if (CC != X86::COND_E && CC != X86::COND_NE)
24106     return SDValue();
24107
24108   SDValue Cmp = SetCC.getOperand(1);
24109   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
24110       !X86::isZeroNode(Cmp.getOperand(1)) ||
24111       !Cmp.getOperand(0).getValueType().isInteger())
24112     return SDValue();
24113
24114   SDValue CmpOp0 = Cmp.getOperand(0);
24115   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
24116                                DAG.getConstant(1, DL, CmpOp0.getValueType()));
24117
24118   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
24119   if (CC == X86::COND_NE)
24120     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
24121                        DL, OtherVal.getValueType(), OtherVal,
24122                        DAG.getConstant(-1ULL, DL, OtherVal.getValueType()),
24123                        NewCmp);
24124   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
24125                      DL, OtherVal.getValueType(), OtherVal,
24126                      DAG.getConstant(0, DL, OtherVal.getValueType()), NewCmp);
24127 }
24128
24129 /// PerformADDCombine - Do target-specific dag combines on integer adds.
24130 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
24131                                  const X86Subtarget *Subtarget) {
24132   EVT VT = N->getValueType(0);
24133   SDValue Op0 = N->getOperand(0);
24134   SDValue Op1 = N->getOperand(1);
24135
24136   // Try to synthesize horizontal adds from adds of shuffles.
24137   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
24138        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
24139       isHorizontalBinOp(Op0, Op1, true))
24140     return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
24141
24142   return OptimizeConditionalInDecrement(N, DAG);
24143 }
24144
24145 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
24146                                  const X86Subtarget *Subtarget) {
24147   SDValue Op0 = N->getOperand(0);
24148   SDValue Op1 = N->getOperand(1);
24149
24150   // X86 can't encode an immediate LHS of a sub. See if we can push the
24151   // negation into a preceding instruction.
24152   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
24153     // If the RHS of the sub is a XOR with one use and a constant, invert the
24154     // immediate. Then add one to the LHS of the sub so we can turn
24155     // X-Y -> X+~Y+1, saving one register.
24156     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
24157         isa<ConstantSDNode>(Op1.getOperand(1))) {
24158       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
24159       EVT VT = Op0.getValueType();
24160       SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
24161                                    Op1.getOperand(0),
24162                                    DAG.getConstant(~XorC, SDLoc(Op1), VT));
24163       return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
24164                          DAG.getConstant(C->getAPIntValue() + 1, SDLoc(N), VT));
24165     }
24166   }
24167
24168   // Try to synthesize horizontal adds from adds of shuffles.
24169   EVT VT = N->getValueType(0);
24170   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
24171        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
24172       isHorizontalBinOp(Op0, Op1, true))
24173     return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
24174
24175   return OptimizeConditionalInDecrement(N, DAG);
24176 }
24177
24178 /// performVZEXTCombine - Performs build vector combines
24179 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
24180                                    TargetLowering::DAGCombinerInfo &DCI,
24181                                    const X86Subtarget *Subtarget) {
24182   SDLoc DL(N);
24183   MVT VT = N->getSimpleValueType(0);
24184   SDValue Op = N->getOperand(0);
24185   MVT OpVT = Op.getSimpleValueType();
24186   MVT OpEltVT = OpVT.getVectorElementType();
24187   unsigned InputBits = OpEltVT.getSizeInBits() * VT.getVectorNumElements();
24188
24189   // (vzext (bitcast (vzext (x)) -> (vzext x)
24190   SDValue V = Op;
24191   while (V.getOpcode() == ISD::BITCAST)
24192     V = V.getOperand(0);
24193
24194   if (V != Op && V.getOpcode() == X86ISD::VZEXT) {
24195     MVT InnerVT = V.getSimpleValueType();
24196     MVT InnerEltVT = InnerVT.getVectorElementType();
24197
24198     // If the element sizes match exactly, we can just do one larger vzext. This
24199     // is always an exact type match as vzext operates on integer types.
24200     if (OpEltVT == InnerEltVT) {
24201       assert(OpVT == InnerVT && "Types must match for vzext!");
24202       return DAG.getNode(X86ISD::VZEXT, DL, VT, V.getOperand(0));
24203     }
24204
24205     // The only other way we can combine them is if only a single element of the
24206     // inner vzext is used in the input to the outer vzext.
24207     if (InnerEltVT.getSizeInBits() < InputBits)
24208       return SDValue();
24209
24210     // In this case, the inner vzext is completely dead because we're going to
24211     // only look at bits inside of the low element. Just do the outer vzext on
24212     // a bitcast of the input to the inner.
24213     return DAG.getNode(X86ISD::VZEXT, DL, VT,
24214                        DAG.getNode(ISD::BITCAST, DL, OpVT, V));
24215   }
24216
24217   // Check if we can bypass extracting and re-inserting an element of an input
24218   // vector. Essentialy:
24219   // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
24220   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR &&
24221       V.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
24222       V.getOperand(0).getSimpleValueType().getSizeInBits() == InputBits) {
24223     SDValue ExtractedV = V.getOperand(0);
24224     SDValue OrigV = ExtractedV.getOperand(0);
24225     if (auto *ExtractIdx = dyn_cast<ConstantSDNode>(ExtractedV.getOperand(1)))
24226       if (ExtractIdx->getZExtValue() == 0) {
24227         MVT OrigVT = OrigV.getSimpleValueType();
24228         // Extract a subvector if necessary...
24229         if (OrigVT.getSizeInBits() > OpVT.getSizeInBits()) {
24230           int Ratio = OrigVT.getSizeInBits() / OpVT.getSizeInBits();
24231           OrigVT = MVT::getVectorVT(OrigVT.getVectorElementType(),
24232                                     OrigVT.getVectorNumElements() / Ratio);
24233           OrigV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigVT, OrigV,
24234                               DAG.getIntPtrConstant(0, DL));
24235         }
24236         Op = DAG.getNode(ISD::BITCAST, DL, OpVT, OrigV);
24237         return DAG.getNode(X86ISD::VZEXT, DL, VT, Op);
24238       }
24239   }
24240
24241   return SDValue();
24242 }
24243
24244 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
24245                                              DAGCombinerInfo &DCI) const {
24246   SelectionDAG &DAG = DCI.DAG;
24247   switch (N->getOpcode()) {
24248   default: break;
24249   case ISD::EXTRACT_VECTOR_ELT:
24250     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
24251   case ISD::VSELECT:
24252   case ISD::SELECT:
24253   case X86ISD::SHRUNKBLEND:
24254     return PerformSELECTCombine(N, DAG, DCI, Subtarget);
24255   case ISD::BITCAST:        return PerformBITCASTCombine(N, DAG);
24256   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
24257   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
24258   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
24259   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
24260   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
24261   case ISD::SHL:
24262   case ISD::SRA:
24263   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
24264   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
24265   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
24266   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
24267   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
24268   case ISD::MLOAD:          return PerformMLOADCombine(N, DAG, DCI, Subtarget);
24269   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
24270   case ISD::MSTORE:         return PerformMSTORECombine(N, DAG, Subtarget);
24271   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, Subtarget);
24272   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
24273   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
24274   case X86ISD::FXOR:
24275   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
24276   case X86ISD::FMIN:
24277   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
24278   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
24279   case X86ISD::FANDN:       return PerformFANDNCombine(N, DAG);
24280   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
24281   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
24282   case ISD::ANY_EXTEND:
24283   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
24284   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
24285   case ISD::SIGN_EXTEND_INREG:
24286     return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
24287   case ISD::TRUNCATE:       return PerformTruncateCombine(N, DAG,DCI,Subtarget);
24288   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG, Subtarget);
24289   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
24290   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
24291   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
24292   case X86ISD::SHUFP:       // Handle all target specific shuffles
24293   case X86ISD::PALIGNR:
24294   case X86ISD::UNPCKH:
24295   case X86ISD::UNPCKL:
24296   case X86ISD::MOVHLPS:
24297   case X86ISD::MOVLHPS:
24298   case X86ISD::PSHUFB:
24299   case X86ISD::PSHUFD:
24300   case X86ISD::PSHUFHW:
24301   case X86ISD::PSHUFLW:
24302   case X86ISD::MOVSS:
24303   case X86ISD::MOVSD:
24304   case X86ISD::VPERMILPI:
24305   case X86ISD::VPERM2X128:
24306   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
24307   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
24308   case ISD::INTRINSIC_WO_CHAIN:
24309     return PerformINTRINSIC_WO_CHAINCombine(N, DAG, Subtarget);
24310   case X86ISD::INSERTPS: {
24311     if (getTargetMachine().getOptLevel() > CodeGenOpt::None)
24312       return PerformINSERTPSCombine(N, DAG, Subtarget);
24313     break;
24314   }
24315   case X86ISD::BLENDI:    return PerformBLENDICombine(N, DAG);
24316   }
24317
24318   return SDValue();
24319 }
24320
24321 /// isTypeDesirableForOp - Return true if the target has native support for
24322 /// the specified value type and it is 'desirable' to use the type for the
24323 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
24324 /// instruction encodings are longer and some i16 instructions are slow.
24325 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
24326   if (!isTypeLegal(VT))
24327     return false;
24328   if (VT != MVT::i16)
24329     return true;
24330
24331   switch (Opc) {
24332   default:
24333     return true;
24334   case ISD::LOAD:
24335   case ISD::SIGN_EXTEND:
24336   case ISD::ZERO_EXTEND:
24337   case ISD::ANY_EXTEND:
24338   case ISD::SHL:
24339   case ISD::SRL:
24340   case ISD::SUB:
24341   case ISD::ADD:
24342   case ISD::MUL:
24343   case ISD::AND:
24344   case ISD::OR:
24345   case ISD::XOR:
24346     return false;
24347   }
24348 }
24349
24350 /// IsDesirableToPromoteOp - This method query the target whether it is
24351 /// beneficial for dag combiner to promote the specified node. If true, it
24352 /// should return the desired promotion type by reference.
24353 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
24354   EVT VT = Op.getValueType();
24355   if (VT != MVT::i16)
24356     return false;
24357
24358   bool Promote = false;
24359   bool Commute = false;
24360   switch (Op.getOpcode()) {
24361   default: break;
24362   case ISD::LOAD: {
24363     LoadSDNode *LD = cast<LoadSDNode>(Op);
24364     // If the non-extending load has a single use and it's not live out, then it
24365     // might be folded.
24366     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
24367                                                      Op.hasOneUse()*/) {
24368       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
24369              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
24370         // The only case where we'd want to promote LOAD (rather then it being
24371         // promoted as an operand is when it's only use is liveout.
24372         if (UI->getOpcode() != ISD::CopyToReg)
24373           return false;
24374       }
24375     }
24376     Promote = true;
24377     break;
24378   }
24379   case ISD::SIGN_EXTEND:
24380   case ISD::ZERO_EXTEND:
24381   case ISD::ANY_EXTEND:
24382     Promote = true;
24383     break;
24384   case ISD::SHL:
24385   case ISD::SRL: {
24386     SDValue N0 = Op.getOperand(0);
24387     // Look out for (store (shl (load), x)).
24388     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
24389       return false;
24390     Promote = true;
24391     break;
24392   }
24393   case ISD::ADD:
24394   case ISD::MUL:
24395   case ISD::AND:
24396   case ISD::OR:
24397   case ISD::XOR:
24398     Commute = true;
24399     // fallthrough
24400   case ISD::SUB: {
24401     SDValue N0 = Op.getOperand(0);
24402     SDValue N1 = Op.getOperand(1);
24403     if (!Commute && MayFoldLoad(N1))
24404       return false;
24405     // Avoid disabling potential load folding opportunities.
24406     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
24407       return false;
24408     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
24409       return false;
24410     Promote = true;
24411   }
24412   }
24413
24414   PVT = MVT::i32;
24415   return Promote;
24416 }
24417
24418 //===----------------------------------------------------------------------===//
24419 //                           X86 Inline Assembly Support
24420 //===----------------------------------------------------------------------===//
24421
24422 // Helper to match a string separated by whitespace.
24423 static bool matchAsm(StringRef S, ArrayRef<const char *> Pieces) {
24424   S = S.substr(S.find_first_not_of(" \t")); // Skip leading whitespace.
24425
24426   for (StringRef Piece : Pieces) {
24427     if (!S.startswith(Piece)) // Check if the piece matches.
24428       return false;
24429
24430     S = S.substr(Piece.size());
24431     StringRef::size_type Pos = S.find_first_not_of(" \t");
24432     if (Pos == 0) // We matched a prefix.
24433       return false;
24434
24435     S = S.substr(Pos);
24436   }
24437
24438   return S.empty();
24439 }
24440
24441 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
24442
24443   if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
24444     if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
24445         std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
24446         std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
24447
24448       if (AsmPieces.size() == 3)
24449         return true;
24450       else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
24451         return true;
24452     }
24453   }
24454   return false;
24455 }
24456
24457 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
24458   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
24459
24460   std::string AsmStr = IA->getAsmString();
24461
24462   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
24463   if (!Ty || Ty->getBitWidth() % 16 != 0)
24464     return false;
24465
24466   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
24467   SmallVector<StringRef, 4> AsmPieces;
24468   SplitString(AsmStr, AsmPieces, ";\n");
24469
24470   switch (AsmPieces.size()) {
24471   default: return false;
24472   case 1:
24473     // FIXME: this should verify that we are targeting a 486 or better.  If not,
24474     // we will turn this bswap into something that will be lowered to logical
24475     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
24476     // lower so don't worry about this.
24477     // bswap $0
24478     if (matchAsm(AsmPieces[0], {"bswap", "$0"}) ||
24479         matchAsm(AsmPieces[0], {"bswapl", "$0"}) ||
24480         matchAsm(AsmPieces[0], {"bswapq", "$0"}) ||
24481         matchAsm(AsmPieces[0], {"bswap", "${0:q}"}) ||
24482         matchAsm(AsmPieces[0], {"bswapl", "${0:q}"}) ||
24483         matchAsm(AsmPieces[0], {"bswapq", "${0:q}"})) {
24484       // No need to check constraints, nothing other than the equivalent of
24485       // "=r,0" would be valid here.
24486       return IntrinsicLowering::LowerToByteSwap(CI);
24487     }
24488
24489     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
24490     if (CI->getType()->isIntegerTy(16) &&
24491         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
24492         (matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) ||
24493          matchAsm(AsmPieces[0], {"rolw", "$$8,", "${0:w}"}))) {
24494       AsmPieces.clear();
24495       const std::string &ConstraintsStr = IA->getConstraintString();
24496       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
24497       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
24498       if (clobbersFlagRegisters(AsmPieces))
24499         return IntrinsicLowering::LowerToByteSwap(CI);
24500     }
24501     break;
24502   case 3:
24503     if (CI->getType()->isIntegerTy(32) &&
24504         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
24505         matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) &&
24506         matchAsm(AsmPieces[1], {"rorl", "$$16,", "$0"}) &&
24507         matchAsm(AsmPieces[2], {"rorw", "$$8,", "${0:w}"})) {
24508       AsmPieces.clear();
24509       const std::string &ConstraintsStr = IA->getConstraintString();
24510       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
24511       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
24512       if (clobbersFlagRegisters(AsmPieces))
24513         return IntrinsicLowering::LowerToByteSwap(CI);
24514     }
24515
24516     if (CI->getType()->isIntegerTy(64)) {
24517       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
24518       if (Constraints.size() >= 2 &&
24519           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
24520           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
24521         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
24522         if (matchAsm(AsmPieces[0], {"bswap", "%eax"}) &&
24523             matchAsm(AsmPieces[1], {"bswap", "%edx"}) &&
24524             matchAsm(AsmPieces[2], {"xchgl", "%eax,", "%edx"}))
24525           return IntrinsicLowering::LowerToByteSwap(CI);
24526       }
24527     }
24528     break;
24529   }
24530   return false;
24531 }
24532
24533 /// getConstraintType - Given a constraint letter, return the type of
24534 /// constraint it is for this target.
24535 X86TargetLowering::ConstraintType
24536 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
24537   if (Constraint.size() == 1) {
24538     switch (Constraint[0]) {
24539     case 'R':
24540     case 'q':
24541     case 'Q':
24542     case 'f':
24543     case 't':
24544     case 'u':
24545     case 'y':
24546     case 'x':
24547     case 'Y':
24548     case 'l':
24549       return C_RegisterClass;
24550     case 'a':
24551     case 'b':
24552     case 'c':
24553     case 'd':
24554     case 'S':
24555     case 'D':
24556     case 'A':
24557       return C_Register;
24558     case 'I':
24559     case 'J':
24560     case 'K':
24561     case 'L':
24562     case 'M':
24563     case 'N':
24564     case 'G':
24565     case 'C':
24566     case 'e':
24567     case 'Z':
24568       return C_Other;
24569     default:
24570       break;
24571     }
24572   }
24573   return TargetLowering::getConstraintType(Constraint);
24574 }
24575
24576 /// Examine constraint type and operand type and determine a weight value.
24577 /// This object must already have been set up with the operand type
24578 /// and the current alternative constraint selected.
24579 TargetLowering::ConstraintWeight
24580   X86TargetLowering::getSingleConstraintMatchWeight(
24581     AsmOperandInfo &info, const char *constraint) const {
24582   ConstraintWeight weight = CW_Invalid;
24583   Value *CallOperandVal = info.CallOperandVal;
24584     // If we don't have a value, we can't do a match,
24585     // but allow it at the lowest weight.
24586   if (!CallOperandVal)
24587     return CW_Default;
24588   Type *type = CallOperandVal->getType();
24589   // Look at the constraint type.
24590   switch (*constraint) {
24591   default:
24592     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
24593   case 'R':
24594   case 'q':
24595   case 'Q':
24596   case 'a':
24597   case 'b':
24598   case 'c':
24599   case 'd':
24600   case 'S':
24601   case 'D':
24602   case 'A':
24603     if (CallOperandVal->getType()->isIntegerTy())
24604       weight = CW_SpecificReg;
24605     break;
24606   case 'f':
24607   case 't':
24608   case 'u':
24609     if (type->isFloatingPointTy())
24610       weight = CW_SpecificReg;
24611     break;
24612   case 'y':
24613     if (type->isX86_MMXTy() && Subtarget->hasMMX())
24614       weight = CW_SpecificReg;
24615     break;
24616   case 'x':
24617   case 'Y':
24618     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
24619         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
24620       weight = CW_Register;
24621     break;
24622   case 'I':
24623     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
24624       if (C->getZExtValue() <= 31)
24625         weight = CW_Constant;
24626     }
24627     break;
24628   case 'J':
24629     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24630       if (C->getZExtValue() <= 63)
24631         weight = CW_Constant;
24632     }
24633     break;
24634   case 'K':
24635     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24636       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
24637         weight = CW_Constant;
24638     }
24639     break;
24640   case 'L':
24641     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24642       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
24643         weight = CW_Constant;
24644     }
24645     break;
24646   case 'M':
24647     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24648       if (C->getZExtValue() <= 3)
24649         weight = CW_Constant;
24650     }
24651     break;
24652   case 'N':
24653     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24654       if (C->getZExtValue() <= 0xff)
24655         weight = CW_Constant;
24656     }
24657     break;
24658   case 'G':
24659   case 'C':
24660     if (isa<ConstantFP>(CallOperandVal)) {
24661       weight = CW_Constant;
24662     }
24663     break;
24664   case 'e':
24665     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24666       if ((C->getSExtValue() >= -0x80000000LL) &&
24667           (C->getSExtValue() <= 0x7fffffffLL))
24668         weight = CW_Constant;
24669     }
24670     break;
24671   case 'Z':
24672     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24673       if (C->getZExtValue() <= 0xffffffff)
24674         weight = CW_Constant;
24675     }
24676     break;
24677   }
24678   return weight;
24679 }
24680
24681 /// LowerXConstraint - try to replace an X constraint, which matches anything,
24682 /// with another that has more specific requirements based on the type of the
24683 /// corresponding operand.
24684 const char *X86TargetLowering::
24685 LowerXConstraint(EVT ConstraintVT) const {
24686   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
24687   // 'f' like normal targets.
24688   if (ConstraintVT.isFloatingPoint()) {
24689     if (Subtarget->hasSSE2())
24690       return "Y";
24691     if (Subtarget->hasSSE1())
24692       return "x";
24693   }
24694
24695   return TargetLowering::LowerXConstraint(ConstraintVT);
24696 }
24697
24698 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
24699 /// vector.  If it is invalid, don't add anything to Ops.
24700 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
24701                                                      std::string &Constraint,
24702                                                      std::vector<SDValue>&Ops,
24703                                                      SelectionDAG &DAG) const {
24704   SDValue Result;
24705
24706   // Only support length 1 constraints for now.
24707   if (Constraint.length() > 1) return;
24708
24709   char ConstraintLetter = Constraint[0];
24710   switch (ConstraintLetter) {
24711   default: break;
24712   case 'I':
24713     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24714       if (C->getZExtValue() <= 31) {
24715         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
24716                                        Op.getValueType());
24717         break;
24718       }
24719     }
24720     return;
24721   case 'J':
24722     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24723       if (C->getZExtValue() <= 63) {
24724         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
24725                                        Op.getValueType());
24726         break;
24727       }
24728     }
24729     return;
24730   case 'K':
24731     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24732       if (isInt<8>(C->getSExtValue())) {
24733         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
24734                                        Op.getValueType());
24735         break;
24736       }
24737     }
24738     return;
24739   case 'L':
24740     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24741       if (C->getZExtValue() == 0xff || C->getZExtValue() == 0xffff ||
24742           (Subtarget->is64Bit() && C->getZExtValue() == 0xffffffff)) {
24743         Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op),
24744                                        Op.getValueType());
24745         break;
24746       }
24747     }
24748     return;
24749   case 'M':
24750     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24751       if (C->getZExtValue() <= 3) {
24752         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
24753                                        Op.getValueType());
24754         break;
24755       }
24756     }
24757     return;
24758   case 'N':
24759     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24760       if (C->getZExtValue() <= 255) {
24761         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
24762                                        Op.getValueType());
24763         break;
24764       }
24765     }
24766     return;
24767   case 'O':
24768     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24769       if (C->getZExtValue() <= 127) {
24770         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
24771                                        Op.getValueType());
24772         break;
24773       }
24774     }
24775     return;
24776   case 'e': {
24777     // 32-bit signed value
24778     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24779       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
24780                                            C->getSExtValue())) {
24781         // Widen to 64 bits here to get it sign extended.
24782         Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op), MVT::i64);
24783         break;
24784       }
24785     // FIXME gcc accepts some relocatable values here too, but only in certain
24786     // memory models; it's complicated.
24787     }
24788     return;
24789   }
24790   case 'Z': {
24791     // 32-bit unsigned value
24792     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24793       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
24794                                            C->getZExtValue())) {
24795         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
24796                                        Op.getValueType());
24797         break;
24798       }
24799     }
24800     // FIXME gcc accepts some relocatable values here too, but only in certain
24801     // memory models; it's complicated.
24802     return;
24803   }
24804   case 'i': {
24805     // Literal immediates are always ok.
24806     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
24807       // Widen to 64 bits here to get it sign extended.
24808       Result = DAG.getTargetConstant(CST->getSExtValue(), SDLoc(Op), MVT::i64);
24809       break;
24810     }
24811
24812     // In any sort of PIC mode addresses need to be computed at runtime by
24813     // adding in a register or some sort of table lookup.  These can't
24814     // be used as immediates.
24815     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
24816       return;
24817
24818     // If we are in non-pic codegen mode, we allow the address of a global (with
24819     // an optional displacement) to be used with 'i'.
24820     GlobalAddressSDNode *GA = nullptr;
24821     int64_t Offset = 0;
24822
24823     // Match either (GA), (GA+C), (GA+C1+C2), etc.
24824     while (1) {
24825       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
24826         Offset += GA->getOffset();
24827         break;
24828       } else if (Op.getOpcode() == ISD::ADD) {
24829         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
24830           Offset += C->getZExtValue();
24831           Op = Op.getOperand(0);
24832           continue;
24833         }
24834       } else if (Op.getOpcode() == ISD::SUB) {
24835         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
24836           Offset += -C->getZExtValue();
24837           Op = Op.getOperand(0);
24838           continue;
24839         }
24840       }
24841
24842       // Otherwise, this isn't something we can handle, reject it.
24843       return;
24844     }
24845
24846     const GlobalValue *GV = GA->getGlobal();
24847     // If we require an extra load to get this address, as in PIC mode, we
24848     // can't accept it.
24849     if (isGlobalStubReference(
24850             Subtarget->ClassifyGlobalReference(GV, DAG.getTarget())))
24851       return;
24852
24853     Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
24854                                         GA->getValueType(0), Offset);
24855     break;
24856   }
24857   }
24858
24859   if (Result.getNode()) {
24860     Ops.push_back(Result);
24861     return;
24862   }
24863   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
24864 }
24865
24866 std::pair<unsigned, const TargetRegisterClass *>
24867 X86TargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
24868                                                 const std::string &Constraint,
24869                                                 MVT VT) const {
24870   // First, see if this is a constraint that directly corresponds to an LLVM
24871   // register class.
24872   if (Constraint.size() == 1) {
24873     // GCC Constraint Letters
24874     switch (Constraint[0]) {
24875     default: break;
24876       // TODO: Slight differences here in allocation order and leaving
24877       // RIP in the class. Do they matter any more here than they do
24878       // in the normal allocation?
24879     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
24880       if (Subtarget->is64Bit()) {
24881         if (VT == MVT::i32 || VT == MVT::f32)
24882           return std::make_pair(0U, &X86::GR32RegClass);
24883         if (VT == MVT::i16)
24884           return std::make_pair(0U, &X86::GR16RegClass);
24885         if (VT == MVT::i8 || VT == MVT::i1)
24886           return std::make_pair(0U, &X86::GR8RegClass);
24887         if (VT == MVT::i64 || VT == MVT::f64)
24888           return std::make_pair(0U, &X86::GR64RegClass);
24889         break;
24890       }
24891       // 32-bit fallthrough
24892     case 'Q':   // Q_REGS
24893       if (VT == MVT::i32 || VT == MVT::f32)
24894         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
24895       if (VT == MVT::i16)
24896         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
24897       if (VT == MVT::i8 || VT == MVT::i1)
24898         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
24899       if (VT == MVT::i64)
24900         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
24901       break;
24902     case 'r':   // GENERAL_REGS
24903     case 'l':   // INDEX_REGS
24904       if (VT == MVT::i8 || VT == MVT::i1)
24905         return std::make_pair(0U, &X86::GR8RegClass);
24906       if (VT == MVT::i16)
24907         return std::make_pair(0U, &X86::GR16RegClass);
24908       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
24909         return std::make_pair(0U, &X86::GR32RegClass);
24910       return std::make_pair(0U, &X86::GR64RegClass);
24911     case 'R':   // LEGACY_REGS
24912       if (VT == MVT::i8 || VT == MVT::i1)
24913         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
24914       if (VT == MVT::i16)
24915         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
24916       if (VT == MVT::i32 || !Subtarget->is64Bit())
24917         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
24918       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
24919     case 'f':  // FP Stack registers.
24920       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
24921       // value to the correct fpstack register class.
24922       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
24923         return std::make_pair(0U, &X86::RFP32RegClass);
24924       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
24925         return std::make_pair(0U, &X86::RFP64RegClass);
24926       return std::make_pair(0U, &X86::RFP80RegClass);
24927     case 'y':   // MMX_REGS if MMX allowed.
24928       if (!Subtarget->hasMMX()) break;
24929       return std::make_pair(0U, &X86::VR64RegClass);
24930     case 'Y':   // SSE_REGS if SSE2 allowed
24931       if (!Subtarget->hasSSE2()) break;
24932       // FALL THROUGH.
24933     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
24934       if (!Subtarget->hasSSE1()) break;
24935
24936       switch (VT.SimpleTy) {
24937       default: break;
24938       // Scalar SSE types.
24939       case MVT::f32:
24940       case MVT::i32:
24941         return std::make_pair(0U, &X86::FR32RegClass);
24942       case MVT::f64:
24943       case MVT::i64:
24944         return std::make_pair(0U, &X86::FR64RegClass);
24945       // Vector types.
24946       case MVT::v16i8:
24947       case MVT::v8i16:
24948       case MVT::v4i32:
24949       case MVT::v2i64:
24950       case MVT::v4f32:
24951       case MVT::v2f64:
24952         return std::make_pair(0U, &X86::VR128RegClass);
24953       // AVX types.
24954       case MVT::v32i8:
24955       case MVT::v16i16:
24956       case MVT::v8i32:
24957       case MVT::v4i64:
24958       case MVT::v8f32:
24959       case MVT::v4f64:
24960         return std::make_pair(0U, &X86::VR256RegClass);
24961       case MVT::v8f64:
24962       case MVT::v16f32:
24963       case MVT::v16i32:
24964       case MVT::v8i64:
24965         return std::make_pair(0U, &X86::VR512RegClass);
24966       }
24967       break;
24968     }
24969   }
24970
24971   // Use the default implementation in TargetLowering to convert the register
24972   // constraint into a member of a register class.
24973   std::pair<unsigned, const TargetRegisterClass*> Res;
24974   Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
24975
24976   // Not found as a standard register?
24977   if (!Res.second) {
24978     // Map st(0) -> st(7) -> ST0
24979     if (Constraint.size() == 7 && Constraint[0] == '{' &&
24980         tolower(Constraint[1]) == 's' &&
24981         tolower(Constraint[2]) == 't' &&
24982         Constraint[3] == '(' &&
24983         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
24984         Constraint[5] == ')' &&
24985         Constraint[6] == '}') {
24986
24987       Res.first = X86::FP0+Constraint[4]-'0';
24988       Res.second = &X86::RFP80RegClass;
24989       return Res;
24990     }
24991
24992     // GCC allows "st(0)" to be called just plain "st".
24993     if (StringRef("{st}").equals_lower(Constraint)) {
24994       Res.first = X86::FP0;
24995       Res.second = &X86::RFP80RegClass;
24996       return Res;
24997     }
24998
24999     // flags -> EFLAGS
25000     if (StringRef("{flags}").equals_lower(Constraint)) {
25001       Res.first = X86::EFLAGS;
25002       Res.second = &X86::CCRRegClass;
25003       return Res;
25004     }
25005
25006     // 'A' means EAX + EDX.
25007     if (Constraint == "A") {
25008       Res.first = X86::EAX;
25009       Res.second = &X86::GR32_ADRegClass;
25010       return Res;
25011     }
25012     return Res;
25013   }
25014
25015   // Otherwise, check to see if this is a register class of the wrong value
25016   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
25017   // turn into {ax},{dx}.
25018   if (Res.second->hasType(VT))
25019     return Res;   // Correct type already, nothing to do.
25020
25021   // All of the single-register GCC register classes map their values onto
25022   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
25023   // really want an 8-bit or 32-bit register, map to the appropriate register
25024   // class and return the appropriate register.
25025   if (Res.second == &X86::GR16RegClass) {
25026     if (VT == MVT::i8 || VT == MVT::i1) {
25027       unsigned DestReg = 0;
25028       switch (Res.first) {
25029       default: break;
25030       case X86::AX: DestReg = X86::AL; break;
25031       case X86::DX: DestReg = X86::DL; break;
25032       case X86::CX: DestReg = X86::CL; break;
25033       case X86::BX: DestReg = X86::BL; break;
25034       }
25035       if (DestReg) {
25036         Res.first = DestReg;
25037         Res.second = &X86::GR8RegClass;
25038       }
25039     } else if (VT == MVT::i32 || VT == MVT::f32) {
25040       unsigned DestReg = 0;
25041       switch (Res.first) {
25042       default: break;
25043       case X86::AX: DestReg = X86::EAX; break;
25044       case X86::DX: DestReg = X86::EDX; break;
25045       case X86::CX: DestReg = X86::ECX; break;
25046       case X86::BX: DestReg = X86::EBX; break;
25047       case X86::SI: DestReg = X86::ESI; break;
25048       case X86::DI: DestReg = X86::EDI; break;
25049       case X86::BP: DestReg = X86::EBP; break;
25050       case X86::SP: DestReg = X86::ESP; break;
25051       }
25052       if (DestReg) {
25053         Res.first = DestReg;
25054         Res.second = &X86::GR32RegClass;
25055       }
25056     } else if (VT == MVT::i64 || VT == MVT::f64) {
25057       unsigned DestReg = 0;
25058       switch (Res.first) {
25059       default: break;
25060       case X86::AX: DestReg = X86::RAX; break;
25061       case X86::DX: DestReg = X86::RDX; break;
25062       case X86::CX: DestReg = X86::RCX; break;
25063       case X86::BX: DestReg = X86::RBX; break;
25064       case X86::SI: DestReg = X86::RSI; break;
25065       case X86::DI: DestReg = X86::RDI; break;
25066       case X86::BP: DestReg = X86::RBP; break;
25067       case X86::SP: DestReg = X86::RSP; break;
25068       }
25069       if (DestReg) {
25070         Res.first = DestReg;
25071         Res.second = &X86::GR64RegClass;
25072       }
25073     }
25074   } else if (Res.second == &X86::FR32RegClass ||
25075              Res.second == &X86::FR64RegClass ||
25076              Res.second == &X86::VR128RegClass ||
25077              Res.second == &X86::VR256RegClass ||
25078              Res.second == &X86::FR32XRegClass ||
25079              Res.second == &X86::FR64XRegClass ||
25080              Res.second == &X86::VR128XRegClass ||
25081              Res.second == &X86::VR256XRegClass ||
25082              Res.second == &X86::VR512RegClass) {
25083     // Handle references to XMM physical registers that got mapped into the
25084     // wrong class.  This can happen with constraints like {xmm0} where the
25085     // target independent register mapper will just pick the first match it can
25086     // find, ignoring the required type.
25087
25088     if (VT == MVT::f32 || VT == MVT::i32)
25089       Res.second = &X86::FR32RegClass;
25090     else if (VT == MVT::f64 || VT == MVT::i64)
25091       Res.second = &X86::FR64RegClass;
25092     else if (X86::VR128RegClass.hasType(VT))
25093       Res.second = &X86::VR128RegClass;
25094     else if (X86::VR256RegClass.hasType(VT))
25095       Res.second = &X86::VR256RegClass;
25096     else if (X86::VR512RegClass.hasType(VT))
25097       Res.second = &X86::VR512RegClass;
25098   }
25099
25100   return Res;
25101 }
25102
25103 int X86TargetLowering::getScalingFactorCost(const AddrMode &AM,
25104                                             Type *Ty) const {
25105   // Scaling factors are not free at all.
25106   // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
25107   // will take 2 allocations in the out of order engine instead of 1
25108   // for plain addressing mode, i.e. inst (reg1).
25109   // E.g.,
25110   // vaddps (%rsi,%drx), %ymm0, %ymm1
25111   // Requires two allocations (one for the load, one for the computation)
25112   // whereas:
25113   // vaddps (%rsi), %ymm0, %ymm1
25114   // Requires just 1 allocation, i.e., freeing allocations for other operations
25115   // and having less micro operations to execute.
25116   //
25117   // For some X86 architectures, this is even worse because for instance for
25118   // stores, the complex addressing mode forces the instruction to use the
25119   // "load" ports instead of the dedicated "store" port.
25120   // E.g., on Haswell:
25121   // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
25122   // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.
25123   if (isLegalAddressingMode(AM, Ty))
25124     // Scale represents reg2 * scale, thus account for 1
25125     // as soon as we use a second register.
25126     return AM.Scale != 0;
25127   return -1;
25128 }
25129
25130 bool X86TargetLowering::isTargetFTOL() const {
25131   return Subtarget->isTargetKnownWindowsMSVC() && !Subtarget->is64Bit();
25132 }