AVX-512: fixed extended load to 512-bit register
[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     setOperationAction(ISD::SELECT,             MVT::v16i1, Custom);
1369     setOperationAction(ISD::SELECT,             MVT::v8i1,  Custom);
1370
1371     setOperationAction(ISD::ADD,                MVT::v8i64, Legal);
1372     setOperationAction(ISD::ADD,                MVT::v16i32, Legal);
1373
1374     setOperationAction(ISD::SUB,                MVT::v8i64, Legal);
1375     setOperationAction(ISD::SUB,                MVT::v16i32, Legal);
1376
1377     setOperationAction(ISD::MUL,                MVT::v16i32, Legal);
1378
1379     setOperationAction(ISD::SRL,                MVT::v8i64, Custom);
1380     setOperationAction(ISD::SRL,                MVT::v16i32, Custom);
1381
1382     setOperationAction(ISD::SHL,                MVT::v8i64, Custom);
1383     setOperationAction(ISD::SHL,                MVT::v16i32, Custom);
1384
1385     setOperationAction(ISD::SRA,                MVT::v8i64, Custom);
1386     setOperationAction(ISD::SRA,                MVT::v16i32, Custom);
1387
1388     setOperationAction(ISD::AND,                MVT::v8i64, Legal);
1389     setOperationAction(ISD::OR,                 MVT::v8i64, Legal);
1390     setOperationAction(ISD::XOR,                MVT::v8i64, Legal);
1391     setOperationAction(ISD::AND,                MVT::v16i32, Legal);
1392     setOperationAction(ISD::OR,                 MVT::v16i32, Legal);
1393     setOperationAction(ISD::XOR,                MVT::v16i32, Legal);
1394
1395     if (Subtarget->hasCDI()) {
1396       setOperationAction(ISD::CTLZ,             MVT::v8i64, Legal);
1397       setOperationAction(ISD::CTLZ,             MVT::v16i32, Legal);
1398     }
1399     if (Subtarget->hasDQI()) {
1400       setOperationAction(ISD::MUL,             MVT::v2i64, Legal);
1401       setOperationAction(ISD::MUL,             MVT::v4i64, Legal);
1402       setOperationAction(ISD::MUL,             MVT::v8i64, Legal);
1403     }
1404     // Custom lower several nodes.
1405     for (MVT VT : MVT::vector_valuetypes()) {
1406       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1407       if (EltSize == 1) {
1408         setOperationAction(ISD::AND, VT, Legal);
1409         setOperationAction(ISD::OR,  VT, Legal);
1410         setOperationAction(ISD::XOR,  VT, Legal);
1411       }
1412       if (EltSize >= 32 && VT.getSizeInBits() <= 512) {
1413         setOperationAction(ISD::MGATHER,  VT, Custom);
1414         setOperationAction(ISD::MSCATTER, VT, Custom);
1415       }
1416       // Extract subvector is special because the value type
1417       // (result) is 256/128-bit but the source is 512-bit wide.
1418       if (VT.is128BitVector() || VT.is256BitVector()) {
1419         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1420       }
1421       if (VT.getVectorElementType() == MVT::i1)
1422         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1423
1424       // Do not attempt to custom lower other non-512-bit vectors
1425       if (!VT.is512BitVector())
1426         continue;
1427
1428       if (EltSize >= 32) {
1429         setOperationAction(ISD::VECTOR_SHUFFLE,      VT, Custom);
1430         setOperationAction(ISD::INSERT_VECTOR_ELT,   VT, Custom);
1431         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1432         setOperationAction(ISD::VSELECT,             VT, Legal);
1433         setOperationAction(ISD::EXTRACT_VECTOR_ELT,  VT, Custom);
1434         setOperationAction(ISD::SCALAR_TO_VECTOR,    VT, Custom);
1435         setOperationAction(ISD::INSERT_SUBVECTOR,    VT, Custom);
1436         setOperationAction(ISD::MLOAD,               VT, Legal);
1437         setOperationAction(ISD::MSTORE,              VT, Legal);
1438       }
1439     }
1440     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1441       MVT VT = (MVT::SimpleValueType)i;
1442
1443       // Do not attempt to promote non-512-bit vectors.
1444       if (!VT.is512BitVector())
1445         continue;
1446
1447       setOperationAction(ISD::SELECT, VT, Promote);
1448       AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1449     }
1450   }// has  AVX-512
1451
1452   if (!Subtarget->useSoftFloat() && Subtarget->hasBWI()) {
1453     addRegisterClass(MVT::v32i16, &X86::VR512RegClass);
1454     addRegisterClass(MVT::v64i8,  &X86::VR512RegClass);
1455
1456     addRegisterClass(MVT::v32i1,  &X86::VK32RegClass);
1457     addRegisterClass(MVT::v64i1,  &X86::VK64RegClass);
1458
1459     setOperationAction(ISD::LOAD,               MVT::v32i16, Legal);
1460     setOperationAction(ISD::LOAD,               MVT::v64i8, Legal);
1461     setOperationAction(ISD::SETCC,              MVT::v32i1, Custom);
1462     setOperationAction(ISD::SETCC,              MVT::v64i1, Custom);
1463     setOperationAction(ISD::ADD,                MVT::v32i16, Legal);
1464     setOperationAction(ISD::ADD,                MVT::v64i8, Legal);
1465     setOperationAction(ISD::SUB,                MVT::v32i16, Legal);
1466     setOperationAction(ISD::SUB,                MVT::v64i8, Legal);
1467     setOperationAction(ISD::MUL,                MVT::v32i16, Legal);
1468     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v32i1, Custom);
1469     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v64i1, Custom);
1470     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v32i1, Custom);
1471     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v64i1, Custom);
1472     setOperationAction(ISD::SELECT,             MVT::v32i1, Custom);
1473     setOperationAction(ISD::SELECT,             MVT::v64i1, Custom);
1474
1475     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1476       const MVT VT = (MVT::SimpleValueType)i;
1477
1478       const unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1479
1480       // Do not attempt to promote non-512-bit vectors.
1481       if (!VT.is512BitVector())
1482         continue;
1483
1484       if (EltSize < 32) {
1485         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1486         setOperationAction(ISD::VSELECT,             VT, Legal);
1487       }
1488     }
1489   }
1490
1491   if (!Subtarget->useSoftFloat() && Subtarget->hasVLX()) {
1492     addRegisterClass(MVT::v4i1,   &X86::VK4RegClass);
1493     addRegisterClass(MVT::v2i1,   &X86::VK2RegClass);
1494
1495     setOperationAction(ISD::SETCC,              MVT::v4i1, Custom);
1496     setOperationAction(ISD::SETCC,              MVT::v2i1, Custom);
1497     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4i1, Custom);
1498     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i1, Custom);
1499     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v8i1, Custom);
1500     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v4i1, Custom);
1501     setOperationAction(ISD::SELECT,             MVT::v4i1, Custom);
1502     setOperationAction(ISD::SELECT,             MVT::v2i1, Custom);
1503
1504     setOperationAction(ISD::AND,                MVT::v8i32, Legal);
1505     setOperationAction(ISD::OR,                 MVT::v8i32, Legal);
1506     setOperationAction(ISD::XOR,                MVT::v8i32, Legal);
1507     setOperationAction(ISD::AND,                MVT::v4i32, Legal);
1508     setOperationAction(ISD::OR,                 MVT::v4i32, Legal);
1509     setOperationAction(ISD::XOR,                MVT::v4i32, Legal);
1510     setOperationAction(ISD::SRA,                MVT::v2i64, Custom);
1511     setOperationAction(ISD::SRA,                MVT::v4i64, Custom);
1512   }
1513
1514   // We want to custom lower some of our intrinsics.
1515   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1516   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1517   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1518   if (!Subtarget->is64Bit())
1519     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1520
1521   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1522   // handle type legalization for these operations here.
1523   //
1524   // FIXME: We really should do custom legalization for addition and
1525   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1526   // than generic legalization for 64-bit multiplication-with-overflow, though.
1527   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1528     // Add/Sub/Mul with overflow operations are custom lowered.
1529     MVT VT = IntVTs[i];
1530     setOperationAction(ISD::SADDO, VT, Custom);
1531     setOperationAction(ISD::UADDO, VT, Custom);
1532     setOperationAction(ISD::SSUBO, VT, Custom);
1533     setOperationAction(ISD::USUBO, VT, Custom);
1534     setOperationAction(ISD::SMULO, VT, Custom);
1535     setOperationAction(ISD::UMULO, VT, Custom);
1536   }
1537
1538
1539   if (!Subtarget->is64Bit()) {
1540     // These libcalls are not available in 32-bit.
1541     setLibcallName(RTLIB::SHL_I128, nullptr);
1542     setLibcallName(RTLIB::SRL_I128, nullptr);
1543     setLibcallName(RTLIB::SRA_I128, nullptr);
1544   }
1545
1546   // Combine sin / cos into one node or libcall if possible.
1547   if (Subtarget->hasSinCos()) {
1548     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1549     setLibcallName(RTLIB::SINCOS_F64, "sincos");
1550     if (Subtarget->isTargetDarwin()) {
1551       // For MacOSX, we don't want the normal expansion of a libcall to sincos.
1552       // We want to issue a libcall to __sincos_stret to avoid memory traffic.
1553       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1554       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1555     }
1556   }
1557
1558   if (Subtarget->isTargetWin64()) {
1559     setOperationAction(ISD::SDIV, MVT::i128, Custom);
1560     setOperationAction(ISD::UDIV, MVT::i128, Custom);
1561     setOperationAction(ISD::SREM, MVT::i128, Custom);
1562     setOperationAction(ISD::UREM, MVT::i128, Custom);
1563     setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1564     setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1565   }
1566
1567   // We have target-specific dag combine patterns for the following nodes:
1568   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1569   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1570   setTargetDAGCombine(ISD::BITCAST);
1571   setTargetDAGCombine(ISD::VSELECT);
1572   setTargetDAGCombine(ISD::SELECT);
1573   setTargetDAGCombine(ISD::SHL);
1574   setTargetDAGCombine(ISD::SRA);
1575   setTargetDAGCombine(ISD::SRL);
1576   setTargetDAGCombine(ISD::OR);
1577   setTargetDAGCombine(ISD::AND);
1578   setTargetDAGCombine(ISD::ADD);
1579   setTargetDAGCombine(ISD::FADD);
1580   setTargetDAGCombine(ISD::FSUB);
1581   setTargetDAGCombine(ISD::FMA);
1582   setTargetDAGCombine(ISD::SUB);
1583   setTargetDAGCombine(ISD::LOAD);
1584   setTargetDAGCombine(ISD::MLOAD);
1585   setTargetDAGCombine(ISD::STORE);
1586   setTargetDAGCombine(ISD::MSTORE);
1587   setTargetDAGCombine(ISD::ZERO_EXTEND);
1588   setTargetDAGCombine(ISD::ANY_EXTEND);
1589   setTargetDAGCombine(ISD::SIGN_EXTEND);
1590   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1591   setTargetDAGCombine(ISD::SINT_TO_FP);
1592   setTargetDAGCombine(ISD::SETCC);
1593   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1594   setTargetDAGCombine(ISD::BUILD_VECTOR);
1595   setTargetDAGCombine(ISD::MUL);
1596   setTargetDAGCombine(ISD::XOR);
1597
1598   computeRegisterProperties(Subtarget->getRegisterInfo());
1599
1600   // On Darwin, -Os means optimize for size without hurting performance,
1601   // do not reduce the limit.
1602   MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1603   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1604   MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1605   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1606   MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1607   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1608   setPrefLoopAlignment(4); // 2^4 bytes.
1609
1610   // Predictable cmov don't hurt on atom because it's in-order.
1611   PredictableSelectIsExpensive = !Subtarget->isAtom();
1612   EnableExtLdPromotion = true;
1613   setPrefFunctionAlignment(4); // 2^4 bytes.
1614
1615   verifyIntrinsicTables();
1616 }
1617
1618 // This has so far only been implemented for 64-bit MachO.
1619 bool X86TargetLowering::useLoadStackGuardNode() const {
1620   return Subtarget->isTargetMachO() && Subtarget->is64Bit();
1621 }
1622
1623 TargetLoweringBase::LegalizeTypeAction
1624 X86TargetLowering::getPreferredVectorAction(EVT VT) const {
1625   if (ExperimentalVectorWideningLegalization &&
1626       VT.getVectorNumElements() != 1 &&
1627       VT.getVectorElementType().getSimpleVT() != MVT::i1)
1628     return TypeWidenVector;
1629
1630   return TargetLoweringBase::getPreferredVectorAction(VT);
1631 }
1632
1633 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1634   if (!VT.isVector())
1635     return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1636
1637   const unsigned NumElts = VT.getVectorNumElements();
1638   const EVT EltVT = VT.getVectorElementType();
1639   if (VT.is512BitVector()) {
1640     if (Subtarget->hasAVX512())
1641       if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1642           EltVT == MVT::f32 || EltVT == MVT::f64)
1643         switch(NumElts) {
1644         case  8: return MVT::v8i1;
1645         case 16: return MVT::v16i1;
1646       }
1647     if (Subtarget->hasBWI())
1648       if (EltVT == MVT::i8 || EltVT == MVT::i16)
1649         switch(NumElts) {
1650         case 32: return MVT::v32i1;
1651         case 64: return MVT::v64i1;
1652       }
1653   }
1654
1655   if (VT.is256BitVector() || VT.is128BitVector()) {
1656     if (Subtarget->hasVLX())
1657       if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1658           EltVT == MVT::f32 || EltVT == MVT::f64)
1659         switch(NumElts) {
1660         case 2: return MVT::v2i1;
1661         case 4: return MVT::v4i1;
1662         case 8: return MVT::v8i1;
1663       }
1664     if (Subtarget->hasBWI() && Subtarget->hasVLX())
1665       if (EltVT == MVT::i8 || EltVT == MVT::i16)
1666         switch(NumElts) {
1667         case  8: return MVT::v8i1;
1668         case 16: return MVT::v16i1;
1669         case 32: return MVT::v32i1;
1670       }
1671   }
1672
1673   return VT.changeVectorElementTypeToInteger();
1674 }
1675
1676 /// Helper for getByValTypeAlignment to determine
1677 /// the desired ByVal argument alignment.
1678 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1679   if (MaxAlign == 16)
1680     return;
1681   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1682     if (VTy->getBitWidth() == 128)
1683       MaxAlign = 16;
1684   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1685     unsigned EltAlign = 0;
1686     getMaxByValAlign(ATy->getElementType(), EltAlign);
1687     if (EltAlign > MaxAlign)
1688       MaxAlign = EltAlign;
1689   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1690     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1691       unsigned EltAlign = 0;
1692       getMaxByValAlign(STy->getElementType(i), EltAlign);
1693       if (EltAlign > MaxAlign)
1694         MaxAlign = EltAlign;
1695       if (MaxAlign == 16)
1696         break;
1697     }
1698   }
1699 }
1700
1701 /// Return the desired alignment for ByVal aggregate
1702 /// function arguments in the caller parameter area. For X86, aggregates
1703 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1704 /// are at 4-byte boundaries.
1705 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1706   if (Subtarget->is64Bit()) {
1707     // Max of 8 and alignment of type.
1708     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1709     if (TyAlign > 8)
1710       return TyAlign;
1711     return 8;
1712   }
1713
1714   unsigned Align = 4;
1715   if (Subtarget->hasSSE1())
1716     getMaxByValAlign(Ty, Align);
1717   return Align;
1718 }
1719
1720 /// Returns the target specific optimal type for load
1721 /// and store operations as a result of memset, memcpy, and memmove
1722 /// lowering. If DstAlign is zero that means it's safe to destination
1723 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1724 /// means there isn't a need to check it against alignment requirement,
1725 /// probably because the source does not need to be loaded. If 'IsMemset' is
1726 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1727 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1728 /// source is constant so it does not need to be loaded.
1729 /// It returns EVT::Other if the type should be determined using generic
1730 /// target-independent logic.
1731 EVT
1732 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1733                                        unsigned DstAlign, unsigned SrcAlign,
1734                                        bool IsMemset, bool ZeroMemset,
1735                                        bool MemcpyStrSrc,
1736                                        MachineFunction &MF) const {
1737   const Function *F = MF.getFunction();
1738   if ((!IsMemset || ZeroMemset) &&
1739       !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
1740     if (Size >= 16 &&
1741         (Subtarget->isUnalignedMemAccessFast() ||
1742          ((DstAlign == 0 || DstAlign >= 16) &&
1743           (SrcAlign == 0 || SrcAlign >= 16)))) {
1744       if (Size >= 32) {
1745         if (Subtarget->hasInt256())
1746           return MVT::v8i32;
1747         if (Subtarget->hasFp256())
1748           return MVT::v8f32;
1749       }
1750       if (Subtarget->hasSSE2())
1751         return MVT::v4i32;
1752       if (Subtarget->hasSSE1())
1753         return MVT::v4f32;
1754     } else if (!MemcpyStrSrc && Size >= 8 &&
1755                !Subtarget->is64Bit() &&
1756                Subtarget->hasSSE2()) {
1757       // Do not use f64 to lower memcpy if source is string constant. It's
1758       // better to use i32 to avoid the loads.
1759       return MVT::f64;
1760     }
1761   }
1762   if (Subtarget->is64Bit() && Size >= 8)
1763     return MVT::i64;
1764   return MVT::i32;
1765 }
1766
1767 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1768   if (VT == MVT::f32)
1769     return X86ScalarSSEf32;
1770   else if (VT == MVT::f64)
1771     return X86ScalarSSEf64;
1772   return true;
1773 }
1774
1775 bool
1776 X86TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
1777                                                   unsigned,
1778                                                   unsigned,
1779                                                   bool *Fast) const {
1780   if (Fast)
1781     *Fast = Subtarget->isUnalignedMemAccessFast();
1782   return true;
1783 }
1784
1785 /// Return the entry encoding for a jump table in the
1786 /// current function.  The returned value is a member of the
1787 /// MachineJumpTableInfo::JTEntryKind enum.
1788 unsigned X86TargetLowering::getJumpTableEncoding() const {
1789   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1790   // symbol.
1791   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1792       Subtarget->isPICStyleGOT())
1793     return MachineJumpTableInfo::EK_Custom32;
1794
1795   // Otherwise, use the normal jump table encoding heuristics.
1796   return TargetLowering::getJumpTableEncoding();
1797 }
1798
1799 bool X86TargetLowering::useSoftFloat() const {
1800   return Subtarget->useSoftFloat();
1801 }
1802
1803 const MCExpr *
1804 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1805                                              const MachineBasicBlock *MBB,
1806                                              unsigned uid,MCContext &Ctx) const{
1807   assert(MBB->getParent()->getTarget().getRelocationModel() == Reloc::PIC_ &&
1808          Subtarget->isPICStyleGOT());
1809   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1810   // entries.
1811   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1812                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1813 }
1814
1815 /// Returns relocation base for the given PIC jumptable.
1816 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1817                                                     SelectionDAG &DAG) const {
1818   if (!Subtarget->is64Bit())
1819     // This doesn't have SDLoc associated with it, but is not really the
1820     // same as a Register.
1821     return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy());
1822   return Table;
1823 }
1824
1825 /// This returns the relocation base for the given PIC jumptable,
1826 /// the same as getPICJumpTableRelocBase, but as an MCExpr.
1827 const MCExpr *X86TargetLowering::
1828 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1829                              MCContext &Ctx) const {
1830   // X86-64 uses RIP relative addressing based on the jump table label.
1831   if (Subtarget->isPICStyleRIPRel())
1832     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1833
1834   // Otherwise, the reference is relative to the PIC base.
1835   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1836 }
1837
1838 std::pair<const TargetRegisterClass *, uint8_t>
1839 X86TargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
1840                                            MVT VT) const {
1841   const TargetRegisterClass *RRC = nullptr;
1842   uint8_t Cost = 1;
1843   switch (VT.SimpleTy) {
1844   default:
1845     return TargetLowering::findRepresentativeClass(TRI, VT);
1846   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1847     RRC = Subtarget->is64Bit() ? &X86::GR64RegClass : &X86::GR32RegClass;
1848     break;
1849   case MVT::x86mmx:
1850     RRC = &X86::VR64RegClass;
1851     break;
1852   case MVT::f32: case MVT::f64:
1853   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1854   case MVT::v4f32: case MVT::v2f64:
1855   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1856   case MVT::v4f64:
1857     RRC = &X86::VR128RegClass;
1858     break;
1859   }
1860   return std::make_pair(RRC, Cost);
1861 }
1862
1863 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1864                                                unsigned &Offset) const {
1865   if (!Subtarget->isTargetLinux())
1866     return false;
1867
1868   if (Subtarget->is64Bit()) {
1869     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1870     Offset = 0x28;
1871     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1872       AddressSpace = 256;
1873     else
1874       AddressSpace = 257;
1875   } else {
1876     // %gs:0x14 on i386
1877     Offset = 0x14;
1878     AddressSpace = 256;
1879   }
1880   return true;
1881 }
1882
1883 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1884                                             unsigned DestAS) const {
1885   assert(SrcAS != DestAS && "Expected different address spaces!");
1886
1887   return SrcAS < 256 && DestAS < 256;
1888 }
1889
1890 //===----------------------------------------------------------------------===//
1891 //               Return Value Calling Convention Implementation
1892 //===----------------------------------------------------------------------===//
1893
1894 #include "X86GenCallingConv.inc"
1895
1896 bool
1897 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1898                                   MachineFunction &MF, bool isVarArg,
1899                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1900                         LLVMContext &Context) const {
1901   SmallVector<CCValAssign, 16> RVLocs;
1902   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
1903   return CCInfo.CheckReturn(Outs, RetCC_X86);
1904 }
1905
1906 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
1907   static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
1908   return ScratchRegs;
1909 }
1910
1911 SDValue
1912 X86TargetLowering::LowerReturn(SDValue Chain,
1913                                CallingConv::ID CallConv, bool isVarArg,
1914                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1915                                const SmallVectorImpl<SDValue> &OutVals,
1916                                SDLoc dl, SelectionDAG &DAG) const {
1917   MachineFunction &MF = DAG.getMachineFunction();
1918   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1919
1920   SmallVector<CCValAssign, 16> RVLocs;
1921   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, *DAG.getContext());
1922   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1923
1924   SDValue Flag;
1925   SmallVector<SDValue, 6> RetOps;
1926   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1927   // Operand #1 = Bytes To Pop
1928   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(), dl,
1929                    MVT::i16));
1930
1931   // Copy the result values into the output registers.
1932   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1933     CCValAssign &VA = RVLocs[i];
1934     assert(VA.isRegLoc() && "Can only return in registers!");
1935     SDValue ValToCopy = OutVals[i];
1936     EVT ValVT = ValToCopy.getValueType();
1937
1938     // Promote values to the appropriate types.
1939     if (VA.getLocInfo() == CCValAssign::SExt)
1940       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1941     else if (VA.getLocInfo() == CCValAssign::ZExt)
1942       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1943     else if (VA.getLocInfo() == CCValAssign::AExt) {
1944       if (ValVT.isVector() && ValVT.getScalarType() == MVT::i1)
1945         ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1946       else
1947         ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1948     }
1949     else if (VA.getLocInfo() == CCValAssign::BCvt)
1950       ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1951
1952     assert(VA.getLocInfo() != CCValAssign::FPExt &&
1953            "Unexpected FP-extend for return value.");
1954
1955     // If this is x86-64, and we disabled SSE, we can't return FP values,
1956     // or SSE or MMX vectors.
1957     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1958          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1959           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1960       report_fatal_error("SSE register return with SSE disabled");
1961     }
1962     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1963     // llvm-gcc has never done it right and no one has noticed, so this
1964     // should be OK for now.
1965     if (ValVT == MVT::f64 &&
1966         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1967       report_fatal_error("SSE2 register return with SSE2 disabled");
1968
1969     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1970     // the RET instruction and handled by the FP Stackifier.
1971     if (VA.getLocReg() == X86::FP0 ||
1972         VA.getLocReg() == X86::FP1) {
1973       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1974       // change the value to the FP stack register class.
1975       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1976         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1977       RetOps.push_back(ValToCopy);
1978       // Don't emit a copytoreg.
1979       continue;
1980     }
1981
1982     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1983     // which is returned in RAX / RDX.
1984     if (Subtarget->is64Bit()) {
1985       if (ValVT == MVT::x86mmx) {
1986         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1987           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1988           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1989                                   ValToCopy);
1990           // If we don't have SSE2 available, convert to v4f32 so the generated
1991           // register is legal.
1992           if (!Subtarget->hasSSE2())
1993             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1994         }
1995       }
1996     }
1997
1998     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1999     Flag = Chain.getValue(1);
2000     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2001   }
2002
2003   // The x86-64 ABIs require that for returning structs by value we copy
2004   // the sret argument into %rax/%eax (depending on ABI) for the return.
2005   // Win32 requires us to put the sret argument to %eax as well.
2006   // We saved the argument into a virtual register in the entry block,
2007   // so now we copy the value out and into %rax/%eax.
2008   //
2009   // Checking Function.hasStructRetAttr() here is insufficient because the IR
2010   // may not have an explicit sret argument. If FuncInfo.CanLowerReturn is
2011   // false, then an sret argument may be implicitly inserted in the SelDAG. In
2012   // either case FuncInfo->setSRetReturnReg() will have been called.
2013   if (unsigned SRetReg = FuncInfo->getSRetReturnReg()) {
2014     assert((Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC()) &&
2015            "No need for an sret register");
2016     SDValue Val = DAG.getCopyFromReg(Chain, dl, SRetReg, getPointerTy());
2017
2018     unsigned RetValReg
2019         = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
2020           X86::RAX : X86::EAX;
2021     Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
2022     Flag = Chain.getValue(1);
2023
2024     // RAX/EAX now acts like a return value.
2025     RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
2026   }
2027
2028   RetOps[0] = Chain;  // Update chain.
2029
2030   // Add the flag if we have it.
2031   if (Flag.getNode())
2032     RetOps.push_back(Flag);
2033
2034   return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
2035 }
2036
2037 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2038   if (N->getNumValues() != 1)
2039     return false;
2040   if (!N->hasNUsesOfValue(1, 0))
2041     return false;
2042
2043   SDValue TCChain = Chain;
2044   SDNode *Copy = *N->use_begin();
2045   if (Copy->getOpcode() == ISD::CopyToReg) {
2046     // If the copy has a glue operand, we conservatively assume it isn't safe to
2047     // perform a tail call.
2048     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2049       return false;
2050     TCChain = Copy->getOperand(0);
2051   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
2052     return false;
2053
2054   bool HasRet = false;
2055   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2056        UI != UE; ++UI) {
2057     if (UI->getOpcode() != X86ISD::RET_FLAG)
2058       return false;
2059     // If we are returning more than one value, we can definitely
2060     // not make a tail call see PR19530
2061     if (UI->getNumOperands() > 4)
2062       return false;
2063     if (UI->getNumOperands() == 4 &&
2064         UI->getOperand(UI->getNumOperands()-1).getValueType() != MVT::Glue)
2065       return false;
2066     HasRet = true;
2067   }
2068
2069   if (!HasRet)
2070     return false;
2071
2072   Chain = TCChain;
2073   return true;
2074 }
2075
2076 EVT
2077 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
2078                                             ISD::NodeType ExtendKind) const {
2079   MVT ReturnMVT;
2080   // TODO: Is this also valid on 32-bit?
2081   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
2082     ReturnMVT = MVT::i8;
2083   else
2084     ReturnMVT = MVT::i32;
2085
2086   EVT MinVT = getRegisterType(Context, ReturnMVT);
2087   return VT.bitsLT(MinVT) ? MinVT : VT;
2088 }
2089
2090 /// Lower the result values of a call into the
2091 /// appropriate copies out of appropriate physical registers.
2092 ///
2093 SDValue
2094 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2095                                    CallingConv::ID CallConv, bool isVarArg,
2096                                    const SmallVectorImpl<ISD::InputArg> &Ins,
2097                                    SDLoc dl, SelectionDAG &DAG,
2098                                    SmallVectorImpl<SDValue> &InVals) const {
2099
2100   // Assign locations to each value returned by this call.
2101   SmallVector<CCValAssign, 16> RVLocs;
2102   bool Is64Bit = Subtarget->is64Bit();
2103   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2104                  *DAG.getContext());
2105   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2106
2107   // Copy all of the result registers out of their specified physreg.
2108   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2109     CCValAssign &VA = RVLocs[i];
2110     EVT CopyVT = VA.getLocVT();
2111
2112     // If this is x86-64, and we disabled SSE, we can't return FP values
2113     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2114         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2115       report_fatal_error("SSE register return with SSE disabled");
2116     }
2117
2118     // If we prefer to use the value in xmm registers, copy it out as f80 and
2119     // use a truncate to move it from fp stack reg to xmm reg.
2120     bool RoundAfterCopy = false;
2121     if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
2122         isScalarFPTypeInSSEReg(VA.getValVT())) {
2123       CopyVT = MVT::f80;
2124       RoundAfterCopy = (CopyVT != VA.getLocVT());
2125     }
2126
2127     Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2128                                CopyVT, InFlag).getValue(1);
2129     SDValue Val = Chain.getValue(0);
2130
2131     if (RoundAfterCopy)
2132       Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2133                         // This truncation won't change the value.
2134                         DAG.getIntPtrConstant(1, dl));
2135
2136     if (VA.isExtInLoc() && VA.getValVT().getScalarType() == MVT::i1)
2137       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
2138
2139     InFlag = Chain.getValue(2);
2140     InVals.push_back(Val);
2141   }
2142
2143   return Chain;
2144 }
2145
2146 //===----------------------------------------------------------------------===//
2147 //                C & StdCall & Fast Calling Convention implementation
2148 //===----------------------------------------------------------------------===//
2149 //  StdCall calling convention seems to be standard for many Windows' API
2150 //  routines and around. It differs from C calling convention just a little:
2151 //  callee should clean up the stack, not caller. Symbols should be also
2152 //  decorated in some fancy way :) It doesn't support any vector arguments.
2153 //  For info on fast calling convention see Fast Calling Convention (tail call)
2154 //  implementation LowerX86_32FastCCCallTo.
2155
2156 /// CallIsStructReturn - Determines whether a call uses struct return
2157 /// semantics.
2158 enum StructReturnType {
2159   NotStructReturn,
2160   RegStructReturn,
2161   StackStructReturn
2162 };
2163 static StructReturnType
2164 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2165   if (Outs.empty())
2166     return NotStructReturn;
2167
2168   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2169   if (!Flags.isSRet())
2170     return NotStructReturn;
2171   if (Flags.isInReg())
2172     return RegStructReturn;
2173   return StackStructReturn;
2174 }
2175
2176 /// Determines whether a function uses struct return semantics.
2177 static StructReturnType
2178 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2179   if (Ins.empty())
2180     return NotStructReturn;
2181
2182   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2183   if (!Flags.isSRet())
2184     return NotStructReturn;
2185   if (Flags.isInReg())
2186     return RegStructReturn;
2187   return StackStructReturn;
2188 }
2189
2190 /// Make a copy of an aggregate at address specified by "Src" to address
2191 /// "Dst" with size and alignment information specified by the specific
2192 /// parameter attribute. The copy will be passed as a byval function parameter.
2193 static SDValue
2194 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2195                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2196                           SDLoc dl) {
2197   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
2198
2199   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2200                        /*isVolatile*/false, /*AlwaysInline=*/true,
2201                        /*isTailCall*/false,
2202                        MachinePointerInfo(), MachinePointerInfo());
2203 }
2204
2205 /// Return true if the calling convention is one that
2206 /// supports tail call optimization.
2207 static bool IsTailCallConvention(CallingConv::ID CC) {
2208   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2209           CC == CallingConv::HiPE);
2210 }
2211
2212 /// \brief Return true if the calling convention is a C calling convention.
2213 static bool IsCCallConvention(CallingConv::ID CC) {
2214   return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2215           CC == CallingConv::X86_64_SysV);
2216 }
2217
2218 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2219   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2220     return false;
2221
2222   CallSite CS(CI);
2223   CallingConv::ID CalleeCC = CS.getCallingConv();
2224   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2225     return false;
2226
2227   return true;
2228 }
2229
2230 /// Return true if the function is being made into
2231 /// a tailcall target by changing its ABI.
2232 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2233                                    bool GuaranteedTailCallOpt) {
2234   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2235 }
2236
2237 SDValue
2238 X86TargetLowering::LowerMemArgument(SDValue Chain,
2239                                     CallingConv::ID CallConv,
2240                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2241                                     SDLoc dl, SelectionDAG &DAG,
2242                                     const CCValAssign &VA,
2243                                     MachineFrameInfo *MFI,
2244                                     unsigned i) const {
2245   // Create the nodes corresponding to a load from this parameter slot.
2246   ISD::ArgFlagsTy Flags = Ins[i].Flags;
2247   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(
2248       CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2249   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2250   EVT ValVT;
2251
2252   // If value is passed by pointer we have address passed instead of the value
2253   // itself.
2254   bool ExtendedInMem = VA.isExtInLoc() &&
2255     VA.getValVT().getScalarType() == MVT::i1;
2256
2257   if (VA.getLocInfo() == CCValAssign::Indirect || ExtendedInMem)
2258     ValVT = VA.getLocVT();
2259   else
2260     ValVT = VA.getValVT();
2261
2262   // FIXME: For now, all byval parameter objects are marked mutable. This can be
2263   // changed with more analysis.
2264   // In case of tail call optimization mark all arguments mutable. Since they
2265   // could be overwritten by lowering of arguments in case of a tail call.
2266   if (Flags.isByVal()) {
2267     unsigned Bytes = Flags.getByValSize();
2268     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2269     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2270     return DAG.getFrameIndex(FI, getPointerTy());
2271   } else {
2272     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2273                                     VA.getLocMemOffset(), isImmutable);
2274     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2275     SDValue Val =  DAG.getLoad(ValVT, dl, Chain, FIN,
2276                                MachinePointerInfo::getFixedStack(FI),
2277                                false, false, false, 0);
2278     return ExtendedInMem ?
2279       DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val) : Val;
2280   }
2281 }
2282
2283 // FIXME: Get this from tablegen.
2284 static ArrayRef<MCPhysReg> get64BitArgumentGPRs(CallingConv::ID CallConv,
2285                                                 const X86Subtarget *Subtarget) {
2286   assert(Subtarget->is64Bit());
2287
2288   if (Subtarget->isCallingConvWin64(CallConv)) {
2289     static const MCPhysReg GPR64ArgRegsWin64[] = {
2290       X86::RCX, X86::RDX, X86::R8,  X86::R9
2291     };
2292     return makeArrayRef(std::begin(GPR64ArgRegsWin64), std::end(GPR64ArgRegsWin64));
2293   }
2294
2295   static const MCPhysReg GPR64ArgRegs64Bit[] = {
2296     X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2297   };
2298   return makeArrayRef(std::begin(GPR64ArgRegs64Bit), std::end(GPR64ArgRegs64Bit));
2299 }
2300
2301 // FIXME: Get this from tablegen.
2302 static ArrayRef<MCPhysReg> get64BitArgumentXMMs(MachineFunction &MF,
2303                                                 CallingConv::ID CallConv,
2304                                                 const X86Subtarget *Subtarget) {
2305   assert(Subtarget->is64Bit());
2306   if (Subtarget->isCallingConvWin64(CallConv)) {
2307     // The XMM registers which might contain var arg parameters are shadowed
2308     // in their paired GPR.  So we only need to save the GPR to their home
2309     // slots.
2310     // TODO: __vectorcall will change this.
2311     return None;
2312   }
2313
2314   const Function *Fn = MF.getFunction();
2315   bool NoImplicitFloatOps = Fn->hasFnAttribute(Attribute::NoImplicitFloat);
2316   bool isSoftFloat = Subtarget->useSoftFloat();
2317   assert(!(isSoftFloat && NoImplicitFloatOps) &&
2318          "SSE register cannot be used when SSE is disabled!");
2319   if (isSoftFloat || NoImplicitFloatOps || !Subtarget->hasSSE1())
2320     // Kernel mode asks for SSE to be disabled, so there are no XMM argument
2321     // registers.
2322     return None;
2323
2324   static const MCPhysReg XMMArgRegs64Bit[] = {
2325     X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2326     X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2327   };
2328   return makeArrayRef(std::begin(XMMArgRegs64Bit), std::end(XMMArgRegs64Bit));
2329 }
2330
2331 SDValue
2332 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2333                                         CallingConv::ID CallConv,
2334                                         bool isVarArg,
2335                                       const SmallVectorImpl<ISD::InputArg> &Ins,
2336                                         SDLoc dl,
2337                                         SelectionDAG &DAG,
2338                                         SmallVectorImpl<SDValue> &InVals)
2339                                           const {
2340   MachineFunction &MF = DAG.getMachineFunction();
2341   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2342   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
2343
2344   const Function* Fn = MF.getFunction();
2345   if (Fn->hasExternalLinkage() &&
2346       Subtarget->isTargetCygMing() &&
2347       Fn->getName() == "main")
2348     FuncInfo->setForceFramePointer(true);
2349
2350   MachineFrameInfo *MFI = MF.getFrameInfo();
2351   bool Is64Bit = Subtarget->is64Bit();
2352   bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2353
2354   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2355          "Var args not supported with calling convention fastcc, ghc or hipe");
2356
2357   // Assign locations to all of the incoming arguments.
2358   SmallVector<CCValAssign, 16> ArgLocs;
2359   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2360
2361   // Allocate shadow area for Win64
2362   if (IsWin64)
2363     CCInfo.AllocateStack(32, 8);
2364
2365   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2366
2367   unsigned LastVal = ~0U;
2368   SDValue ArgValue;
2369   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2370     CCValAssign &VA = ArgLocs[i];
2371     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2372     // places.
2373     assert(VA.getValNo() != LastVal &&
2374            "Don't support value assigned to multiple locs yet");
2375     (void)LastVal;
2376     LastVal = VA.getValNo();
2377
2378     if (VA.isRegLoc()) {
2379       EVT RegVT = VA.getLocVT();
2380       const TargetRegisterClass *RC;
2381       if (RegVT == MVT::i32)
2382         RC = &X86::GR32RegClass;
2383       else if (Is64Bit && RegVT == MVT::i64)
2384         RC = &X86::GR64RegClass;
2385       else if (RegVT == MVT::f32)
2386         RC = &X86::FR32RegClass;
2387       else if (RegVT == MVT::f64)
2388         RC = &X86::FR64RegClass;
2389       else if (RegVT.is512BitVector())
2390         RC = &X86::VR512RegClass;
2391       else if (RegVT.is256BitVector())
2392         RC = &X86::VR256RegClass;
2393       else if (RegVT.is128BitVector())
2394         RC = &X86::VR128RegClass;
2395       else if (RegVT == MVT::x86mmx)
2396         RC = &X86::VR64RegClass;
2397       else if (RegVT == MVT::i1)
2398         RC = &X86::VK1RegClass;
2399       else if (RegVT == MVT::v8i1)
2400         RC = &X86::VK8RegClass;
2401       else if (RegVT == MVT::v16i1)
2402         RC = &X86::VK16RegClass;
2403       else if (RegVT == MVT::v32i1)
2404         RC = &X86::VK32RegClass;
2405       else if (RegVT == MVT::v64i1)
2406         RC = &X86::VK64RegClass;
2407       else
2408         llvm_unreachable("Unknown argument type!");
2409
2410       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2411       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2412
2413       // If this is an 8 or 16-bit value, it is really passed promoted to 32
2414       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
2415       // right size.
2416       if (VA.getLocInfo() == CCValAssign::SExt)
2417         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2418                                DAG.getValueType(VA.getValVT()));
2419       else if (VA.getLocInfo() == CCValAssign::ZExt)
2420         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2421                                DAG.getValueType(VA.getValVT()));
2422       else if (VA.getLocInfo() == CCValAssign::BCvt)
2423         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2424
2425       if (VA.isExtInLoc()) {
2426         // Handle MMX values passed in XMM regs.
2427         if (RegVT.isVector() && VA.getValVT().getScalarType() != MVT::i1)
2428           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2429         else
2430           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2431       }
2432     } else {
2433       assert(VA.isMemLoc());
2434       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2435     }
2436
2437     // If value is passed via pointer - do a load.
2438     if (VA.getLocInfo() == CCValAssign::Indirect)
2439       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2440                              MachinePointerInfo(), false, false, false, 0);
2441
2442     InVals.push_back(ArgValue);
2443   }
2444
2445   if (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC()) {
2446     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2447       // The x86-64 ABIs require that for returning structs by value we copy
2448       // the sret argument into %rax/%eax (depending on ABI) for the return.
2449       // Win32 requires us to put the sret argument to %eax as well.
2450       // Save the argument into a virtual register so that we can access it
2451       // from the return points.
2452       if (Ins[i].Flags.isSRet()) {
2453         unsigned Reg = FuncInfo->getSRetReturnReg();
2454         if (!Reg) {
2455           MVT PtrTy = getPointerTy();
2456           Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2457           FuncInfo->setSRetReturnReg(Reg);
2458         }
2459         SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2460         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2461         break;
2462       }
2463     }
2464   }
2465
2466   unsigned StackSize = CCInfo.getNextStackOffset();
2467   // Align stack specially for tail calls.
2468   if (FuncIsMadeTailCallSafe(CallConv,
2469                              MF.getTarget().Options.GuaranteedTailCallOpt))
2470     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2471
2472   // If the function takes variable number of arguments, make a frame index for
2473   // the start of the first vararg value... for expansion of llvm.va_start. We
2474   // can skip this if there are no va_start calls.
2475   if (MFI->hasVAStart() &&
2476       (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2477                    CallConv != CallingConv::X86_ThisCall))) {
2478     FuncInfo->setVarArgsFrameIndex(
2479         MFI->CreateFixedObject(1, StackSize, true));
2480   }
2481
2482   MachineModuleInfo &MMI = MF.getMMI();
2483   const Function *WinEHParent = nullptr;
2484   if (IsWin64 && MMI.hasWinEHFuncInfo(Fn))
2485     WinEHParent = MMI.getWinEHParent(Fn);
2486   bool IsWinEHOutlined = WinEHParent && WinEHParent != Fn;
2487   bool IsWinEHParent = WinEHParent && WinEHParent == Fn;
2488
2489   // Figure out if XMM registers are in use.
2490   assert(!(Subtarget->useSoftFloat() &&
2491            Fn->hasFnAttribute(Attribute::NoImplicitFloat)) &&
2492          "SSE register cannot be used when SSE is disabled!");
2493
2494   // 64-bit calling conventions support varargs and register parameters, so we
2495   // have to do extra work to spill them in the prologue.
2496   if (Is64Bit && isVarArg && MFI->hasVAStart()) {
2497     // Find the first unallocated argument registers.
2498     ArrayRef<MCPhysReg> ArgGPRs = get64BitArgumentGPRs(CallConv, Subtarget);
2499     ArrayRef<MCPhysReg> ArgXMMs = get64BitArgumentXMMs(MF, CallConv, Subtarget);
2500     unsigned NumIntRegs = CCInfo.getFirstUnallocated(ArgGPRs);
2501     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(ArgXMMs);
2502     assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2503            "SSE register cannot be used when SSE is disabled!");
2504
2505     // Gather all the live in physical registers.
2506     SmallVector<SDValue, 6> LiveGPRs;
2507     SmallVector<SDValue, 8> LiveXMMRegs;
2508     SDValue ALVal;
2509     for (MCPhysReg Reg : ArgGPRs.slice(NumIntRegs)) {
2510       unsigned GPR = MF.addLiveIn(Reg, &X86::GR64RegClass);
2511       LiveGPRs.push_back(
2512           DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64));
2513     }
2514     if (!ArgXMMs.empty()) {
2515       unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2516       ALVal = DAG.getCopyFromReg(Chain, dl, AL, MVT::i8);
2517       for (MCPhysReg Reg : ArgXMMs.slice(NumXMMRegs)) {
2518         unsigned XMMReg = MF.addLiveIn(Reg, &X86::VR128RegClass);
2519         LiveXMMRegs.push_back(
2520             DAG.getCopyFromReg(Chain, dl, XMMReg, MVT::v4f32));
2521       }
2522     }
2523
2524     if (IsWin64) {
2525       // Get to the caller-allocated home save location.  Add 8 to account
2526       // for the return address.
2527       int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2528       FuncInfo->setRegSaveFrameIndex(
2529           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2530       // Fixup to set vararg frame on shadow area (4 x i64).
2531       if (NumIntRegs < 4)
2532         FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2533     } else {
2534       // For X86-64, if there are vararg parameters that are passed via
2535       // registers, then we must store them to their spots on the stack so
2536       // they may be loaded by deferencing the result of va_next.
2537       FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2538       FuncInfo->setVarArgsFPOffset(ArgGPRs.size() * 8 + NumXMMRegs * 16);
2539       FuncInfo->setRegSaveFrameIndex(MFI->CreateStackObject(
2540           ArgGPRs.size() * 8 + ArgXMMs.size() * 16, 16, false));
2541     }
2542
2543     // Store the integer parameter registers.
2544     SmallVector<SDValue, 8> MemOps;
2545     SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2546                                       getPointerTy());
2547     unsigned Offset = FuncInfo->getVarArgsGPOffset();
2548     for (SDValue Val : LiveGPRs) {
2549       SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2550                                 DAG.getIntPtrConstant(Offset, dl));
2551       SDValue Store =
2552         DAG.getStore(Val.getValue(1), dl, Val, FIN,
2553                      MachinePointerInfo::getFixedStack(
2554                        FuncInfo->getRegSaveFrameIndex(), Offset),
2555                      false, false, 0);
2556       MemOps.push_back(Store);
2557       Offset += 8;
2558     }
2559
2560     if (!ArgXMMs.empty() && NumXMMRegs != ArgXMMs.size()) {
2561       // Now store the XMM (fp + vector) parameter registers.
2562       SmallVector<SDValue, 12> SaveXMMOps;
2563       SaveXMMOps.push_back(Chain);
2564       SaveXMMOps.push_back(ALVal);
2565       SaveXMMOps.push_back(DAG.getIntPtrConstant(
2566                              FuncInfo->getRegSaveFrameIndex(), dl));
2567       SaveXMMOps.push_back(DAG.getIntPtrConstant(
2568                              FuncInfo->getVarArgsFPOffset(), dl));
2569       SaveXMMOps.insert(SaveXMMOps.end(), LiveXMMRegs.begin(),
2570                         LiveXMMRegs.end());
2571       MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2572                                    MVT::Other, SaveXMMOps));
2573     }
2574
2575     if (!MemOps.empty())
2576       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2577   } else if (IsWinEHOutlined) {
2578     // Get to the caller-allocated home save location.  Add 8 to account
2579     // for the return address.
2580     int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2581     FuncInfo->setRegSaveFrameIndex(MFI->CreateFixedObject(
2582         /*Size=*/1, /*SPOffset=*/HomeOffset + 8, /*Immutable=*/false));
2583
2584     MMI.getWinEHFuncInfo(Fn)
2585         .CatchHandlerParentFrameObjIdx[const_cast<Function *>(Fn)] =
2586         FuncInfo->getRegSaveFrameIndex();
2587
2588     // Store the second integer parameter (rdx) into rsp+16 relative to the
2589     // stack pointer at the entry of the function.
2590     SDValue RSFIN =
2591         DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(), getPointerTy());
2592     unsigned GPR = MF.addLiveIn(X86::RDX, &X86::GR64RegClass);
2593     SDValue Val = DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64);
2594     Chain = DAG.getStore(
2595         Val.getValue(1), dl, Val, RSFIN,
2596         MachinePointerInfo::getFixedStack(FuncInfo->getRegSaveFrameIndex()),
2597         /*isVolatile=*/true, /*isNonTemporal=*/false, /*Alignment=*/0);
2598   }
2599
2600   if (isVarArg && MFI->hasMustTailInVarArgFunc()) {
2601     // Find the largest legal vector type.
2602     MVT VecVT = MVT::Other;
2603     // FIXME: Only some x86_32 calling conventions support AVX512.
2604     if (Subtarget->hasAVX512() &&
2605         (Is64Bit || (CallConv == CallingConv::X86_VectorCall ||
2606                      CallConv == CallingConv::Intel_OCL_BI)))
2607       VecVT = MVT::v16f32;
2608     else if (Subtarget->hasAVX())
2609       VecVT = MVT::v8f32;
2610     else if (Subtarget->hasSSE2())
2611       VecVT = MVT::v4f32;
2612
2613     // We forward some GPRs and some vector types.
2614     SmallVector<MVT, 2> RegParmTypes;
2615     MVT IntVT = Is64Bit ? MVT::i64 : MVT::i32;
2616     RegParmTypes.push_back(IntVT);
2617     if (VecVT != MVT::Other)
2618       RegParmTypes.push_back(VecVT);
2619
2620     // Compute the set of forwarded registers. The rest are scratch.
2621     SmallVectorImpl<ForwardedRegister> &Forwards =
2622         FuncInfo->getForwardedMustTailRegParms();
2623     CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes, CC_X86);
2624
2625     // Conservatively forward AL on x86_64, since it might be used for varargs.
2626     if (Is64Bit && !CCInfo.isAllocated(X86::AL)) {
2627       unsigned ALVReg = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2628       Forwards.push_back(ForwardedRegister(ALVReg, X86::AL, MVT::i8));
2629     }
2630
2631     // Copy all forwards from physical to virtual registers.
2632     for (ForwardedRegister &F : Forwards) {
2633       // FIXME: Can we use a less constrained schedule?
2634       SDValue RegVal = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
2635       F.VReg = MF.getRegInfo().createVirtualRegister(getRegClassFor(F.VT));
2636       Chain = DAG.getCopyToReg(Chain, dl, F.VReg, RegVal);
2637     }
2638   }
2639
2640   // Some CCs need callee pop.
2641   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2642                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2643     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2644   } else {
2645     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2646     // If this is an sret function, the return should pop the hidden pointer.
2647     if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2648         !Subtarget->getTargetTriple().isOSMSVCRT() &&
2649         argsAreStructReturn(Ins) == StackStructReturn)
2650       FuncInfo->setBytesToPopOnReturn(4);
2651   }
2652
2653   if (!Is64Bit) {
2654     // RegSaveFrameIndex is X86-64 only.
2655     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2656     if (CallConv == CallingConv::X86_FastCall ||
2657         CallConv == CallingConv::X86_ThisCall)
2658       // fastcc functions can't have varargs.
2659       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2660   }
2661
2662   FuncInfo->setArgumentStackSize(StackSize);
2663
2664   if (IsWinEHParent) {
2665     int UnwindHelpFI = MFI->CreateStackObject(8, 8, /*isSS=*/false);
2666     SDValue StackSlot = DAG.getFrameIndex(UnwindHelpFI, MVT::i64);
2667     MMI.getWinEHFuncInfo(MF.getFunction()).UnwindHelpFrameIdx = UnwindHelpFI;
2668     SDValue Neg2 = DAG.getConstant(-2, dl, MVT::i64);
2669     Chain = DAG.getStore(Chain, dl, Neg2, StackSlot,
2670                          MachinePointerInfo::getFixedStack(UnwindHelpFI),
2671                          /*isVolatile=*/true,
2672                          /*isNonTemporal=*/false, /*Alignment=*/0);
2673   }
2674
2675   return Chain;
2676 }
2677
2678 SDValue
2679 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2680                                     SDValue StackPtr, SDValue Arg,
2681                                     SDLoc dl, SelectionDAG &DAG,
2682                                     const CCValAssign &VA,
2683                                     ISD::ArgFlagsTy Flags) const {
2684   unsigned LocMemOffset = VA.getLocMemOffset();
2685   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
2686   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2687   if (Flags.isByVal())
2688     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2689
2690   return DAG.getStore(Chain, dl, Arg, PtrOff,
2691                       MachinePointerInfo::getStack(LocMemOffset),
2692                       false, false, 0);
2693 }
2694
2695 /// Emit a load of return address if tail call
2696 /// optimization is performed and it is required.
2697 SDValue
2698 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2699                                            SDValue &OutRetAddr, SDValue Chain,
2700                                            bool IsTailCall, bool Is64Bit,
2701                                            int FPDiff, SDLoc dl) const {
2702   // Adjust the Return address stack slot.
2703   EVT VT = getPointerTy();
2704   OutRetAddr = getReturnAddressFrameIndex(DAG);
2705
2706   // Load the "old" Return address.
2707   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2708                            false, false, false, 0);
2709   return SDValue(OutRetAddr.getNode(), 1);
2710 }
2711
2712 /// Emit a store of the return address if tail call
2713 /// optimization is performed and it is required (FPDiff!=0).
2714 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2715                                         SDValue Chain, SDValue RetAddrFrIdx,
2716                                         EVT PtrVT, unsigned SlotSize,
2717                                         int FPDiff, SDLoc dl) {
2718   // Store the return address to the appropriate stack slot.
2719   if (!FPDiff) return Chain;
2720   // Calculate the new stack slot for the return address.
2721   int NewReturnAddrFI =
2722     MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2723                                          false);
2724   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2725   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2726                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2727                        false, false, 0);
2728   return Chain;
2729 }
2730
2731 SDValue
2732 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2733                              SmallVectorImpl<SDValue> &InVals) const {
2734   SelectionDAG &DAG                     = CLI.DAG;
2735   SDLoc &dl                             = CLI.DL;
2736   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2737   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
2738   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
2739   SDValue Chain                         = CLI.Chain;
2740   SDValue Callee                        = CLI.Callee;
2741   CallingConv::ID CallConv              = CLI.CallConv;
2742   bool &isTailCall                      = CLI.IsTailCall;
2743   bool isVarArg                         = CLI.IsVarArg;
2744
2745   MachineFunction &MF = DAG.getMachineFunction();
2746   bool Is64Bit        = Subtarget->is64Bit();
2747   bool IsWin64        = Subtarget->isCallingConvWin64(CallConv);
2748   StructReturnType SR = callIsStructReturn(Outs);
2749   bool IsSibcall      = false;
2750   X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2751
2752   if (MF.getTarget().Options.DisableTailCalls)
2753     isTailCall = false;
2754
2755   bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
2756   if (IsMustTail) {
2757     // Force this to be a tail call.  The verifier rules are enough to ensure
2758     // that we can lower this successfully without moving the return address
2759     // around.
2760     isTailCall = true;
2761   } else if (isTailCall) {
2762     // Check if it's really possible to do a tail call.
2763     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2764                     isVarArg, SR != NotStructReturn,
2765                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2766                     Outs, OutVals, Ins, DAG);
2767
2768     // Sibcalls are automatically detected tailcalls which do not require
2769     // ABI changes.
2770     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2771       IsSibcall = true;
2772
2773     if (isTailCall)
2774       ++NumTailCalls;
2775   }
2776
2777   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2778          "Var args not supported with calling convention fastcc, ghc or hipe");
2779
2780   // Analyze operands of the call, assigning locations to each operand.
2781   SmallVector<CCValAssign, 16> ArgLocs;
2782   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2783
2784   // Allocate shadow area for Win64
2785   if (IsWin64)
2786     CCInfo.AllocateStack(32, 8);
2787
2788   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2789
2790   // Get a count of how many bytes are to be pushed on the stack.
2791   unsigned NumBytes = CCInfo.getNextStackOffset();
2792   if (IsSibcall)
2793     // This is a sibcall. The memory operands are available in caller's
2794     // own caller's stack.
2795     NumBytes = 0;
2796   else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
2797            IsTailCallConvention(CallConv))
2798     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2799
2800   int FPDiff = 0;
2801   if (isTailCall && !IsSibcall && !IsMustTail) {
2802     // Lower arguments at fp - stackoffset + fpdiff.
2803     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2804
2805     FPDiff = NumBytesCallerPushed - NumBytes;
2806
2807     // Set the delta of movement of the returnaddr stackslot.
2808     // But only set if delta is greater than previous delta.
2809     if (FPDiff < X86Info->getTCReturnAddrDelta())
2810       X86Info->setTCReturnAddrDelta(FPDiff);
2811   }
2812
2813   unsigned NumBytesToPush = NumBytes;
2814   unsigned NumBytesToPop = NumBytes;
2815
2816   // If we have an inalloca argument, all stack space has already been allocated
2817   // for us and be right at the top of the stack.  We don't support multiple
2818   // arguments passed in memory when using inalloca.
2819   if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
2820     NumBytesToPush = 0;
2821     if (!ArgLocs.back().isMemLoc())
2822       report_fatal_error("cannot use inalloca attribute on a register "
2823                          "parameter");
2824     if (ArgLocs.back().getLocMemOffset() != 0)
2825       report_fatal_error("any parameter with the inalloca attribute must be "
2826                          "the only memory argument");
2827   }
2828
2829   if (!IsSibcall)
2830     Chain = DAG.getCALLSEQ_START(
2831         Chain, DAG.getIntPtrConstant(NumBytesToPush, dl, true), dl);
2832
2833   SDValue RetAddrFrIdx;
2834   // Load return address for tail calls.
2835   if (isTailCall && FPDiff)
2836     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2837                                     Is64Bit, FPDiff, dl);
2838
2839   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2840   SmallVector<SDValue, 8> MemOpChains;
2841   SDValue StackPtr;
2842
2843   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2844   // of tail call optimization arguments are handle later.
2845   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
2846   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2847     // Skip inalloca arguments, they have already been written.
2848     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2849     if (Flags.isInAlloca())
2850       continue;
2851
2852     CCValAssign &VA = ArgLocs[i];
2853     EVT RegVT = VA.getLocVT();
2854     SDValue Arg = OutVals[i];
2855     bool isByVal = Flags.isByVal();
2856
2857     // Promote the value if needed.
2858     switch (VA.getLocInfo()) {
2859     default: llvm_unreachable("Unknown loc info!");
2860     case CCValAssign::Full: break;
2861     case CCValAssign::SExt:
2862       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2863       break;
2864     case CCValAssign::ZExt:
2865       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2866       break;
2867     case CCValAssign::AExt:
2868       if (Arg.getValueType().isVector() &&
2869           Arg.getValueType().getScalarType() == MVT::i1)
2870         Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2871       else if (RegVT.is128BitVector()) {
2872         // Special case: passing MMX values in XMM registers.
2873         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2874         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2875         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2876       } else
2877         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2878       break;
2879     case CCValAssign::BCvt:
2880       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2881       break;
2882     case CCValAssign::Indirect: {
2883       // Store the argument.
2884       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2885       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2886       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2887                            MachinePointerInfo::getFixedStack(FI),
2888                            false, false, 0);
2889       Arg = SpillSlot;
2890       break;
2891     }
2892     }
2893
2894     if (VA.isRegLoc()) {
2895       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2896       if (isVarArg && IsWin64) {
2897         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2898         // shadow reg if callee is a varargs function.
2899         unsigned ShadowReg = 0;
2900         switch (VA.getLocReg()) {
2901         case X86::XMM0: ShadowReg = X86::RCX; break;
2902         case X86::XMM1: ShadowReg = X86::RDX; break;
2903         case X86::XMM2: ShadowReg = X86::R8; break;
2904         case X86::XMM3: ShadowReg = X86::R9; break;
2905         }
2906         if (ShadowReg)
2907           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2908       }
2909     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2910       assert(VA.isMemLoc());
2911       if (!StackPtr.getNode())
2912         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2913                                       getPointerTy());
2914       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2915                                              dl, DAG, VA, Flags));
2916     }
2917   }
2918
2919   if (!MemOpChains.empty())
2920     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
2921
2922   if (Subtarget->isPICStyleGOT()) {
2923     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2924     // GOT pointer.
2925     if (!isTailCall) {
2926       RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2927                DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
2928     } else {
2929       // If we are tail calling and generating PIC/GOT style code load the
2930       // address of the callee into ECX. The value in ecx is used as target of
2931       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2932       // for tail calls on PIC/GOT architectures. Normally we would just put the
2933       // address of GOT into ebx and then call target@PLT. But for tail calls
2934       // ebx would be restored (since ebx is callee saved) before jumping to the
2935       // target@PLT.
2936
2937       // Note: The actual moving to ECX is done further down.
2938       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2939       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2940           !G->getGlobal()->hasProtectedVisibility())
2941         Callee = LowerGlobalAddress(Callee, DAG);
2942       else if (isa<ExternalSymbolSDNode>(Callee))
2943         Callee = LowerExternalSymbol(Callee, DAG);
2944     }
2945   }
2946
2947   if (Is64Bit && isVarArg && !IsWin64 && !IsMustTail) {
2948     // From AMD64 ABI document:
2949     // For calls that may call functions that use varargs or stdargs
2950     // (prototype-less calls or calls to functions containing ellipsis (...) in
2951     // the declaration) %al is used as hidden argument to specify the number
2952     // of SSE registers used. The contents of %al do not need to match exactly
2953     // the number of registers, but must be an ubound on the number of SSE
2954     // registers used and is in the range 0 - 8 inclusive.
2955
2956     // Count the number of XMM registers allocated.
2957     static const MCPhysReg XMMArgRegs[] = {
2958       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2959       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2960     };
2961     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs);
2962     assert((Subtarget->hasSSE1() || !NumXMMRegs)
2963            && "SSE registers cannot be used when SSE is disabled");
2964
2965     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2966                                         DAG.getConstant(NumXMMRegs, dl,
2967                                                         MVT::i8)));
2968   }
2969
2970   if (isVarArg && IsMustTail) {
2971     const auto &Forwards = X86Info->getForwardedMustTailRegParms();
2972     for (const auto &F : Forwards) {
2973       SDValue Val = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
2974       RegsToPass.push_back(std::make_pair(unsigned(F.PReg), Val));
2975     }
2976   }
2977
2978   // For tail calls lower the arguments to the 'real' stack slots.  Sibcalls
2979   // don't need this because the eligibility check rejects calls that require
2980   // shuffling arguments passed in memory.
2981   if (!IsSibcall && isTailCall) {
2982     // Force all the incoming stack arguments to be loaded from the stack
2983     // before any new outgoing arguments are stored to the stack, because the
2984     // outgoing stack slots may alias the incoming argument stack slots, and
2985     // the alias isn't otherwise explicit. This is slightly more conservative
2986     // than necessary, because it means that each store effectively depends
2987     // on every argument instead of just those arguments it would clobber.
2988     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2989
2990     SmallVector<SDValue, 8> MemOpChains2;
2991     SDValue FIN;
2992     int FI = 0;
2993     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2994       CCValAssign &VA = ArgLocs[i];
2995       if (VA.isRegLoc())
2996         continue;
2997       assert(VA.isMemLoc());
2998       SDValue Arg = OutVals[i];
2999       ISD::ArgFlagsTy Flags = Outs[i].Flags;
3000       // Skip inalloca arguments.  They don't require any work.
3001       if (Flags.isInAlloca())
3002         continue;
3003       // Create frame index.
3004       int32_t Offset = VA.getLocMemOffset()+FPDiff;
3005       uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
3006       FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3007       FIN = DAG.getFrameIndex(FI, getPointerTy());
3008
3009       if (Flags.isByVal()) {
3010         // Copy relative to framepointer.
3011         SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset(), dl);
3012         if (!StackPtr.getNode())
3013           StackPtr = DAG.getCopyFromReg(Chain, dl,
3014                                         RegInfo->getStackRegister(),
3015                                         getPointerTy());
3016         Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
3017
3018         MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
3019                                                          ArgChain,
3020                                                          Flags, DAG, dl));
3021       } else {
3022         // Store relative to framepointer.
3023         MemOpChains2.push_back(
3024           DAG.getStore(ArgChain, dl, Arg, FIN,
3025                        MachinePointerInfo::getFixedStack(FI),
3026                        false, false, 0));
3027       }
3028     }
3029
3030     if (!MemOpChains2.empty())
3031       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
3032
3033     // Store the return address to the appropriate stack slot.
3034     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
3035                                      getPointerTy(), RegInfo->getSlotSize(),
3036                                      FPDiff, dl);
3037   }
3038
3039   // Build a sequence of copy-to-reg nodes chained together with token chain
3040   // and flag operands which copy the outgoing args into registers.
3041   SDValue InFlag;
3042   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
3043     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
3044                              RegsToPass[i].second, InFlag);
3045     InFlag = Chain.getValue(1);
3046   }
3047
3048   if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
3049     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
3050     // In the 64-bit large code model, we have to make all calls
3051     // through a register, since the call instruction's 32-bit
3052     // pc-relative offset may not be large enough to hold the whole
3053     // address.
3054   } else if (Callee->getOpcode() == ISD::GlobalAddress) {
3055     // If the callee is a GlobalAddress node (quite common, every direct call
3056     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
3057     // it.
3058     GlobalAddressSDNode* G = cast<GlobalAddressSDNode>(Callee);
3059
3060     // We should use extra load for direct calls to dllimported functions in
3061     // non-JIT mode.
3062     const GlobalValue *GV = G->getGlobal();
3063     if (!GV->hasDLLImportStorageClass()) {
3064       unsigned char OpFlags = 0;
3065       bool ExtraLoad = false;
3066       unsigned WrapperKind = ISD::DELETED_NODE;
3067
3068       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
3069       // external symbols most go through the PLT in PIC mode.  If the symbol
3070       // has hidden or protected visibility, or if it is static or local, then
3071       // we don't need to use the PLT - we can directly call it.
3072       if (Subtarget->isTargetELF() &&
3073           DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
3074           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
3075         OpFlags = X86II::MO_PLT;
3076       } else if (Subtarget->isPICStyleStubAny() &&
3077                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
3078                  (!Subtarget->getTargetTriple().isMacOSX() ||
3079                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3080         // PC-relative references to external symbols should go through $stub,
3081         // unless we're building with the leopard linker or later, which
3082         // automatically synthesizes these stubs.
3083         OpFlags = X86II::MO_DARWIN_STUB;
3084       } else if (Subtarget->isPICStyleRIPRel() && isa<Function>(GV) &&
3085                  cast<Function>(GV)->hasFnAttribute(Attribute::NonLazyBind)) {
3086         // If the function is marked as non-lazy, generate an indirect call
3087         // which loads from the GOT directly. This avoids runtime overhead
3088         // at the cost of eager binding (and one extra byte of encoding).
3089         OpFlags = X86II::MO_GOTPCREL;
3090         WrapperKind = X86ISD::WrapperRIP;
3091         ExtraLoad = true;
3092       }
3093
3094       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
3095                                           G->getOffset(), OpFlags);
3096
3097       // Add a wrapper if needed.
3098       if (WrapperKind != ISD::DELETED_NODE)
3099         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
3100       // Add extra indirection if needed.
3101       if (ExtraLoad)
3102         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
3103                              MachinePointerInfo::getGOT(),
3104                              false, false, false, 0);
3105     }
3106   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3107     unsigned char OpFlags = 0;
3108
3109     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
3110     // external symbols should go through the PLT.
3111     if (Subtarget->isTargetELF() &&
3112         DAG.getTarget().getRelocationModel() == Reloc::PIC_) {
3113       OpFlags = X86II::MO_PLT;
3114     } else if (Subtarget->isPICStyleStubAny() &&
3115                (!Subtarget->getTargetTriple().isMacOSX() ||
3116                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3117       // PC-relative references to external symbols should go through $stub,
3118       // unless we're building with the leopard linker or later, which
3119       // automatically synthesizes these stubs.
3120       OpFlags = X86II::MO_DARWIN_STUB;
3121     }
3122
3123     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
3124                                          OpFlags);
3125   } else if (Subtarget->isTarget64BitILP32() &&
3126              Callee->getValueType(0) == MVT::i32) {
3127     // Zero-extend the 32-bit Callee address into a 64-bit according to x32 ABI
3128     Callee = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, Callee);
3129   }
3130
3131   // Returns a chain & a flag for retval copy to use.
3132   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3133   SmallVector<SDValue, 8> Ops;
3134
3135   if (!IsSibcall && isTailCall) {
3136     Chain = DAG.getCALLSEQ_END(Chain,
3137                                DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3138                                DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
3139     InFlag = Chain.getValue(1);
3140   }
3141
3142   Ops.push_back(Chain);
3143   Ops.push_back(Callee);
3144
3145   if (isTailCall)
3146     Ops.push_back(DAG.getConstant(FPDiff, dl, MVT::i32));
3147
3148   // Add argument registers to the end of the list so that they are known live
3149   // into the call.
3150   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3151     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3152                                   RegsToPass[i].second.getValueType()));
3153
3154   // Add a register mask operand representing the call-preserved registers.
3155   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
3156   const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
3157   assert(Mask && "Missing call preserved mask for calling convention");
3158   Ops.push_back(DAG.getRegisterMask(Mask));
3159
3160   if (InFlag.getNode())
3161     Ops.push_back(InFlag);
3162
3163   if (isTailCall) {
3164     // We used to do:
3165     //// If this is the first return lowered for this function, add the regs
3166     //// to the liveout set for the function.
3167     // This isn't right, although it's probably harmless on x86; liveouts
3168     // should be computed from returns not tail calls.  Consider a void
3169     // function making a tail call to a function returning int.
3170     MF.getFrameInfo()->setHasTailCall();
3171     return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
3172   }
3173
3174   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
3175   InFlag = Chain.getValue(1);
3176
3177   // Create the CALLSEQ_END node.
3178   unsigned NumBytesForCalleeToPop;
3179   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
3180                        DAG.getTarget().Options.GuaranteedTailCallOpt))
3181     NumBytesForCalleeToPop = NumBytes;    // Callee pops everything
3182   else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
3183            !Subtarget->getTargetTriple().isOSMSVCRT() &&
3184            SR == StackStructReturn)
3185     // If this is a call to a struct-return function, the callee
3186     // pops the hidden struct pointer, so we have to push it back.
3187     // This is common for Darwin/X86, Linux & Mingw32 targets.
3188     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
3189     NumBytesForCalleeToPop = 4;
3190   else
3191     NumBytesForCalleeToPop = 0;  // Callee pops nothing.
3192
3193   // Returns a flag for retval copy to use.
3194   if (!IsSibcall) {
3195     Chain = DAG.getCALLSEQ_END(Chain,
3196                                DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3197                                DAG.getIntPtrConstant(NumBytesForCalleeToPop, dl,
3198                                                      true),
3199                                InFlag, dl);
3200     InFlag = Chain.getValue(1);
3201   }
3202
3203   // Handle result values, copying them out of physregs into vregs that we
3204   // return.
3205   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3206                          Ins, dl, DAG, InVals);
3207 }
3208
3209 //===----------------------------------------------------------------------===//
3210 //                Fast Calling Convention (tail call) implementation
3211 //===----------------------------------------------------------------------===//
3212
3213 //  Like std call, callee cleans arguments, convention except that ECX is
3214 //  reserved for storing the tail called function address. Only 2 registers are
3215 //  free for argument passing (inreg). Tail call optimization is performed
3216 //  provided:
3217 //                * tailcallopt is enabled
3218 //                * caller/callee are fastcc
3219 //  On X86_64 architecture with GOT-style position independent code only local
3220 //  (within module) calls are supported at the moment.
3221 //  To keep the stack aligned according to platform abi the function
3222 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
3223 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3224 //  If a tail called function callee has more arguments than the caller the
3225 //  caller needs to make sure that there is room to move the RETADDR to. This is
3226 //  achieved by reserving an area the size of the argument delta right after the
3227 //  original RETADDR, but before the saved framepointer or the spilled registers
3228 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3229 //  stack layout:
3230 //    arg1
3231 //    arg2
3232 //    RETADDR
3233 //    [ new RETADDR
3234 //      move area ]
3235 //    (possible EBP)
3236 //    ESI
3237 //    EDI
3238 //    local1 ..
3239
3240 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
3241 /// for a 16 byte align requirement.
3242 unsigned
3243 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3244                                                SelectionDAG& DAG) const {
3245   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3246   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
3247   unsigned StackAlignment = TFI.getStackAlignment();
3248   uint64_t AlignMask = StackAlignment - 1;
3249   int64_t Offset = StackSize;
3250   unsigned SlotSize = RegInfo->getSlotSize();
3251   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3252     // Number smaller than 12 so just add the difference.
3253     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3254   } else {
3255     // Mask out lower bits, add stackalignment once plus the 12 bytes.
3256     Offset = ((~AlignMask) & Offset) + StackAlignment +
3257       (StackAlignment-SlotSize);
3258   }
3259   return Offset;
3260 }
3261
3262 /// MatchingStackOffset - Return true if the given stack call argument is
3263 /// already available in the same position (relatively) of the caller's
3264 /// incoming argument stack.
3265 static
3266 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3267                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3268                          const X86InstrInfo *TII) {
3269   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3270   int FI = INT_MAX;
3271   if (Arg.getOpcode() == ISD::CopyFromReg) {
3272     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3273     if (!TargetRegisterInfo::isVirtualRegister(VR))
3274       return false;
3275     MachineInstr *Def = MRI->getVRegDef(VR);
3276     if (!Def)
3277       return false;
3278     if (!Flags.isByVal()) {
3279       if (!TII->isLoadFromStackSlot(Def, FI))
3280         return false;
3281     } else {
3282       unsigned Opcode = Def->getOpcode();
3283       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r ||
3284            Opcode == X86::LEA64_32r) &&
3285           Def->getOperand(1).isFI()) {
3286         FI = Def->getOperand(1).getIndex();
3287         Bytes = Flags.getByValSize();
3288       } else
3289         return false;
3290     }
3291   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3292     if (Flags.isByVal())
3293       // ByVal argument is passed in as a pointer but it's now being
3294       // dereferenced. e.g.
3295       // define @foo(%struct.X* %A) {
3296       //   tail call @bar(%struct.X* byval %A)
3297       // }
3298       return false;
3299     SDValue Ptr = Ld->getBasePtr();
3300     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3301     if (!FINode)
3302       return false;
3303     FI = FINode->getIndex();
3304   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3305     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3306     FI = FINode->getIndex();
3307     Bytes = Flags.getByValSize();
3308   } else
3309     return false;
3310
3311   assert(FI != INT_MAX);
3312   if (!MFI->isFixedObjectIndex(FI))
3313     return false;
3314   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3315 }
3316
3317 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3318 /// for tail call optimization. Targets which want to do tail call
3319 /// optimization should implement this function.
3320 bool
3321 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3322                                                      CallingConv::ID CalleeCC,
3323                                                      bool isVarArg,
3324                                                      bool isCalleeStructRet,
3325                                                      bool isCallerStructRet,
3326                                                      Type *RetTy,
3327                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
3328                                     const SmallVectorImpl<SDValue> &OutVals,
3329                                     const SmallVectorImpl<ISD::InputArg> &Ins,
3330                                                      SelectionDAG &DAG) const {
3331   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3332     return false;
3333
3334   // If -tailcallopt is specified, make fastcc functions tail-callable.
3335   const MachineFunction &MF = DAG.getMachineFunction();
3336   const Function *CallerF = MF.getFunction();
3337
3338   // If the function return type is x86_fp80 and the callee return type is not,
3339   // then the FP_EXTEND of the call result is not a nop. It's not safe to
3340   // perform a tailcall optimization here.
3341   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3342     return false;
3343
3344   CallingConv::ID CallerCC = CallerF->getCallingConv();
3345   bool CCMatch = CallerCC == CalleeCC;
3346   bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3347   bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3348
3349   // Win64 functions have extra shadow space for argument homing. Don't do the
3350   // sibcall if the caller and callee have mismatched expectations for this
3351   // space.
3352   if (IsCalleeWin64 != IsCallerWin64)
3353     return false;
3354
3355   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3356     if (IsTailCallConvention(CalleeCC) && CCMatch)
3357       return true;
3358     return false;
3359   }
3360
3361   // Look for obvious safe cases to perform tail call optimization that do not
3362   // require ABI changes. This is what gcc calls sibcall.
3363
3364   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3365   // emit a special epilogue.
3366   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3367   if (RegInfo->needsStackRealignment(MF))
3368     return false;
3369
3370   // Also avoid sibcall optimization if either caller or callee uses struct
3371   // return semantics.
3372   if (isCalleeStructRet || isCallerStructRet)
3373     return false;
3374
3375   // An stdcall/thiscall caller is expected to clean up its arguments; the
3376   // callee isn't going to do that.
3377   // FIXME: this is more restrictive than needed. We could produce a tailcall
3378   // when the stack adjustment matches. For example, with a thiscall that takes
3379   // only one argument.
3380   if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3381                    CallerCC == CallingConv::X86_ThisCall))
3382     return false;
3383
3384   // Do not sibcall optimize vararg calls unless all arguments are passed via
3385   // registers.
3386   if (isVarArg && !Outs.empty()) {
3387
3388     // Optimizing for varargs on Win64 is unlikely to be safe without
3389     // additional testing.
3390     if (IsCalleeWin64 || IsCallerWin64)
3391       return false;
3392
3393     SmallVector<CCValAssign, 16> ArgLocs;
3394     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3395                    *DAG.getContext());
3396
3397     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3398     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3399       if (!ArgLocs[i].isRegLoc())
3400         return false;
3401   }
3402
3403   // If the call result is in ST0 / ST1, it needs to be popped off the x87
3404   // stack.  Therefore, if it's not used by the call it is not safe to optimize
3405   // this into a sibcall.
3406   bool Unused = false;
3407   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3408     if (!Ins[i].Used) {
3409       Unused = true;
3410       break;
3411     }
3412   }
3413   if (Unused) {
3414     SmallVector<CCValAssign, 16> RVLocs;
3415     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(), RVLocs,
3416                    *DAG.getContext());
3417     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3418     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3419       CCValAssign &VA = RVLocs[i];
3420       if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
3421         return false;
3422     }
3423   }
3424
3425   // If the calling conventions do not match, then we'd better make sure the
3426   // results are returned in the same way as what the caller expects.
3427   if (!CCMatch) {
3428     SmallVector<CCValAssign, 16> RVLocs1;
3429     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
3430                     *DAG.getContext());
3431     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3432
3433     SmallVector<CCValAssign, 16> RVLocs2;
3434     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
3435                     *DAG.getContext());
3436     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3437
3438     if (RVLocs1.size() != RVLocs2.size())
3439       return false;
3440     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3441       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3442         return false;
3443       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3444         return false;
3445       if (RVLocs1[i].isRegLoc()) {
3446         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3447           return false;
3448       } else {
3449         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3450           return false;
3451       }
3452     }
3453   }
3454
3455   // If the callee takes no arguments then go on to check the results of the
3456   // call.
3457   if (!Outs.empty()) {
3458     // Check if stack adjustment is needed. For now, do not do this if any
3459     // argument is passed on the stack.
3460     SmallVector<CCValAssign, 16> ArgLocs;
3461     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3462                    *DAG.getContext());
3463
3464     // Allocate shadow area for Win64
3465     if (IsCalleeWin64)
3466       CCInfo.AllocateStack(32, 8);
3467
3468     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3469     if (CCInfo.getNextStackOffset()) {
3470       MachineFunction &MF = DAG.getMachineFunction();
3471       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3472         return false;
3473
3474       // Check if the arguments are already laid out in the right way as
3475       // the caller's fixed stack objects.
3476       MachineFrameInfo *MFI = MF.getFrameInfo();
3477       const MachineRegisterInfo *MRI = &MF.getRegInfo();
3478       const X86InstrInfo *TII = Subtarget->getInstrInfo();
3479       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3480         CCValAssign &VA = ArgLocs[i];
3481         SDValue Arg = OutVals[i];
3482         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3483         if (VA.getLocInfo() == CCValAssign::Indirect)
3484           return false;
3485         if (!VA.isRegLoc()) {
3486           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3487                                    MFI, MRI, TII))
3488             return false;
3489         }
3490       }
3491     }
3492
3493     // If the tailcall address may be in a register, then make sure it's
3494     // possible to register allocate for it. In 32-bit, the call address can
3495     // only target EAX, EDX, or ECX since the tail call must be scheduled after
3496     // callee-saved registers are restored. These happen to be the same
3497     // registers used to pass 'inreg' arguments so watch out for those.
3498     if (!Subtarget->is64Bit() &&
3499         ((!isa<GlobalAddressSDNode>(Callee) &&
3500           !isa<ExternalSymbolSDNode>(Callee)) ||
3501          DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3502       unsigned NumInRegs = 0;
3503       // In PIC we need an extra register to formulate the address computation
3504       // for the callee.
3505       unsigned MaxInRegs =
3506         (DAG.getTarget().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3507
3508       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3509         CCValAssign &VA = ArgLocs[i];
3510         if (!VA.isRegLoc())
3511           continue;
3512         unsigned Reg = VA.getLocReg();
3513         switch (Reg) {
3514         default: break;
3515         case X86::EAX: case X86::EDX: case X86::ECX:
3516           if (++NumInRegs == MaxInRegs)
3517             return false;
3518           break;
3519         }
3520       }
3521     }
3522   }
3523
3524   return true;
3525 }
3526
3527 FastISel *
3528 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3529                                   const TargetLibraryInfo *libInfo) const {
3530   return X86::createFastISel(funcInfo, libInfo);
3531 }
3532
3533 //===----------------------------------------------------------------------===//
3534 //                           Other Lowering Hooks
3535 //===----------------------------------------------------------------------===//
3536
3537 static bool MayFoldLoad(SDValue Op) {
3538   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3539 }
3540
3541 static bool MayFoldIntoStore(SDValue Op) {
3542   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3543 }
3544
3545 static bool isTargetShuffle(unsigned Opcode) {
3546   switch(Opcode) {
3547   default: return false;
3548   case X86ISD::BLENDI:
3549   case X86ISD::PSHUFB:
3550   case X86ISD::PSHUFD:
3551   case X86ISD::PSHUFHW:
3552   case X86ISD::PSHUFLW:
3553   case X86ISD::SHUFP:
3554   case X86ISD::PALIGNR:
3555   case X86ISD::MOVLHPS:
3556   case X86ISD::MOVLHPD:
3557   case X86ISD::MOVHLPS:
3558   case X86ISD::MOVLPS:
3559   case X86ISD::MOVLPD:
3560   case X86ISD::MOVSHDUP:
3561   case X86ISD::MOVSLDUP:
3562   case X86ISD::MOVDDUP:
3563   case X86ISD::MOVSS:
3564   case X86ISD::MOVSD:
3565   case X86ISD::UNPCKL:
3566   case X86ISD::UNPCKH:
3567   case X86ISD::VPERMILPI:
3568   case X86ISD::VPERM2X128:
3569   case X86ISD::VPERMI:
3570     return true;
3571   }
3572 }
3573
3574 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3575                                     SDValue V1, unsigned TargetMask,
3576                                     SelectionDAG &DAG) {
3577   switch(Opc) {
3578   default: llvm_unreachable("Unknown x86 shuffle node");
3579   case X86ISD::PSHUFD:
3580   case X86ISD::PSHUFHW:
3581   case X86ISD::PSHUFLW:
3582   case X86ISD::VPERMILPI:
3583   case X86ISD::VPERMI:
3584     return DAG.getNode(Opc, dl, VT, V1,
3585                        DAG.getConstant(TargetMask, dl, MVT::i8));
3586   }
3587 }
3588
3589 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3590                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
3591   switch(Opc) {
3592   default: llvm_unreachable("Unknown x86 shuffle node");
3593   case X86ISD::MOVLHPS:
3594   case X86ISD::MOVLHPD:
3595   case X86ISD::MOVHLPS:
3596   case X86ISD::MOVLPS:
3597   case X86ISD::MOVLPD:
3598   case X86ISD::MOVSS:
3599   case X86ISD::MOVSD:
3600   case X86ISD::UNPCKL:
3601   case X86ISD::UNPCKH:
3602     return DAG.getNode(Opc, dl, VT, V1, V2);
3603   }
3604 }
3605
3606 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3607   MachineFunction &MF = DAG.getMachineFunction();
3608   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3609   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3610   int ReturnAddrIndex = FuncInfo->getRAIndex();
3611
3612   if (ReturnAddrIndex == 0) {
3613     // Set up a frame object for the return address.
3614     unsigned SlotSize = RegInfo->getSlotSize();
3615     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3616                                                            -(int64_t)SlotSize,
3617                                                            false);
3618     FuncInfo->setRAIndex(ReturnAddrIndex);
3619   }
3620
3621   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3622 }
3623
3624 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3625                                        bool hasSymbolicDisplacement) {
3626   // Offset should fit into 32 bit immediate field.
3627   if (!isInt<32>(Offset))
3628     return false;
3629
3630   // If we don't have a symbolic displacement - we don't have any extra
3631   // restrictions.
3632   if (!hasSymbolicDisplacement)
3633     return true;
3634
3635   // FIXME: Some tweaks might be needed for medium code model.
3636   if (M != CodeModel::Small && M != CodeModel::Kernel)
3637     return false;
3638
3639   // For small code model we assume that latest object is 16MB before end of 31
3640   // bits boundary. We may also accept pretty large negative constants knowing
3641   // that all objects are in the positive half of address space.
3642   if (M == CodeModel::Small && Offset < 16*1024*1024)
3643     return true;
3644
3645   // For kernel code model we know that all object resist in the negative half
3646   // of 32bits address space. We may not accept negative offsets, since they may
3647   // be just off and we may accept pretty large positive ones.
3648   if (M == CodeModel::Kernel && Offset >= 0)
3649     return true;
3650
3651   return false;
3652 }
3653
3654 /// isCalleePop - Determines whether the callee is required to pop its
3655 /// own arguments. Callee pop is necessary to support tail calls.
3656 bool X86::isCalleePop(CallingConv::ID CallingConv,
3657                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3658   switch (CallingConv) {
3659   default:
3660     return false;
3661   case CallingConv::X86_StdCall:
3662   case CallingConv::X86_FastCall:
3663   case CallingConv::X86_ThisCall:
3664     return !is64Bit;
3665   case CallingConv::Fast:
3666   case CallingConv::GHC:
3667   case CallingConv::HiPE:
3668     if (IsVarArg)
3669       return false;
3670     return TailCallOpt;
3671   }
3672 }
3673
3674 /// \brief Return true if the condition is an unsigned comparison operation.
3675 static bool isX86CCUnsigned(unsigned X86CC) {
3676   switch (X86CC) {
3677   default: llvm_unreachable("Invalid integer condition!");
3678   case X86::COND_E:     return true;
3679   case X86::COND_G:     return false;
3680   case X86::COND_GE:    return false;
3681   case X86::COND_L:     return false;
3682   case X86::COND_LE:    return false;
3683   case X86::COND_NE:    return true;
3684   case X86::COND_B:     return true;
3685   case X86::COND_A:     return true;
3686   case X86::COND_BE:    return true;
3687   case X86::COND_AE:    return true;
3688   }
3689   llvm_unreachable("covered switch fell through?!");
3690 }
3691
3692 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3693 /// specific condition code, returning the condition code and the LHS/RHS of the
3694 /// comparison to make.
3695 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, SDLoc DL, bool isFP,
3696                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3697   if (!isFP) {
3698     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3699       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3700         // X > -1   -> X == 0, jump !sign.
3701         RHS = DAG.getConstant(0, DL, RHS.getValueType());
3702         return X86::COND_NS;
3703       }
3704       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3705         // X < 0   -> X == 0, jump on sign.
3706         return X86::COND_S;
3707       }
3708       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3709         // X < 1   -> X <= 0
3710         RHS = DAG.getConstant(0, DL, RHS.getValueType());
3711         return X86::COND_LE;
3712       }
3713     }
3714
3715     switch (SetCCOpcode) {
3716     default: llvm_unreachable("Invalid integer condition!");
3717     case ISD::SETEQ:  return X86::COND_E;
3718     case ISD::SETGT:  return X86::COND_G;
3719     case ISD::SETGE:  return X86::COND_GE;
3720     case ISD::SETLT:  return X86::COND_L;
3721     case ISD::SETLE:  return X86::COND_LE;
3722     case ISD::SETNE:  return X86::COND_NE;
3723     case ISD::SETULT: return X86::COND_B;
3724     case ISD::SETUGT: return X86::COND_A;
3725     case ISD::SETULE: return X86::COND_BE;
3726     case ISD::SETUGE: return X86::COND_AE;
3727     }
3728   }
3729
3730   // First determine if it is required or is profitable to flip the operands.
3731
3732   // If LHS is a foldable load, but RHS is not, flip the condition.
3733   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3734       !ISD::isNON_EXTLoad(RHS.getNode())) {
3735     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3736     std::swap(LHS, RHS);
3737   }
3738
3739   switch (SetCCOpcode) {
3740   default: break;
3741   case ISD::SETOLT:
3742   case ISD::SETOLE:
3743   case ISD::SETUGT:
3744   case ISD::SETUGE:
3745     std::swap(LHS, RHS);
3746     break;
3747   }
3748
3749   // On a floating point condition, the flags are set as follows:
3750   // ZF  PF  CF   op
3751   //  0 | 0 | 0 | X > Y
3752   //  0 | 0 | 1 | X < Y
3753   //  1 | 0 | 0 | X == Y
3754   //  1 | 1 | 1 | unordered
3755   switch (SetCCOpcode) {
3756   default: llvm_unreachable("Condcode should be pre-legalized away");
3757   case ISD::SETUEQ:
3758   case ISD::SETEQ:   return X86::COND_E;
3759   case ISD::SETOLT:              // flipped
3760   case ISD::SETOGT:
3761   case ISD::SETGT:   return X86::COND_A;
3762   case ISD::SETOLE:              // flipped
3763   case ISD::SETOGE:
3764   case ISD::SETGE:   return X86::COND_AE;
3765   case ISD::SETUGT:              // flipped
3766   case ISD::SETULT:
3767   case ISD::SETLT:   return X86::COND_B;
3768   case ISD::SETUGE:              // flipped
3769   case ISD::SETULE:
3770   case ISD::SETLE:   return X86::COND_BE;
3771   case ISD::SETONE:
3772   case ISD::SETNE:   return X86::COND_NE;
3773   case ISD::SETUO:   return X86::COND_P;
3774   case ISD::SETO:    return X86::COND_NP;
3775   case ISD::SETOEQ:
3776   case ISD::SETUNE:  return X86::COND_INVALID;
3777   }
3778 }
3779
3780 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3781 /// code. Current x86 isa includes the following FP cmov instructions:
3782 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3783 static bool hasFPCMov(unsigned X86CC) {
3784   switch (X86CC) {
3785   default:
3786     return false;
3787   case X86::COND_B:
3788   case X86::COND_BE:
3789   case X86::COND_E:
3790   case X86::COND_P:
3791   case X86::COND_A:
3792   case X86::COND_AE:
3793   case X86::COND_NE:
3794   case X86::COND_NP:
3795     return true;
3796   }
3797 }
3798
3799 /// isFPImmLegal - Returns true if the target can instruction select the
3800 /// specified FP immediate natively. If false, the legalizer will
3801 /// materialize the FP immediate as a load from a constant pool.
3802 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3803   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3804     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3805       return true;
3806   }
3807   return false;
3808 }
3809
3810 bool X86TargetLowering::shouldReduceLoadWidth(SDNode *Load,
3811                                               ISD::LoadExtType ExtTy,
3812                                               EVT NewVT) const {
3813   // "ELF Handling for Thread-Local Storage" specifies that R_X86_64_GOTTPOFF
3814   // relocation target a movq or addq instruction: don't let the load shrink.
3815   SDValue BasePtr = cast<LoadSDNode>(Load)->getBasePtr();
3816   if (BasePtr.getOpcode() == X86ISD::WrapperRIP)
3817     if (const auto *GA = dyn_cast<GlobalAddressSDNode>(BasePtr.getOperand(0)))
3818       return GA->getTargetFlags() != X86II::MO_GOTTPOFF;
3819   return true;
3820 }
3821
3822 /// \brief Returns true if it is beneficial to convert a load of a constant
3823 /// to just the constant itself.
3824 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
3825                                                           Type *Ty) const {
3826   assert(Ty->isIntegerTy());
3827
3828   unsigned BitSize = Ty->getPrimitiveSizeInBits();
3829   if (BitSize == 0 || BitSize > 64)
3830     return false;
3831   return true;
3832 }
3833
3834 bool X86TargetLowering::isExtractSubvectorCheap(EVT ResVT,
3835                                                 unsigned Index) const {
3836   if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
3837     return false;
3838
3839   return (Index == 0 || Index == ResVT.getVectorNumElements());
3840 }
3841
3842 bool X86TargetLowering::isCheapToSpeculateCttz() const {
3843   // Speculate cttz only if we can directly use TZCNT.
3844   return Subtarget->hasBMI();
3845 }
3846
3847 bool X86TargetLowering::isCheapToSpeculateCtlz() const {
3848   // Speculate ctlz only if we can directly use LZCNT.
3849   return Subtarget->hasLZCNT();
3850 }
3851
3852 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3853 /// the specified range (L, H].
3854 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3855   return (Val < 0) || (Val >= Low && Val < Hi);
3856 }
3857
3858 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3859 /// specified value.
3860 static bool isUndefOrEqual(int Val, int CmpVal) {
3861   return (Val < 0 || Val == CmpVal);
3862 }
3863
3864 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3865 /// from position Pos and ending in Pos+Size, falls within the specified
3866 /// sequential range (Low, Low+Size]. or is undef.
3867 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3868                                        unsigned Pos, unsigned Size, int Low) {
3869   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3870     if (!isUndefOrEqual(Mask[i], Low))
3871       return false;
3872   return true;
3873 }
3874
3875 /// isVEXTRACTIndex - Return true if the specified
3876 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
3877 /// suitable for instruction that extract 128 or 256 bit vectors
3878 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
3879   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
3880   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3881     return false;
3882
3883   // The index should be aligned on a vecWidth-bit boundary.
3884   uint64_t Index =
3885     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3886
3887   MVT VT = N->getSimpleValueType(0);
3888   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
3889   bool Result = (Index * ElSize) % vecWidth == 0;
3890
3891   return Result;
3892 }
3893
3894 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
3895 /// operand specifies a subvector insert that is suitable for input to
3896 /// insertion of 128 or 256-bit subvectors
3897 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
3898   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
3899   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3900     return false;
3901   // The index should be aligned on a vecWidth-bit boundary.
3902   uint64_t Index =
3903     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3904
3905   MVT VT = N->getSimpleValueType(0);
3906   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
3907   bool Result = (Index * ElSize) % vecWidth == 0;
3908
3909   return Result;
3910 }
3911
3912 bool X86::isVINSERT128Index(SDNode *N) {
3913   return isVINSERTIndex(N, 128);
3914 }
3915
3916 bool X86::isVINSERT256Index(SDNode *N) {
3917   return isVINSERTIndex(N, 256);
3918 }
3919
3920 bool X86::isVEXTRACT128Index(SDNode *N) {
3921   return isVEXTRACTIndex(N, 128);
3922 }
3923
3924 bool X86::isVEXTRACT256Index(SDNode *N) {
3925   return isVEXTRACTIndex(N, 256);
3926 }
3927
3928 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
3929   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
3930   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3931     llvm_unreachable("Illegal extract subvector for VEXTRACT");
3932
3933   uint64_t Index =
3934     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3935
3936   MVT VecVT = N->getOperand(0).getSimpleValueType();
3937   MVT ElVT = VecVT.getVectorElementType();
3938
3939   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
3940   return Index / NumElemsPerChunk;
3941 }
3942
3943 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
3944   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
3945   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3946     llvm_unreachable("Illegal insert subvector for VINSERT");
3947
3948   uint64_t Index =
3949     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3950
3951   MVT VecVT = N->getSimpleValueType(0);
3952   MVT ElVT = VecVT.getVectorElementType();
3953
3954   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
3955   return Index / NumElemsPerChunk;
3956 }
3957
3958 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
3959 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
3960 /// and VINSERTI128 instructions.
3961 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
3962   return getExtractVEXTRACTImmediate(N, 128);
3963 }
3964
3965 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
3966 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
3967 /// and VINSERTI64x4 instructions.
3968 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
3969   return getExtractVEXTRACTImmediate(N, 256);
3970 }
3971
3972 /// getInsertVINSERT128Immediate - Return the appropriate immediate
3973 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
3974 /// and VINSERTI128 instructions.
3975 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
3976   return getInsertVINSERTImmediate(N, 128);
3977 }
3978
3979 /// getInsertVINSERT256Immediate - Return the appropriate immediate
3980 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
3981 /// and VINSERTI64x4 instructions.
3982 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
3983   return getInsertVINSERTImmediate(N, 256);
3984 }
3985
3986 /// isZero - Returns true if Elt is a constant integer zero
3987 static bool isZero(SDValue V) {
3988   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
3989   return C && C->isNullValue();
3990 }
3991
3992 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
3993 /// constant +0.0.
3994 bool X86::isZeroNode(SDValue Elt) {
3995   if (isZero(Elt))
3996     return true;
3997   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
3998     return CFP->getValueAPF().isPosZero();
3999   return false;
4000 }
4001
4002 /// getZeroVector - Returns a vector of specified type with all zero elements.
4003 ///
4004 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4005                              SelectionDAG &DAG, SDLoc dl) {
4006   assert(VT.isVector() && "Expected a vector type");
4007
4008   // Always build SSE zero vectors as <4 x i32> bitcasted
4009   // to their dest type. This ensures they get CSE'd.
4010   SDValue Vec;
4011   if (VT.is128BitVector()) {  // SSE
4012     if (Subtarget->hasSSE2()) {  // SSE2
4013       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4014       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4015     } else { // SSE1
4016       SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4017       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4018     }
4019   } else if (VT.is256BitVector()) { // AVX
4020     if (Subtarget->hasInt256()) { // AVX2
4021       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4022       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4023       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4024     } else {
4025       // 256-bit logic and arithmetic instructions in AVX are all
4026       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4027       SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4028       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4029       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
4030     }
4031   } else if (VT.is512BitVector()) { // AVX-512
4032       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4033       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4034                         Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4035       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4036   } else if (VT.getScalarType() == MVT::i1) {
4037
4038     assert((Subtarget->hasBWI() || VT.getVectorNumElements() <= 16)
4039             && "Unexpected vector type");
4040     assert((Subtarget->hasVLX() || VT.getVectorNumElements() >= 8)
4041             && "Unexpected vector type");
4042     SDValue Cst = DAG.getConstant(0, dl, MVT::i1);
4043     SmallVector<SDValue, 64> Ops(VT.getVectorNumElements(), Cst);
4044     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
4045   } else
4046     llvm_unreachable("Unexpected vector type");
4047
4048   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4049 }
4050
4051 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
4052                                 SelectionDAG &DAG, SDLoc dl,
4053                                 unsigned vectorWidth) {
4054   assert((vectorWidth == 128 || vectorWidth == 256) &&
4055          "Unsupported vector width");
4056   EVT VT = Vec.getValueType();
4057   EVT ElVT = VT.getVectorElementType();
4058   unsigned Factor = VT.getSizeInBits()/vectorWidth;
4059   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
4060                                   VT.getVectorNumElements()/Factor);
4061
4062   // Extract from UNDEF is UNDEF.
4063   if (Vec.getOpcode() == ISD::UNDEF)
4064     return DAG.getUNDEF(ResultVT);
4065
4066   // Extract the relevant vectorWidth bits.  Generate an EXTRACT_SUBVECTOR
4067   unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
4068
4069   // This is the index of the first element of the vectorWidth-bit chunk
4070   // we want.
4071   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / vectorWidth)
4072                                * ElemsPerChunk);
4073
4074   // If the input is a buildvector just emit a smaller one.
4075   if (Vec.getOpcode() == ISD::BUILD_VECTOR)
4076     return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
4077                        makeArrayRef(Vec->op_begin() + NormalizedIdxVal,
4078                                     ElemsPerChunk));
4079
4080   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal, dl);
4081   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec, VecIdx);
4082 }
4083
4084 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
4085 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
4086 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
4087 /// instructions or a simple subregister reference. Idx is an index in the
4088 /// 128 bits we want.  It need not be aligned to a 128-bit boundary.  That makes
4089 /// lowering EXTRACT_VECTOR_ELT operations easier.
4090 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
4091                                    SelectionDAG &DAG, SDLoc dl) {
4092   assert((Vec.getValueType().is256BitVector() ||
4093           Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
4094   return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
4095 }
4096
4097 /// Generate a DAG to grab 256-bits from a 512-bit vector.
4098 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
4099                                    SelectionDAG &DAG, SDLoc dl) {
4100   assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
4101   return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
4102 }
4103
4104 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
4105                                unsigned IdxVal, SelectionDAG &DAG,
4106                                SDLoc dl, unsigned vectorWidth) {
4107   assert((vectorWidth == 128 || vectorWidth == 256) &&
4108          "Unsupported vector width");
4109   // Inserting UNDEF is Result
4110   if (Vec.getOpcode() == ISD::UNDEF)
4111     return Result;
4112   EVT VT = Vec.getValueType();
4113   EVT ElVT = VT.getVectorElementType();
4114   EVT ResultVT = Result.getValueType();
4115
4116   // Insert the relevant vectorWidth bits.
4117   unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
4118
4119   // This is the index of the first element of the vectorWidth-bit chunk
4120   // we want.
4121   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/vectorWidth)
4122                                * ElemsPerChunk);
4123
4124   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal, dl);
4125   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec, VecIdx);
4126 }
4127
4128 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
4129 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
4130 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
4131 /// simple superregister reference.  Idx is an index in the 128 bits
4132 /// we want.  It need not be aligned to a 128-bit boundary.  That makes
4133 /// lowering INSERT_VECTOR_ELT operations easier.
4134 static SDValue Insert128BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4135                                   SelectionDAG &DAG, SDLoc dl) {
4136   assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
4137
4138   // For insertion into the zero index (low half) of a 256-bit vector, it is
4139   // more efficient to generate a blend with immediate instead of an insert*128.
4140   // We are still creating an INSERT_SUBVECTOR below with an undef node to
4141   // extend the subvector to the size of the result vector. Make sure that
4142   // we are not recursing on that node by checking for undef here.
4143   if (IdxVal == 0 && Result.getValueType().is256BitVector() &&
4144       Result.getOpcode() != ISD::UNDEF) {
4145     EVT ResultVT = Result.getValueType();
4146     SDValue ZeroIndex = DAG.getIntPtrConstant(0, dl);
4147     SDValue Undef = DAG.getUNDEF(ResultVT);
4148     SDValue Vec256 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Undef,
4149                                  Vec, ZeroIndex);
4150
4151     // The blend instruction, and therefore its mask, depend on the data type.
4152     MVT ScalarType = ResultVT.getScalarType().getSimpleVT();
4153     if (ScalarType.isFloatingPoint()) {
4154       // Choose either vblendps (float) or vblendpd (double).
4155       unsigned ScalarSize = ScalarType.getSizeInBits();
4156       assert((ScalarSize == 64 || ScalarSize == 32) && "Unknown float type");
4157       unsigned MaskVal = (ScalarSize == 64) ? 0x03 : 0x0f;
4158       SDValue Mask = DAG.getConstant(MaskVal, dl, MVT::i8);
4159       return DAG.getNode(X86ISD::BLENDI, dl, ResultVT, Result, Vec256, Mask);
4160     }
4161
4162     const X86Subtarget &Subtarget =
4163     static_cast<const X86Subtarget &>(DAG.getSubtarget());
4164
4165     // AVX2 is needed for 256-bit integer blend support.
4166     // Integers must be cast to 32-bit because there is only vpblendd;
4167     // vpblendw can't be used for this because it has a handicapped mask.
4168
4169     // If we don't have AVX2, then cast to float. Using a wrong domain blend
4170     // is still more efficient than using the wrong domain vinsertf128 that
4171     // will be created by InsertSubVector().
4172     MVT CastVT = Subtarget.hasAVX2() ? MVT::v8i32 : MVT::v8f32;
4173
4174     SDValue Mask = DAG.getConstant(0x0f, dl, MVT::i8);
4175     Vec256 = DAG.getNode(ISD::BITCAST, dl, CastVT, Vec256);
4176     Vec256 = DAG.getNode(X86ISD::BLENDI, dl, CastVT, Result, Vec256, Mask);
4177     return DAG.getNode(ISD::BITCAST, dl, ResultVT, Vec256);
4178   }
4179
4180   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
4181 }
4182
4183 static SDValue Insert256BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4184                                   SelectionDAG &DAG, SDLoc dl) {
4185   assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
4186   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
4187 }
4188
4189 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
4190 /// instructions. This is used because creating CONCAT_VECTOR nodes of
4191 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
4192 /// large BUILD_VECTORS.
4193 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
4194                                    unsigned NumElems, SelectionDAG &DAG,
4195                                    SDLoc dl) {
4196   SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4197   return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
4198 }
4199
4200 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
4201                                    unsigned NumElems, SelectionDAG &DAG,
4202                                    SDLoc dl) {
4203   SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4204   return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
4205 }
4206
4207 /// getOnesVector - Returns a vector of specified type with all bits set.
4208 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4209 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4210 /// Then bitcast to their original type, ensuring they get CSE'd.
4211 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4212                              SDLoc dl) {
4213   assert(VT.isVector() && "Expected a vector type");
4214
4215   SDValue Cst = DAG.getConstant(~0U, dl, MVT::i32);
4216   SDValue Vec;
4217   if (VT.is256BitVector()) {
4218     if (HasInt256) { // AVX2
4219       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4220       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4221     } else { // AVX
4222       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4223       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4224     }
4225   } else if (VT.is128BitVector()) {
4226     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4227   } else
4228     llvm_unreachable("Unexpected vector type");
4229
4230   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4231 }
4232
4233 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4234 /// operation of specified width.
4235 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4236                        SDValue V2) {
4237   unsigned NumElems = VT.getVectorNumElements();
4238   SmallVector<int, 8> Mask;
4239   Mask.push_back(NumElems);
4240   for (unsigned i = 1; i != NumElems; ++i)
4241     Mask.push_back(i);
4242   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4243 }
4244
4245 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4246 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4247                           SDValue V2) {
4248   unsigned NumElems = VT.getVectorNumElements();
4249   SmallVector<int, 8> Mask;
4250   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4251     Mask.push_back(i);
4252     Mask.push_back(i + NumElems);
4253   }
4254   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4255 }
4256
4257 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4258 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4259                           SDValue V2) {
4260   unsigned NumElems = VT.getVectorNumElements();
4261   SmallVector<int, 8> Mask;
4262   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4263     Mask.push_back(i + Half);
4264     Mask.push_back(i + NumElems + Half);
4265   }
4266   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4267 }
4268
4269 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4270 /// vector of zero or undef vector.  This produces a shuffle where the low
4271 /// element of V2 is swizzled into the zero/undef vector, landing at element
4272 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
4273 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4274                                            bool IsZero,
4275                                            const X86Subtarget *Subtarget,
4276                                            SelectionDAG &DAG) {
4277   MVT VT = V2.getSimpleValueType();
4278   SDValue V1 = IsZero
4279     ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
4280   unsigned NumElems = VT.getVectorNumElements();
4281   SmallVector<int, 16> MaskVec;
4282   for (unsigned i = 0; i != NumElems; ++i)
4283     // If this is the insertion idx, put the low elt of V2 here.
4284     MaskVec.push_back(i == Idx ? NumElems : i);
4285   return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
4286 }
4287
4288 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
4289 /// target specific opcode. Returns true if the Mask could be calculated. Sets
4290 /// IsUnary to true if only uses one source. Note that this will set IsUnary for
4291 /// shuffles which use a single input multiple times, and in those cases it will
4292 /// adjust the mask to only have indices within that single input.
4293 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4294                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
4295   unsigned NumElems = VT.getVectorNumElements();
4296   SDValue ImmN;
4297
4298   IsUnary = false;
4299   bool IsFakeUnary = false;
4300   switch(N->getOpcode()) {
4301   case X86ISD::BLENDI:
4302     ImmN = N->getOperand(N->getNumOperands()-1);
4303     DecodeBLENDMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4304     break;
4305   case X86ISD::SHUFP:
4306     ImmN = N->getOperand(N->getNumOperands()-1);
4307     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4308     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4309     break;
4310   case X86ISD::UNPCKH:
4311     DecodeUNPCKHMask(VT, Mask);
4312     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4313     break;
4314   case X86ISD::UNPCKL:
4315     DecodeUNPCKLMask(VT, Mask);
4316     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4317     break;
4318   case X86ISD::MOVHLPS:
4319     DecodeMOVHLPSMask(NumElems, Mask);
4320     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4321     break;
4322   case X86ISD::MOVLHPS:
4323     DecodeMOVLHPSMask(NumElems, Mask);
4324     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4325     break;
4326   case X86ISD::PALIGNR:
4327     ImmN = N->getOperand(N->getNumOperands()-1);
4328     DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4329     break;
4330   case X86ISD::PSHUFD:
4331   case X86ISD::VPERMILPI:
4332     ImmN = N->getOperand(N->getNumOperands()-1);
4333     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4334     IsUnary = true;
4335     break;
4336   case X86ISD::PSHUFHW:
4337     ImmN = N->getOperand(N->getNumOperands()-1);
4338     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4339     IsUnary = true;
4340     break;
4341   case X86ISD::PSHUFLW:
4342     ImmN = N->getOperand(N->getNumOperands()-1);
4343     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4344     IsUnary = true;
4345     break;
4346   case X86ISD::PSHUFB: {
4347     IsUnary = true;
4348     SDValue MaskNode = N->getOperand(1);
4349     while (MaskNode->getOpcode() == ISD::BITCAST)
4350       MaskNode = MaskNode->getOperand(0);
4351
4352     if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
4353       // If we have a build-vector, then things are easy.
4354       EVT VT = MaskNode.getValueType();
4355       assert(VT.isVector() &&
4356              "Can't produce a non-vector with a build_vector!");
4357       if (!VT.isInteger())
4358         return false;
4359
4360       int NumBytesPerElement = VT.getVectorElementType().getSizeInBits() / 8;
4361
4362       SmallVector<uint64_t, 32> RawMask;
4363       for (int i = 0, e = MaskNode->getNumOperands(); i < e; ++i) {
4364         SDValue Op = MaskNode->getOperand(i);
4365         if (Op->getOpcode() == ISD::UNDEF) {
4366           RawMask.push_back((uint64_t)SM_SentinelUndef);
4367           continue;
4368         }
4369         auto *CN = dyn_cast<ConstantSDNode>(Op.getNode());
4370         if (!CN)
4371           return false;
4372         APInt MaskElement = CN->getAPIntValue();
4373
4374         // We now have to decode the element which could be any integer size and
4375         // extract each byte of it.
4376         for (int j = 0; j < NumBytesPerElement; ++j) {
4377           // Note that this is x86 and so always little endian: the low byte is
4378           // the first byte of the mask.
4379           RawMask.push_back(MaskElement.getLoBits(8).getZExtValue());
4380           MaskElement = MaskElement.lshr(8);
4381         }
4382       }
4383       DecodePSHUFBMask(RawMask, Mask);
4384       break;
4385     }
4386
4387     auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
4388     if (!MaskLoad)
4389       return false;
4390
4391     SDValue Ptr = MaskLoad->getBasePtr();
4392     if (Ptr->getOpcode() == X86ISD::Wrapper ||
4393         Ptr->getOpcode() == X86ISD::WrapperRIP)
4394       Ptr = Ptr->getOperand(0);
4395
4396     auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
4397     if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
4398       return false;
4399
4400     if (auto *C = dyn_cast<Constant>(MaskCP->getConstVal())) {
4401       DecodePSHUFBMask(C, Mask);
4402       if (Mask.empty())
4403         return false;
4404       break;
4405     }
4406
4407     return false;
4408   }
4409   case X86ISD::VPERMI:
4410     ImmN = N->getOperand(N->getNumOperands()-1);
4411     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4412     IsUnary = true;
4413     break;
4414   case X86ISD::MOVSS:
4415   case X86ISD::MOVSD:
4416     DecodeScalarMoveMask(VT, /* IsLoad */ false, Mask);
4417     break;
4418   case X86ISD::VPERM2X128:
4419     ImmN = N->getOperand(N->getNumOperands()-1);
4420     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4421     if (Mask.empty()) return false;
4422     break;
4423   case X86ISD::MOVSLDUP:
4424     DecodeMOVSLDUPMask(VT, Mask);
4425     IsUnary = true;
4426     break;
4427   case X86ISD::MOVSHDUP:
4428     DecodeMOVSHDUPMask(VT, Mask);
4429     IsUnary = true;
4430     break;
4431   case X86ISD::MOVDDUP:
4432     DecodeMOVDDUPMask(VT, Mask);
4433     IsUnary = true;
4434     break;
4435   case X86ISD::MOVLHPD:
4436   case X86ISD::MOVLPD:
4437   case X86ISD::MOVLPS:
4438     // Not yet implemented
4439     return false;
4440   default: llvm_unreachable("unknown target shuffle node");
4441   }
4442
4443   // If we have a fake unary shuffle, the shuffle mask is spread across two
4444   // inputs that are actually the same node. Re-map the mask to always point
4445   // into the first input.
4446   if (IsFakeUnary)
4447     for (int &M : Mask)
4448       if (M >= (int)Mask.size())
4449         M -= Mask.size();
4450
4451   return true;
4452 }
4453
4454 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4455 /// element of the result of the vector shuffle.
4456 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4457                                    unsigned Depth) {
4458   if (Depth == 6)
4459     return SDValue();  // Limit search depth.
4460
4461   SDValue V = SDValue(N, 0);
4462   EVT VT = V.getValueType();
4463   unsigned Opcode = V.getOpcode();
4464
4465   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4466   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4467     int Elt = SV->getMaskElt(Index);
4468
4469     if (Elt < 0)
4470       return DAG.getUNDEF(VT.getVectorElementType());
4471
4472     unsigned NumElems = VT.getVectorNumElements();
4473     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4474                                          : SV->getOperand(1);
4475     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4476   }
4477
4478   // Recurse into target specific vector shuffles to find scalars.
4479   if (isTargetShuffle(Opcode)) {
4480     MVT ShufVT = V.getSimpleValueType();
4481     unsigned NumElems = ShufVT.getVectorNumElements();
4482     SmallVector<int, 16> ShuffleMask;
4483     bool IsUnary;
4484
4485     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4486       return SDValue();
4487
4488     int Elt = ShuffleMask[Index];
4489     if (Elt < 0)
4490       return DAG.getUNDEF(ShufVT.getVectorElementType());
4491
4492     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4493                                          : N->getOperand(1);
4494     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4495                                Depth+1);
4496   }
4497
4498   // Actual nodes that may contain scalar elements
4499   if (Opcode == ISD::BITCAST) {
4500     V = V.getOperand(0);
4501     EVT SrcVT = V.getValueType();
4502     unsigned NumElems = VT.getVectorNumElements();
4503
4504     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4505       return SDValue();
4506   }
4507
4508   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4509     return (Index == 0) ? V.getOperand(0)
4510                         : DAG.getUNDEF(VT.getVectorElementType());
4511
4512   if (V.getOpcode() == ISD::BUILD_VECTOR)
4513     return V.getOperand(Index);
4514
4515   return SDValue();
4516 }
4517
4518 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4519 ///
4520 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4521                                        unsigned NumNonZero, unsigned NumZero,
4522                                        SelectionDAG &DAG,
4523                                        const X86Subtarget* Subtarget,
4524                                        const TargetLowering &TLI) {
4525   if (NumNonZero > 8)
4526     return SDValue();
4527
4528   SDLoc dl(Op);
4529   SDValue V;
4530   bool First = true;
4531
4532   // SSE4.1 - use PINSRB to insert each byte directly.
4533   if (Subtarget->hasSSE41()) {
4534     for (unsigned i = 0; i < 16; ++i) {
4535       bool isNonZero = (NonZeros & (1 << i)) != 0;
4536       if (isNonZero) {
4537         if (First) {
4538           if (NumZero)
4539             V = getZeroVector(MVT::v16i8, Subtarget, DAG, dl);
4540           else
4541             V = DAG.getUNDEF(MVT::v16i8);
4542           First = false;
4543         }
4544         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4545                         MVT::v16i8, V, Op.getOperand(i),
4546                         DAG.getIntPtrConstant(i, dl));
4547       }
4548     }
4549
4550     return V;
4551   }
4552
4553   // Pre-SSE4.1 - merge byte pairs and insert with PINSRW.
4554   for (unsigned i = 0; i < 16; ++i) {
4555     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4556     if (ThisIsNonZero && First) {
4557       if (NumZero)
4558         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4559       else
4560         V = DAG.getUNDEF(MVT::v8i16);
4561       First = false;
4562     }
4563
4564     if ((i & 1) != 0) {
4565       SDValue ThisElt, LastElt;
4566       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4567       if (LastIsNonZero) {
4568         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4569                               MVT::i16, Op.getOperand(i-1));
4570       }
4571       if (ThisIsNonZero) {
4572         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4573         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4574                               ThisElt, DAG.getConstant(8, dl, MVT::i8));
4575         if (LastIsNonZero)
4576           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4577       } else
4578         ThisElt = LastElt;
4579
4580       if (ThisElt.getNode())
4581         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4582                         DAG.getIntPtrConstant(i/2, dl));
4583     }
4584   }
4585
4586   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4587 }
4588
4589 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4590 ///
4591 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4592                                      unsigned NumNonZero, unsigned NumZero,
4593                                      SelectionDAG &DAG,
4594                                      const X86Subtarget* Subtarget,
4595                                      const TargetLowering &TLI) {
4596   if (NumNonZero > 4)
4597     return SDValue();
4598
4599   SDLoc dl(Op);
4600   SDValue V;
4601   bool First = true;
4602   for (unsigned i = 0; i < 8; ++i) {
4603     bool isNonZero = (NonZeros & (1 << i)) != 0;
4604     if (isNonZero) {
4605       if (First) {
4606         if (NumZero)
4607           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4608         else
4609           V = DAG.getUNDEF(MVT::v8i16);
4610         First = false;
4611       }
4612       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4613                       MVT::v8i16, V, Op.getOperand(i),
4614                       DAG.getIntPtrConstant(i, dl));
4615     }
4616   }
4617
4618   return V;
4619 }
4620
4621 /// LowerBuildVectorv4x32 - Custom lower build_vector of v4i32 or v4f32.
4622 static SDValue LowerBuildVectorv4x32(SDValue Op, SelectionDAG &DAG,
4623                                      const X86Subtarget *Subtarget,
4624                                      const TargetLowering &TLI) {
4625   // Find all zeroable elements.
4626   std::bitset<4> Zeroable;
4627   for (int i=0; i < 4; ++i) {
4628     SDValue Elt = Op->getOperand(i);
4629     Zeroable[i] = (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt));
4630   }
4631   assert(Zeroable.size() - Zeroable.count() > 1 &&
4632          "We expect at least two non-zero elements!");
4633
4634   // We only know how to deal with build_vector nodes where elements are either
4635   // zeroable or extract_vector_elt with constant index.
4636   SDValue FirstNonZero;
4637   unsigned FirstNonZeroIdx;
4638   for (unsigned i=0; i < 4; ++i) {
4639     if (Zeroable[i])
4640       continue;
4641     SDValue Elt = Op->getOperand(i);
4642     if (Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4643         !isa<ConstantSDNode>(Elt.getOperand(1)))
4644       return SDValue();
4645     // Make sure that this node is extracting from a 128-bit vector.
4646     MVT VT = Elt.getOperand(0).getSimpleValueType();
4647     if (!VT.is128BitVector())
4648       return SDValue();
4649     if (!FirstNonZero.getNode()) {
4650       FirstNonZero = Elt;
4651       FirstNonZeroIdx = i;
4652     }
4653   }
4654
4655   assert(FirstNonZero.getNode() && "Unexpected build vector of all zeros!");
4656   SDValue V1 = FirstNonZero.getOperand(0);
4657   MVT VT = V1.getSimpleValueType();
4658
4659   // See if this build_vector can be lowered as a blend with zero.
4660   SDValue Elt;
4661   unsigned EltMaskIdx, EltIdx;
4662   int Mask[4];
4663   for (EltIdx = 0; EltIdx < 4; ++EltIdx) {
4664     if (Zeroable[EltIdx]) {
4665       // The zero vector will be on the right hand side.
4666       Mask[EltIdx] = EltIdx+4;
4667       continue;
4668     }
4669
4670     Elt = Op->getOperand(EltIdx);
4671     // By construction, Elt is a EXTRACT_VECTOR_ELT with constant index.
4672     EltMaskIdx = cast<ConstantSDNode>(Elt.getOperand(1))->getZExtValue();
4673     if (Elt.getOperand(0) != V1 || EltMaskIdx != EltIdx)
4674       break;
4675     Mask[EltIdx] = EltIdx;
4676   }
4677
4678   if (EltIdx == 4) {
4679     // Let the shuffle legalizer deal with blend operations.
4680     SDValue VZero = getZeroVector(VT, Subtarget, DAG, SDLoc(Op));
4681     if (V1.getSimpleValueType() != VT)
4682       V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), VT, V1);
4683     return DAG.getVectorShuffle(VT, SDLoc(V1), V1, VZero, &Mask[0]);
4684   }
4685
4686   // See if we can lower this build_vector to a INSERTPS.
4687   if (!Subtarget->hasSSE41())
4688     return SDValue();
4689
4690   SDValue V2 = Elt.getOperand(0);
4691   if (Elt == FirstNonZero && EltIdx == FirstNonZeroIdx)
4692     V1 = SDValue();
4693
4694   bool CanFold = true;
4695   for (unsigned i = EltIdx + 1; i < 4 && CanFold; ++i) {
4696     if (Zeroable[i])
4697       continue;
4698
4699     SDValue Current = Op->getOperand(i);
4700     SDValue SrcVector = Current->getOperand(0);
4701     if (!V1.getNode())
4702       V1 = SrcVector;
4703     CanFold = SrcVector == V1 &&
4704       cast<ConstantSDNode>(Current.getOperand(1))->getZExtValue() == i;
4705   }
4706
4707   if (!CanFold)
4708     return SDValue();
4709
4710   assert(V1.getNode() && "Expected at least two non-zero elements!");
4711   if (V1.getSimpleValueType() != MVT::v4f32)
4712     V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), MVT::v4f32, V1);
4713   if (V2.getSimpleValueType() != MVT::v4f32)
4714     V2 = DAG.getNode(ISD::BITCAST, SDLoc(V2), MVT::v4f32, V2);
4715
4716   // Ok, we can emit an INSERTPS instruction.
4717   unsigned ZMask = Zeroable.to_ulong();
4718
4719   unsigned InsertPSMask = EltMaskIdx << 6 | EltIdx << 4 | ZMask;
4720   assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
4721   SDLoc DL(Op);
4722   SDValue Result = DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
4723                                DAG.getIntPtrConstant(InsertPSMask, DL));
4724   return DAG.getNode(ISD::BITCAST, DL, VT, Result);
4725 }
4726
4727 /// Return a vector logical shift node.
4728 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4729                          unsigned NumBits, SelectionDAG &DAG,
4730                          const TargetLowering &TLI, SDLoc dl) {
4731   assert(VT.is128BitVector() && "Unknown type for VShift");
4732   MVT ShVT = MVT::v2i64;
4733   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
4734   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4735   MVT ScalarShiftTy = TLI.getScalarShiftAmountTy(SrcOp.getValueType());
4736   assert(NumBits % 8 == 0 && "Only support byte sized shifts");
4737   SDValue ShiftVal = DAG.getConstant(NumBits/8, dl, ScalarShiftTy);
4738   return DAG.getNode(ISD::BITCAST, dl, VT,
4739                      DAG.getNode(Opc, dl, ShVT, SrcOp, ShiftVal));
4740 }
4741
4742 static SDValue
4743 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
4744
4745   // Check if the scalar load can be widened into a vector load. And if
4746   // the address is "base + cst" see if the cst can be "absorbed" into
4747   // the shuffle mask.
4748   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4749     SDValue Ptr = LD->getBasePtr();
4750     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4751       return SDValue();
4752     EVT PVT = LD->getValueType(0);
4753     if (PVT != MVT::i32 && PVT != MVT::f32)
4754       return SDValue();
4755
4756     int FI = -1;
4757     int64_t Offset = 0;
4758     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4759       FI = FINode->getIndex();
4760       Offset = 0;
4761     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4762                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4763       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4764       Offset = Ptr.getConstantOperandVal(1);
4765       Ptr = Ptr.getOperand(0);
4766     } else {
4767       return SDValue();
4768     }
4769
4770     // FIXME: 256-bit vector instructions don't require a strict alignment,
4771     // improve this code to support it better.
4772     unsigned RequiredAlign = VT.getSizeInBits()/8;
4773     SDValue Chain = LD->getChain();
4774     // Make sure the stack object alignment is at least 16 or 32.
4775     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4776     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
4777       if (MFI->isFixedObjectIndex(FI)) {
4778         // Can't change the alignment. FIXME: It's possible to compute
4779         // the exact stack offset and reference FI + adjust offset instead.
4780         // If someone *really* cares about this. That's the way to implement it.
4781         return SDValue();
4782       } else {
4783         MFI->setObjectAlignment(FI, RequiredAlign);
4784       }
4785     }
4786
4787     // (Offset % 16 or 32) must be multiple of 4. Then address is then
4788     // Ptr + (Offset & ~15).
4789     if (Offset < 0)
4790       return SDValue();
4791     if ((Offset % RequiredAlign) & 3)
4792       return SDValue();
4793     int64_t StartOffset = Offset & ~(RequiredAlign-1);
4794     if (StartOffset) {
4795       SDLoc DL(Ptr);
4796       Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
4797                         DAG.getConstant(StartOffset, DL, Ptr.getValueType()));
4798     }
4799
4800     int EltNo = (Offset - StartOffset) >> 2;
4801     unsigned NumElems = VT.getVectorNumElements();
4802
4803     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
4804     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
4805                              LD->getPointerInfo().getWithOffset(StartOffset),
4806                              false, false, false, 0);
4807
4808     SmallVector<int, 8> Mask(NumElems, EltNo);
4809
4810     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
4811   }
4812
4813   return SDValue();
4814 }
4815
4816 /// Given the initializing elements 'Elts' of a vector of type 'VT', see if the
4817 /// elements can be replaced by a single large load which has the same value as
4818 /// a build_vector or insert_subvector whose loaded operands are 'Elts'.
4819 ///
4820 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4821 ///
4822 /// FIXME: we'd also like to handle the case where the last elements are zero
4823 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4824 /// There's even a handy isZeroNode for that purpose.
4825 static SDValue EltsFromConsecutiveLoads(EVT VT, ArrayRef<SDValue> Elts,
4826                                         SDLoc &DL, SelectionDAG &DAG,
4827                                         bool isAfterLegalize) {
4828   unsigned NumElems = Elts.size();
4829
4830   LoadSDNode *LDBase = nullptr;
4831   unsigned LastLoadedElt = -1U;
4832
4833   // For each element in the initializer, see if we've found a load or an undef.
4834   // If we don't find an initial load element, or later load elements are
4835   // non-consecutive, bail out.
4836   for (unsigned i = 0; i < NumElems; ++i) {
4837     SDValue Elt = Elts[i];
4838     // Look through a bitcast.
4839     if (Elt.getNode() && Elt.getOpcode() == ISD::BITCAST)
4840       Elt = Elt.getOperand(0);
4841     if (!Elt.getNode() ||
4842         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
4843       return SDValue();
4844     if (!LDBase) {
4845       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
4846         return SDValue();
4847       LDBase = cast<LoadSDNode>(Elt.getNode());
4848       LastLoadedElt = i;
4849       continue;
4850     }
4851     if (Elt.getOpcode() == ISD::UNDEF)
4852       continue;
4853
4854     LoadSDNode *LD = cast<LoadSDNode>(Elt);
4855     EVT LdVT = Elt.getValueType();
4856     // Each loaded element must be the correct fractional portion of the
4857     // requested vector load.
4858     if (LdVT.getSizeInBits() != VT.getSizeInBits() / NumElems)
4859       return SDValue();
4860     if (!DAG.isConsecutiveLoad(LD, LDBase, LdVT.getSizeInBits() / 8, i))
4861       return SDValue();
4862     LastLoadedElt = i;
4863   }
4864
4865   // If we have found an entire vector of loads and undefs, then return a large
4866   // load of the entire vector width starting at the base pointer.  If we found
4867   // consecutive loads for the low half, generate a vzext_load node.
4868   if (LastLoadedElt == NumElems - 1) {
4869     assert(LDBase && "Did not find base load for merging consecutive loads");
4870     EVT EltVT = LDBase->getValueType(0);
4871     // Ensure that the input vector size for the merged loads matches the
4872     // cumulative size of the input elements.
4873     if (VT.getSizeInBits() != EltVT.getSizeInBits() * NumElems)
4874       return SDValue();
4875
4876     if (isAfterLegalize &&
4877         !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
4878       return SDValue();
4879
4880     SDValue NewLd = SDValue();
4881
4882     NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4883                         LDBase->getPointerInfo(), LDBase->isVolatile(),
4884                         LDBase->isNonTemporal(), LDBase->isInvariant(),
4885                         LDBase->getAlignment());
4886
4887     if (LDBase->hasAnyUseOfValue(1)) {
4888       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
4889                                      SDValue(LDBase, 1),
4890                                      SDValue(NewLd.getNode(), 1));
4891       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
4892       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
4893                              SDValue(NewLd.getNode(), 1));
4894     }
4895
4896     return NewLd;
4897   }
4898
4899   //TODO: The code below fires only for for loading the low v2i32 / v2f32
4900   //of a v4i32 / v4f32. It's probably worth generalizing.
4901   EVT EltVT = VT.getVectorElementType();
4902   if (NumElems == 4 && LastLoadedElt == 1 && (EltVT.getSizeInBits() == 32) &&
4903       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
4904     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
4905     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
4906     SDValue ResNode =
4907         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
4908                                 LDBase->getPointerInfo(),
4909                                 LDBase->getAlignment(),
4910                                 false/*isVolatile*/, true/*ReadMem*/,
4911                                 false/*WriteMem*/);
4912
4913     // Make sure the newly-created LOAD is in the same position as LDBase in
4914     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
4915     // update uses of LDBase's output chain to use the TokenFactor.
4916     if (LDBase->hasAnyUseOfValue(1)) {
4917       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
4918                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
4919       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
4920       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
4921                              SDValue(ResNode.getNode(), 1));
4922     }
4923
4924     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
4925   }
4926   return SDValue();
4927 }
4928
4929 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
4930 /// to generate a splat value for the following cases:
4931 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
4932 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
4933 /// a scalar load, or a constant.
4934 /// The VBROADCAST node is returned when a pattern is found,
4935 /// or SDValue() otherwise.
4936 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
4937                                     SelectionDAG &DAG) {
4938   // VBROADCAST requires AVX.
4939   // TODO: Splats could be generated for non-AVX CPUs using SSE
4940   // instructions, but there's less potential gain for only 128-bit vectors.
4941   if (!Subtarget->hasAVX())
4942     return SDValue();
4943
4944   MVT VT = Op.getSimpleValueType();
4945   SDLoc dl(Op);
4946
4947   assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
4948          "Unsupported vector type for broadcast.");
4949
4950   SDValue Ld;
4951   bool ConstSplatVal;
4952
4953   switch (Op.getOpcode()) {
4954     default:
4955       // Unknown pattern found.
4956       return SDValue();
4957
4958     case ISD::BUILD_VECTOR: {
4959       auto *BVOp = cast<BuildVectorSDNode>(Op.getNode());
4960       BitVector UndefElements;
4961       SDValue Splat = BVOp->getSplatValue(&UndefElements);
4962
4963       // We need a splat of a single value to use broadcast, and it doesn't
4964       // make any sense if the value is only in one element of the vector.
4965       if (!Splat || (VT.getVectorNumElements() - UndefElements.count()) <= 1)
4966         return SDValue();
4967
4968       Ld = Splat;
4969       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
4970                        Ld.getOpcode() == ISD::ConstantFP);
4971
4972       // Make sure that all of the users of a non-constant load are from the
4973       // BUILD_VECTOR node.
4974       if (!ConstSplatVal && !BVOp->isOnlyUserOf(Ld.getNode()))
4975         return SDValue();
4976       break;
4977     }
4978
4979     case ISD::VECTOR_SHUFFLE: {
4980       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
4981
4982       // Shuffles must have a splat mask where the first element is
4983       // broadcasted.
4984       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
4985         return SDValue();
4986
4987       SDValue Sc = Op.getOperand(0);
4988       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
4989           Sc.getOpcode() != ISD::BUILD_VECTOR) {
4990
4991         if (!Subtarget->hasInt256())
4992           return SDValue();
4993
4994         // Use the register form of the broadcast instruction available on AVX2.
4995         if (VT.getSizeInBits() >= 256)
4996           Sc = Extract128BitVector(Sc, 0, DAG, dl);
4997         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
4998       }
4999
5000       Ld = Sc.getOperand(0);
5001       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5002                        Ld.getOpcode() == ISD::ConstantFP);
5003
5004       // The scalar_to_vector node and the suspected
5005       // load node must have exactly one user.
5006       // Constants may have multiple users.
5007
5008       // AVX-512 has register version of the broadcast
5009       bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5010         Ld.getValueType().getSizeInBits() >= 32;
5011       if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5012           !hasRegVer))
5013         return SDValue();
5014       break;
5015     }
5016   }
5017
5018   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5019   bool IsGE256 = (VT.getSizeInBits() >= 256);
5020
5021   // When optimizing for size, generate up to 5 extra bytes for a broadcast
5022   // instruction to save 8 or more bytes of constant pool data.
5023   // TODO: If multiple splats are generated to load the same constant,
5024   // it may be detrimental to overall size. There needs to be a way to detect
5025   // that condition to know if this is truly a size win.
5026   const Function *F = DAG.getMachineFunction().getFunction();
5027   bool OptForSize = F->hasFnAttribute(Attribute::OptimizeForSize);
5028
5029   // Handle broadcasting a single constant scalar from the constant pool
5030   // into a vector.
5031   // On Sandybridge (no AVX2), it is still better to load a constant vector
5032   // from the constant pool and not to broadcast it from a scalar.
5033   // But override that restriction when optimizing for size.
5034   // TODO: Check if splatting is recommended for other AVX-capable CPUs.
5035   if (ConstSplatVal && (Subtarget->hasAVX2() || OptForSize)) {
5036     EVT CVT = Ld.getValueType();
5037     assert(!CVT.isVector() && "Must not broadcast a vector type");
5038
5039     // Splat f32, i32, v4f64, v4i64 in all cases with AVX2.
5040     // For size optimization, also splat v2f64 and v2i64, and for size opt
5041     // with AVX2, also splat i8 and i16.
5042     // With pattern matching, the VBROADCAST node may become a VMOVDDUP.
5043     if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5044         (OptForSize && (ScalarSize == 64 || Subtarget->hasAVX2()))) {
5045       const Constant *C = nullptr;
5046       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5047         C = CI->getConstantIntValue();
5048       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5049         C = CF->getConstantFPValue();
5050
5051       assert(C && "Invalid constant type");
5052
5053       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5054       SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
5055       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5056       Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5057                        MachinePointerInfo::getConstantPool(),
5058                        false, false, false, Alignment);
5059
5060       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5061     }
5062   }
5063
5064   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5065
5066   // Handle AVX2 in-register broadcasts.
5067   if (!IsLoad && Subtarget->hasInt256() &&
5068       (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5069     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5070
5071   // The scalar source must be a normal load.
5072   if (!IsLoad)
5073     return SDValue();
5074
5075   if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5076       (Subtarget->hasVLX() && ScalarSize == 64))
5077     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5078
5079   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5080   // double since there is no vbroadcastsd xmm
5081   if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5082     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5083       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5084   }
5085
5086   // Unsupported broadcast.
5087   return SDValue();
5088 }
5089
5090 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
5091 /// underlying vector and index.
5092 ///
5093 /// Modifies \p ExtractedFromVec to the real vector and returns the real
5094 /// index.
5095 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
5096                                          SDValue ExtIdx) {
5097   int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5098   if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
5099     return Idx;
5100
5101   // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
5102   // lowered this:
5103   //   (extract_vector_elt (v8f32 %vreg1), Constant<6>)
5104   // to:
5105   //   (extract_vector_elt (vector_shuffle<2,u,u,u>
5106   //                           (extract_subvector (v8f32 %vreg0), Constant<4>),
5107   //                           undef)
5108   //                       Constant<0>)
5109   // In this case the vector is the extract_subvector expression and the index
5110   // is 2, as specified by the shuffle.
5111   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
5112   SDValue ShuffleVec = SVOp->getOperand(0);
5113   MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
5114   assert(ShuffleVecVT.getVectorElementType() ==
5115          ExtractedFromVec.getSimpleValueType().getVectorElementType());
5116
5117   int ShuffleIdx = SVOp->getMaskElt(Idx);
5118   if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
5119     ExtractedFromVec = ShuffleVec;
5120     return ShuffleIdx;
5121   }
5122   return Idx;
5123 }
5124
5125 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5126   MVT VT = Op.getSimpleValueType();
5127
5128   // Skip if insert_vec_elt is not supported.
5129   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5130   if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5131     return SDValue();
5132
5133   SDLoc DL(Op);
5134   unsigned NumElems = Op.getNumOperands();
5135
5136   SDValue VecIn1;
5137   SDValue VecIn2;
5138   SmallVector<unsigned, 4> InsertIndices;
5139   SmallVector<int, 8> Mask(NumElems, -1);
5140
5141   for (unsigned i = 0; i != NumElems; ++i) {
5142     unsigned Opc = Op.getOperand(i).getOpcode();
5143
5144     if (Opc == ISD::UNDEF)
5145       continue;
5146
5147     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5148       // Quit if more than 1 elements need inserting.
5149       if (InsertIndices.size() > 1)
5150         return SDValue();
5151
5152       InsertIndices.push_back(i);
5153       continue;
5154     }
5155
5156     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5157     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5158     // Quit if non-constant index.
5159     if (!isa<ConstantSDNode>(ExtIdx))
5160       return SDValue();
5161     int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5162
5163     // Quit if extracted from vector of different type.
5164     if (ExtractedFromVec.getValueType() != VT)
5165       return SDValue();
5166
5167     if (!VecIn1.getNode())
5168       VecIn1 = ExtractedFromVec;
5169     else if (VecIn1 != ExtractedFromVec) {
5170       if (!VecIn2.getNode())
5171         VecIn2 = ExtractedFromVec;
5172       else if (VecIn2 != ExtractedFromVec)
5173         // Quit if more than 2 vectors to shuffle
5174         return SDValue();
5175     }
5176
5177     if (ExtractedFromVec == VecIn1)
5178       Mask[i] = Idx;
5179     else if (ExtractedFromVec == VecIn2)
5180       Mask[i] = Idx + NumElems;
5181   }
5182
5183   if (!VecIn1.getNode())
5184     return SDValue();
5185
5186   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5187   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5188   for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5189     unsigned Idx = InsertIndices[i];
5190     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5191                      DAG.getIntPtrConstant(Idx, DL));
5192   }
5193
5194   return NV;
5195 }
5196
5197 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5198 SDValue
5199 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5200
5201   MVT VT = Op.getSimpleValueType();
5202   assert((VT.getVectorElementType() == MVT::i1) && (VT.getSizeInBits() <= 16) &&
5203          "Unexpected type in LowerBUILD_VECTORvXi1!");
5204
5205   SDLoc dl(Op);
5206   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5207     SDValue Cst = DAG.getTargetConstant(0, dl, MVT::i1);
5208     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5209     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5210   }
5211
5212   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5213     SDValue Cst = DAG.getTargetConstant(1, dl, MVT::i1);
5214     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5215     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5216   }
5217
5218   bool AllContants = true;
5219   uint64_t Immediate = 0;
5220   int NonConstIdx = -1;
5221   bool IsSplat = true;
5222   unsigned NumNonConsts = 0;
5223   unsigned NumConsts = 0;
5224   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5225     SDValue In = Op.getOperand(idx);
5226     if (In.getOpcode() == ISD::UNDEF)
5227       continue;
5228     if (!isa<ConstantSDNode>(In)) {
5229       AllContants = false;
5230       NonConstIdx = idx;
5231       NumNonConsts++;
5232     } else {
5233       NumConsts++;
5234       if (cast<ConstantSDNode>(In)->getZExtValue())
5235       Immediate |= (1ULL << idx);
5236     }
5237     if (In != Op.getOperand(0))
5238       IsSplat = false;
5239   }
5240
5241   if (AllContants) {
5242     SDValue FullMask = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1,
5243       DAG.getConstant(Immediate, dl, MVT::i16));
5244     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, FullMask,
5245                        DAG.getIntPtrConstant(0, dl));
5246   }
5247
5248   if (NumNonConsts == 1 && NonConstIdx != 0) {
5249     SDValue DstVec;
5250     if (NumConsts) {
5251       SDValue VecAsImm = DAG.getConstant(Immediate, dl,
5252                                          MVT::getIntegerVT(VT.getSizeInBits()));
5253       DstVec = DAG.getNode(ISD::BITCAST, dl, VT, VecAsImm);
5254     }
5255     else
5256       DstVec = DAG.getUNDEF(VT);
5257     return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5258                        Op.getOperand(NonConstIdx),
5259                        DAG.getIntPtrConstant(NonConstIdx, dl));
5260   }
5261   if (!IsSplat && (NonConstIdx != 0))
5262     llvm_unreachable("Unsupported BUILD_VECTOR operation");
5263   MVT SelectVT = (VT == MVT::v16i1)? MVT::i16 : MVT::i8;
5264   SDValue Select;
5265   if (IsSplat)
5266     Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
5267                           DAG.getConstant(-1, dl, SelectVT),
5268                           DAG.getConstant(0, dl, SelectVT));
5269   else
5270     Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
5271                          DAG.getConstant((Immediate | 1), dl, SelectVT),
5272                          DAG.getConstant(Immediate, dl, SelectVT));
5273   return DAG.getNode(ISD::BITCAST, dl, VT, Select);
5274 }
5275
5276 /// \brief Return true if \p N implements a horizontal binop and return the
5277 /// operands for the horizontal binop into V0 and V1.
5278 ///
5279 /// This is a helper function of LowerToHorizontalOp().
5280 /// This function checks that the build_vector \p N in input implements a
5281 /// horizontal operation. Parameter \p Opcode defines the kind of horizontal
5282 /// operation to match.
5283 /// For example, if \p Opcode is equal to ISD::ADD, then this function
5284 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
5285 /// is equal to ISD::SUB, then this function checks if this is a horizontal
5286 /// arithmetic sub.
5287 ///
5288 /// This function only analyzes elements of \p N whose indices are
5289 /// in range [BaseIdx, LastIdx).
5290 static bool isHorizontalBinOp(const BuildVectorSDNode *N, unsigned Opcode,
5291                               SelectionDAG &DAG,
5292                               unsigned BaseIdx, unsigned LastIdx,
5293                               SDValue &V0, SDValue &V1) {
5294   EVT VT = N->getValueType(0);
5295
5296   assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
5297   assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
5298          "Invalid Vector in input!");
5299
5300   bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
5301   bool CanFold = true;
5302   unsigned ExpectedVExtractIdx = BaseIdx;
5303   unsigned NumElts = LastIdx - BaseIdx;
5304   V0 = DAG.getUNDEF(VT);
5305   V1 = DAG.getUNDEF(VT);
5306
5307   // Check if N implements a horizontal binop.
5308   for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
5309     SDValue Op = N->getOperand(i + BaseIdx);
5310
5311     // Skip UNDEFs.
5312     if (Op->getOpcode() == ISD::UNDEF) {
5313       // Update the expected vector extract index.
5314       if (i * 2 == NumElts)
5315         ExpectedVExtractIdx = BaseIdx;
5316       ExpectedVExtractIdx += 2;
5317       continue;
5318     }
5319
5320     CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
5321
5322     if (!CanFold)
5323       break;
5324
5325     SDValue Op0 = Op.getOperand(0);
5326     SDValue Op1 = Op.getOperand(1);
5327
5328     // Try to match the following pattern:
5329     // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
5330     CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5331         Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5332         Op0.getOperand(0) == Op1.getOperand(0) &&
5333         isa<ConstantSDNode>(Op0.getOperand(1)) &&
5334         isa<ConstantSDNode>(Op1.getOperand(1)));
5335     if (!CanFold)
5336       break;
5337
5338     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5339     unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
5340
5341     if (i * 2 < NumElts) {
5342       if (V0.getOpcode() == ISD::UNDEF) {
5343         V0 = Op0.getOperand(0);
5344         if (V0.getValueType() != VT)
5345           return false;
5346       }
5347     } else {
5348       if (V1.getOpcode() == ISD::UNDEF) {
5349         V1 = Op0.getOperand(0);
5350         if (V1.getValueType() != VT)
5351           return false;
5352       }
5353       if (i * 2 == NumElts)
5354         ExpectedVExtractIdx = BaseIdx;
5355     }
5356
5357     SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
5358     if (I0 == ExpectedVExtractIdx)
5359       CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
5360     else if (IsCommutable && I1 == ExpectedVExtractIdx) {
5361       // Try to match the following dag sequence:
5362       // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
5363       CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
5364     } else
5365       CanFold = false;
5366
5367     ExpectedVExtractIdx += 2;
5368   }
5369
5370   return CanFold;
5371 }
5372
5373 /// \brief Emit a sequence of two 128-bit horizontal add/sub followed by
5374 /// a concat_vector.
5375 ///
5376 /// This is a helper function of LowerToHorizontalOp().
5377 /// This function expects two 256-bit vectors called V0 and V1.
5378 /// At first, each vector is split into two separate 128-bit vectors.
5379 /// Then, the resulting 128-bit vectors are used to implement two
5380 /// horizontal binary operations.
5381 ///
5382 /// The kind of horizontal binary operation is defined by \p X86Opcode.
5383 ///
5384 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
5385 /// the two new horizontal binop.
5386 /// When Mode is set, the first horizontal binop dag node would take as input
5387 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
5388 /// horizontal binop dag node would take as input the lower 128-bit of V1
5389 /// and the upper 128-bit of V1.
5390 ///   Example:
5391 ///     HADD V0_LO, V0_HI
5392 ///     HADD V1_LO, V1_HI
5393 ///
5394 /// Otherwise, the first horizontal binop dag node takes as input the lower
5395 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
5396 /// dag node takes the the upper 128-bit of V0 and the upper 128-bit of V1.
5397 ///   Example:
5398 ///     HADD V0_LO, V1_LO
5399 ///     HADD V0_HI, V1_HI
5400 ///
5401 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
5402 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
5403 /// the upper 128-bits of the result.
5404 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
5405                                      SDLoc DL, SelectionDAG &DAG,
5406                                      unsigned X86Opcode, bool Mode,
5407                                      bool isUndefLO, bool isUndefHI) {
5408   EVT VT = V0.getValueType();
5409   assert(VT.is256BitVector() && VT == V1.getValueType() &&
5410          "Invalid nodes in input!");
5411
5412   unsigned NumElts = VT.getVectorNumElements();
5413   SDValue V0_LO = Extract128BitVector(V0, 0, DAG, DL);
5414   SDValue V0_HI = Extract128BitVector(V0, NumElts/2, DAG, DL);
5415   SDValue V1_LO = Extract128BitVector(V1, 0, DAG, DL);
5416   SDValue V1_HI = Extract128BitVector(V1, NumElts/2, DAG, DL);
5417   EVT NewVT = V0_LO.getValueType();
5418
5419   SDValue LO = DAG.getUNDEF(NewVT);
5420   SDValue HI = DAG.getUNDEF(NewVT);
5421
5422   if (Mode) {
5423     // Don't emit a horizontal binop if the result is expected to be UNDEF.
5424     if (!isUndefLO && V0->getOpcode() != ISD::UNDEF)
5425       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
5426     if (!isUndefHI && V1->getOpcode() != ISD::UNDEF)
5427       HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
5428   } else {
5429     // Don't emit a horizontal binop if the result is expected to be UNDEF.
5430     if (!isUndefLO && (V0_LO->getOpcode() != ISD::UNDEF ||
5431                        V1_LO->getOpcode() != ISD::UNDEF))
5432       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
5433
5434     if (!isUndefHI && (V0_HI->getOpcode() != ISD::UNDEF ||
5435                        V1_HI->getOpcode() != ISD::UNDEF))
5436       HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
5437   }
5438
5439   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
5440 }
5441
5442 /// Try to fold a build_vector that performs an 'addsub' to an X86ISD::ADDSUB
5443 /// node.
5444 static SDValue LowerToAddSub(const BuildVectorSDNode *BV,
5445                              const X86Subtarget *Subtarget, SelectionDAG &DAG) {
5446   EVT VT = BV->getValueType(0);
5447   if ((!Subtarget->hasSSE3() || (VT != MVT::v4f32 && VT != MVT::v2f64)) &&
5448       (!Subtarget->hasAVX() || (VT != MVT::v8f32 && VT != MVT::v4f64)))
5449     return SDValue();
5450
5451   SDLoc DL(BV);
5452   unsigned NumElts = VT.getVectorNumElements();
5453   SDValue InVec0 = DAG.getUNDEF(VT);
5454   SDValue InVec1 = DAG.getUNDEF(VT);
5455
5456   assert((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v4f32 ||
5457           VT == MVT::v2f64) && "build_vector with an invalid type found!");
5458
5459   // Odd-numbered elements in the input build vector are obtained from
5460   // adding two integer/float elements.
5461   // Even-numbered elements in the input build vector are obtained from
5462   // subtracting two integer/float elements.
5463   unsigned ExpectedOpcode = ISD::FSUB;
5464   unsigned NextExpectedOpcode = ISD::FADD;
5465   bool AddFound = false;
5466   bool SubFound = false;
5467
5468   for (unsigned i = 0, e = NumElts; i != e; ++i) {
5469     SDValue Op = BV->getOperand(i);
5470
5471     // Skip 'undef' values.
5472     unsigned Opcode = Op.getOpcode();
5473     if (Opcode == ISD::UNDEF) {
5474       std::swap(ExpectedOpcode, NextExpectedOpcode);
5475       continue;
5476     }
5477
5478     // Early exit if we found an unexpected opcode.
5479     if (Opcode != ExpectedOpcode)
5480       return SDValue();
5481
5482     SDValue Op0 = Op.getOperand(0);
5483     SDValue Op1 = Op.getOperand(1);
5484
5485     // Try to match the following pattern:
5486     // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
5487     // Early exit if we cannot match that sequence.
5488     if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5489         Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5490         !isa<ConstantSDNode>(Op0.getOperand(1)) ||
5491         !isa<ConstantSDNode>(Op1.getOperand(1)) ||
5492         Op0.getOperand(1) != Op1.getOperand(1))
5493       return SDValue();
5494
5495     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5496     if (I0 != i)
5497       return SDValue();
5498
5499     // We found a valid add/sub node. Update the information accordingly.
5500     if (i & 1)
5501       AddFound = true;
5502     else
5503       SubFound = true;
5504
5505     // Update InVec0 and InVec1.
5506     if (InVec0.getOpcode() == ISD::UNDEF) {
5507       InVec0 = Op0.getOperand(0);
5508       if (InVec0.getValueType() != VT)
5509         return SDValue();
5510     }
5511     if (InVec1.getOpcode() == ISD::UNDEF) {
5512       InVec1 = Op1.getOperand(0);
5513       if (InVec1.getValueType() != VT)
5514         return SDValue();
5515     }
5516
5517     // Make sure that operands in input to each add/sub node always
5518     // come from a same pair of vectors.
5519     if (InVec0 != Op0.getOperand(0)) {
5520       if (ExpectedOpcode == ISD::FSUB)
5521         return SDValue();
5522
5523       // FADD is commutable. Try to commute the operands
5524       // and then test again.
5525       std::swap(Op0, Op1);
5526       if (InVec0 != Op0.getOperand(0))
5527         return SDValue();
5528     }
5529
5530     if (InVec1 != Op1.getOperand(0))
5531       return SDValue();
5532
5533     // Update the pair of expected opcodes.
5534     std::swap(ExpectedOpcode, NextExpectedOpcode);
5535   }
5536
5537   // Don't try to fold this build_vector into an ADDSUB if the inputs are undef.
5538   if (AddFound && SubFound && InVec0.getOpcode() != ISD::UNDEF &&
5539       InVec1.getOpcode() != ISD::UNDEF)
5540     return DAG.getNode(X86ISD::ADDSUB, DL, VT, InVec0, InVec1);
5541
5542   return SDValue();
5543 }
5544
5545 /// Lower BUILD_VECTOR to a horizontal add/sub operation if possible.
5546 static SDValue LowerToHorizontalOp(const BuildVectorSDNode *BV,
5547                                    const X86Subtarget *Subtarget,
5548                                    SelectionDAG &DAG) {
5549   EVT VT = BV->getValueType(0);
5550   unsigned NumElts = VT.getVectorNumElements();
5551   unsigned NumUndefsLO = 0;
5552   unsigned NumUndefsHI = 0;
5553   unsigned Half = NumElts/2;
5554
5555   // Count the number of UNDEF operands in the build_vector in input.
5556   for (unsigned i = 0, e = Half; i != e; ++i)
5557     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
5558       NumUndefsLO++;
5559
5560   for (unsigned i = Half, e = NumElts; i != e; ++i)
5561     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
5562       NumUndefsHI++;
5563
5564   // Early exit if this is either a build_vector of all UNDEFs or all the
5565   // operands but one are UNDEF.
5566   if (NumUndefsLO + NumUndefsHI + 1 >= NumElts)
5567     return SDValue();
5568
5569   SDLoc DL(BV);
5570   SDValue InVec0, InVec1;
5571   if ((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) {
5572     // Try to match an SSE3 float HADD/HSUB.
5573     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
5574       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
5575
5576     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
5577       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
5578   } else if ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) {
5579     // Try to match an SSSE3 integer HADD/HSUB.
5580     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
5581       return DAG.getNode(X86ISD::HADD, DL, VT, InVec0, InVec1);
5582
5583     if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
5584       return DAG.getNode(X86ISD::HSUB, DL, VT, InVec0, InVec1);
5585   }
5586
5587   if (!Subtarget->hasAVX())
5588     return SDValue();
5589
5590   if ((VT == MVT::v8f32 || VT == MVT::v4f64)) {
5591     // Try to match an AVX horizontal add/sub of packed single/double
5592     // precision floating point values from 256-bit vectors.
5593     SDValue InVec2, InVec3;
5594     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, Half, InVec0, InVec1) &&
5595         isHorizontalBinOp(BV, ISD::FADD, DAG, Half, NumElts, InVec2, InVec3) &&
5596         ((InVec0.getOpcode() == ISD::UNDEF ||
5597           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5598         ((InVec1.getOpcode() == ISD::UNDEF ||
5599           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5600       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
5601
5602     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, Half, InVec0, InVec1) &&
5603         isHorizontalBinOp(BV, ISD::FSUB, DAG, Half, NumElts, InVec2, InVec3) &&
5604         ((InVec0.getOpcode() == ISD::UNDEF ||
5605           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5606         ((InVec1.getOpcode() == ISD::UNDEF ||
5607           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5608       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
5609   } else if (VT == MVT::v8i32 || VT == MVT::v16i16) {
5610     // Try to match an AVX2 horizontal add/sub of signed integers.
5611     SDValue InVec2, InVec3;
5612     unsigned X86Opcode;
5613     bool CanFold = true;
5614
5615     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
5616         isHorizontalBinOp(BV, ISD::ADD, DAG, Half, NumElts, InVec2, InVec3) &&
5617         ((InVec0.getOpcode() == ISD::UNDEF ||
5618           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5619         ((InVec1.getOpcode() == ISD::UNDEF ||
5620           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5621       X86Opcode = X86ISD::HADD;
5622     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, Half, InVec0, InVec1) &&
5623         isHorizontalBinOp(BV, ISD::SUB, DAG, Half, NumElts, InVec2, InVec3) &&
5624         ((InVec0.getOpcode() == ISD::UNDEF ||
5625           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5626         ((InVec1.getOpcode() == ISD::UNDEF ||
5627           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5628       X86Opcode = X86ISD::HSUB;
5629     else
5630       CanFold = false;
5631
5632     if (CanFold) {
5633       // Fold this build_vector into a single horizontal add/sub.
5634       // Do this only if the target has AVX2.
5635       if (Subtarget->hasAVX2())
5636         return DAG.getNode(X86Opcode, DL, VT, InVec0, InVec1);
5637
5638       // Do not try to expand this build_vector into a pair of horizontal
5639       // add/sub if we can emit a pair of scalar add/sub.
5640       if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
5641         return SDValue();
5642
5643       // Convert this build_vector into a pair of horizontal binop followed by
5644       // a concat vector.
5645       bool isUndefLO = NumUndefsLO == Half;
5646       bool isUndefHI = NumUndefsHI == Half;
5647       return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, false,
5648                                    isUndefLO, isUndefHI);
5649     }
5650   }
5651
5652   if ((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
5653        VT == MVT::v16i16) && Subtarget->hasAVX()) {
5654     unsigned X86Opcode;
5655     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
5656       X86Opcode = X86ISD::HADD;
5657     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
5658       X86Opcode = X86ISD::HSUB;
5659     else if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
5660       X86Opcode = X86ISD::FHADD;
5661     else if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
5662       X86Opcode = X86ISD::FHSUB;
5663     else
5664       return SDValue();
5665
5666     // Don't try to expand this build_vector into a pair of horizontal add/sub
5667     // if we can simply emit a pair of scalar add/sub.
5668     if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
5669       return SDValue();
5670
5671     // Convert this build_vector into two horizontal add/sub followed by
5672     // a concat vector.
5673     bool isUndefLO = NumUndefsLO == Half;
5674     bool isUndefHI = NumUndefsHI == Half;
5675     return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
5676                                  isUndefLO, isUndefHI);
5677   }
5678
5679   return SDValue();
5680 }
5681
5682 SDValue
5683 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5684   SDLoc dl(Op);
5685
5686   MVT VT = Op.getSimpleValueType();
5687   MVT ExtVT = VT.getVectorElementType();
5688   unsigned NumElems = Op.getNumOperands();
5689
5690   // Generate vectors for predicate vectors.
5691   if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
5692     return LowerBUILD_VECTORvXi1(Op, DAG);
5693
5694   // Vectors containing all zeros can be matched by pxor and xorps later
5695   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5696     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5697     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5698     if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
5699       return Op;
5700
5701     return getZeroVector(VT, Subtarget, DAG, dl);
5702   }
5703
5704   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5705   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5706   // vpcmpeqd on 256-bit vectors.
5707   if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
5708     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
5709       return Op;
5710
5711     if (!VT.is512BitVector())
5712       return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
5713   }
5714
5715   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(Op.getNode());
5716   if (SDValue AddSub = LowerToAddSub(BV, Subtarget, DAG))
5717     return AddSub;
5718   if (SDValue HorizontalOp = LowerToHorizontalOp(BV, Subtarget, DAG))
5719     return HorizontalOp;
5720   if (SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG))
5721     return Broadcast;
5722
5723   unsigned EVTBits = ExtVT.getSizeInBits();
5724
5725   unsigned NumZero  = 0;
5726   unsigned NumNonZero = 0;
5727   unsigned NonZeros = 0;
5728   bool IsAllConstants = true;
5729   SmallSet<SDValue, 8> Values;
5730   for (unsigned i = 0; i < NumElems; ++i) {
5731     SDValue Elt = Op.getOperand(i);
5732     if (Elt.getOpcode() == ISD::UNDEF)
5733       continue;
5734     Values.insert(Elt);
5735     if (Elt.getOpcode() != ISD::Constant &&
5736         Elt.getOpcode() != ISD::ConstantFP)
5737       IsAllConstants = false;
5738     if (X86::isZeroNode(Elt))
5739       NumZero++;
5740     else {
5741       NonZeros |= (1 << i);
5742       NumNonZero++;
5743     }
5744   }
5745
5746   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
5747   if (NumNonZero == 0)
5748     return DAG.getUNDEF(VT);
5749
5750   // Special case for single non-zero, non-undef, element.
5751   if (NumNonZero == 1) {
5752     unsigned Idx = countTrailingZeros(NonZeros);
5753     SDValue Item = Op.getOperand(Idx);
5754
5755     // If this is an insertion of an i64 value on x86-32, and if the top bits of
5756     // the value are obviously zero, truncate the value to i32 and do the
5757     // insertion that way.  Only do this if the value is non-constant or if the
5758     // value is a constant being inserted into element 0.  It is cheaper to do
5759     // a constant pool load than it is to do a movd + shuffle.
5760     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5761         (!IsAllConstants || Idx == 0)) {
5762       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5763         // Handle SSE only.
5764         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5765         EVT VecVT = MVT::v4i32;
5766
5767         // Truncate the value (which may itself be a constant) to i32, and
5768         // convert it to a vector with movd (S2V+shuffle to zero extend).
5769         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5770         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5771         return DAG.getNode(
5772             ISD::BITCAST, dl, VT,
5773             getShuffleVectorZeroOrUndef(Item, Idx * 2, true, Subtarget, DAG));
5774       }
5775     }
5776
5777     // If we have a constant or non-constant insertion into the low element of
5778     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5779     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
5780     // depending on what the source datatype is.
5781     if (Idx == 0) {
5782       if (NumZero == 0)
5783         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5784
5785       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5786           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5787         if (VT.is512BitVector()) {
5788           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
5789           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
5790                              Item, DAG.getIntPtrConstant(0, dl));
5791         }
5792         assert((VT.is128BitVector() || VT.is256BitVector()) &&
5793                "Expected an SSE value type!");
5794         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5795         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5796         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5797       }
5798
5799       // We can't directly insert an i8 or i16 into a vector, so zero extend
5800       // it to i32 first.
5801       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5802         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5803         if (VT.is256BitVector()) {
5804           if (Subtarget->hasAVX()) {
5805             Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v8i32, Item);
5806             Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5807           } else {
5808             // Without AVX, we need to extend to a 128-bit vector and then
5809             // insert into the 256-bit vector.
5810             Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5811             SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
5812             Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
5813           }
5814         } else {
5815           assert(VT.is128BitVector() && "Expected an SSE value type!");
5816           Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5817           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5818         }
5819         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5820       }
5821     }
5822
5823     // Is it a vector logical left shift?
5824     if (NumElems == 2 && Idx == 1 &&
5825         X86::isZeroNode(Op.getOperand(0)) &&
5826         !X86::isZeroNode(Op.getOperand(1))) {
5827       unsigned NumBits = VT.getSizeInBits();
5828       return getVShift(true, VT,
5829                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5830                                    VT, Op.getOperand(1)),
5831                        NumBits/2, DAG, *this, dl);
5832     }
5833
5834     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5835       return SDValue();
5836
5837     // Otherwise, if this is a vector with i32 or f32 elements, and the element
5838     // is a non-constant being inserted into an element other than the low one,
5839     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
5840     // movd/movss) to move this into the low element, then shuffle it into
5841     // place.
5842     if (EVTBits == 32) {
5843       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5844       return getShuffleVectorZeroOrUndef(Item, Idx, NumZero > 0, Subtarget, DAG);
5845     }
5846   }
5847
5848   // Splat is obviously ok. Let legalizer expand it to a shuffle.
5849   if (Values.size() == 1) {
5850     if (EVTBits == 32) {
5851       // Instead of a shuffle like this:
5852       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
5853       // Check if it's possible to issue this instead.
5854       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
5855       unsigned Idx = countTrailingZeros(NonZeros);
5856       SDValue Item = Op.getOperand(Idx);
5857       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
5858         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
5859     }
5860     return SDValue();
5861   }
5862
5863   // A vector full of immediates; various special cases are already
5864   // handled, so this is best done with a single constant-pool load.
5865   if (IsAllConstants)
5866     return SDValue();
5867
5868   // For AVX-length vectors, see if we can use a vector load to get all of the
5869   // elements, otherwise build the individual 128-bit pieces and use
5870   // shuffles to put them in place.
5871   if (VT.is256BitVector() || VT.is512BitVector()) {
5872     SmallVector<SDValue, 64> V(Op->op_begin(), Op->op_begin() + NumElems);
5873
5874     // Check for a build vector of consecutive loads.
5875     if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
5876       return LD;
5877
5878     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
5879
5880     // Build both the lower and upper subvector.
5881     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
5882                                 makeArrayRef(&V[0], NumElems/2));
5883     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
5884                                 makeArrayRef(&V[NumElems / 2], NumElems/2));
5885
5886     // Recreate the wider vector with the lower and upper part.
5887     if (VT.is256BitVector())
5888       return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
5889     return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
5890   }
5891
5892   // Let legalizer expand 2-wide build_vectors.
5893   if (EVTBits == 64) {
5894     if (NumNonZero == 1) {
5895       // One half is zero or undef.
5896       unsigned Idx = countTrailingZeros(NonZeros);
5897       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
5898                                  Op.getOperand(Idx));
5899       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
5900     }
5901     return SDValue();
5902   }
5903
5904   // If element VT is < 32 bits, convert it to inserts into a zero vector.
5905   if (EVTBits == 8 && NumElems == 16)
5906     if (SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
5907                                         Subtarget, *this))
5908       return V;
5909
5910   if (EVTBits == 16 && NumElems == 8)
5911     if (SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
5912                                       Subtarget, *this))
5913       return V;
5914
5915   // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
5916   if (EVTBits == 32 && NumElems == 4)
5917     if (SDValue V = LowerBuildVectorv4x32(Op, DAG, Subtarget, *this))
5918       return V;
5919
5920   // If element VT is == 32 bits, turn it into a number of shuffles.
5921   SmallVector<SDValue, 8> V(NumElems);
5922   if (NumElems == 4 && NumZero > 0) {
5923     for (unsigned i = 0; i < 4; ++i) {
5924       bool isZero = !(NonZeros & (1 << i));
5925       if (isZero)
5926         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
5927       else
5928         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5929     }
5930
5931     for (unsigned i = 0; i < 2; ++i) {
5932       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
5933         default: break;
5934         case 0:
5935           V[i] = V[i*2];  // Must be a zero vector.
5936           break;
5937         case 1:
5938           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
5939           break;
5940         case 2:
5941           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
5942           break;
5943         case 3:
5944           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
5945           break;
5946       }
5947     }
5948
5949     bool Reverse1 = (NonZeros & 0x3) == 2;
5950     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
5951     int MaskVec[] = {
5952       Reverse1 ? 1 : 0,
5953       Reverse1 ? 0 : 1,
5954       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
5955       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
5956     };
5957     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
5958   }
5959
5960   if (Values.size() > 1 && VT.is128BitVector()) {
5961     // Check for a build vector of consecutive loads.
5962     for (unsigned i = 0; i < NumElems; ++i)
5963       V[i] = Op.getOperand(i);
5964
5965     // Check for elements which are consecutive loads.
5966     if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
5967       return LD;
5968
5969     // Check for a build vector from mostly shuffle plus few inserting.
5970     if (SDValue Sh = buildFromShuffleMostly(Op, DAG))
5971       return Sh;
5972
5973     // For SSE 4.1, use insertps to put the high elements into the low element.
5974     if (Subtarget->hasSSE41()) {
5975       SDValue Result;
5976       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
5977         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
5978       else
5979         Result = DAG.getUNDEF(VT);
5980
5981       for (unsigned i = 1; i < NumElems; ++i) {
5982         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
5983         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
5984                              Op.getOperand(i), DAG.getIntPtrConstant(i, dl));
5985       }
5986       return Result;
5987     }
5988
5989     // Otherwise, expand into a number of unpckl*, start by extending each of
5990     // our (non-undef) elements to the full vector width with the element in the
5991     // bottom slot of the vector (which generates no code for SSE).
5992     for (unsigned i = 0; i < NumElems; ++i) {
5993       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
5994         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5995       else
5996         V[i] = DAG.getUNDEF(VT);
5997     }
5998
5999     // Next, we iteratively mix elements, e.g. for v4f32:
6000     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6001     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6002     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
6003     unsigned EltStride = NumElems >> 1;
6004     while (EltStride != 0) {
6005       for (unsigned i = 0; i < EltStride; ++i) {
6006         // If V[i+EltStride] is undef and this is the first round of mixing,
6007         // then it is safe to just drop this shuffle: V[i] is already in the
6008         // right place, the one element (since it's the first round) being
6009         // inserted as undef can be dropped.  This isn't safe for successive
6010         // rounds because they will permute elements within both vectors.
6011         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6012             EltStride == NumElems/2)
6013           continue;
6014
6015         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6016       }
6017       EltStride >>= 1;
6018     }
6019     return V[0];
6020   }
6021   return SDValue();
6022 }
6023
6024 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
6025 // to create 256-bit vectors from two other 128-bit ones.
6026 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6027   SDLoc dl(Op);
6028   MVT ResVT = Op.getSimpleValueType();
6029
6030   assert((ResVT.is256BitVector() ||
6031           ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6032
6033   SDValue V1 = Op.getOperand(0);
6034   SDValue V2 = Op.getOperand(1);
6035   unsigned NumElems = ResVT.getVectorNumElements();
6036   if (ResVT.is256BitVector())
6037     return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6038
6039   if (Op.getNumOperands() == 4) {
6040     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6041                                 ResVT.getVectorNumElements()/2);
6042     SDValue V3 = Op.getOperand(2);
6043     SDValue V4 = Op.getOperand(3);
6044     return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6045       Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6046   }
6047   return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6048 }
6049
6050 static SDValue LowerCONCAT_VECTORSvXi1(SDValue Op,
6051                                        const X86Subtarget *Subtarget,
6052                                        SelectionDAG & DAG) {
6053   SDLoc dl(Op);
6054   MVT ResVT = Op.getSimpleValueType();
6055   unsigned NumOfOperands = Op.getNumOperands();
6056
6057   assert(isPowerOf2_32(NumOfOperands) &&
6058          "Unexpected number of operands in CONCAT_VECTORS");
6059
6060   if (NumOfOperands > 2) {
6061     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6062                                   ResVT.getVectorNumElements()/2);
6063     SmallVector<SDValue, 2> Ops;
6064     for (unsigned i = 0; i < NumOfOperands/2; i++)
6065       Ops.push_back(Op.getOperand(i));
6066     SDValue Lo = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6067     Ops.clear();
6068     for (unsigned i = NumOfOperands/2; i < NumOfOperands; i++)
6069       Ops.push_back(Op.getOperand(i));
6070     SDValue Hi = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6071     return DAG.getNode(ISD::CONCAT_VECTORS, dl, ResVT, Lo, Hi);
6072   }
6073
6074   SDValue V1 = Op.getOperand(0);
6075   SDValue V2 = Op.getOperand(1);
6076   bool IsZeroV1 = ISD::isBuildVectorAllZeros(V1.getNode());
6077   bool IsZeroV2 = ISD::isBuildVectorAllZeros(V2.getNode());
6078
6079   if (IsZeroV1 && IsZeroV2)
6080     return getZeroVector(ResVT, Subtarget, DAG, dl);
6081
6082   SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
6083   SDValue Undef = DAG.getUNDEF(ResVT);
6084   unsigned NumElems = ResVT.getVectorNumElements();
6085   SDValue ShiftBits = DAG.getConstant(NumElems/2, dl, MVT::i8);
6086
6087   V2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V2, ZeroIdx);
6088   V2 = DAG.getNode(X86ISD::VSHLI, dl, ResVT, V2, ShiftBits);
6089   if (IsZeroV1)
6090     return V2;
6091
6092   V1 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V1, ZeroIdx);
6093   // Zero the upper bits of V1
6094   V1 = DAG.getNode(X86ISD::VSHLI, dl, ResVT, V1, ShiftBits);
6095   V1 = DAG.getNode(X86ISD::VSRLI, dl, ResVT, V1, ShiftBits);
6096   if (IsZeroV2)
6097     return V1;
6098   return DAG.getNode(ISD::OR, dl, ResVT, V1, V2);
6099 }
6100
6101 static SDValue LowerCONCAT_VECTORS(SDValue Op,
6102                                    const X86Subtarget *Subtarget,
6103                                    SelectionDAG &DAG) {
6104   MVT VT = Op.getSimpleValueType();
6105   if (VT.getVectorElementType() == MVT::i1)
6106     return LowerCONCAT_VECTORSvXi1(Op, Subtarget, DAG);
6107
6108   assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6109          (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6110           Op.getNumOperands() == 4)));
6111
6112   // AVX can use the vinsertf128 instruction to create 256-bit vectors
6113   // from two other 128-bit ones.
6114
6115   // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6116   return LowerAVXCONCAT_VECTORS(Op, DAG);
6117 }
6118
6119
6120 //===----------------------------------------------------------------------===//
6121 // Vector shuffle lowering
6122 //
6123 // This is an experimental code path for lowering vector shuffles on x86. It is
6124 // designed to handle arbitrary vector shuffles and blends, gracefully
6125 // degrading performance as necessary. It works hard to recognize idiomatic
6126 // shuffles and lower them to optimal instruction patterns without leaving
6127 // a framework that allows reasonably efficient handling of all vector shuffle
6128 // patterns.
6129 //===----------------------------------------------------------------------===//
6130
6131 /// \brief Tiny helper function to identify a no-op mask.
6132 ///
6133 /// This is a somewhat boring predicate function. It checks whether the mask
6134 /// array input, which is assumed to be a single-input shuffle mask of the kind
6135 /// used by the X86 shuffle instructions (not a fully general
6136 /// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
6137 /// in-place shuffle are 'no-op's.
6138 static bool isNoopShuffleMask(ArrayRef<int> Mask) {
6139   for (int i = 0, Size = Mask.size(); i < Size; ++i)
6140     if (Mask[i] != -1 && Mask[i] != i)
6141       return false;
6142   return true;
6143 }
6144
6145 /// \brief Helper function to classify a mask as a single-input mask.
6146 ///
6147 /// This isn't a generic single-input test because in the vector shuffle
6148 /// lowering we canonicalize single inputs to be the first input operand. This
6149 /// means we can more quickly test for a single input by only checking whether
6150 /// an input from the second operand exists. We also assume that the size of
6151 /// mask corresponds to the size of the input vectors which isn't true in the
6152 /// fully general case.
6153 static bool isSingleInputShuffleMask(ArrayRef<int> Mask) {
6154   for (int M : Mask)
6155     if (M >= (int)Mask.size())
6156       return false;
6157   return true;
6158 }
6159
6160 /// \brief Test whether there are elements crossing 128-bit lanes in this
6161 /// shuffle mask.
6162 ///
6163 /// X86 divides up its shuffles into in-lane and cross-lane shuffle operations
6164 /// and we routinely test for these.
6165 static bool is128BitLaneCrossingShuffleMask(MVT VT, ArrayRef<int> Mask) {
6166   int LaneSize = 128 / VT.getScalarSizeInBits();
6167   int Size = Mask.size();
6168   for (int i = 0; i < Size; ++i)
6169     if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
6170       return true;
6171   return false;
6172 }
6173
6174 /// \brief Test whether a shuffle mask is equivalent within each 128-bit lane.
6175 ///
6176 /// This checks a shuffle mask to see if it is performing the same
6177 /// 128-bit lane-relative shuffle in each 128-bit lane. This trivially implies
6178 /// that it is also not lane-crossing. It may however involve a blend from the
6179 /// same lane of a second vector.
6180 ///
6181 /// The specific repeated shuffle mask is populated in \p RepeatedMask, as it is
6182 /// non-trivial to compute in the face of undef lanes. The representation is
6183 /// *not* suitable for use with existing 128-bit shuffles as it will contain
6184 /// entries from both V1 and V2 inputs to the wider mask.
6185 static bool
6186 is128BitLaneRepeatedShuffleMask(MVT VT, ArrayRef<int> Mask,
6187                                 SmallVectorImpl<int> &RepeatedMask) {
6188   int LaneSize = 128 / VT.getScalarSizeInBits();
6189   RepeatedMask.resize(LaneSize, -1);
6190   int Size = Mask.size();
6191   for (int i = 0; i < Size; ++i) {
6192     if (Mask[i] < 0)
6193       continue;
6194     if ((Mask[i] % Size) / LaneSize != i / LaneSize)
6195       // This entry crosses lanes, so there is no way to model this shuffle.
6196       return false;
6197
6198     // Ok, handle the in-lane shuffles by detecting if and when they repeat.
6199     if (RepeatedMask[i % LaneSize] == -1)
6200       // This is the first non-undef entry in this slot of a 128-bit lane.
6201       RepeatedMask[i % LaneSize] =
6202           Mask[i] < Size ? Mask[i] % LaneSize : Mask[i] % LaneSize + Size;
6203     else if (RepeatedMask[i % LaneSize] + (i / LaneSize) * LaneSize != Mask[i])
6204       // Found a mismatch with the repeated mask.
6205       return false;
6206   }
6207   return true;
6208 }
6209
6210 /// \brief Checks whether a shuffle mask is equivalent to an explicit list of
6211 /// arguments.
6212 ///
6213 /// This is a fast way to test a shuffle mask against a fixed pattern:
6214 ///
6215 ///   if (isShuffleEquivalent(Mask, 3, 2, {1, 0})) { ... }
6216 ///
6217 /// It returns true if the mask is exactly as wide as the argument list, and
6218 /// each element of the mask is either -1 (signifying undef) or the value given
6219 /// in the argument.
6220 static bool isShuffleEquivalent(SDValue V1, SDValue V2, ArrayRef<int> Mask,
6221                                 ArrayRef<int> ExpectedMask) {
6222   if (Mask.size() != ExpectedMask.size())
6223     return false;
6224
6225   int Size = Mask.size();
6226
6227   // If the values are build vectors, we can look through them to find
6228   // equivalent inputs that make the shuffles equivalent.
6229   auto *BV1 = dyn_cast<BuildVectorSDNode>(V1);
6230   auto *BV2 = dyn_cast<BuildVectorSDNode>(V2);
6231
6232   for (int i = 0; i < Size; ++i)
6233     if (Mask[i] != -1 && Mask[i] != ExpectedMask[i]) {
6234       auto *MaskBV = Mask[i] < Size ? BV1 : BV2;
6235       auto *ExpectedBV = ExpectedMask[i] < Size ? BV1 : BV2;
6236       if (!MaskBV || !ExpectedBV ||
6237           MaskBV->getOperand(Mask[i] % Size) !=
6238               ExpectedBV->getOperand(ExpectedMask[i] % Size))
6239         return false;
6240     }
6241
6242   return true;
6243 }
6244
6245 /// \brief Get a 4-lane 8-bit shuffle immediate for a mask.
6246 ///
6247 /// This helper function produces an 8-bit shuffle immediate corresponding to
6248 /// the ubiquitous shuffle encoding scheme used in x86 instructions for
6249 /// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
6250 /// example.
6251 ///
6252 /// NB: We rely heavily on "undef" masks preserving the input lane.
6253 static SDValue getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask, SDLoc DL,
6254                                           SelectionDAG &DAG) {
6255   assert(Mask.size() == 4 && "Only 4-lane shuffle masks");
6256   assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!");
6257   assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!");
6258   assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!");
6259   assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!");
6260
6261   unsigned Imm = 0;
6262   Imm |= (Mask[0] == -1 ? 0 : Mask[0]) << 0;
6263   Imm |= (Mask[1] == -1 ? 1 : Mask[1]) << 2;
6264   Imm |= (Mask[2] == -1 ? 2 : Mask[2]) << 4;
6265   Imm |= (Mask[3] == -1 ? 3 : Mask[3]) << 6;
6266   return DAG.getConstant(Imm, DL, MVT::i8);
6267 }
6268
6269 /// \brief Try to emit a blend instruction for a shuffle using bit math.
6270 ///
6271 /// This is used as a fallback approach when first class blend instructions are
6272 /// unavailable. Currently it is only suitable for integer vectors, but could
6273 /// be generalized for floating point vectors if desirable.
6274 static SDValue lowerVectorShuffleAsBitBlend(SDLoc DL, MVT VT, SDValue V1,
6275                                             SDValue V2, ArrayRef<int> Mask,
6276                                             SelectionDAG &DAG) {
6277   assert(VT.isInteger() && "Only supports integer vector types!");
6278   MVT EltVT = VT.getScalarType();
6279   int NumEltBits = EltVT.getSizeInBits();
6280   SDValue Zero = DAG.getConstant(0, DL, EltVT);
6281   SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
6282                                     EltVT);
6283   SmallVector<SDValue, 16> MaskOps;
6284   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6285     if (Mask[i] != -1 && Mask[i] != i && Mask[i] != i + Size)
6286       return SDValue(); // Shuffled input!
6287     MaskOps.push_back(Mask[i] < Size ? AllOnes : Zero);
6288   }
6289
6290   SDValue V1Mask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, MaskOps);
6291   V1 = DAG.getNode(ISD::AND, DL, VT, V1, V1Mask);
6292   // We have to cast V2 around.
6293   MVT MaskVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
6294   V2 = DAG.getNode(ISD::BITCAST, DL, VT,
6295                    DAG.getNode(X86ISD::ANDNP, DL, MaskVT,
6296                                DAG.getNode(ISD::BITCAST, DL, MaskVT, V1Mask),
6297                                DAG.getNode(ISD::BITCAST, DL, MaskVT, V2)));
6298   return DAG.getNode(ISD::OR, DL, VT, V1, V2);
6299 }
6300
6301 /// \brief Try to emit a blend instruction for a shuffle.
6302 ///
6303 /// This doesn't do any checks for the availability of instructions for blending
6304 /// these values. It relies on the availability of the X86ISD::BLENDI pattern to
6305 /// be matched in the backend with the type given. What it does check for is
6306 /// that the shuffle mask is in fact a blend.
6307 static SDValue lowerVectorShuffleAsBlend(SDLoc DL, MVT VT, SDValue V1,
6308                                          SDValue V2, ArrayRef<int> Mask,
6309                                          const X86Subtarget *Subtarget,
6310                                          SelectionDAG &DAG) {
6311   unsigned BlendMask = 0;
6312   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6313     if (Mask[i] >= Size) {
6314       if (Mask[i] != i + Size)
6315         return SDValue(); // Shuffled V2 input!
6316       BlendMask |= 1u << i;
6317       continue;
6318     }
6319     if (Mask[i] >= 0 && Mask[i] != i)
6320       return SDValue(); // Shuffled V1 input!
6321   }
6322   switch (VT.SimpleTy) {
6323   case MVT::v2f64:
6324   case MVT::v4f32:
6325   case MVT::v4f64:
6326   case MVT::v8f32:
6327     return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V2,
6328                        DAG.getConstant(BlendMask, DL, MVT::i8));
6329
6330   case MVT::v4i64:
6331   case MVT::v8i32:
6332     assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6333     // FALLTHROUGH
6334   case MVT::v2i64:
6335   case MVT::v4i32:
6336     // If we have AVX2 it is faster to use VPBLENDD when the shuffle fits into
6337     // that instruction.
6338     if (Subtarget->hasAVX2()) {
6339       // Scale the blend by the number of 32-bit dwords per element.
6340       int Scale =  VT.getScalarSizeInBits() / 32;
6341       BlendMask = 0;
6342       for (int i = 0, Size = Mask.size(); i < Size; ++i)
6343         if (Mask[i] >= Size)
6344           for (int j = 0; j < Scale; ++j)
6345             BlendMask |= 1u << (i * Scale + j);
6346
6347       MVT BlendVT = VT.getSizeInBits() > 128 ? MVT::v8i32 : MVT::v4i32;
6348       V1 = DAG.getNode(ISD::BITCAST, DL, BlendVT, V1);
6349       V2 = DAG.getNode(ISD::BITCAST, DL, BlendVT, V2);
6350       return DAG.getNode(ISD::BITCAST, DL, VT,
6351                          DAG.getNode(X86ISD::BLENDI, DL, BlendVT, V1, V2,
6352                                      DAG.getConstant(BlendMask, DL, MVT::i8)));
6353     }
6354     // FALLTHROUGH
6355   case MVT::v8i16: {
6356     // For integer shuffles we need to expand the mask and cast the inputs to
6357     // v8i16s prior to blending.
6358     int Scale = 8 / VT.getVectorNumElements();
6359     BlendMask = 0;
6360     for (int i = 0, Size = Mask.size(); i < Size; ++i)
6361       if (Mask[i] >= Size)
6362         for (int j = 0; j < Scale; ++j)
6363           BlendMask |= 1u << (i * Scale + j);
6364
6365     V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1);
6366     V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V2);
6367     return DAG.getNode(ISD::BITCAST, DL, VT,
6368                        DAG.getNode(X86ISD::BLENDI, DL, MVT::v8i16, V1, V2,
6369                                    DAG.getConstant(BlendMask, DL, MVT::i8)));
6370   }
6371
6372   case MVT::v16i16: {
6373     assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6374     SmallVector<int, 8> RepeatedMask;
6375     if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
6376       // We can lower these with PBLENDW which is mirrored across 128-bit lanes.
6377       assert(RepeatedMask.size() == 8 && "Repeated mask size doesn't match!");
6378       BlendMask = 0;
6379       for (int i = 0; i < 8; ++i)
6380         if (RepeatedMask[i] >= 16)
6381           BlendMask |= 1u << i;
6382       return DAG.getNode(X86ISD::BLENDI, DL, MVT::v16i16, V1, V2,
6383                          DAG.getConstant(BlendMask, DL, MVT::i8));
6384     }
6385   }
6386     // FALLTHROUGH
6387   case MVT::v16i8:
6388   case MVT::v32i8: {
6389     assert((VT.getSizeInBits() == 128 || Subtarget->hasAVX2()) &&
6390            "256-bit byte-blends require AVX2 support!");
6391
6392     // Scale the blend by the number of bytes per element.
6393     int Scale = VT.getScalarSizeInBits() / 8;
6394
6395     // This form of blend is always done on bytes. Compute the byte vector
6396     // type.
6397     MVT BlendVT = MVT::getVectorVT(MVT::i8, VT.getSizeInBits() / 8);
6398
6399     // Compute the VSELECT mask. Note that VSELECT is really confusing in the
6400     // mix of LLVM's code generator and the x86 backend. We tell the code
6401     // generator that boolean values in the elements of an x86 vector register
6402     // are -1 for true and 0 for false. We then use the LLVM semantics of 'true'
6403     // mapping a select to operand #1, and 'false' mapping to operand #2. The
6404     // reality in x86 is that vector masks (pre-AVX-512) use only the high bit
6405     // of the element (the remaining are ignored) and 0 in that high bit would
6406     // mean operand #1 while 1 in the high bit would mean operand #2. So while
6407     // the LLVM model for boolean values in vector elements gets the relevant
6408     // bit set, it is set backwards and over constrained relative to x86's
6409     // actual model.
6410     SmallVector<SDValue, 32> VSELECTMask;
6411     for (int i = 0, Size = Mask.size(); i < Size; ++i)
6412       for (int j = 0; j < Scale; ++j)
6413         VSELECTMask.push_back(
6414             Mask[i] < 0 ? DAG.getUNDEF(MVT::i8)
6415                         : DAG.getConstant(Mask[i] < Size ? -1 : 0, DL,
6416                                           MVT::i8));
6417
6418     V1 = DAG.getNode(ISD::BITCAST, DL, BlendVT, V1);
6419     V2 = DAG.getNode(ISD::BITCAST, DL, BlendVT, V2);
6420     return DAG.getNode(
6421         ISD::BITCAST, DL, VT,
6422         DAG.getNode(ISD::VSELECT, DL, BlendVT,
6423                     DAG.getNode(ISD::BUILD_VECTOR, DL, BlendVT, VSELECTMask),
6424                     V1, V2));
6425   }
6426
6427   default:
6428     llvm_unreachable("Not a supported integer vector type!");
6429   }
6430 }
6431
6432 /// \brief Try to lower as a blend of elements from two inputs followed by
6433 /// a single-input permutation.
6434 ///
6435 /// This matches the pattern where we can blend elements from two inputs and
6436 /// then reduce the shuffle to a single-input permutation.
6437 static SDValue lowerVectorShuffleAsBlendAndPermute(SDLoc DL, MVT VT, SDValue V1,
6438                                                    SDValue V2,
6439                                                    ArrayRef<int> Mask,
6440                                                    SelectionDAG &DAG) {
6441   // We build up the blend mask while checking whether a blend is a viable way
6442   // to reduce the shuffle.
6443   SmallVector<int, 32> BlendMask(Mask.size(), -1);
6444   SmallVector<int, 32> PermuteMask(Mask.size(), -1);
6445
6446   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6447     if (Mask[i] < 0)
6448       continue;
6449
6450     assert(Mask[i] < Size * 2 && "Shuffle input is out of bounds.");
6451
6452     if (BlendMask[Mask[i] % Size] == -1)
6453       BlendMask[Mask[i] % Size] = Mask[i];
6454     else if (BlendMask[Mask[i] % Size] != Mask[i])
6455       return SDValue(); // Can't blend in the needed input!
6456
6457     PermuteMask[i] = Mask[i] % Size;
6458   }
6459
6460   SDValue V = DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
6461   return DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), PermuteMask);
6462 }
6463
6464 /// \brief Generic routine to decompose a shuffle and blend into indepndent
6465 /// blends and permutes.
6466 ///
6467 /// This matches the extremely common pattern for handling combined
6468 /// shuffle+blend operations on newer X86 ISAs where we have very fast blend
6469 /// operations. It will try to pick the best arrangement of shuffles and
6470 /// blends.
6471 static SDValue lowerVectorShuffleAsDecomposedShuffleBlend(SDLoc DL, MVT VT,
6472                                                           SDValue V1,
6473                                                           SDValue V2,
6474                                                           ArrayRef<int> Mask,
6475                                                           SelectionDAG &DAG) {
6476   // Shuffle the input elements into the desired positions in V1 and V2 and
6477   // blend them together.
6478   SmallVector<int, 32> V1Mask(Mask.size(), -1);
6479   SmallVector<int, 32> V2Mask(Mask.size(), -1);
6480   SmallVector<int, 32> BlendMask(Mask.size(), -1);
6481   for (int i = 0, Size = Mask.size(); i < Size; ++i)
6482     if (Mask[i] >= 0 && Mask[i] < Size) {
6483       V1Mask[i] = Mask[i];
6484       BlendMask[i] = i;
6485     } else if (Mask[i] >= Size) {
6486       V2Mask[i] = Mask[i] - Size;
6487       BlendMask[i] = i + Size;
6488     }
6489
6490   // Try to lower with the simpler initial blend strategy unless one of the
6491   // input shuffles would be a no-op. We prefer to shuffle inputs as the
6492   // shuffle may be able to fold with a load or other benefit. However, when
6493   // we'll have to do 2x as many shuffles in order to achieve this, blending
6494   // first is a better strategy.
6495   if (!isNoopShuffleMask(V1Mask) && !isNoopShuffleMask(V2Mask))
6496     if (SDValue BlendPerm =
6497             lowerVectorShuffleAsBlendAndPermute(DL, VT, V1, V2, Mask, DAG))
6498       return BlendPerm;
6499
6500   V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
6501   V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
6502   return DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
6503 }
6504
6505 /// \brief Try to lower a vector shuffle as a byte rotation.
6506 ///
6507 /// SSSE3 has a generic PALIGNR instruction in x86 that will do an arbitrary
6508 /// byte-rotation of the concatenation of two vectors; pre-SSSE3 can use
6509 /// a PSRLDQ/PSLLDQ/POR pattern to get a similar effect. This routine will
6510 /// try to generically lower a vector shuffle through such an pattern. It
6511 /// does not check for the profitability of lowering either as PALIGNR or
6512 /// PSRLDQ/PSLLDQ/POR, only whether the mask is valid to lower in that form.
6513 /// This matches shuffle vectors that look like:
6514 ///
6515 ///   v8i16 [11, 12, 13, 14, 15, 0, 1, 2]
6516 ///
6517 /// Essentially it concatenates V1 and V2, shifts right by some number of
6518 /// elements, and takes the low elements as the result. Note that while this is
6519 /// specified as a *right shift* because x86 is little-endian, it is a *left
6520 /// rotate* of the vector lanes.
6521 static SDValue lowerVectorShuffleAsByteRotate(SDLoc DL, MVT VT, SDValue V1,
6522                                               SDValue V2,
6523                                               ArrayRef<int> Mask,
6524                                               const X86Subtarget *Subtarget,
6525                                               SelectionDAG &DAG) {
6526   assert(!isNoopShuffleMask(Mask) && "We shouldn't lower no-op shuffles!");
6527
6528   int NumElts = Mask.size();
6529   int NumLanes = VT.getSizeInBits() / 128;
6530   int NumLaneElts = NumElts / NumLanes;
6531
6532   // We need to detect various ways of spelling a rotation:
6533   //   [11, 12, 13, 14, 15,  0,  1,  2]
6534   //   [-1, 12, 13, 14, -1, -1,  1, -1]
6535   //   [-1, -1, -1, -1, -1, -1,  1,  2]
6536   //   [ 3,  4,  5,  6,  7,  8,  9, 10]
6537   //   [-1,  4,  5,  6, -1, -1,  9, -1]
6538   //   [-1,  4,  5,  6, -1, -1, -1, -1]
6539   int Rotation = 0;
6540   SDValue Lo, Hi;
6541   for (int l = 0; l < NumElts; l += NumLaneElts) {
6542     for (int i = 0; i < NumLaneElts; ++i) {
6543       if (Mask[l + i] == -1)
6544         continue;
6545       assert(Mask[l + i] >= 0 && "Only -1 is a valid negative mask element!");
6546
6547       // Get the mod-Size index and lane correct it.
6548       int LaneIdx = (Mask[l + i] % NumElts) - l;
6549       // Make sure it was in this lane.
6550       if (LaneIdx < 0 || LaneIdx >= NumLaneElts)
6551         return SDValue();
6552
6553       // Determine where a rotated vector would have started.
6554       int StartIdx = i - LaneIdx;
6555       if (StartIdx == 0)
6556         // The identity rotation isn't interesting, stop.
6557         return SDValue();
6558
6559       // If we found the tail of a vector the rotation must be the missing
6560       // front. If we found the head of a vector, it must be how much of the
6561       // head.
6562       int CandidateRotation = StartIdx < 0 ? -StartIdx : NumLaneElts - StartIdx;
6563
6564       if (Rotation == 0)
6565         Rotation = CandidateRotation;
6566       else if (Rotation != CandidateRotation)
6567         // The rotations don't match, so we can't match this mask.
6568         return SDValue();
6569
6570       // Compute which value this mask is pointing at.
6571       SDValue MaskV = Mask[l + i] < NumElts ? V1 : V2;
6572
6573       // Compute which of the two target values this index should be assigned
6574       // to. This reflects whether the high elements are remaining or the low
6575       // elements are remaining.
6576       SDValue &TargetV = StartIdx < 0 ? Hi : Lo;
6577
6578       // Either set up this value if we've not encountered it before, or check
6579       // that it remains consistent.
6580       if (!TargetV)
6581         TargetV = MaskV;
6582       else if (TargetV != MaskV)
6583         // This may be a rotation, but it pulls from the inputs in some
6584         // unsupported interleaving.
6585         return SDValue();
6586     }
6587   }
6588
6589   // Check that we successfully analyzed the mask, and normalize the results.
6590   assert(Rotation != 0 && "Failed to locate a viable rotation!");
6591   assert((Lo || Hi) && "Failed to find a rotated input vector!");
6592   if (!Lo)
6593     Lo = Hi;
6594   else if (!Hi)
6595     Hi = Lo;
6596
6597   // The actual rotate instruction rotates bytes, so we need to scale the
6598   // rotation based on how many bytes are in the vector lane.
6599   int Scale = 16 / NumLaneElts;
6600
6601   // SSSE3 targets can use the palignr instruction.
6602   if (Subtarget->hasSSSE3()) {
6603     // Cast the inputs to i8 vector of correct length to match PALIGNR.
6604     MVT AlignVT = MVT::getVectorVT(MVT::i8, 16 * NumLanes);
6605     Lo = DAG.getNode(ISD::BITCAST, DL, AlignVT, Lo);
6606     Hi = DAG.getNode(ISD::BITCAST, DL, AlignVT, Hi);
6607
6608     return DAG.getNode(ISD::BITCAST, DL, VT,
6609                        DAG.getNode(X86ISD::PALIGNR, DL, AlignVT, Hi, Lo,
6610                                    DAG.getConstant(Rotation * Scale, DL,
6611                                                    MVT::i8)));
6612   }
6613
6614   assert(VT.getSizeInBits() == 128 &&
6615          "Rotate-based lowering only supports 128-bit lowering!");
6616   assert(Mask.size() <= 16 &&
6617          "Can shuffle at most 16 bytes in a 128-bit vector!");
6618
6619   // Default SSE2 implementation
6620   int LoByteShift = 16 - Rotation * Scale;
6621   int HiByteShift = Rotation * Scale;
6622
6623   // Cast the inputs to v2i64 to match PSLLDQ/PSRLDQ.
6624   Lo = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Lo);
6625   Hi = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Hi);
6626
6627   SDValue LoShift = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v2i64, Lo,
6628                                 DAG.getConstant(LoByteShift, DL, MVT::i8));
6629   SDValue HiShift = DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v2i64, Hi,
6630                                 DAG.getConstant(HiByteShift, DL, MVT::i8));
6631   return DAG.getNode(ISD::BITCAST, DL, VT,
6632                      DAG.getNode(ISD::OR, DL, MVT::v2i64, LoShift, HiShift));
6633 }
6634
6635 /// \brief Compute whether each element of a shuffle is zeroable.
6636 ///
6637 /// A "zeroable" vector shuffle element is one which can be lowered to zero.
6638 /// Either it is an undef element in the shuffle mask, the element of the input
6639 /// referenced is undef, or the element of the input referenced is known to be
6640 /// zero. Many x86 shuffles can zero lanes cheaply and we often want to handle
6641 /// as many lanes with this technique as possible to simplify the remaining
6642 /// shuffle.
6643 static SmallBitVector computeZeroableShuffleElements(ArrayRef<int> Mask,
6644                                                      SDValue V1, SDValue V2) {
6645   SmallBitVector Zeroable(Mask.size(), false);
6646
6647   while (V1.getOpcode() == ISD::BITCAST)
6648     V1 = V1->getOperand(0);
6649   while (V2.getOpcode() == ISD::BITCAST)
6650     V2 = V2->getOperand(0);
6651
6652   bool V1IsZero = ISD::isBuildVectorAllZeros(V1.getNode());
6653   bool V2IsZero = ISD::isBuildVectorAllZeros(V2.getNode());
6654
6655   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6656     int M = Mask[i];
6657     // Handle the easy cases.
6658     if (M < 0 || (M >= 0 && M < Size && V1IsZero) || (M >= Size && V2IsZero)) {
6659       Zeroable[i] = true;
6660       continue;
6661     }
6662
6663     // If this is an index into a build_vector node (which has the same number
6664     // of elements), dig out the input value and use it.
6665     SDValue V = M < Size ? V1 : V2;
6666     if (V.getOpcode() != ISD::BUILD_VECTOR || Size != (int)V.getNumOperands())
6667       continue;
6668
6669     SDValue Input = V.getOperand(M % Size);
6670     // The UNDEF opcode check really should be dead code here, but not quite
6671     // worth asserting on (it isn't invalid, just unexpected).
6672     if (Input.getOpcode() == ISD::UNDEF || X86::isZeroNode(Input))
6673       Zeroable[i] = true;
6674   }
6675
6676   return Zeroable;
6677 }
6678
6679 /// \brief Try to emit a bitmask instruction for a shuffle.
6680 ///
6681 /// This handles cases where we can model a blend exactly as a bitmask due to
6682 /// one of the inputs being zeroable.
6683 static SDValue lowerVectorShuffleAsBitMask(SDLoc DL, MVT VT, SDValue V1,
6684                                            SDValue V2, ArrayRef<int> Mask,
6685                                            SelectionDAG &DAG) {
6686   MVT EltVT = VT.getScalarType();
6687   int NumEltBits = EltVT.getSizeInBits();
6688   MVT IntEltVT = MVT::getIntegerVT(NumEltBits);
6689   SDValue Zero = DAG.getConstant(0, DL, IntEltVT);
6690   SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
6691                                     IntEltVT);
6692   if (EltVT.isFloatingPoint()) {
6693     Zero = DAG.getNode(ISD::BITCAST, DL, EltVT, Zero);
6694     AllOnes = DAG.getNode(ISD::BITCAST, DL, EltVT, AllOnes);
6695   }
6696   SmallVector<SDValue, 16> VMaskOps(Mask.size(), Zero);
6697   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6698   SDValue V;
6699   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6700     if (Zeroable[i])
6701       continue;
6702     if (Mask[i] % Size != i)
6703       return SDValue(); // Not a blend.
6704     if (!V)
6705       V = Mask[i] < Size ? V1 : V2;
6706     else if (V != (Mask[i] < Size ? V1 : V2))
6707       return SDValue(); // Can only let one input through the mask.
6708
6709     VMaskOps[i] = AllOnes;
6710   }
6711   if (!V)
6712     return SDValue(); // No non-zeroable elements!
6713
6714   SDValue VMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, VMaskOps);
6715   V = DAG.getNode(VT.isFloatingPoint()
6716                   ? (unsigned) X86ISD::FAND : (unsigned) ISD::AND,
6717                   DL, VT, V, VMask);
6718   return V;
6719 }
6720
6721 /// \brief Try to lower a vector shuffle as a bit shift (shifts in zeros).
6722 ///
6723 /// Attempts to match a shuffle mask against the PSLL(W/D/Q/DQ) and
6724 /// PSRL(W/D/Q/DQ) SSE2 and AVX2 logical bit-shift instructions. The function
6725 /// matches elements from one of the input vectors shuffled to the left or
6726 /// right with zeroable elements 'shifted in'. It handles both the strictly
6727 /// bit-wise element shifts and the byte shift across an entire 128-bit double
6728 /// quad word lane.
6729 ///
6730 /// PSHL : (little-endian) left bit shift.
6731 /// [ zz, 0, zz,  2 ]
6732 /// [ -1, 4, zz, -1 ]
6733 /// PSRL : (little-endian) right bit shift.
6734 /// [  1, zz,  3, zz]
6735 /// [ -1, -1,  7, zz]
6736 /// PSLLDQ : (little-endian) left byte shift
6737 /// [ zz,  0,  1,  2,  3,  4,  5,  6]
6738 /// [ zz, zz, -1, -1,  2,  3,  4, -1]
6739 /// [ zz, zz, zz, zz, zz, zz, -1,  1]
6740 /// PSRLDQ : (little-endian) right byte shift
6741 /// [  5, 6,  7, zz, zz, zz, zz, zz]
6742 /// [ -1, 5,  6,  7, zz, zz, zz, zz]
6743 /// [  1, 2, -1, -1, -1, -1, zz, zz]
6744 static SDValue lowerVectorShuffleAsShift(SDLoc DL, MVT VT, SDValue V1,
6745                                          SDValue V2, ArrayRef<int> Mask,
6746                                          SelectionDAG &DAG) {
6747   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6748
6749   int Size = Mask.size();
6750   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
6751
6752   auto CheckZeros = [&](int Shift, int Scale, bool Left) {
6753     for (int i = 0; i < Size; i += Scale)
6754       for (int j = 0; j < Shift; ++j)
6755         if (!Zeroable[i + j + (Left ? 0 : (Scale - Shift))])
6756           return false;
6757
6758     return true;
6759   };
6760
6761   auto MatchShift = [&](int Shift, int Scale, bool Left, SDValue V) {
6762     for (int i = 0; i != Size; i += Scale) {
6763       unsigned Pos = Left ? i + Shift : i;
6764       unsigned Low = Left ? i : i + Shift;
6765       unsigned Len = Scale - Shift;
6766       if (!isSequentialOrUndefInRange(Mask, Pos, Len,
6767                                       Low + (V == V1 ? 0 : Size)))
6768         return SDValue();
6769     }
6770
6771     int ShiftEltBits = VT.getScalarSizeInBits() * Scale;
6772     bool ByteShift = ShiftEltBits > 64;
6773     unsigned OpCode = Left ? (ByteShift ? X86ISD::VSHLDQ : X86ISD::VSHLI)
6774                            : (ByteShift ? X86ISD::VSRLDQ : X86ISD::VSRLI);
6775     int ShiftAmt = Shift * VT.getScalarSizeInBits() / (ByteShift ? 8 : 1);
6776
6777     // Normalize the scale for byte shifts to still produce an i64 element
6778     // type.
6779     Scale = ByteShift ? Scale / 2 : Scale;
6780
6781     // We need to round trip through the appropriate type for the shift.
6782     MVT ShiftSVT = MVT::getIntegerVT(VT.getScalarSizeInBits() * Scale);
6783     MVT ShiftVT = MVT::getVectorVT(ShiftSVT, Size / Scale);
6784     assert(DAG.getTargetLoweringInfo().isTypeLegal(ShiftVT) &&
6785            "Illegal integer vector type");
6786     V = DAG.getNode(ISD::BITCAST, DL, ShiftVT, V);
6787
6788     V = DAG.getNode(OpCode, DL, ShiftVT, V,
6789                     DAG.getConstant(ShiftAmt, DL, MVT::i8));
6790     return DAG.getNode(ISD::BITCAST, DL, VT, V);
6791   };
6792
6793   // SSE/AVX supports logical shifts up to 64-bit integers - so we can just
6794   // keep doubling the size of the integer elements up to that. We can
6795   // then shift the elements of the integer vector by whole multiples of
6796   // their width within the elements of the larger integer vector. Test each
6797   // multiple to see if we can find a match with the moved element indices
6798   // and that the shifted in elements are all zeroable.
6799   for (int Scale = 2; Scale * VT.getScalarSizeInBits() <= 128; Scale *= 2)
6800     for (int Shift = 1; Shift != Scale; ++Shift)
6801       for (bool Left : {true, false})
6802         if (CheckZeros(Shift, Scale, Left))
6803           for (SDValue V : {V1, V2})
6804             if (SDValue Match = MatchShift(Shift, Scale, Left, V))
6805               return Match;
6806
6807   // no match
6808   return SDValue();
6809 }
6810
6811 /// \brief Lower a vector shuffle as a zero or any extension.
6812 ///
6813 /// Given a specific number of elements, element bit width, and extension
6814 /// stride, produce either a zero or any extension based on the available
6815 /// features of the subtarget.
6816 static SDValue lowerVectorShuffleAsSpecificZeroOrAnyExtend(
6817     SDLoc DL, MVT VT, int Scale, bool AnyExt, SDValue InputV,
6818     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
6819   assert(Scale > 1 && "Need a scale to extend.");
6820   int NumElements = VT.getVectorNumElements();
6821   int EltBits = VT.getScalarSizeInBits();
6822   assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
6823          "Only 8, 16, and 32 bit elements can be extended.");
6824   assert(Scale * EltBits <= 64 && "Cannot zero extend past 64 bits.");
6825
6826   // Found a valid zext mask! Try various lowering strategies based on the
6827   // input type and available ISA extensions.
6828   if (Subtarget->hasSSE41()) {
6829     MVT ExtVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits * Scale),
6830                                  NumElements / Scale);
6831     return DAG.getNode(ISD::BITCAST, DL, VT,
6832                        DAG.getNode(X86ISD::VZEXT, DL, ExtVT, InputV));
6833   }
6834
6835   // For any extends we can cheat for larger element sizes and use shuffle
6836   // instructions that can fold with a load and/or copy.
6837   if (AnyExt && EltBits == 32) {
6838     int PSHUFDMask[4] = {0, -1, 1, -1};
6839     return DAG.getNode(
6840         ISD::BITCAST, DL, VT,
6841         DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
6842                     DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, InputV),
6843                     getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
6844   }
6845   if (AnyExt && EltBits == 16 && Scale > 2) {
6846     int PSHUFDMask[4] = {0, -1, 0, -1};
6847     InputV = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
6848                          DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, InputV),
6849                          getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG));
6850     int PSHUFHWMask[4] = {1, -1, -1, -1};
6851     return DAG.getNode(
6852         ISD::BITCAST, DL, VT,
6853         DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16,
6854                     DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, InputV),
6855                     getV4X86ShuffleImm8ForMask(PSHUFHWMask, DL, DAG)));
6856   }
6857
6858   // If this would require more than 2 unpack instructions to expand, use
6859   // pshufb when available. We can only use more than 2 unpack instructions
6860   // when zero extending i8 elements which also makes it easier to use pshufb.
6861   if (Scale > 4 && EltBits == 8 && Subtarget->hasSSSE3()) {
6862     assert(NumElements == 16 && "Unexpected byte vector width!");
6863     SDValue PSHUFBMask[16];
6864     for (int i = 0; i < 16; ++i)
6865       PSHUFBMask[i] =
6866           DAG.getConstant((i % Scale == 0) ? i / Scale : 0x80, DL, MVT::i8);
6867     InputV = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, InputV);
6868     return DAG.getNode(ISD::BITCAST, DL, VT,
6869                        DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, InputV,
6870                                    DAG.getNode(ISD::BUILD_VECTOR, DL,
6871                                                MVT::v16i8, PSHUFBMask)));
6872   }
6873
6874   // Otherwise emit a sequence of unpacks.
6875   do {
6876     MVT InputVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits), NumElements);
6877     SDValue Ext = AnyExt ? DAG.getUNDEF(InputVT)
6878                          : getZeroVector(InputVT, Subtarget, DAG, DL);
6879     InputV = DAG.getNode(ISD::BITCAST, DL, InputVT, InputV);
6880     InputV = DAG.getNode(X86ISD::UNPCKL, DL, InputVT, InputV, Ext);
6881     Scale /= 2;
6882     EltBits *= 2;
6883     NumElements /= 2;
6884   } while (Scale > 1);
6885   return DAG.getNode(ISD::BITCAST, DL, VT, InputV);
6886 }
6887
6888 /// \brief Try to lower a vector shuffle as a zero extension on any microarch.
6889 ///
6890 /// This routine will try to do everything in its power to cleverly lower
6891 /// a shuffle which happens to match the pattern of a zero extend. It doesn't
6892 /// check for the profitability of this lowering,  it tries to aggressively
6893 /// match this pattern. It will use all of the micro-architectural details it
6894 /// can to emit an efficient lowering. It handles both blends with all-zero
6895 /// inputs to explicitly zero-extend and undef-lanes (sometimes undef due to
6896 /// masking out later).
6897 ///
6898 /// The reason we have dedicated lowering for zext-style shuffles is that they
6899 /// are both incredibly common and often quite performance sensitive.
6900 static SDValue lowerVectorShuffleAsZeroOrAnyExtend(
6901     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
6902     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
6903   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6904
6905   int Bits = VT.getSizeInBits();
6906   int NumElements = VT.getVectorNumElements();
6907   assert(VT.getScalarSizeInBits() <= 32 &&
6908          "Exceeds 32-bit integer zero extension limit");
6909   assert((int)Mask.size() == NumElements && "Unexpected shuffle mask size");
6910
6911   // Define a helper function to check a particular ext-scale and lower to it if
6912   // valid.
6913   auto Lower = [&](int Scale) -> SDValue {
6914     SDValue InputV;
6915     bool AnyExt = true;
6916     for (int i = 0; i < NumElements; ++i) {
6917       if (Mask[i] == -1)
6918         continue; // Valid anywhere but doesn't tell us anything.
6919       if (i % Scale != 0) {
6920         // Each of the extended elements need to be zeroable.
6921         if (!Zeroable[i])
6922           return SDValue();
6923
6924         // We no longer are in the anyext case.
6925         AnyExt = false;
6926         continue;
6927       }
6928
6929       // Each of the base elements needs to be consecutive indices into the
6930       // same input vector.
6931       SDValue V = Mask[i] < NumElements ? V1 : V2;
6932       if (!InputV)
6933         InputV = V;
6934       else if (InputV != V)
6935         return SDValue(); // Flip-flopping inputs.
6936
6937       if (Mask[i] % NumElements != i / Scale)
6938         return SDValue(); // Non-consecutive strided elements.
6939     }
6940
6941     // If we fail to find an input, we have a zero-shuffle which should always
6942     // have already been handled.
6943     // FIXME: Maybe handle this here in case during blending we end up with one?
6944     if (!InputV)
6945       return SDValue();
6946
6947     return lowerVectorShuffleAsSpecificZeroOrAnyExtend(
6948         DL, VT, Scale, AnyExt, InputV, Subtarget, DAG);
6949   };
6950
6951   // The widest scale possible for extending is to a 64-bit integer.
6952   assert(Bits % 64 == 0 &&
6953          "The number of bits in a vector must be divisible by 64 on x86!");
6954   int NumExtElements = Bits / 64;
6955
6956   // Each iteration, try extending the elements half as much, but into twice as
6957   // many elements.
6958   for (; NumExtElements < NumElements; NumExtElements *= 2) {
6959     assert(NumElements % NumExtElements == 0 &&
6960            "The input vector size must be divisible by the extended size.");
6961     if (SDValue V = Lower(NumElements / NumExtElements))
6962       return V;
6963   }
6964
6965   // General extends failed, but 128-bit vectors may be able to use MOVQ.
6966   if (Bits != 128)
6967     return SDValue();
6968
6969   // Returns one of the source operands if the shuffle can be reduced to a
6970   // MOVQ, copying the lower 64-bits and zero-extending to the upper 64-bits.
6971   auto CanZExtLowHalf = [&]() {
6972     for (int i = NumElements / 2; i != NumElements; ++i)
6973       if (!Zeroable[i])
6974         return SDValue();
6975     if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, 0))
6976       return V1;
6977     if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, NumElements))
6978       return V2;
6979     return SDValue();
6980   };
6981
6982   if (SDValue V = CanZExtLowHalf()) {
6983     V = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, V);
6984     V = DAG.getNode(X86ISD::VZEXT_MOVL, DL, MVT::v2i64, V);
6985     return DAG.getNode(ISD::BITCAST, DL, VT, V);
6986   }
6987
6988   // No viable ext lowering found.
6989   return SDValue();
6990 }
6991
6992 /// \brief Try to get a scalar value for a specific element of a vector.
6993 ///
6994 /// Looks through BUILD_VECTOR and SCALAR_TO_VECTOR nodes to find a scalar.
6995 static SDValue getScalarValueForVectorElement(SDValue V, int Idx,
6996                                               SelectionDAG &DAG) {
6997   MVT VT = V.getSimpleValueType();
6998   MVT EltVT = VT.getVectorElementType();
6999   while (V.getOpcode() == ISD::BITCAST)
7000     V = V.getOperand(0);
7001   // If the bitcasts shift the element size, we can't extract an equivalent
7002   // element from it.
7003   MVT NewVT = V.getSimpleValueType();
7004   if (!NewVT.isVector() || NewVT.getScalarSizeInBits() != VT.getScalarSizeInBits())
7005     return SDValue();
7006
7007   if (V.getOpcode() == ISD::BUILD_VECTOR ||
7008       (Idx == 0 && V.getOpcode() == ISD::SCALAR_TO_VECTOR)) {
7009     // Ensure the scalar operand is the same size as the destination.
7010     // FIXME: Add support for scalar truncation where possible.
7011     SDValue S = V.getOperand(Idx);
7012     if (EltVT.getSizeInBits() == S.getSimpleValueType().getSizeInBits())
7013       return DAG.getNode(ISD::BITCAST, SDLoc(V), EltVT, S);
7014   }
7015
7016   return SDValue();
7017 }
7018
7019 /// \brief Helper to test for a load that can be folded with x86 shuffles.
7020 ///
7021 /// This is particularly important because the set of instructions varies
7022 /// significantly based on whether the operand is a load or not.
7023 static bool isShuffleFoldableLoad(SDValue V) {
7024   while (V.getOpcode() == ISD::BITCAST)
7025     V = V.getOperand(0);
7026
7027   return ISD::isNON_EXTLoad(V.getNode());
7028 }
7029
7030 /// \brief Try to lower insertion of a single element into a zero vector.
7031 ///
7032 /// This is a common pattern that we have especially efficient patterns to lower
7033 /// across all subtarget feature sets.
7034 static SDValue lowerVectorShuffleAsElementInsertion(
7035     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7036     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7037   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7038   MVT ExtVT = VT;
7039   MVT EltVT = VT.getVectorElementType();
7040
7041   int V2Index = std::find_if(Mask.begin(), Mask.end(),
7042                              [&Mask](int M) { return M >= (int)Mask.size(); }) -
7043                 Mask.begin();
7044   bool IsV1Zeroable = true;
7045   for (int i = 0, Size = Mask.size(); i < Size; ++i)
7046     if (i != V2Index && !Zeroable[i]) {
7047       IsV1Zeroable = false;
7048       break;
7049     }
7050
7051   // Check for a single input from a SCALAR_TO_VECTOR node.
7052   // FIXME: All of this should be canonicalized into INSERT_VECTOR_ELT and
7053   // all the smarts here sunk into that routine. However, the current
7054   // lowering of BUILD_VECTOR makes that nearly impossible until the old
7055   // vector shuffle lowering is dead.
7056   if (SDValue V2S = getScalarValueForVectorElement(
7057           V2, Mask[V2Index] - Mask.size(), DAG)) {
7058     // We need to zext the scalar if it is smaller than an i32.
7059     V2S = DAG.getNode(ISD::BITCAST, DL, EltVT, V2S);
7060     if (EltVT == MVT::i8 || EltVT == MVT::i16) {
7061       // Using zext to expand a narrow element won't work for non-zero
7062       // insertions.
7063       if (!IsV1Zeroable)
7064         return SDValue();
7065
7066       // Zero-extend directly to i32.
7067       ExtVT = MVT::v4i32;
7068       V2S = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, V2S);
7069     }
7070     V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, ExtVT, V2S);
7071   } else if (Mask[V2Index] != (int)Mask.size() || EltVT == MVT::i8 ||
7072              EltVT == MVT::i16) {
7073     // Either not inserting from the low element of the input or the input
7074     // element size is too small to use VZEXT_MOVL to clear the high bits.
7075     return SDValue();
7076   }
7077
7078   if (!IsV1Zeroable) {
7079     // If V1 can't be treated as a zero vector we have fewer options to lower
7080     // this. We can't support integer vectors or non-zero targets cheaply, and
7081     // the V1 elements can't be permuted in any way.
7082     assert(VT == ExtVT && "Cannot change extended type when non-zeroable!");
7083     if (!VT.isFloatingPoint() || V2Index != 0)
7084       return SDValue();
7085     SmallVector<int, 8> V1Mask(Mask.begin(), Mask.end());
7086     V1Mask[V2Index] = -1;
7087     if (!isNoopShuffleMask(V1Mask))
7088       return SDValue();
7089     // This is essentially a special case blend operation, but if we have
7090     // general purpose blend operations, they are always faster. Bail and let
7091     // the rest of the lowering handle these as blends.
7092     if (Subtarget->hasSSE41())
7093       return SDValue();
7094
7095     // Otherwise, use MOVSD or MOVSS.
7096     assert((EltVT == MVT::f32 || EltVT == MVT::f64) &&
7097            "Only two types of floating point element types to handle!");
7098     return DAG.getNode(EltVT == MVT::f32 ? X86ISD::MOVSS : X86ISD::MOVSD, DL,
7099                        ExtVT, V1, V2);
7100   }
7101
7102   // This lowering only works for the low element with floating point vectors.
7103   if (VT.isFloatingPoint() && V2Index != 0)
7104     return SDValue();
7105
7106   V2 = DAG.getNode(X86ISD::VZEXT_MOVL, DL, ExtVT, V2);
7107   if (ExtVT != VT)
7108     V2 = DAG.getNode(ISD::BITCAST, DL, VT, V2);
7109
7110   if (V2Index != 0) {
7111     // If we have 4 or fewer lanes we can cheaply shuffle the element into
7112     // the desired position. Otherwise it is more efficient to do a vector
7113     // shift left. We know that we can do a vector shift left because all
7114     // the inputs are zero.
7115     if (VT.isFloatingPoint() || VT.getVectorNumElements() <= 4) {
7116       SmallVector<int, 4> V2Shuffle(Mask.size(), 1);
7117       V2Shuffle[V2Index] = 0;
7118       V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Shuffle);
7119     } else {
7120       V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, V2);
7121       V2 = DAG.getNode(
7122           X86ISD::VSHLDQ, DL, MVT::v2i64, V2,
7123           DAG.getConstant(
7124               V2Index * EltVT.getSizeInBits()/8, DL,
7125               DAG.getTargetLoweringInfo().getScalarShiftAmountTy(MVT::v2i64)));
7126       V2 = DAG.getNode(ISD::BITCAST, DL, VT, V2);
7127     }
7128   }
7129   return V2;
7130 }
7131
7132 /// \brief Try to lower broadcast of a single element.
7133 ///
7134 /// For convenience, this code also bundles all of the subtarget feature set
7135 /// filtering. While a little annoying to re-dispatch on type here, there isn't
7136 /// a convenient way to factor it out.
7137 static SDValue lowerVectorShuffleAsBroadcast(SDLoc DL, MVT VT, SDValue V,
7138                                              ArrayRef<int> Mask,
7139                                              const X86Subtarget *Subtarget,
7140                                              SelectionDAG &DAG) {
7141   if (!Subtarget->hasAVX())
7142     return SDValue();
7143   if (VT.isInteger() && !Subtarget->hasAVX2())
7144     return SDValue();
7145
7146   // Check that the mask is a broadcast.
7147   int BroadcastIdx = -1;
7148   for (int M : Mask)
7149     if (M >= 0 && BroadcastIdx == -1)
7150       BroadcastIdx = M;
7151     else if (M >= 0 && M != BroadcastIdx)
7152       return SDValue();
7153
7154   assert(BroadcastIdx < (int)Mask.size() && "We only expect to be called with "
7155                                             "a sorted mask where the broadcast "
7156                                             "comes from V1.");
7157
7158   // Go up the chain of (vector) values to find a scalar load that we can
7159   // combine with the broadcast.
7160   for (;;) {
7161     switch (V.getOpcode()) {
7162     case ISD::CONCAT_VECTORS: {
7163       int OperandSize = Mask.size() / V.getNumOperands();
7164       V = V.getOperand(BroadcastIdx / OperandSize);
7165       BroadcastIdx %= OperandSize;
7166       continue;
7167     }
7168
7169     case ISD::INSERT_SUBVECTOR: {
7170       SDValue VOuter = V.getOperand(0), VInner = V.getOperand(1);
7171       auto ConstantIdx = dyn_cast<ConstantSDNode>(V.getOperand(2));
7172       if (!ConstantIdx)
7173         break;
7174
7175       int BeginIdx = (int)ConstantIdx->getZExtValue();
7176       int EndIdx =
7177           BeginIdx + (int)VInner.getValueType().getVectorNumElements();
7178       if (BroadcastIdx >= BeginIdx && BroadcastIdx < EndIdx) {
7179         BroadcastIdx -= BeginIdx;
7180         V = VInner;
7181       } else {
7182         V = VOuter;
7183       }
7184       continue;
7185     }
7186     }
7187     break;
7188   }
7189
7190   // Check if this is a broadcast of a scalar. We special case lowering
7191   // for scalars so that we can more effectively fold with loads.
7192   if (V.getOpcode() == ISD::BUILD_VECTOR ||
7193       (V.getOpcode() == ISD::SCALAR_TO_VECTOR && BroadcastIdx == 0)) {
7194     V = V.getOperand(BroadcastIdx);
7195
7196     // If the scalar isn't a load, we can't broadcast from it in AVX1.
7197     // Only AVX2 has register broadcasts.
7198     if (!Subtarget->hasAVX2() && !isShuffleFoldableLoad(V))
7199       return SDValue();
7200   } else if (BroadcastIdx != 0 || !Subtarget->hasAVX2()) {
7201     // We can't broadcast from a vector register without AVX2, and we can only
7202     // broadcast from the zero-element of a vector register.
7203     return SDValue();
7204   }
7205
7206   return DAG.getNode(X86ISD::VBROADCAST, DL, VT, V);
7207 }
7208
7209 // Check for whether we can use INSERTPS to perform the shuffle. We only use
7210 // INSERTPS when the V1 elements are already in the correct locations
7211 // because otherwise we can just always use two SHUFPS instructions which
7212 // are much smaller to encode than a SHUFPS and an INSERTPS. We can also
7213 // perform INSERTPS if a single V1 element is out of place and all V2
7214 // elements are zeroable.
7215 static SDValue lowerVectorShuffleAsInsertPS(SDValue Op, SDValue V1, SDValue V2,
7216                                             ArrayRef<int> Mask,
7217                                             SelectionDAG &DAG) {
7218   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
7219   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7220   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7221   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7222
7223   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7224
7225   unsigned ZMask = 0;
7226   int V1DstIndex = -1;
7227   int V2DstIndex = -1;
7228   bool V1UsedInPlace = false;
7229
7230   for (int i = 0; i < 4; ++i) {
7231     // Synthesize a zero mask from the zeroable elements (includes undefs).
7232     if (Zeroable[i]) {
7233       ZMask |= 1 << i;
7234       continue;
7235     }
7236
7237     // Flag if we use any V1 inputs in place.
7238     if (i == Mask[i]) {
7239       V1UsedInPlace = true;
7240       continue;
7241     }
7242
7243     // We can only insert a single non-zeroable element.
7244     if (V1DstIndex != -1 || V2DstIndex != -1)
7245       return SDValue();
7246
7247     if (Mask[i] < 4) {
7248       // V1 input out of place for insertion.
7249       V1DstIndex = i;
7250     } else {
7251       // V2 input for insertion.
7252       V2DstIndex = i;
7253     }
7254   }
7255
7256   // Don't bother if we have no (non-zeroable) element for insertion.
7257   if (V1DstIndex == -1 && V2DstIndex == -1)
7258     return SDValue();
7259
7260   // Determine element insertion src/dst indices. The src index is from the
7261   // start of the inserted vector, not the start of the concatenated vector.
7262   unsigned V2SrcIndex = 0;
7263   if (V1DstIndex != -1) {
7264     // If we have a V1 input out of place, we use V1 as the V2 element insertion
7265     // and don't use the original V2 at all.
7266     V2SrcIndex = Mask[V1DstIndex];
7267     V2DstIndex = V1DstIndex;
7268     V2 = V1;
7269   } else {
7270     V2SrcIndex = Mask[V2DstIndex] - 4;
7271   }
7272
7273   // If no V1 inputs are used in place, then the result is created only from
7274   // the zero mask and the V2 insertion - so remove V1 dependency.
7275   if (!V1UsedInPlace)
7276     V1 = DAG.getUNDEF(MVT::v4f32);
7277
7278   unsigned InsertPSMask = V2SrcIndex << 6 | V2DstIndex << 4 | ZMask;
7279   assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
7280
7281   // Insert the V2 element into the desired position.
7282   SDLoc DL(Op);
7283   return DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
7284                      DAG.getConstant(InsertPSMask, DL, MVT::i8));
7285 }
7286
7287 /// \brief Try to lower a shuffle as a permute of the inputs followed by an
7288 /// UNPCK instruction.
7289 ///
7290 /// This specifically targets cases where we end up with alternating between
7291 /// the two inputs, and so can permute them into something that feeds a single
7292 /// UNPCK instruction. Note that this routine only targets integer vectors
7293 /// because for floating point vectors we have a generalized SHUFPS lowering
7294 /// strategy that handles everything that doesn't *exactly* match an unpack,
7295 /// making this clever lowering unnecessary.
7296 static SDValue lowerVectorShuffleAsUnpack(SDLoc DL, MVT VT, SDValue V1,
7297                                           SDValue V2, ArrayRef<int> Mask,
7298                                           SelectionDAG &DAG) {
7299   assert(!VT.isFloatingPoint() &&
7300          "This routine only supports integer vectors.");
7301   assert(!isSingleInputShuffleMask(Mask) &&
7302          "This routine should only be used when blending two inputs.");
7303   assert(Mask.size() >= 2 && "Single element masks are invalid.");
7304
7305   int Size = Mask.size();
7306
7307   int NumLoInputs = std::count_if(Mask.begin(), Mask.end(), [Size](int M) {
7308     return M >= 0 && M % Size < Size / 2;
7309   });
7310   int NumHiInputs = std::count_if(
7311       Mask.begin(), Mask.end(), [Size](int M) { return M % Size >= Size / 2; });
7312
7313   bool UnpackLo = NumLoInputs >= NumHiInputs;
7314
7315   auto TryUnpack = [&](MVT UnpackVT, int Scale) {
7316     SmallVector<int, 32> V1Mask(Mask.size(), -1);
7317     SmallVector<int, 32> V2Mask(Mask.size(), -1);
7318
7319     for (int i = 0; i < Size; ++i) {
7320       if (Mask[i] < 0)
7321         continue;
7322
7323       // Each element of the unpack contains Scale elements from this mask.
7324       int UnpackIdx = i / Scale;
7325
7326       // We only handle the case where V1 feeds the first slots of the unpack.
7327       // We rely on canonicalization to ensure this is the case.
7328       if ((UnpackIdx % 2 == 0) != (Mask[i] < Size))
7329         return SDValue();
7330
7331       // Setup the mask for this input. The indexing is tricky as we have to
7332       // handle the unpack stride.
7333       SmallVectorImpl<int> &VMask = (UnpackIdx % 2 == 0) ? V1Mask : V2Mask;
7334       VMask[(UnpackIdx / 2) * Scale + i % Scale + (UnpackLo ? 0 : Size / 2)] =
7335           Mask[i] % Size;
7336     }
7337
7338     // If we will have to shuffle both inputs to use the unpack, check whether
7339     // we can just unpack first and shuffle the result. If so, skip this unpack.
7340     if ((NumLoInputs == 0 || NumHiInputs == 0) && !isNoopShuffleMask(V1Mask) &&
7341         !isNoopShuffleMask(V2Mask))
7342       return SDValue();
7343
7344     // Shuffle the inputs into place.
7345     V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
7346     V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
7347
7348     // Cast the inputs to the type we will use to unpack them.
7349     V1 = DAG.getNode(ISD::BITCAST, DL, UnpackVT, V1);
7350     V2 = DAG.getNode(ISD::BITCAST, DL, UnpackVT, V2);
7351
7352     // Unpack the inputs and cast the result back to the desired type.
7353     return DAG.getNode(ISD::BITCAST, DL, VT,
7354                        DAG.getNode(UnpackLo ? X86ISD::UNPCKL : X86ISD::UNPCKH,
7355                                    DL, UnpackVT, V1, V2));
7356   };
7357
7358   // We try each unpack from the largest to the smallest to try and find one
7359   // that fits this mask.
7360   int OrigNumElements = VT.getVectorNumElements();
7361   int OrigScalarSize = VT.getScalarSizeInBits();
7362   for (int ScalarSize = 64; ScalarSize >= OrigScalarSize; ScalarSize /= 2) {
7363     int Scale = ScalarSize / OrigScalarSize;
7364     int NumElements = OrigNumElements / Scale;
7365     MVT UnpackVT = MVT::getVectorVT(MVT::getIntegerVT(ScalarSize), NumElements);
7366     if (SDValue Unpack = TryUnpack(UnpackVT, Scale))
7367       return Unpack;
7368   }
7369
7370   // If none of the unpack-rooted lowerings worked (or were profitable) try an
7371   // initial unpack.
7372   if (NumLoInputs == 0 || NumHiInputs == 0) {
7373     assert((NumLoInputs > 0 || NumHiInputs > 0) &&
7374            "We have to have *some* inputs!");
7375     int HalfOffset = NumLoInputs == 0 ? Size / 2 : 0;
7376
7377     // FIXME: We could consider the total complexity of the permute of each
7378     // possible unpacking. Or at the least we should consider how many
7379     // half-crossings are created.
7380     // FIXME: We could consider commuting the unpacks.
7381
7382     SmallVector<int, 32> PermMask;
7383     PermMask.assign(Size, -1);
7384     for (int i = 0; i < Size; ++i) {
7385       if (Mask[i] < 0)
7386         continue;
7387
7388       assert(Mask[i] % Size >= HalfOffset && "Found input from wrong half!");
7389
7390       PermMask[i] =
7391           2 * ((Mask[i] % Size) - HalfOffset) + (Mask[i] < Size ? 0 : 1);
7392     }
7393     return DAG.getVectorShuffle(
7394         VT, DL, DAG.getNode(NumLoInputs == 0 ? X86ISD::UNPCKH : X86ISD::UNPCKL,
7395                             DL, VT, V1, V2),
7396         DAG.getUNDEF(VT), PermMask);
7397   }
7398
7399   return SDValue();
7400 }
7401
7402 /// \brief Handle lowering of 2-lane 64-bit floating point shuffles.
7403 ///
7404 /// This is the basis function for the 2-lane 64-bit shuffles as we have full
7405 /// support for floating point shuffles but not integer shuffles. These
7406 /// instructions will incur a domain crossing penalty on some chips though so
7407 /// it is better to avoid lowering through this for integer vectors where
7408 /// possible.
7409 static SDValue lowerV2F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7410                                        const X86Subtarget *Subtarget,
7411                                        SelectionDAG &DAG) {
7412   SDLoc DL(Op);
7413   assert(Op.getSimpleValueType() == MVT::v2f64 && "Bad shuffle type!");
7414   assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7415   assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7416   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7417   ArrayRef<int> Mask = SVOp->getMask();
7418   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7419
7420   if (isSingleInputShuffleMask(Mask)) {
7421     // Use low duplicate instructions for masks that match their pattern.
7422     if (Subtarget->hasSSE3())
7423       if (isShuffleEquivalent(V1, V2, Mask, {0, 0}))
7424         return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v2f64, V1);
7425
7426     // Straight shuffle of a single input vector. Simulate this by using the
7427     // single input as both of the "inputs" to this instruction..
7428     unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
7429
7430     if (Subtarget->hasAVX()) {
7431       // If we have AVX, we can use VPERMILPS which will allow folding a load
7432       // into the shuffle.
7433       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v2f64, V1,
7434                          DAG.getConstant(SHUFPDMask, DL, MVT::i8));
7435     }
7436
7437     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V1,
7438                        DAG.getConstant(SHUFPDMask, DL, MVT::i8));
7439   }
7440   assert(Mask[0] >= 0 && Mask[0] < 2 && "Non-canonicalized blend!");
7441   assert(Mask[1] >= 2 && "Non-canonicalized blend!");
7442
7443   // If we have a single input, insert that into V1 if we can do so cheaply.
7444   if ((Mask[0] >= 2) + (Mask[1] >= 2) == 1) {
7445     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7446             DL, MVT::v2f64, V1, V2, Mask, Subtarget, DAG))
7447       return Insertion;
7448     // Try inverting the insertion since for v2 masks it is easy to do and we
7449     // can't reliably sort the mask one way or the other.
7450     int InverseMask[2] = {Mask[0] < 0 ? -1 : (Mask[0] ^ 2),
7451                           Mask[1] < 0 ? -1 : (Mask[1] ^ 2)};
7452     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7453             DL, MVT::v2f64, V2, V1, InverseMask, Subtarget, DAG))
7454       return Insertion;
7455   }
7456
7457   // Try to use one of the special instruction patterns to handle two common
7458   // blend patterns if a zero-blend above didn't work.
7459   if (isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
7460       isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7461     if (SDValue V1S = getScalarValueForVectorElement(V1, Mask[0], DAG))
7462       // We can either use a special instruction to load over the low double or
7463       // to move just the low double.
7464       return DAG.getNode(
7465           isShuffleFoldableLoad(V1S) ? X86ISD::MOVLPD : X86ISD::MOVSD,
7466           DL, MVT::v2f64, V2,
7467           DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64, V1S));
7468
7469   if (Subtarget->hasSSE41())
7470     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2f64, V1, V2, Mask,
7471                                                   Subtarget, DAG))
7472       return Blend;
7473
7474   // Use dedicated unpack instructions for masks that match their pattern.
7475   if (isShuffleEquivalent(V1, V2, Mask, {0, 2}))
7476     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2f64, V1, V2);
7477   if (isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7478     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2f64, V1, V2);
7479
7480   unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
7481   return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V2,
7482                      DAG.getConstant(SHUFPDMask, DL, MVT::i8));
7483 }
7484
7485 /// \brief Handle lowering of 2-lane 64-bit integer shuffles.
7486 ///
7487 /// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
7488 /// the integer unit to minimize domain crossing penalties. However, for blends
7489 /// it falls back to the floating point shuffle operation with appropriate bit
7490 /// casting.
7491 static SDValue lowerV2I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7492                                        const X86Subtarget *Subtarget,
7493                                        SelectionDAG &DAG) {
7494   SDLoc DL(Op);
7495   assert(Op.getSimpleValueType() == MVT::v2i64 && "Bad shuffle type!");
7496   assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7497   assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7498   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7499   ArrayRef<int> Mask = SVOp->getMask();
7500   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7501
7502   if (isSingleInputShuffleMask(Mask)) {
7503     // Check for being able to broadcast a single element.
7504     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v2i64, V1,
7505                                                           Mask, Subtarget, DAG))
7506       return Broadcast;
7507
7508     // Straight shuffle of a single input vector. For everything from SSE2
7509     // onward this has a single fast instruction with no scary immediates.
7510     // We have to map the mask as it is actually a v4i32 shuffle instruction.
7511     V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V1);
7512     int WidenedMask[4] = {
7513         std::max(Mask[0], 0) * 2, std::max(Mask[0], 0) * 2 + 1,
7514         std::max(Mask[1], 0) * 2, std::max(Mask[1], 0) * 2 + 1};
7515     return DAG.getNode(
7516         ISD::BITCAST, DL, MVT::v2i64,
7517         DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
7518                     getV4X86ShuffleImm8ForMask(WidenedMask, DL, DAG)));
7519   }
7520   assert(Mask[0] != -1 && "No undef lanes in multi-input v2 shuffles!");
7521   assert(Mask[1] != -1 && "No undef lanes in multi-input v2 shuffles!");
7522   assert(Mask[0] < 2 && "We sort V1 to be the first input.");
7523   assert(Mask[1] >= 2 && "We sort V2 to be the second input.");
7524
7525   // If we have a blend of two PACKUS operations an the blend aligns with the
7526   // low and half halves, we can just merge the PACKUS operations. This is
7527   // particularly important as it lets us merge shuffles that this routine itself
7528   // creates.
7529   auto GetPackNode = [](SDValue V) {
7530     while (V.getOpcode() == ISD::BITCAST)
7531       V = V.getOperand(0);
7532
7533     return V.getOpcode() == X86ISD::PACKUS ? V : SDValue();
7534   };
7535   if (SDValue V1Pack = GetPackNode(V1))
7536     if (SDValue V2Pack = GetPackNode(V2))
7537       return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7538                          DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8,
7539                                      Mask[0] == 0 ? V1Pack.getOperand(0)
7540                                                   : V1Pack.getOperand(1),
7541                                      Mask[1] == 2 ? V2Pack.getOperand(0)
7542                                                   : V2Pack.getOperand(1)));
7543
7544   // Try to use shift instructions.
7545   if (SDValue Shift =
7546           lowerVectorShuffleAsShift(DL, MVT::v2i64, V1, V2, Mask, DAG))
7547     return Shift;
7548
7549   // When loading a scalar and then shuffling it into a vector we can often do
7550   // the insertion cheaply.
7551   if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7552           DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
7553     return Insertion;
7554   // Try inverting the insertion since for v2 masks it is easy to do and we
7555   // can't reliably sort the mask one way or the other.
7556   int InverseMask[2] = {Mask[0] ^ 2, Mask[1] ^ 2};
7557   if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7558           DL, MVT::v2i64, V2, V1, InverseMask, Subtarget, DAG))
7559     return Insertion;
7560
7561   // We have different paths for blend lowering, but they all must use the
7562   // *exact* same predicate.
7563   bool IsBlendSupported = Subtarget->hasSSE41();
7564   if (IsBlendSupported)
7565     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2i64, V1, V2, Mask,
7566                                                   Subtarget, DAG))
7567       return Blend;
7568
7569   // Use dedicated unpack instructions for masks that match their pattern.
7570   if (isShuffleEquivalent(V1, V2, Mask, {0, 2}))
7571     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, V1, V2);
7572   if (isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7573     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2i64, V1, V2);
7574
7575   // Try to use byte rotation instructions.
7576   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
7577   if (Subtarget->hasSSSE3())
7578     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
7579             DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
7580       return Rotate;
7581
7582   // If we have direct support for blends, we should lower by decomposing into
7583   // a permute. That will be faster than the domain cross.
7584   if (IsBlendSupported)
7585     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v2i64, V1, V2,
7586                                                       Mask, DAG);
7587
7588   // We implement this with SHUFPD which is pretty lame because it will likely
7589   // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
7590   // However, all the alternatives are still more cycles and newer chips don't
7591   // have this problem. It would be really nice if x86 had better shuffles here.
7592   V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V1);
7593   V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V2);
7594   return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7595                      DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
7596 }
7597
7598 /// \brief Test whether this can be lowered with a single SHUFPS instruction.
7599 ///
7600 /// This is used to disable more specialized lowerings when the shufps lowering
7601 /// will happen to be efficient.
7602 static bool isSingleSHUFPSMask(ArrayRef<int> Mask) {
7603   // This routine only handles 128-bit shufps.
7604   assert(Mask.size() == 4 && "Unsupported mask size!");
7605
7606   // To lower with a single SHUFPS we need to have the low half and high half
7607   // each requiring a single input.
7608   if (Mask[0] != -1 && Mask[1] != -1 && (Mask[0] < 4) != (Mask[1] < 4))
7609     return false;
7610   if (Mask[2] != -1 && Mask[3] != -1 && (Mask[2] < 4) != (Mask[3] < 4))
7611     return false;
7612
7613   return true;
7614 }
7615
7616 /// \brief Lower a vector shuffle using the SHUFPS instruction.
7617 ///
7618 /// This is a helper routine dedicated to lowering vector shuffles using SHUFPS.
7619 /// It makes no assumptions about whether this is the *best* lowering, it simply
7620 /// uses it.
7621 static SDValue lowerVectorShuffleWithSHUFPS(SDLoc DL, MVT VT,
7622                                             ArrayRef<int> Mask, SDValue V1,
7623                                             SDValue V2, SelectionDAG &DAG) {
7624   SDValue LowV = V1, HighV = V2;
7625   int NewMask[4] = {Mask[0], Mask[1], Mask[2], Mask[3]};
7626
7627   int NumV2Elements =
7628       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7629
7630   if (NumV2Elements == 1) {
7631     int V2Index =
7632         std::find_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; }) -
7633         Mask.begin();
7634
7635     // Compute the index adjacent to V2Index and in the same half by toggling
7636     // the low bit.
7637     int V2AdjIndex = V2Index ^ 1;
7638
7639     if (Mask[V2AdjIndex] == -1) {
7640       // Handles all the cases where we have a single V2 element and an undef.
7641       // This will only ever happen in the high lanes because we commute the
7642       // vector otherwise.
7643       if (V2Index < 2)
7644         std::swap(LowV, HighV);
7645       NewMask[V2Index] -= 4;
7646     } else {
7647       // Handle the case where the V2 element ends up adjacent to a V1 element.
7648       // To make this work, blend them together as the first step.
7649       int V1Index = V2AdjIndex;
7650       int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
7651       V2 = DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
7652                        getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
7653
7654       // Now proceed to reconstruct the final blend as we have the necessary
7655       // high or low half formed.
7656       if (V2Index < 2) {
7657         LowV = V2;
7658         HighV = V1;
7659       } else {
7660         HighV = V2;
7661       }
7662       NewMask[V1Index] = 2; // We put the V1 element in V2[2].
7663       NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
7664     }
7665   } else if (NumV2Elements == 2) {
7666     if (Mask[0] < 4 && Mask[1] < 4) {
7667       // Handle the easy case where we have V1 in the low lanes and V2 in the
7668       // high lanes.
7669       NewMask[2] -= 4;
7670       NewMask[3] -= 4;
7671     } else if (Mask[2] < 4 && Mask[3] < 4) {
7672       // We also handle the reversed case because this utility may get called
7673       // when we detect a SHUFPS pattern but can't easily commute the shuffle to
7674       // arrange things in the right direction.
7675       NewMask[0] -= 4;
7676       NewMask[1] -= 4;
7677       HighV = V1;
7678       LowV = V2;
7679     } else {
7680       // We have a mixture of V1 and V2 in both low and high lanes. Rather than
7681       // trying to place elements directly, just blend them and set up the final
7682       // shuffle to place them.
7683
7684       // The first two blend mask elements are for V1, the second two are for
7685       // V2.
7686       int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
7687                           Mask[2] < 4 ? Mask[2] : Mask[3],
7688                           (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
7689                           (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
7690       V1 = DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
7691                        getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
7692
7693       // Now we do a normal shuffle of V1 by giving V1 as both operands to
7694       // a blend.
7695       LowV = HighV = V1;
7696       NewMask[0] = Mask[0] < 4 ? 0 : 2;
7697       NewMask[1] = Mask[0] < 4 ? 2 : 0;
7698       NewMask[2] = Mask[2] < 4 ? 1 : 3;
7699       NewMask[3] = Mask[2] < 4 ? 3 : 1;
7700     }
7701   }
7702   return DAG.getNode(X86ISD::SHUFP, DL, VT, LowV, HighV,
7703                      getV4X86ShuffleImm8ForMask(NewMask, DL, DAG));
7704 }
7705
7706 /// \brief Lower 4-lane 32-bit floating point shuffles.
7707 ///
7708 /// Uses instructions exclusively from the floating point unit to minimize
7709 /// domain crossing penalties, as these are sufficient to implement all v4f32
7710 /// shuffles.
7711 static SDValue lowerV4F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7712                                        const X86Subtarget *Subtarget,
7713                                        SelectionDAG &DAG) {
7714   SDLoc DL(Op);
7715   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
7716   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7717   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7718   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7719   ArrayRef<int> Mask = SVOp->getMask();
7720   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7721
7722   int NumV2Elements =
7723       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7724
7725   if (NumV2Elements == 0) {
7726     // Check for being able to broadcast a single element.
7727     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f32, V1,
7728                                                           Mask, Subtarget, DAG))
7729       return Broadcast;
7730
7731     // Use even/odd duplicate instructions for masks that match their pattern.
7732     if (Subtarget->hasSSE3()) {
7733       if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
7734         return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v4f32, V1);
7735       if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3}))
7736         return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v4f32, V1);
7737     }
7738
7739     if (Subtarget->hasAVX()) {
7740       // If we have AVX, we can use VPERMILPS which will allow folding a load
7741       // into the shuffle.
7742       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f32, V1,
7743                          getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
7744     }
7745
7746     // Otherwise, use a straight shuffle of a single input vector. We pass the
7747     // input vector to both operands to simulate this with a SHUFPS.
7748     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
7749                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
7750   }
7751
7752   // There are special ways we can lower some single-element blends. However, we
7753   // have custom ways we can lower more complex single-element blends below that
7754   // we defer to if both this and BLENDPS fail to match, so restrict this to
7755   // when the V2 input is targeting element 0 of the mask -- that is the fast
7756   // case here.
7757   if (NumV2Elements == 1 && Mask[0] >= 4)
7758     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4f32, V1, V2,
7759                                                          Mask, Subtarget, DAG))
7760       return V;
7761
7762   if (Subtarget->hasSSE41()) {
7763     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f32, V1, V2, Mask,
7764                                                   Subtarget, DAG))
7765       return Blend;
7766
7767     // Use INSERTPS if we can complete the shuffle efficiently.
7768     if (SDValue V = lowerVectorShuffleAsInsertPS(Op, V1, V2, Mask, DAG))
7769       return V;
7770
7771     if (!isSingleSHUFPSMask(Mask))
7772       if (SDValue BlendPerm = lowerVectorShuffleAsBlendAndPermute(
7773               DL, MVT::v4f32, V1, V2, Mask, DAG))
7774         return BlendPerm;
7775   }
7776
7777   // Use dedicated unpack instructions for masks that match their pattern.
7778   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 1, 5}))
7779     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V1, V2);
7780   if (isShuffleEquivalent(V1, V2, Mask, {2, 6, 3, 7}))
7781     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V1, V2);
7782   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 5, 1}))
7783     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V2, V1);
7784   if (isShuffleEquivalent(V1, V2, Mask, {6, 2, 7, 3}))
7785     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V2, V1);
7786
7787   // Otherwise fall back to a SHUFPS lowering strategy.
7788   return lowerVectorShuffleWithSHUFPS(DL, MVT::v4f32, Mask, V1, V2, DAG);
7789 }
7790
7791 /// \brief Lower 4-lane i32 vector shuffles.
7792 ///
7793 /// We try to handle these with integer-domain shuffles where we can, but for
7794 /// blends we use the floating point domain blend instructions.
7795 static SDValue lowerV4I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7796                                        const X86Subtarget *Subtarget,
7797                                        SelectionDAG &DAG) {
7798   SDLoc DL(Op);
7799   assert(Op.getSimpleValueType() == MVT::v4i32 && "Bad shuffle type!");
7800   assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
7801   assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
7802   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7803   ArrayRef<int> Mask = SVOp->getMask();
7804   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7805
7806   // Whenever we can lower this as a zext, that instruction is strictly faster
7807   // than any alternative. It also allows us to fold memory operands into the
7808   // shuffle in many cases.
7809   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v4i32, V1, V2,
7810                                                          Mask, Subtarget, DAG))
7811     return ZExt;
7812
7813   int NumV2Elements =
7814       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7815
7816   if (NumV2Elements == 0) {
7817     // Check for being able to broadcast a single element.
7818     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i32, V1,
7819                                                           Mask, Subtarget, DAG))
7820       return Broadcast;
7821
7822     // Straight shuffle of a single input vector. For everything from SSE2
7823     // onward this has a single fast instruction with no scary immediates.
7824     // We coerce the shuffle pattern to be compatible with UNPCK instructions
7825     // but we aren't actually going to use the UNPCK instruction because doing
7826     // so prevents folding a load into this instruction or making a copy.
7827     const int UnpackLoMask[] = {0, 0, 1, 1};
7828     const int UnpackHiMask[] = {2, 2, 3, 3};
7829     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 1, 1}))
7830       Mask = UnpackLoMask;
7831     else if (isShuffleEquivalent(V1, V2, Mask, {2, 2, 3, 3}))
7832       Mask = UnpackHiMask;
7833
7834     return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
7835                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
7836   }
7837
7838   // Try to use shift instructions.
7839   if (SDValue Shift =
7840           lowerVectorShuffleAsShift(DL, MVT::v4i32, V1, V2, Mask, DAG))
7841     return Shift;
7842
7843   // There are special ways we can lower some single-element blends.
7844   if (NumV2Elements == 1)
7845     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4i32, V1, V2,
7846                                                          Mask, Subtarget, DAG))
7847       return V;
7848
7849   // We have different paths for blend lowering, but they all must use the
7850   // *exact* same predicate.
7851   bool IsBlendSupported = Subtarget->hasSSE41();
7852   if (IsBlendSupported)
7853     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i32, V1, V2, Mask,
7854                                                   Subtarget, DAG))
7855       return Blend;
7856
7857   if (SDValue Masked =
7858           lowerVectorShuffleAsBitMask(DL, MVT::v4i32, V1, V2, Mask, DAG))
7859     return Masked;
7860
7861   // Use dedicated unpack instructions for masks that match their pattern.
7862   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 1, 5}))
7863     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V1, V2);
7864   if (isShuffleEquivalent(V1, V2, Mask, {2, 6, 3, 7}))
7865     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V1, V2);
7866   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 5, 1}))
7867     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V2, V1);
7868   if (isShuffleEquivalent(V1, V2, Mask, {6, 2, 7, 3}))
7869     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V2, V1);
7870
7871   // Try to use byte rotation instructions.
7872   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
7873   if (Subtarget->hasSSSE3())
7874     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
7875             DL, MVT::v4i32, V1, V2, Mask, Subtarget, DAG))
7876       return Rotate;
7877
7878   // If we have direct support for blends, we should lower by decomposing into
7879   // a permute. That will be faster than the domain cross.
7880   if (IsBlendSupported)
7881     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i32, V1, V2,
7882                                                       Mask, DAG);
7883
7884   // Try to lower by permuting the inputs into an unpack instruction.
7885   if (SDValue Unpack =
7886           lowerVectorShuffleAsUnpack(DL, MVT::v4i32, V1, V2, Mask, DAG))
7887     return Unpack;
7888
7889   // We implement this with SHUFPS because it can blend from two vectors.
7890   // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
7891   // up the inputs, bypassing domain shift penalties that we would encur if we
7892   // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
7893   // relevant.
7894   return DAG.getNode(ISD::BITCAST, DL, MVT::v4i32,
7895                      DAG.getVectorShuffle(
7896                          MVT::v4f32, DL,
7897                          DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V1),
7898                          DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V2), Mask));
7899 }
7900
7901 /// \brief Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
7902 /// shuffle lowering, and the most complex part.
7903 ///
7904 /// The lowering strategy is to try to form pairs of input lanes which are
7905 /// targeted at the same half of the final vector, and then use a dword shuffle
7906 /// to place them onto the right half, and finally unpack the paired lanes into
7907 /// their final position.
7908 ///
7909 /// The exact breakdown of how to form these dword pairs and align them on the
7910 /// correct sides is really tricky. See the comments within the function for
7911 /// more of the details.
7912 ///
7913 /// This code also handles repeated 128-bit lanes of v8i16 shuffles, but each
7914 /// lane must shuffle the *exact* same way. In fact, you must pass a v8 Mask to
7915 /// this routine for it to work correctly. To shuffle a 256-bit or 512-bit i16
7916 /// vector, form the analogous 128-bit 8-element Mask.
7917 static SDValue lowerV8I16GeneralSingleInputVectorShuffle(
7918     SDLoc DL, MVT VT, SDValue V, MutableArrayRef<int> Mask,
7919     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7920   assert(VT.getScalarType() == MVT::i16 && "Bad input type!");
7921   MVT PSHUFDVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
7922
7923   assert(Mask.size() == 8 && "Shuffle mask length doen't match!");
7924   MutableArrayRef<int> LoMask = Mask.slice(0, 4);
7925   MutableArrayRef<int> HiMask = Mask.slice(4, 4);
7926
7927   SmallVector<int, 4> LoInputs;
7928   std::copy_if(LoMask.begin(), LoMask.end(), std::back_inserter(LoInputs),
7929                [](int M) { return M >= 0; });
7930   std::sort(LoInputs.begin(), LoInputs.end());
7931   LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()), LoInputs.end());
7932   SmallVector<int, 4> HiInputs;
7933   std::copy_if(HiMask.begin(), HiMask.end(), std::back_inserter(HiInputs),
7934                [](int M) { return M >= 0; });
7935   std::sort(HiInputs.begin(), HiInputs.end());
7936   HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()), HiInputs.end());
7937   int NumLToL =
7938       std::lower_bound(LoInputs.begin(), LoInputs.end(), 4) - LoInputs.begin();
7939   int NumHToL = LoInputs.size() - NumLToL;
7940   int NumLToH =
7941       std::lower_bound(HiInputs.begin(), HiInputs.end(), 4) - HiInputs.begin();
7942   int NumHToH = HiInputs.size() - NumLToH;
7943   MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
7944   MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
7945   MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
7946   MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
7947
7948   // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
7949   // such inputs we can swap two of the dwords across the half mark and end up
7950   // with <=2 inputs to each half in each half. Once there, we can fall through
7951   // to the generic code below. For example:
7952   //
7953   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
7954   // Mask:  [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
7955   //
7956   // However in some very rare cases we have a 1-into-3 or 3-into-1 on one half
7957   // and an existing 2-into-2 on the other half. In this case we may have to
7958   // pre-shuffle the 2-into-2 half to avoid turning it into a 3-into-1 or
7959   // 1-into-3 which could cause us to cycle endlessly fixing each side in turn.
7960   // Fortunately, we don't have to handle anything but a 2-into-2 pattern
7961   // because any other situation (including a 3-into-1 or 1-into-3 in the other
7962   // half than the one we target for fixing) will be fixed when we re-enter this
7963   // path. We will also combine away any sequence of PSHUFD instructions that
7964   // result into a single instruction. Here is an example of the tricky case:
7965   //
7966   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
7967   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -THIS-IS-BAD!!!!-> [5, 7, 1, 0, 4, 7, 5, 3]
7968   //
7969   // This now has a 1-into-3 in the high half! Instead, we do two shuffles:
7970   //
7971   // Input: [a, b, c, d, e, f, g, h] PSHUFHW[0,2,1,3]-> [a, b, c, d, e, g, f, h]
7972   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -----------------> [3, 7, 1, 0, 2, 7, 3, 6]
7973   //
7974   // Input: [a, b, c, d, e, g, f, h] -PSHUFD[0,2,1,3]-> [a, b, e, g, c, d, f, h]
7975   // Mask:  [3, 7, 1, 0, 2, 7, 3, 6] -----------------> [5, 7, 1, 0, 4, 7, 5, 6]
7976   //
7977   // The result is fine to be handled by the generic logic.
7978   auto balanceSides = [&](ArrayRef<int> AToAInputs, ArrayRef<int> BToAInputs,
7979                           ArrayRef<int> BToBInputs, ArrayRef<int> AToBInputs,
7980                           int AOffset, int BOffset) {
7981     assert((AToAInputs.size() == 3 || AToAInputs.size() == 1) &&
7982            "Must call this with A having 3 or 1 inputs from the A half.");
7983     assert((BToAInputs.size() == 1 || BToAInputs.size() == 3) &&
7984            "Must call this with B having 1 or 3 inputs from the B half.");
7985     assert(AToAInputs.size() + BToAInputs.size() == 4 &&
7986            "Must call this with either 3:1 or 1:3 inputs (summing to 4).");
7987
7988     // Compute the index of dword with only one word among the three inputs in
7989     // a half by taking the sum of the half with three inputs and subtracting
7990     // the sum of the actual three inputs. The difference is the remaining
7991     // slot.
7992     int ADWord, BDWord;
7993     int &TripleDWord = AToAInputs.size() == 3 ? ADWord : BDWord;
7994     int &OneInputDWord = AToAInputs.size() == 3 ? BDWord : ADWord;
7995     int TripleInputOffset = AToAInputs.size() == 3 ? AOffset : BOffset;
7996     ArrayRef<int> TripleInputs = AToAInputs.size() == 3 ? AToAInputs : BToAInputs;
7997     int OneInput = AToAInputs.size() == 3 ? BToAInputs[0] : AToAInputs[0];
7998     int TripleInputSum = 0 + 1 + 2 + 3 + (4 * TripleInputOffset);
7999     int TripleNonInputIdx =
8000         TripleInputSum - std::accumulate(TripleInputs.begin(), TripleInputs.end(), 0);
8001     TripleDWord = TripleNonInputIdx / 2;
8002
8003     // We use xor with one to compute the adjacent DWord to whichever one the
8004     // OneInput is in.
8005     OneInputDWord = (OneInput / 2) ^ 1;
8006
8007     // Check for one tricky case: We're fixing a 3<-1 or a 1<-3 shuffle for AToA
8008     // and BToA inputs. If there is also such a problem with the BToB and AToB
8009     // inputs, we don't try to fix it necessarily -- we'll recurse and see it in
8010     // the next pass. However, if we have a 2<-2 in the BToB and AToB inputs, it
8011     // is essential that we don't *create* a 3<-1 as then we might oscillate.
8012     if (BToBInputs.size() == 2 && AToBInputs.size() == 2) {
8013       // Compute how many inputs will be flipped by swapping these DWords. We
8014       // need
8015       // to balance this to ensure we don't form a 3-1 shuffle in the other
8016       // half.
8017       int NumFlippedAToBInputs =
8018           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord) +
8019           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord + 1);
8020       int NumFlippedBToBInputs =
8021           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord) +
8022           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord + 1);
8023       if ((NumFlippedAToBInputs == 1 &&
8024            (NumFlippedBToBInputs == 0 || NumFlippedBToBInputs == 2)) ||
8025           (NumFlippedBToBInputs == 1 &&
8026            (NumFlippedAToBInputs == 0 || NumFlippedAToBInputs == 2))) {
8027         // We choose whether to fix the A half or B half based on whether that
8028         // half has zero flipped inputs. At zero, we may not be able to fix it
8029         // with that half. We also bias towards fixing the B half because that
8030         // will more commonly be the high half, and we have to bias one way.
8031         auto FixFlippedInputs = [&V, &DL, &Mask, &DAG](int PinnedIdx, int DWord,
8032                                                        ArrayRef<int> Inputs) {
8033           int FixIdx = PinnedIdx ^ 1; // The adjacent slot to the pinned slot.
8034           bool IsFixIdxInput = std::find(Inputs.begin(), Inputs.end(),
8035                                          PinnedIdx ^ 1) != Inputs.end();
8036           // Determine whether the free index is in the flipped dword or the
8037           // unflipped dword based on where the pinned index is. We use this bit
8038           // in an xor to conditionally select the adjacent dword.
8039           int FixFreeIdx = 2 * (DWord ^ (PinnedIdx / 2 == DWord));
8040           bool IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
8041                                              FixFreeIdx) != Inputs.end();
8042           if (IsFixIdxInput == IsFixFreeIdxInput)
8043             FixFreeIdx += 1;
8044           IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
8045                                         FixFreeIdx) != Inputs.end();
8046           assert(IsFixIdxInput != IsFixFreeIdxInput &&
8047                  "We need to be changing the number of flipped inputs!");
8048           int PSHUFHalfMask[] = {0, 1, 2, 3};
8049           std::swap(PSHUFHalfMask[FixFreeIdx % 4], PSHUFHalfMask[FixIdx % 4]);
8050           V = DAG.getNode(FixIdx < 4 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW, DL,
8051                           MVT::v8i16, V,
8052                           getV4X86ShuffleImm8ForMask(PSHUFHalfMask, DL, DAG));
8053
8054           for (int &M : Mask)
8055             if (M != -1 && M == FixIdx)
8056               M = FixFreeIdx;
8057             else if (M != -1 && M == FixFreeIdx)
8058               M = FixIdx;
8059         };
8060         if (NumFlippedBToBInputs != 0) {
8061           int BPinnedIdx =
8062               BToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
8063           FixFlippedInputs(BPinnedIdx, BDWord, BToBInputs);
8064         } else {
8065           assert(NumFlippedAToBInputs != 0 && "Impossible given predicates!");
8066           int APinnedIdx =
8067               AToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
8068           FixFlippedInputs(APinnedIdx, ADWord, AToBInputs);
8069         }
8070       }
8071     }
8072
8073     int PSHUFDMask[] = {0, 1, 2, 3};
8074     PSHUFDMask[ADWord] = BDWord;
8075     PSHUFDMask[BDWord] = ADWord;
8076     V = DAG.getNode(ISD::BITCAST, DL, VT,
8077                     DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT,
8078                                 DAG.getNode(ISD::BITCAST, DL, PSHUFDVT, V),
8079                                 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL,
8080                                                            DAG)));
8081
8082     // Adjust the mask to match the new locations of A and B.
8083     for (int &M : Mask)
8084       if (M != -1 && M/2 == ADWord)
8085         M = 2 * BDWord + M % 2;
8086       else if (M != -1 && M/2 == BDWord)
8087         M = 2 * ADWord + M % 2;
8088
8089     // Recurse back into this routine to re-compute state now that this isn't
8090     // a 3 and 1 problem.
8091     return lowerV8I16GeneralSingleInputVectorShuffle(DL, VT, V, Mask, Subtarget,
8092                                                      DAG);
8093   };
8094   if ((NumLToL == 3 && NumHToL == 1) || (NumLToL == 1 && NumHToL == 3))
8095     return balanceSides(LToLInputs, HToLInputs, HToHInputs, LToHInputs, 0, 4);
8096   else if ((NumHToH == 3 && NumLToH == 1) || (NumHToH == 1 && NumLToH == 3))
8097     return balanceSides(HToHInputs, LToHInputs, LToLInputs, HToLInputs, 4, 0);
8098
8099   // At this point there are at most two inputs to the low and high halves from
8100   // each half. That means the inputs can always be grouped into dwords and
8101   // those dwords can then be moved to the correct half with a dword shuffle.
8102   // We use at most one low and one high word shuffle to collect these paired
8103   // inputs into dwords, and finally a dword shuffle to place them.
8104   int PSHUFLMask[4] = {-1, -1, -1, -1};
8105   int PSHUFHMask[4] = {-1, -1, -1, -1};
8106   int PSHUFDMask[4] = {-1, -1, -1, -1};
8107
8108   // First fix the masks for all the inputs that are staying in their
8109   // original halves. This will then dictate the targets of the cross-half
8110   // shuffles.
8111   auto fixInPlaceInputs =
8112       [&PSHUFDMask](ArrayRef<int> InPlaceInputs, ArrayRef<int> IncomingInputs,
8113                     MutableArrayRef<int> SourceHalfMask,
8114                     MutableArrayRef<int> HalfMask, int HalfOffset) {
8115     if (InPlaceInputs.empty())
8116       return;
8117     if (InPlaceInputs.size() == 1) {
8118       SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8119           InPlaceInputs[0] - HalfOffset;
8120       PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
8121       return;
8122     }
8123     if (IncomingInputs.empty()) {
8124       // Just fix all of the in place inputs.
8125       for (int Input : InPlaceInputs) {
8126         SourceHalfMask[Input - HalfOffset] = Input - HalfOffset;
8127         PSHUFDMask[Input / 2] = Input / 2;
8128       }
8129       return;
8130     }
8131
8132     assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!");
8133     SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8134         InPlaceInputs[0] - HalfOffset;
8135     // Put the second input next to the first so that they are packed into
8136     // a dword. We find the adjacent index by toggling the low bit.
8137     int AdjIndex = InPlaceInputs[0] ^ 1;
8138     SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
8139     std::replace(HalfMask.begin(), HalfMask.end(), InPlaceInputs[1], AdjIndex);
8140     PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
8141   };
8142   fixInPlaceInputs(LToLInputs, HToLInputs, PSHUFLMask, LoMask, 0);
8143   fixInPlaceInputs(HToHInputs, LToHInputs, PSHUFHMask, HiMask, 4);
8144
8145   // Now gather the cross-half inputs and place them into a free dword of
8146   // their target half.
8147   // FIXME: This operation could almost certainly be simplified dramatically to
8148   // look more like the 3-1 fixing operation.
8149   auto moveInputsToRightHalf = [&PSHUFDMask](
8150       MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
8151       MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
8152       MutableArrayRef<int> FinalSourceHalfMask, int SourceOffset,
8153       int DestOffset) {
8154     auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
8155       return SourceHalfMask[Word] != -1 && SourceHalfMask[Word] != Word;
8156     };
8157     auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
8158                                                int Word) {
8159       int LowWord = Word & ~1;
8160       int HighWord = Word | 1;
8161       return isWordClobbered(SourceHalfMask, LowWord) ||
8162              isWordClobbered(SourceHalfMask, HighWord);
8163     };
8164
8165     if (IncomingInputs.empty())
8166       return;
8167
8168     if (ExistingInputs.empty()) {
8169       // Map any dwords with inputs from them into the right half.
8170       for (int Input : IncomingInputs) {
8171         // If the source half mask maps over the inputs, turn those into
8172         // swaps and use the swapped lane.
8173         if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
8174           if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] == -1) {
8175             SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
8176                 Input - SourceOffset;
8177             // We have to swap the uses in our half mask in one sweep.
8178             for (int &M : HalfMask)
8179               if (M == SourceHalfMask[Input - SourceOffset] + SourceOffset)
8180                 M = Input;
8181               else if (M == Input)
8182                 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8183           } else {
8184             assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==
8185                        Input - SourceOffset &&
8186                    "Previous placement doesn't match!");
8187           }
8188           // Note that this correctly re-maps both when we do a swap and when
8189           // we observe the other side of the swap above. We rely on that to
8190           // avoid swapping the members of the input list directly.
8191           Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8192         }
8193
8194         // Map the input's dword into the correct half.
8195         if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] == -1)
8196           PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
8197         else
8198           assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==
8199                      Input / 2 &&
8200                  "Previous placement doesn't match!");
8201       }
8202
8203       // And just directly shift any other-half mask elements to be same-half
8204       // as we will have mirrored the dword containing the element into the
8205       // same position within that half.
8206       for (int &M : HalfMask)
8207         if (M >= SourceOffset && M < SourceOffset + 4) {
8208           M = M - SourceOffset + DestOffset;
8209           assert(M >= 0 && "This should never wrap below zero!");
8210         }
8211       return;
8212     }
8213
8214     // Ensure we have the input in a viable dword of its current half. This
8215     // is particularly tricky because the original position may be clobbered
8216     // by inputs being moved and *staying* in that half.
8217     if (IncomingInputs.size() == 1) {
8218       if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8219         int InputFixed = std::find(std::begin(SourceHalfMask),
8220                                    std::end(SourceHalfMask), -1) -
8221                          std::begin(SourceHalfMask) + SourceOffset;
8222         SourceHalfMask[InputFixed - SourceOffset] =
8223             IncomingInputs[0] - SourceOffset;
8224         std::replace(HalfMask.begin(), HalfMask.end(), IncomingInputs[0],
8225                      InputFixed);
8226         IncomingInputs[0] = InputFixed;
8227       }
8228     } else if (IncomingInputs.size() == 2) {
8229       if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
8230           isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8231         // We have two non-adjacent or clobbered inputs we need to extract from
8232         // the source half. To do this, we need to map them into some adjacent
8233         // dword slot in the source mask.
8234         int InputsFixed[2] = {IncomingInputs[0] - SourceOffset,
8235                               IncomingInputs[1] - SourceOffset};
8236
8237         // If there is a free slot in the source half mask adjacent to one of
8238         // the inputs, place the other input in it. We use (Index XOR 1) to
8239         // compute an adjacent index.
8240         if (!isWordClobbered(SourceHalfMask, InputsFixed[0]) &&
8241             SourceHalfMask[InputsFixed[0] ^ 1] == -1) {
8242           SourceHalfMask[InputsFixed[0]] = InputsFixed[0];
8243           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8244           InputsFixed[1] = InputsFixed[0] ^ 1;
8245         } else if (!isWordClobbered(SourceHalfMask, InputsFixed[1]) &&
8246                    SourceHalfMask[InputsFixed[1] ^ 1] == -1) {
8247           SourceHalfMask[InputsFixed[1]] = InputsFixed[1];
8248           SourceHalfMask[InputsFixed[1] ^ 1] = InputsFixed[0];
8249           InputsFixed[0] = InputsFixed[1] ^ 1;
8250         } else if (SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] == -1 &&
8251                    SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] == -1) {
8252           // The two inputs are in the same DWord but it is clobbered and the
8253           // adjacent DWord isn't used at all. Move both inputs to the free
8254           // slot.
8255           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] = InputsFixed[0];
8256           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] = InputsFixed[1];
8257           InputsFixed[0] = 2 * ((InputsFixed[0] / 2) ^ 1);
8258           InputsFixed[1] = 2 * ((InputsFixed[0] / 2) ^ 1) + 1;
8259         } else {
8260           // The only way we hit this point is if there is no clobbering
8261           // (because there are no off-half inputs to this half) and there is no
8262           // free slot adjacent to one of the inputs. In this case, we have to
8263           // swap an input with a non-input.
8264           for (int i = 0; i < 4; ++i)
8265             assert((SourceHalfMask[i] == -1 || SourceHalfMask[i] == i) &&
8266                    "We can't handle any clobbers here!");
8267           assert(InputsFixed[1] != (InputsFixed[0] ^ 1) &&
8268                  "Cannot have adjacent inputs here!");
8269
8270           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8271           SourceHalfMask[InputsFixed[1]] = InputsFixed[0] ^ 1;
8272
8273           // We also have to update the final source mask in this case because
8274           // it may need to undo the above swap.
8275           for (int &M : FinalSourceHalfMask)
8276             if (M == (InputsFixed[0] ^ 1) + SourceOffset)
8277               M = InputsFixed[1] + SourceOffset;
8278             else if (M == InputsFixed[1] + SourceOffset)
8279               M = (InputsFixed[0] ^ 1) + SourceOffset;
8280
8281           InputsFixed[1] = InputsFixed[0] ^ 1;
8282         }
8283
8284         // Point everything at the fixed inputs.
8285         for (int &M : HalfMask)
8286           if (M == IncomingInputs[0])
8287             M = InputsFixed[0] + SourceOffset;
8288           else if (M == IncomingInputs[1])
8289             M = InputsFixed[1] + SourceOffset;
8290
8291         IncomingInputs[0] = InputsFixed[0] + SourceOffset;
8292         IncomingInputs[1] = InputsFixed[1] + SourceOffset;
8293       }
8294     } else {
8295       llvm_unreachable("Unhandled input size!");
8296     }
8297
8298     // Now hoist the DWord down to the right half.
8299     int FreeDWord = (PSHUFDMask[DestOffset / 2] == -1 ? 0 : 1) + DestOffset / 2;
8300     assert(PSHUFDMask[FreeDWord] == -1 && "DWord not free");
8301     PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
8302     for (int &M : HalfMask)
8303       for (int Input : IncomingInputs)
8304         if (M == Input)
8305           M = FreeDWord * 2 + Input % 2;
8306   };
8307   moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask, HiMask,
8308                         /*SourceOffset*/ 4, /*DestOffset*/ 0);
8309   moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask, LoMask,
8310                         /*SourceOffset*/ 0, /*DestOffset*/ 4);
8311
8312   // Now enact all the shuffles we've computed to move the inputs into their
8313   // target half.
8314   if (!isNoopShuffleMask(PSHUFLMask))
8315     V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
8316                     getV4X86ShuffleImm8ForMask(PSHUFLMask, DL, DAG));
8317   if (!isNoopShuffleMask(PSHUFHMask))
8318     V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
8319                     getV4X86ShuffleImm8ForMask(PSHUFHMask, DL, DAG));
8320   if (!isNoopShuffleMask(PSHUFDMask))
8321     V = DAG.getNode(ISD::BITCAST, DL, VT,
8322                     DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT,
8323                                 DAG.getNode(ISD::BITCAST, DL, PSHUFDVT, V),
8324                                 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL,
8325                                                            DAG)));
8326
8327   // At this point, each half should contain all its inputs, and we can then
8328   // just shuffle them into their final position.
8329   assert(std::count_if(LoMask.begin(), LoMask.end(),
8330                        [](int M) { return M >= 4; }) == 0 &&
8331          "Failed to lift all the high half inputs to the low mask!");
8332   assert(std::count_if(HiMask.begin(), HiMask.end(),
8333                        [](int M) { return M >= 0 && M < 4; }) == 0 &&
8334          "Failed to lift all the low half inputs to the high mask!");
8335
8336   // Do a half shuffle for the low mask.
8337   if (!isNoopShuffleMask(LoMask))
8338     V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
8339                     getV4X86ShuffleImm8ForMask(LoMask, DL, DAG));
8340
8341   // Do a half shuffle with the high mask after shifting its values down.
8342   for (int &M : HiMask)
8343     if (M >= 0)
8344       M -= 4;
8345   if (!isNoopShuffleMask(HiMask))
8346     V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
8347                     getV4X86ShuffleImm8ForMask(HiMask, DL, DAG));
8348
8349   return V;
8350 }
8351
8352 /// \brief Helper to form a PSHUFB-based shuffle+blend.
8353 static SDValue lowerVectorShuffleAsPSHUFB(SDLoc DL, MVT VT, SDValue V1,
8354                                           SDValue V2, ArrayRef<int> Mask,
8355                                           SelectionDAG &DAG, bool &V1InUse,
8356                                           bool &V2InUse) {
8357   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
8358   SDValue V1Mask[16];
8359   SDValue V2Mask[16];
8360   V1InUse = false;
8361   V2InUse = false;
8362
8363   int Size = Mask.size();
8364   int Scale = 16 / Size;
8365   for (int i = 0; i < 16; ++i) {
8366     if (Mask[i / Scale] == -1) {
8367       V1Mask[i] = V2Mask[i] = DAG.getUNDEF(MVT::i8);
8368     } else {
8369       const int ZeroMask = 0x80;
8370       int V1Idx = Mask[i / Scale] < Size ? Mask[i / Scale] * Scale + i % Scale
8371                                           : ZeroMask;
8372       int V2Idx = Mask[i / Scale] < Size
8373                       ? ZeroMask
8374                       : (Mask[i / Scale] - Size) * Scale + i % Scale;
8375       if (Zeroable[i / Scale])
8376         V1Idx = V2Idx = ZeroMask;
8377       V1Mask[i] = DAG.getConstant(V1Idx, DL, MVT::i8);
8378       V2Mask[i] = DAG.getConstant(V2Idx, DL, MVT::i8);
8379       V1InUse |= (ZeroMask != V1Idx);
8380       V2InUse |= (ZeroMask != V2Idx);
8381     }
8382   }
8383
8384   if (V1InUse)
8385     V1 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
8386                      DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, V1),
8387                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V1Mask));
8388   if (V2InUse)
8389     V2 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
8390                      DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, V2),
8391                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V2Mask));
8392
8393   // If we need shuffled inputs from both, blend the two.
8394   SDValue V;
8395   if (V1InUse && V2InUse)
8396     V = DAG.getNode(ISD::OR, DL, MVT::v16i8, V1, V2);
8397   else
8398     V = V1InUse ? V1 : V2;
8399
8400   // Cast the result back to the correct type.
8401   return DAG.getNode(ISD::BITCAST, DL, VT, V);
8402 }
8403
8404 /// \brief Generic lowering of 8-lane i16 shuffles.
8405 ///
8406 /// This handles both single-input shuffles and combined shuffle/blends with
8407 /// two inputs. The single input shuffles are immediately delegated to
8408 /// a dedicated lowering routine.
8409 ///
8410 /// The blends are lowered in one of three fundamental ways. If there are few
8411 /// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
8412 /// of the input is significantly cheaper when lowered as an interleaving of
8413 /// the two inputs, try to interleave them. Otherwise, blend the low and high
8414 /// halves of the inputs separately (making them have relatively few inputs)
8415 /// and then concatenate them.
8416 static SDValue lowerV8I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8417                                        const X86Subtarget *Subtarget,
8418                                        SelectionDAG &DAG) {
8419   SDLoc DL(Op);
8420   assert(Op.getSimpleValueType() == MVT::v8i16 && "Bad shuffle type!");
8421   assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
8422   assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
8423   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8424   ArrayRef<int> OrigMask = SVOp->getMask();
8425   int MaskStorage[8] = {OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
8426                         OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7]};
8427   MutableArrayRef<int> Mask(MaskStorage);
8428
8429   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
8430
8431   // Whenever we can lower this as a zext, that instruction is strictly faster
8432   // than any alternative.
8433   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
8434           DL, MVT::v8i16, V1, V2, OrigMask, Subtarget, DAG))
8435     return ZExt;
8436
8437   auto isV1 = [](int M) { return M >= 0 && M < 8; };
8438   (void)isV1;
8439   auto isV2 = [](int M) { return M >= 8; };
8440
8441   int NumV2Inputs = std::count_if(Mask.begin(), Mask.end(), isV2);
8442
8443   if (NumV2Inputs == 0) {
8444     // Check for being able to broadcast a single element.
8445     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i16, V1,
8446                                                           Mask, Subtarget, DAG))
8447       return Broadcast;
8448
8449     // Try to use shift instructions.
8450     if (SDValue Shift =
8451             lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V1, Mask, DAG))
8452       return Shift;
8453
8454     // Use dedicated unpack instructions for masks that match their pattern.
8455     if (isShuffleEquivalent(V1, V1, Mask, {0, 0, 1, 1, 2, 2, 3, 3}))
8456       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V1, V1);
8457     if (isShuffleEquivalent(V1, V1, Mask, {4, 4, 5, 5, 6, 6, 7, 7}))
8458       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V1, V1);
8459
8460     // Try to use byte rotation instructions.
8461     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(DL, MVT::v8i16, V1, V1,
8462                                                         Mask, Subtarget, DAG))
8463       return Rotate;
8464
8465     return lowerV8I16GeneralSingleInputVectorShuffle(DL, MVT::v8i16, V1, Mask,
8466                                                      Subtarget, DAG);
8467   }
8468
8469   assert(std::any_of(Mask.begin(), Mask.end(), isV1) &&
8470          "All single-input shuffles should be canonicalized to be V1-input "
8471          "shuffles.");
8472
8473   // Try to use shift instructions.
8474   if (SDValue Shift =
8475           lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V2, Mask, DAG))
8476     return Shift;
8477
8478   // There are special ways we can lower some single-element blends.
8479   if (NumV2Inputs == 1)
8480     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v8i16, V1, V2,
8481                                                          Mask, Subtarget, DAG))
8482       return V;
8483
8484   // We have different paths for blend lowering, but they all must use the
8485   // *exact* same predicate.
8486   bool IsBlendSupported = Subtarget->hasSSE41();
8487   if (IsBlendSupported)
8488     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i16, V1, V2, Mask,
8489                                                   Subtarget, DAG))
8490       return Blend;
8491
8492   if (SDValue Masked =
8493           lowerVectorShuffleAsBitMask(DL, MVT::v8i16, V1, V2, Mask, DAG))
8494     return Masked;
8495
8496   // Use dedicated unpack instructions for masks that match their pattern.
8497   if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 2, 10, 3, 11}))
8498     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V1, V2);
8499   if (isShuffleEquivalent(V1, V2, Mask, {4, 12, 5, 13, 6, 14, 7, 15}))
8500     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V1, V2);
8501
8502   // Try to use byte rotation instructions.
8503   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8504           DL, MVT::v8i16, V1, V2, Mask, Subtarget, DAG))
8505     return Rotate;
8506
8507   if (SDValue BitBlend =
8508           lowerVectorShuffleAsBitBlend(DL, MVT::v8i16, V1, V2, Mask, DAG))
8509     return BitBlend;
8510
8511   if (SDValue Unpack =
8512           lowerVectorShuffleAsUnpack(DL, MVT::v8i16, V1, V2, Mask, DAG))
8513     return Unpack;
8514
8515   // If we can't directly blend but can use PSHUFB, that will be better as it
8516   // can both shuffle and set up the inefficient blend.
8517   if (!IsBlendSupported && Subtarget->hasSSSE3()) {
8518     bool V1InUse, V2InUse;
8519     return lowerVectorShuffleAsPSHUFB(DL, MVT::v8i16, V1, V2, Mask, DAG,
8520                                       V1InUse, V2InUse);
8521   }
8522
8523   // We can always bit-blend if we have to so the fallback strategy is to
8524   // decompose into single-input permutes and blends.
8525   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i16, V1, V2,
8526                                                       Mask, DAG);
8527 }
8528
8529 /// \brief Check whether a compaction lowering can be done by dropping even
8530 /// elements and compute how many times even elements must be dropped.
8531 ///
8532 /// This handles shuffles which take every Nth element where N is a power of
8533 /// two. Example shuffle masks:
8534 ///
8535 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14,  0,  2,  4,  6,  8, 10, 12, 14
8536 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30
8537 ///  N = 2:  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12
8538 ///  N = 2:  0,  4,  8, 12, 16, 20, 24, 28,  0,  4,  8, 12, 16, 20, 24, 28
8539 ///  N = 3:  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8
8540 ///  N = 3:  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24
8541 ///
8542 /// Any of these lanes can of course be undef.
8543 ///
8544 /// This routine only supports N <= 3.
8545 /// FIXME: Evaluate whether either AVX or AVX-512 have any opportunities here
8546 /// for larger N.
8547 ///
8548 /// \returns N above, or the number of times even elements must be dropped if
8549 /// there is such a number. Otherwise returns zero.
8550 static int canLowerByDroppingEvenElements(ArrayRef<int> Mask) {
8551   // Figure out whether we're looping over two inputs or just one.
8552   bool IsSingleInput = isSingleInputShuffleMask(Mask);
8553
8554   // The modulus for the shuffle vector entries is based on whether this is
8555   // a single input or not.
8556   int ShuffleModulus = Mask.size() * (IsSingleInput ? 1 : 2);
8557   assert(isPowerOf2_32((uint32_t)ShuffleModulus) &&
8558          "We should only be called with masks with a power-of-2 size!");
8559
8560   uint64_t ModMask = (uint64_t)ShuffleModulus - 1;
8561
8562   // We track whether the input is viable for all power-of-2 strides 2^1, 2^2,
8563   // and 2^3 simultaneously. This is because we may have ambiguity with
8564   // partially undef inputs.
8565   bool ViableForN[3] = {true, true, true};
8566
8567   for (int i = 0, e = Mask.size(); i < e; ++i) {
8568     // Ignore undef lanes, we'll optimistically collapse them to the pattern we
8569     // want.
8570     if (Mask[i] == -1)
8571       continue;
8572
8573     bool IsAnyViable = false;
8574     for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
8575       if (ViableForN[j]) {
8576         uint64_t N = j + 1;
8577
8578         // The shuffle mask must be equal to (i * 2^N) % M.
8579         if ((uint64_t)Mask[i] == (((uint64_t)i << N) & ModMask))
8580           IsAnyViable = true;
8581         else
8582           ViableForN[j] = false;
8583       }
8584     // Early exit if we exhaust the possible powers of two.
8585     if (!IsAnyViable)
8586       break;
8587   }
8588
8589   for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
8590     if (ViableForN[j])
8591       return j + 1;
8592
8593   // Return 0 as there is no viable power of two.
8594   return 0;
8595 }
8596
8597 /// \brief Generic lowering of v16i8 shuffles.
8598 ///
8599 /// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
8600 /// detect any complexity reducing interleaving. If that doesn't help, it uses
8601 /// UNPCK to spread the i8 elements across two i16-element vectors, and uses
8602 /// the existing lowering for v8i16 blends on each half, finally PACK-ing them
8603 /// back together.
8604 static SDValue lowerV16I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8605                                        const X86Subtarget *Subtarget,
8606                                        SelectionDAG &DAG) {
8607   SDLoc DL(Op);
8608   assert(Op.getSimpleValueType() == MVT::v16i8 && "Bad shuffle type!");
8609   assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
8610   assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
8611   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8612   ArrayRef<int> Mask = SVOp->getMask();
8613   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
8614
8615   // Try to use shift instructions.
8616   if (SDValue Shift =
8617           lowerVectorShuffleAsShift(DL, MVT::v16i8, V1, V2, Mask, DAG))
8618     return Shift;
8619
8620   // Try to use byte rotation instructions.
8621   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8622           DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
8623     return Rotate;
8624
8625   // Try to use a zext lowering.
8626   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
8627           DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
8628     return ZExt;
8629
8630   int NumV2Elements =
8631       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 16; });
8632
8633   // For single-input shuffles, there are some nicer lowering tricks we can use.
8634   if (NumV2Elements == 0) {
8635     // Check for being able to broadcast a single element.
8636     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i8, V1,
8637                                                           Mask, Subtarget, DAG))
8638       return Broadcast;
8639
8640     // Check whether we can widen this to an i16 shuffle by duplicating bytes.
8641     // Notably, this handles splat and partial-splat shuffles more efficiently.
8642     // However, it only makes sense if the pre-duplication shuffle simplifies
8643     // things significantly. Currently, this means we need to be able to
8644     // express the pre-duplication shuffle as an i16 shuffle.
8645     //
8646     // FIXME: We should check for other patterns which can be widened into an
8647     // i16 shuffle as well.
8648     auto canWidenViaDuplication = [](ArrayRef<int> Mask) {
8649       for (int i = 0; i < 16; i += 2)
8650         if (Mask[i] != -1 && Mask[i + 1] != -1 && Mask[i] != Mask[i + 1])
8651           return false;
8652
8653       return true;
8654     };
8655     auto tryToWidenViaDuplication = [&]() -> SDValue {
8656       if (!canWidenViaDuplication(Mask))
8657         return SDValue();
8658       SmallVector<int, 4> LoInputs;
8659       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(LoInputs),
8660                    [](int M) { return M >= 0 && M < 8; });
8661       std::sort(LoInputs.begin(), LoInputs.end());
8662       LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()),
8663                      LoInputs.end());
8664       SmallVector<int, 4> HiInputs;
8665       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(HiInputs),
8666                    [](int M) { return M >= 8; });
8667       std::sort(HiInputs.begin(), HiInputs.end());
8668       HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()),
8669                      HiInputs.end());
8670
8671       bool TargetLo = LoInputs.size() >= HiInputs.size();
8672       ArrayRef<int> InPlaceInputs = TargetLo ? LoInputs : HiInputs;
8673       ArrayRef<int> MovingInputs = TargetLo ? HiInputs : LoInputs;
8674
8675       int PreDupI16Shuffle[] = {-1, -1, -1, -1, -1, -1, -1, -1};
8676       SmallDenseMap<int, int, 8> LaneMap;
8677       for (int I : InPlaceInputs) {
8678         PreDupI16Shuffle[I/2] = I/2;
8679         LaneMap[I] = I;
8680       }
8681       int j = TargetLo ? 0 : 4, je = j + 4;
8682       for (int i = 0, ie = MovingInputs.size(); i < ie; ++i) {
8683         // Check if j is already a shuffle of this input. This happens when
8684         // there are two adjacent bytes after we move the low one.
8685         if (PreDupI16Shuffle[j] != MovingInputs[i] / 2) {
8686           // If we haven't yet mapped the input, search for a slot into which
8687           // we can map it.
8688           while (j < je && PreDupI16Shuffle[j] != -1)
8689             ++j;
8690
8691           if (j == je)
8692             // We can't place the inputs into a single half with a simple i16 shuffle, so bail.
8693             return SDValue();
8694
8695           // Map this input with the i16 shuffle.
8696           PreDupI16Shuffle[j] = MovingInputs[i] / 2;
8697         }
8698
8699         // Update the lane map based on the mapping we ended up with.
8700         LaneMap[MovingInputs[i]] = 2 * j + MovingInputs[i] % 2;
8701       }
8702       V1 = DAG.getNode(
8703           ISD::BITCAST, DL, MVT::v16i8,
8704           DAG.getVectorShuffle(MVT::v8i16, DL,
8705                                DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1),
8706                                DAG.getUNDEF(MVT::v8i16), PreDupI16Shuffle));
8707
8708       // Unpack the bytes to form the i16s that will be shuffled into place.
8709       V1 = DAG.getNode(TargetLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
8710                        MVT::v16i8, V1, V1);
8711
8712       int PostDupI16Shuffle[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8713       for (int i = 0; i < 16; ++i)
8714         if (Mask[i] != -1) {
8715           int MappedMask = LaneMap[Mask[i]] - (TargetLo ? 0 : 8);
8716           assert(MappedMask < 8 && "Invalid v8 shuffle mask!");
8717           if (PostDupI16Shuffle[i / 2] == -1)
8718             PostDupI16Shuffle[i / 2] = MappedMask;
8719           else
8720             assert(PostDupI16Shuffle[i / 2] == MappedMask &&
8721                    "Conflicting entrties in the original shuffle!");
8722         }
8723       return DAG.getNode(
8724           ISD::BITCAST, DL, MVT::v16i8,
8725           DAG.getVectorShuffle(MVT::v8i16, DL,
8726                                DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1),
8727                                DAG.getUNDEF(MVT::v8i16), PostDupI16Shuffle));
8728     };
8729     if (SDValue V = tryToWidenViaDuplication())
8730       return V;
8731   }
8732
8733   // Use dedicated unpack instructions for masks that match their pattern.
8734   if (isShuffleEquivalent(V1, V2, Mask, {// Low half.
8735                                          0, 16, 1, 17, 2, 18, 3, 19,
8736                                          // High half.
8737                                          4, 20, 5, 21, 6, 22, 7, 23}))
8738     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V1, V2);
8739   if (isShuffleEquivalent(V1, V2, Mask, {// Low half.
8740                                          8, 24, 9, 25, 10, 26, 11, 27,
8741                                          // High half.
8742                                          12, 28, 13, 29, 14, 30, 15, 31}))
8743     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V1, V2);
8744
8745   // Check for SSSE3 which lets us lower all v16i8 shuffles much more directly
8746   // with PSHUFB. It is important to do this before we attempt to generate any
8747   // blends but after all of the single-input lowerings. If the single input
8748   // lowerings can find an instruction sequence that is faster than a PSHUFB, we
8749   // want to preserve that and we can DAG combine any longer sequences into
8750   // a PSHUFB in the end. But once we start blending from multiple inputs,
8751   // the complexity of DAG combining bad patterns back into PSHUFB is too high,
8752   // and there are *very* few patterns that would actually be faster than the
8753   // PSHUFB approach because of its ability to zero lanes.
8754   //
8755   // FIXME: The only exceptions to the above are blends which are exact
8756   // interleavings with direct instructions supporting them. We currently don't
8757   // handle those well here.
8758   if (Subtarget->hasSSSE3()) {
8759     bool V1InUse = false;
8760     bool V2InUse = false;
8761
8762     SDValue PSHUFB = lowerVectorShuffleAsPSHUFB(DL, MVT::v16i8, V1, V2, Mask,
8763                                                 DAG, V1InUse, V2InUse);
8764
8765     // If both V1 and V2 are in use and we can use a direct blend or an unpack,
8766     // do so. This avoids using them to handle blends-with-zero which is
8767     // important as a single pshufb is significantly faster for that.
8768     if (V1InUse && V2InUse) {
8769       if (Subtarget->hasSSE41())
8770         if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i8, V1, V2,
8771                                                       Mask, Subtarget, DAG))
8772           return Blend;
8773
8774       // We can use an unpack to do the blending rather than an or in some
8775       // cases. Even though the or may be (very minorly) more efficient, we
8776       // preference this lowering because there are common cases where part of
8777       // the complexity of the shuffles goes away when we do the final blend as
8778       // an unpack.
8779       // FIXME: It might be worth trying to detect if the unpack-feeding
8780       // shuffles will both be pshufb, in which case we shouldn't bother with
8781       // this.
8782       if (SDValue Unpack =
8783               lowerVectorShuffleAsUnpack(DL, MVT::v16i8, V1, V2, Mask, DAG))
8784         return Unpack;
8785     }
8786
8787     return PSHUFB;
8788   }
8789
8790   // There are special ways we can lower some single-element blends.
8791   if (NumV2Elements == 1)
8792     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v16i8, V1, V2,
8793                                                          Mask, Subtarget, DAG))
8794       return V;
8795
8796   if (SDValue BitBlend =
8797           lowerVectorShuffleAsBitBlend(DL, MVT::v16i8, V1, V2, Mask, DAG))
8798     return BitBlend;
8799
8800   // Check whether a compaction lowering can be done. This handles shuffles
8801   // which take every Nth element for some even N. See the helper function for
8802   // details.
8803   //
8804   // We special case these as they can be particularly efficiently handled with
8805   // the PACKUSB instruction on x86 and they show up in common patterns of
8806   // rearranging bytes to truncate wide elements.
8807   if (int NumEvenDrops = canLowerByDroppingEvenElements(Mask)) {
8808     // NumEvenDrops is the power of two stride of the elements. Another way of
8809     // thinking about it is that we need to drop the even elements this many
8810     // times to get the original input.
8811     bool IsSingleInput = isSingleInputShuffleMask(Mask);
8812
8813     // First we need to zero all the dropped bytes.
8814     assert(NumEvenDrops <= 3 &&
8815            "No support for dropping even elements more than 3 times.");
8816     // We use the mask type to pick which bytes are preserved based on how many
8817     // elements are dropped.
8818     MVT MaskVTs[] = { MVT::v8i16, MVT::v4i32, MVT::v2i64 };
8819     SDValue ByteClearMask =
8820         DAG.getNode(ISD::BITCAST, DL, MVT::v16i8,
8821                     DAG.getConstant(0xFF, DL, MaskVTs[NumEvenDrops - 1]));
8822     V1 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V1, ByteClearMask);
8823     if (!IsSingleInput)
8824       V2 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V2, ByteClearMask);
8825
8826     // Now pack things back together.
8827     V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1);
8828     V2 = IsSingleInput ? V1 : DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V2);
8829     SDValue Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, V1, V2);
8830     for (int i = 1; i < NumEvenDrops; ++i) {
8831       Result = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, Result);
8832       Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, Result, Result);
8833     }
8834
8835     return Result;
8836   }
8837
8838   // Handle multi-input cases by blending single-input shuffles.
8839   if (NumV2Elements > 0)
8840     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v16i8, V1, V2,
8841                                                       Mask, DAG);
8842
8843   // The fallback path for single-input shuffles widens this into two v8i16
8844   // vectors with unpacks, shuffles those, and then pulls them back together
8845   // with a pack.
8846   SDValue V = V1;
8847
8848   int LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8849   int HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8850   for (int i = 0; i < 16; ++i)
8851     if (Mask[i] >= 0)
8852       (i < 8 ? LoBlendMask[i] : HiBlendMask[i % 8]) = Mask[i];
8853
8854   SDValue Zero = getZeroVector(MVT::v8i16, Subtarget, DAG, DL);
8855
8856   SDValue VLoHalf, VHiHalf;
8857   // Check if any of the odd lanes in the v16i8 are used. If not, we can mask
8858   // them out and avoid using UNPCK{L,H} to extract the elements of V as
8859   // i16s.
8860   if (std::none_of(std::begin(LoBlendMask), std::end(LoBlendMask),
8861                    [](int M) { return M >= 0 && M % 2 == 1; }) &&
8862       std::none_of(std::begin(HiBlendMask), std::end(HiBlendMask),
8863                    [](int M) { return M >= 0 && M % 2 == 1; })) {
8864     // Use a mask to drop the high bytes.
8865     VLoHalf = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V);
8866     VLoHalf = DAG.getNode(ISD::AND, DL, MVT::v8i16, VLoHalf,
8867                      DAG.getConstant(0x00FF, DL, MVT::v8i16));
8868
8869     // This will be a single vector shuffle instead of a blend so nuke VHiHalf.
8870     VHiHalf = DAG.getUNDEF(MVT::v8i16);
8871
8872     // Squash the masks to point directly into VLoHalf.
8873     for (int &M : LoBlendMask)
8874       if (M >= 0)
8875         M /= 2;
8876     for (int &M : HiBlendMask)
8877       if (M >= 0)
8878         M /= 2;
8879   } else {
8880     // Otherwise just unpack the low half of V into VLoHalf and the high half into
8881     // VHiHalf so that we can blend them as i16s.
8882     VLoHalf = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
8883                      DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V, Zero));
8884     VHiHalf = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
8885                      DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V, Zero));
8886   }
8887
8888   SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, LoBlendMask);
8889   SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, HiBlendMask);
8890
8891   return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
8892 }
8893
8894 /// \brief Dispatching routine to lower various 128-bit x86 vector shuffles.
8895 ///
8896 /// This routine breaks down the specific type of 128-bit shuffle and
8897 /// dispatches to the lowering routines accordingly.
8898 static SDValue lower128BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8899                                         MVT VT, const X86Subtarget *Subtarget,
8900                                         SelectionDAG &DAG) {
8901   switch (VT.SimpleTy) {
8902   case MVT::v2i64:
8903     return lowerV2I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
8904   case MVT::v2f64:
8905     return lowerV2F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
8906   case MVT::v4i32:
8907     return lowerV4I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
8908   case MVT::v4f32:
8909     return lowerV4F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
8910   case MVT::v8i16:
8911     return lowerV8I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
8912   case MVT::v16i8:
8913     return lowerV16I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
8914
8915   default:
8916     llvm_unreachable("Unimplemented!");
8917   }
8918 }
8919
8920 /// \brief Helper function to test whether a shuffle mask could be
8921 /// simplified by widening the elements being shuffled.
8922 ///
8923 /// Appends the mask for wider elements in WidenedMask if valid. Otherwise
8924 /// leaves it in an unspecified state.
8925 ///
8926 /// NOTE: This must handle normal vector shuffle masks and *target* vector
8927 /// shuffle masks. The latter have the special property of a '-2' representing
8928 /// a zero-ed lane of a vector.
8929 static bool canWidenShuffleElements(ArrayRef<int> Mask,
8930                                     SmallVectorImpl<int> &WidenedMask) {
8931   for (int i = 0, Size = Mask.size(); i < Size; i += 2) {
8932     // If both elements are undef, its trivial.
8933     if (Mask[i] == SM_SentinelUndef && Mask[i + 1] == SM_SentinelUndef) {
8934       WidenedMask.push_back(SM_SentinelUndef);
8935       continue;
8936     }
8937
8938     // Check for an undef mask and a mask value properly aligned to fit with
8939     // a pair of values. If we find such a case, use the non-undef mask's value.
8940     if (Mask[i] == SM_SentinelUndef && Mask[i + 1] >= 0 && Mask[i + 1] % 2 == 1) {
8941       WidenedMask.push_back(Mask[i + 1] / 2);
8942       continue;
8943     }
8944     if (Mask[i + 1] == SM_SentinelUndef && Mask[i] >= 0 && Mask[i] % 2 == 0) {
8945       WidenedMask.push_back(Mask[i] / 2);
8946       continue;
8947     }
8948
8949     // When zeroing, we need to spread the zeroing across both lanes to widen.
8950     if (Mask[i] == SM_SentinelZero || Mask[i + 1] == SM_SentinelZero) {
8951       if ((Mask[i] == SM_SentinelZero || Mask[i] == SM_SentinelUndef) &&
8952           (Mask[i + 1] == SM_SentinelZero || Mask[i + 1] == SM_SentinelUndef)) {
8953         WidenedMask.push_back(SM_SentinelZero);
8954         continue;
8955       }
8956       return false;
8957     }
8958
8959     // Finally check if the two mask values are adjacent and aligned with
8960     // a pair.
8961     if (Mask[i] != SM_SentinelUndef && Mask[i] % 2 == 0 && Mask[i] + 1 == Mask[i + 1]) {
8962       WidenedMask.push_back(Mask[i] / 2);
8963       continue;
8964     }
8965
8966     // Otherwise we can't safely widen the elements used in this shuffle.
8967     return false;
8968   }
8969   assert(WidenedMask.size() == Mask.size() / 2 &&
8970          "Incorrect size of mask after widening the elements!");
8971
8972   return true;
8973 }
8974
8975 /// \brief Generic routine to split vector shuffle into half-sized shuffles.
8976 ///
8977 /// This routine just extracts two subvectors, shuffles them independently, and
8978 /// then concatenates them back together. This should work effectively with all
8979 /// AVX vector shuffle types.
8980 static SDValue splitAndLowerVectorShuffle(SDLoc DL, MVT VT, SDValue V1,
8981                                           SDValue V2, ArrayRef<int> Mask,
8982                                           SelectionDAG &DAG) {
8983   assert(VT.getSizeInBits() >= 256 &&
8984          "Only for 256-bit or wider vector shuffles!");
8985   assert(V1.getSimpleValueType() == VT && "Bad operand type!");
8986   assert(V2.getSimpleValueType() == VT && "Bad operand type!");
8987
8988   ArrayRef<int> LoMask = Mask.slice(0, Mask.size() / 2);
8989   ArrayRef<int> HiMask = Mask.slice(Mask.size() / 2);
8990
8991   int NumElements = VT.getVectorNumElements();
8992   int SplitNumElements = NumElements / 2;
8993   MVT ScalarVT = VT.getScalarType();
8994   MVT SplitVT = MVT::getVectorVT(ScalarVT, NumElements / 2);
8995
8996   // Rather than splitting build-vectors, just build two narrower build
8997   // vectors. This helps shuffling with splats and zeros.
8998   auto SplitVector = [&](SDValue V) {
8999     while (V.getOpcode() == ISD::BITCAST)
9000       V = V->getOperand(0);
9001
9002     MVT OrigVT = V.getSimpleValueType();
9003     int OrigNumElements = OrigVT.getVectorNumElements();
9004     int OrigSplitNumElements = OrigNumElements / 2;
9005     MVT OrigScalarVT = OrigVT.getScalarType();
9006     MVT OrigSplitVT = MVT::getVectorVT(OrigScalarVT, OrigNumElements / 2);
9007
9008     SDValue LoV, HiV;
9009
9010     auto *BV = dyn_cast<BuildVectorSDNode>(V);
9011     if (!BV) {
9012       LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
9013                         DAG.getIntPtrConstant(0, DL));
9014       HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
9015                         DAG.getIntPtrConstant(OrigSplitNumElements, DL));
9016     } else {
9017
9018       SmallVector<SDValue, 16> LoOps, HiOps;
9019       for (int i = 0; i < OrigSplitNumElements; ++i) {
9020         LoOps.push_back(BV->getOperand(i));
9021         HiOps.push_back(BV->getOperand(i + OrigSplitNumElements));
9022       }
9023       LoV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, LoOps);
9024       HiV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, HiOps);
9025     }
9026     return std::make_pair(DAG.getNode(ISD::BITCAST, DL, SplitVT, LoV),
9027                           DAG.getNode(ISD::BITCAST, DL, SplitVT, HiV));
9028   };
9029
9030   SDValue LoV1, HiV1, LoV2, HiV2;
9031   std::tie(LoV1, HiV1) = SplitVector(V1);
9032   std::tie(LoV2, HiV2) = SplitVector(V2);
9033
9034   // Now create two 4-way blends of these half-width vectors.
9035   auto HalfBlend = [&](ArrayRef<int> HalfMask) {
9036     bool UseLoV1 = false, UseHiV1 = false, UseLoV2 = false, UseHiV2 = false;
9037     SmallVector<int, 32> V1BlendMask, V2BlendMask, BlendMask;
9038     for (int i = 0; i < SplitNumElements; ++i) {
9039       int M = HalfMask[i];
9040       if (M >= NumElements) {
9041         if (M >= NumElements + SplitNumElements)
9042           UseHiV2 = true;
9043         else
9044           UseLoV2 = true;
9045         V2BlendMask.push_back(M - NumElements);
9046         V1BlendMask.push_back(-1);
9047         BlendMask.push_back(SplitNumElements + i);
9048       } else if (M >= 0) {
9049         if (M >= SplitNumElements)
9050           UseHiV1 = true;
9051         else
9052           UseLoV1 = true;
9053         V2BlendMask.push_back(-1);
9054         V1BlendMask.push_back(M);
9055         BlendMask.push_back(i);
9056       } else {
9057         V2BlendMask.push_back(-1);
9058         V1BlendMask.push_back(-1);
9059         BlendMask.push_back(-1);
9060       }
9061     }
9062
9063     // Because the lowering happens after all combining takes place, we need to
9064     // manually combine these blend masks as much as possible so that we create
9065     // a minimal number of high-level vector shuffle nodes.
9066
9067     // First try just blending the halves of V1 or V2.
9068     if (!UseLoV1 && !UseHiV1 && !UseLoV2 && !UseHiV2)
9069       return DAG.getUNDEF(SplitVT);
9070     if (!UseLoV2 && !UseHiV2)
9071       return DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9072     if (!UseLoV1 && !UseHiV1)
9073       return DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9074
9075     SDValue V1Blend, V2Blend;
9076     if (UseLoV1 && UseHiV1) {
9077       V1Blend =
9078         DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9079     } else {
9080       // We only use half of V1 so map the usage down into the final blend mask.
9081       V1Blend = UseLoV1 ? LoV1 : HiV1;
9082       for (int i = 0; i < SplitNumElements; ++i)
9083         if (BlendMask[i] >= 0 && BlendMask[i] < SplitNumElements)
9084           BlendMask[i] = V1BlendMask[i] - (UseLoV1 ? 0 : SplitNumElements);
9085     }
9086     if (UseLoV2 && UseHiV2) {
9087       V2Blend =
9088         DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9089     } else {
9090       // We only use half of V2 so map the usage down into the final blend mask.
9091       V2Blend = UseLoV2 ? LoV2 : HiV2;
9092       for (int i = 0; i < SplitNumElements; ++i)
9093         if (BlendMask[i] >= SplitNumElements)
9094           BlendMask[i] = V2BlendMask[i] + (UseLoV2 ? SplitNumElements : 0);
9095     }
9096     return DAG.getVectorShuffle(SplitVT, DL, V1Blend, V2Blend, BlendMask);
9097   };
9098   SDValue Lo = HalfBlend(LoMask);
9099   SDValue Hi = HalfBlend(HiMask);
9100   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
9101 }
9102
9103 /// \brief Either split a vector in halves or decompose the shuffles and the
9104 /// blend.
9105 ///
9106 /// This is provided as a good fallback for many lowerings of non-single-input
9107 /// shuffles with more than one 128-bit lane. In those cases, we want to select
9108 /// between splitting the shuffle into 128-bit components and stitching those
9109 /// back together vs. extracting the single-input shuffles and blending those
9110 /// results.
9111 static SDValue lowerVectorShuffleAsSplitOrBlend(SDLoc DL, MVT VT, SDValue V1,
9112                                                 SDValue V2, ArrayRef<int> Mask,
9113                                                 SelectionDAG &DAG) {
9114   assert(!isSingleInputShuffleMask(Mask) && "This routine must not be used to "
9115                                             "lower single-input shuffles as it "
9116                                             "could then recurse on itself.");
9117   int Size = Mask.size();
9118
9119   // If this can be modeled as a broadcast of two elements followed by a blend,
9120   // prefer that lowering. This is especially important because broadcasts can
9121   // often fold with memory operands.
9122   auto DoBothBroadcast = [&] {
9123     int V1BroadcastIdx = -1, V2BroadcastIdx = -1;
9124     for (int M : Mask)
9125       if (M >= Size) {
9126         if (V2BroadcastIdx == -1)
9127           V2BroadcastIdx = M - Size;
9128         else if (M - Size != V2BroadcastIdx)
9129           return false;
9130       } else if (M >= 0) {
9131         if (V1BroadcastIdx == -1)
9132           V1BroadcastIdx = M;
9133         else if (M != V1BroadcastIdx)
9134           return false;
9135       }
9136     return true;
9137   };
9138   if (DoBothBroadcast())
9139     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask,
9140                                                       DAG);
9141
9142   // If the inputs all stem from a single 128-bit lane of each input, then we
9143   // split them rather than blending because the split will decompose to
9144   // unusually few instructions.
9145   int LaneCount = VT.getSizeInBits() / 128;
9146   int LaneSize = Size / LaneCount;
9147   SmallBitVector LaneInputs[2];
9148   LaneInputs[0].resize(LaneCount, false);
9149   LaneInputs[1].resize(LaneCount, false);
9150   for (int i = 0; i < Size; ++i)
9151     if (Mask[i] >= 0)
9152       LaneInputs[Mask[i] / Size][(Mask[i] % Size) / LaneSize] = true;
9153   if (LaneInputs[0].count() <= 1 && LaneInputs[1].count() <= 1)
9154     return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9155
9156   // Otherwise, just fall back to decomposed shuffles and a blend. This requires
9157   // that the decomposed single-input shuffles don't end up here.
9158   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9159 }
9160
9161 /// \brief Lower a vector shuffle crossing multiple 128-bit lanes as
9162 /// a permutation and blend of those lanes.
9163 ///
9164 /// This essentially blends the out-of-lane inputs to each lane into the lane
9165 /// from a permuted copy of the vector. This lowering strategy results in four
9166 /// instructions in the worst case for a single-input cross lane shuffle which
9167 /// is lower than any other fully general cross-lane shuffle strategy I'm aware
9168 /// of. Special cases for each particular shuffle pattern should be handled
9169 /// prior to trying this lowering.
9170 static SDValue lowerVectorShuffleAsLanePermuteAndBlend(SDLoc DL, MVT VT,
9171                                                        SDValue V1, SDValue V2,
9172                                                        ArrayRef<int> Mask,
9173                                                        SelectionDAG &DAG) {
9174   // FIXME: This should probably be generalized for 512-bit vectors as well.
9175   assert(VT.getSizeInBits() == 256 && "Only for 256-bit vector shuffles!");
9176   int LaneSize = Mask.size() / 2;
9177
9178   // If there are only inputs from one 128-bit lane, splitting will in fact be
9179   // less expensive. The flags track whether the given lane contains an element
9180   // that crosses to another lane.
9181   bool LaneCrossing[2] = {false, false};
9182   for (int i = 0, Size = Mask.size(); i < Size; ++i)
9183     if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
9184       LaneCrossing[(Mask[i] % Size) / LaneSize] = true;
9185   if (!LaneCrossing[0] || !LaneCrossing[1])
9186     return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9187
9188   if (isSingleInputShuffleMask(Mask)) {
9189     SmallVector<int, 32> FlippedBlendMask;
9190     for (int i = 0, Size = Mask.size(); i < Size; ++i)
9191       FlippedBlendMask.push_back(
9192           Mask[i] < 0 ? -1 : (((Mask[i] % Size) / LaneSize == i / LaneSize)
9193                                   ? Mask[i]
9194                                   : Mask[i] % LaneSize +
9195                                         (i / LaneSize) * LaneSize + Size));
9196
9197     // Flip the vector, and blend the results which should now be in-lane. The
9198     // VPERM2X128 mask uses the low 2 bits for the low source and bits 4 and
9199     // 5 for the high source. The value 3 selects the high half of source 2 and
9200     // the value 2 selects the low half of source 2. We only use source 2 to
9201     // allow folding it into a memory operand.
9202     unsigned PERMMask = 3 | 2 << 4;
9203     SDValue Flipped = DAG.getNode(X86ISD::VPERM2X128, DL, VT, DAG.getUNDEF(VT),
9204                                   V1, DAG.getConstant(PERMMask, DL, MVT::i8));
9205     return DAG.getVectorShuffle(VT, DL, V1, Flipped, FlippedBlendMask);
9206   }
9207
9208   // This now reduces to two single-input shuffles of V1 and V2 which at worst
9209   // will be handled by the above logic and a blend of the results, much like
9210   // other patterns in AVX.
9211   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9212 }
9213
9214 /// \brief Handle lowering 2-lane 128-bit shuffles.
9215 static SDValue lowerV2X128VectorShuffle(SDLoc DL, MVT VT, SDValue V1,
9216                                         SDValue V2, ArrayRef<int> Mask,
9217                                         const X86Subtarget *Subtarget,
9218                                         SelectionDAG &DAG) {
9219   // TODO: If minimizing size and one of the inputs is a zero vector and the
9220   // the zero vector has only one use, we could use a VPERM2X128 to save the
9221   // instruction bytes needed to explicitly generate the zero vector.
9222
9223   // Blends are faster and handle all the non-lane-crossing cases.
9224   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, VT, V1, V2, Mask,
9225                                                 Subtarget, DAG))
9226     return Blend;
9227
9228   bool IsV1Zero = ISD::isBuildVectorAllZeros(V1.getNode());
9229   bool IsV2Zero = ISD::isBuildVectorAllZeros(V2.getNode());
9230
9231   // If either input operand is a zero vector, use VPERM2X128 because its mask
9232   // allows us to replace the zero input with an implicit zero.
9233   if (!IsV1Zero && !IsV2Zero) {
9234     // Check for patterns which can be matched with a single insert of a 128-bit
9235     // subvector.
9236     bool OnlyUsesV1 = isShuffleEquivalent(V1, V2, Mask, {0, 1, 0, 1});
9237     if (OnlyUsesV1 || isShuffleEquivalent(V1, V2, Mask, {0, 1, 4, 5})) {
9238       MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(),
9239                                    VT.getVectorNumElements() / 2);
9240       SDValue LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V1,
9241                                 DAG.getIntPtrConstant(0, DL));
9242       SDValue HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT,
9243                                 OnlyUsesV1 ? V1 : V2,
9244                                 DAG.getIntPtrConstant(0, DL));
9245       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LoV, HiV);
9246     }
9247   }
9248
9249   // Otherwise form a 128-bit permutation. After accounting for undefs,
9250   // convert the 64-bit shuffle mask selection values into 128-bit
9251   // selection bits by dividing the indexes by 2 and shifting into positions
9252   // defined by a vperm2*128 instruction's immediate control byte.
9253
9254   // The immediate permute control byte looks like this:
9255   //    [1:0] - select 128 bits from sources for low half of destination
9256   //    [2]   - ignore
9257   //    [3]   - zero low half of destination
9258   //    [5:4] - select 128 bits from sources for high half of destination
9259   //    [6]   - ignore
9260   //    [7]   - zero high half of destination
9261
9262   int MaskLO = Mask[0];
9263   if (MaskLO == SM_SentinelUndef)
9264     MaskLO = Mask[1] == SM_SentinelUndef ? 0 : Mask[1];
9265
9266   int MaskHI = Mask[2];
9267   if (MaskHI == SM_SentinelUndef)
9268     MaskHI = Mask[3] == SM_SentinelUndef ? 0 : Mask[3];
9269
9270   unsigned PermMask = MaskLO / 2 | (MaskHI / 2) << 4;
9271
9272   // If either input is a zero vector, replace it with an undef input.
9273   // Shuffle mask values <  4 are selecting elements of V1.
9274   // Shuffle mask values >= 4 are selecting elements of V2.
9275   // Adjust each half of the permute mask by clearing the half that was
9276   // selecting the zero vector and setting the zero mask bit.
9277   if (IsV1Zero) {
9278     V1 = DAG.getUNDEF(VT);
9279     if (MaskLO < 4)
9280       PermMask = (PermMask & 0xf0) | 0x08;
9281     if (MaskHI < 4)
9282       PermMask = (PermMask & 0x0f) | 0x80;
9283   }
9284   if (IsV2Zero) {
9285     V2 = DAG.getUNDEF(VT);
9286     if (MaskLO >= 4)
9287       PermMask = (PermMask & 0xf0) | 0x08;
9288     if (MaskHI >= 4)
9289       PermMask = (PermMask & 0x0f) | 0x80;
9290   }
9291
9292   return DAG.getNode(X86ISD::VPERM2X128, DL, VT, V1, V2,
9293                      DAG.getConstant(PermMask, DL, MVT::i8));
9294 }
9295
9296 /// \brief Lower a vector shuffle by first fixing the 128-bit lanes and then
9297 /// shuffling each lane.
9298 ///
9299 /// This will only succeed when the result of fixing the 128-bit lanes results
9300 /// in a single-input non-lane-crossing shuffle with a repeating shuffle mask in
9301 /// each 128-bit lanes. This handles many cases where we can quickly blend away
9302 /// the lane crosses early and then use simpler shuffles within each lane.
9303 ///
9304 /// FIXME: It might be worthwhile at some point to support this without
9305 /// requiring the 128-bit lane-relative shuffles to be repeating, but currently
9306 /// in x86 only floating point has interesting non-repeating shuffles, and even
9307 /// those are still *marginally* more expensive.
9308 static SDValue lowerVectorShuffleByMerging128BitLanes(
9309     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
9310     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
9311   assert(!isSingleInputShuffleMask(Mask) &&
9312          "This is only useful with multiple inputs.");
9313
9314   int Size = Mask.size();
9315   int LaneSize = 128 / VT.getScalarSizeInBits();
9316   int NumLanes = Size / LaneSize;
9317   assert(NumLanes > 1 && "Only handles 256-bit and wider shuffles.");
9318
9319   // See if we can build a hypothetical 128-bit lane-fixing shuffle mask. Also
9320   // check whether the in-128-bit lane shuffles share a repeating pattern.
9321   SmallVector<int, 4> Lanes;
9322   Lanes.resize(NumLanes, -1);
9323   SmallVector<int, 4> InLaneMask;
9324   InLaneMask.resize(LaneSize, -1);
9325   for (int i = 0; i < Size; ++i) {
9326     if (Mask[i] < 0)
9327       continue;
9328
9329     int j = i / LaneSize;
9330
9331     if (Lanes[j] < 0) {
9332       // First entry we've seen for this lane.
9333       Lanes[j] = Mask[i] / LaneSize;
9334     } else if (Lanes[j] != Mask[i] / LaneSize) {
9335       // This doesn't match the lane selected previously!
9336       return SDValue();
9337     }
9338
9339     // Check that within each lane we have a consistent shuffle mask.
9340     int k = i % LaneSize;
9341     if (InLaneMask[k] < 0) {
9342       InLaneMask[k] = Mask[i] % LaneSize;
9343     } else if (InLaneMask[k] != Mask[i] % LaneSize) {
9344       // This doesn't fit a repeating in-lane mask.
9345       return SDValue();
9346     }
9347   }
9348
9349   // First shuffle the lanes into place.
9350   MVT LaneVT = MVT::getVectorVT(VT.isFloatingPoint() ? MVT::f64 : MVT::i64,
9351                                 VT.getSizeInBits() / 64);
9352   SmallVector<int, 8> LaneMask;
9353   LaneMask.resize(NumLanes * 2, -1);
9354   for (int i = 0; i < NumLanes; ++i)
9355     if (Lanes[i] >= 0) {
9356       LaneMask[2 * i + 0] = 2*Lanes[i] + 0;
9357       LaneMask[2 * i + 1] = 2*Lanes[i] + 1;
9358     }
9359
9360   V1 = DAG.getNode(ISD::BITCAST, DL, LaneVT, V1);
9361   V2 = DAG.getNode(ISD::BITCAST, DL, LaneVT, V2);
9362   SDValue LaneShuffle = DAG.getVectorShuffle(LaneVT, DL, V1, V2, LaneMask);
9363
9364   // Cast it back to the type we actually want.
9365   LaneShuffle = DAG.getNode(ISD::BITCAST, DL, VT, LaneShuffle);
9366
9367   // Now do a simple shuffle that isn't lane crossing.
9368   SmallVector<int, 8> NewMask;
9369   NewMask.resize(Size, -1);
9370   for (int i = 0; i < Size; ++i)
9371     if (Mask[i] >= 0)
9372       NewMask[i] = (i / LaneSize) * LaneSize + Mask[i] % LaneSize;
9373   assert(!is128BitLaneCrossingShuffleMask(VT, NewMask) &&
9374          "Must not introduce lane crosses at this point!");
9375
9376   return DAG.getVectorShuffle(VT, DL, LaneShuffle, DAG.getUNDEF(VT), NewMask);
9377 }
9378
9379 /// \brief Test whether the specified input (0 or 1) is in-place blended by the
9380 /// given mask.
9381 ///
9382 /// This returns true if the elements from a particular input are already in the
9383 /// slot required by the given mask and require no permutation.
9384 static bool isShuffleMaskInputInPlace(int Input, ArrayRef<int> Mask) {
9385   assert((Input == 0 || Input == 1) && "Only two inputs to shuffles.");
9386   int Size = Mask.size();
9387   for (int i = 0; i < Size; ++i)
9388     if (Mask[i] >= 0 && Mask[i] / Size == Input && Mask[i] % Size != i)
9389       return false;
9390
9391   return true;
9392 }
9393
9394 /// \brief Handle lowering of 4-lane 64-bit floating point shuffles.
9395 ///
9396 /// Also ends up handling lowering of 4-lane 64-bit integer shuffles when AVX2
9397 /// isn't available.
9398 static SDValue lowerV4F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9399                                        const X86Subtarget *Subtarget,
9400                                        SelectionDAG &DAG) {
9401   SDLoc DL(Op);
9402   assert(V1.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
9403   assert(V2.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
9404   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9405   ArrayRef<int> Mask = SVOp->getMask();
9406   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
9407
9408   SmallVector<int, 4> WidenedMask;
9409   if (canWidenShuffleElements(Mask, WidenedMask))
9410     return lowerV2X128VectorShuffle(DL, MVT::v4f64, V1, V2, Mask, Subtarget,
9411                                     DAG);
9412
9413   if (isSingleInputShuffleMask(Mask)) {
9414     // Check for being able to broadcast a single element.
9415     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f64, V1,
9416                                                           Mask, Subtarget, DAG))
9417       return Broadcast;
9418
9419     // Use low duplicate instructions for masks that match their pattern.
9420     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
9421       return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v4f64, V1);
9422
9423     if (!is128BitLaneCrossingShuffleMask(MVT::v4f64, Mask)) {
9424       // Non-half-crossing single input shuffles can be lowerid with an
9425       // interleaved permutation.
9426       unsigned VPERMILPMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1) |
9427                               ((Mask[2] == 3) << 2) | ((Mask[3] == 3) << 3);
9428       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f64, V1,
9429                          DAG.getConstant(VPERMILPMask, DL, MVT::i8));
9430     }
9431
9432     // With AVX2 we have direct support for this permutation.
9433     if (Subtarget->hasAVX2())
9434       return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4f64, V1,
9435                          getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
9436
9437     // Otherwise, fall back.
9438     return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v4f64, V1, V2, Mask,
9439                                                    DAG);
9440   }
9441
9442   // X86 has dedicated unpack instructions that can handle specific blend
9443   // operations: UNPCKH and UNPCKL.
9444   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 2, 6}))
9445     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V1, V2);
9446   if (isShuffleEquivalent(V1, V2, Mask, {1, 5, 3, 7}))
9447     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V1, V2);
9448   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 6, 2}))
9449     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V2, V1);
9450   if (isShuffleEquivalent(V1, V2, Mask, {5, 1, 7, 3}))
9451     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V2, V1);
9452
9453   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f64, V1, V2, Mask,
9454                                                 Subtarget, DAG))
9455     return Blend;
9456
9457   // Check if the blend happens to exactly fit that of SHUFPD.
9458   if ((Mask[0] == -1 || Mask[0] < 2) &&
9459       (Mask[1] == -1 || (Mask[1] >= 4 && Mask[1] < 6)) &&
9460       (Mask[2] == -1 || (Mask[2] >= 2 && Mask[2] < 4)) &&
9461       (Mask[3] == -1 || Mask[3] >= 6)) {
9462     unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 5) << 1) |
9463                           ((Mask[2] == 3) << 2) | ((Mask[3] == 7) << 3);
9464     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f64, V1, V2,
9465                        DAG.getConstant(SHUFPDMask, DL, MVT::i8));
9466   }
9467   if ((Mask[0] == -1 || (Mask[0] >= 4 && Mask[0] < 6)) &&
9468       (Mask[1] == -1 || Mask[1] < 2) &&
9469       (Mask[2] == -1 || Mask[2] >= 6) &&
9470       (Mask[3] == -1 || (Mask[3] >= 2 && Mask[3] < 4))) {
9471     unsigned SHUFPDMask = (Mask[0] == 5) | ((Mask[1] == 1) << 1) |
9472                           ((Mask[2] == 7) << 2) | ((Mask[3] == 3) << 3);
9473     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f64, V2, V1,
9474                        DAG.getConstant(SHUFPDMask, DL, MVT::i8));
9475   }
9476
9477   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9478   // shuffle. However, if we have AVX2 and either inputs are already in place,
9479   // we will be able to shuffle even across lanes the other input in a single
9480   // instruction so skip this pattern.
9481   if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
9482                                  isShuffleMaskInputInPlace(1, Mask))))
9483     if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9484             DL, MVT::v4f64, V1, V2, Mask, Subtarget, DAG))
9485       return Result;
9486
9487   // If we have AVX2 then we always want to lower with a blend because an v4 we
9488   // can fully permute the elements.
9489   if (Subtarget->hasAVX2())
9490     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4f64, V1, V2,
9491                                                       Mask, DAG);
9492
9493   // Otherwise fall back on generic lowering.
9494   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v4f64, V1, V2, Mask, DAG);
9495 }
9496
9497 /// \brief Handle lowering of 4-lane 64-bit integer shuffles.
9498 ///
9499 /// This routine is only called when we have AVX2 and thus a reasonable
9500 /// instruction set for v4i64 shuffling..
9501 static SDValue lowerV4I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9502                                        const X86Subtarget *Subtarget,
9503                                        SelectionDAG &DAG) {
9504   SDLoc DL(Op);
9505   assert(V1.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
9506   assert(V2.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
9507   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9508   ArrayRef<int> Mask = SVOp->getMask();
9509   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
9510   assert(Subtarget->hasAVX2() && "We can only lower v4i64 with AVX2!");
9511
9512   SmallVector<int, 4> WidenedMask;
9513   if (canWidenShuffleElements(Mask, WidenedMask))
9514     return lowerV2X128VectorShuffle(DL, MVT::v4i64, V1, V2, Mask, Subtarget,
9515                                     DAG);
9516
9517   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i64, V1, V2, Mask,
9518                                                 Subtarget, DAG))
9519     return Blend;
9520
9521   // Check for being able to broadcast a single element.
9522   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i64, V1,
9523                                                         Mask, Subtarget, DAG))
9524     return Broadcast;
9525
9526   // When the shuffle is mirrored between the 128-bit lanes of the unit, we can
9527   // use lower latency instructions that will operate on both 128-bit lanes.
9528   SmallVector<int, 2> RepeatedMask;
9529   if (is128BitLaneRepeatedShuffleMask(MVT::v4i64, Mask, RepeatedMask)) {
9530     if (isSingleInputShuffleMask(Mask)) {
9531       int PSHUFDMask[] = {-1, -1, -1, -1};
9532       for (int i = 0; i < 2; ++i)
9533         if (RepeatedMask[i] >= 0) {
9534           PSHUFDMask[2 * i] = 2 * RepeatedMask[i];
9535           PSHUFDMask[2 * i + 1] = 2 * RepeatedMask[i] + 1;
9536         }
9537       return DAG.getNode(
9538           ISD::BITCAST, DL, MVT::v4i64,
9539           DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32,
9540                       DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, V1),
9541                       getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
9542     }
9543   }
9544
9545   // AVX2 provides a direct instruction for permuting a single input across
9546   // lanes.
9547   if (isSingleInputShuffleMask(Mask))
9548     return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4i64, V1,
9549                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
9550
9551   // Try to use shift instructions.
9552   if (SDValue Shift =
9553           lowerVectorShuffleAsShift(DL, MVT::v4i64, V1, V2, Mask, DAG))
9554     return Shift;
9555
9556   // Use dedicated unpack instructions for masks that match their pattern.
9557   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 2, 6}))
9558     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V1, V2);
9559   if (isShuffleEquivalent(V1, V2, Mask, {1, 5, 3, 7}))
9560     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V1, V2);
9561   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 6, 2}))
9562     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V2, V1);
9563   if (isShuffleEquivalent(V1, V2, Mask, {5, 1, 7, 3}))
9564     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V2, V1);
9565
9566   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9567   // shuffle. However, if we have AVX2 and either inputs are already in place,
9568   // we will be able to shuffle even across lanes the other input in a single
9569   // instruction so skip this pattern.
9570   if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
9571                                  isShuffleMaskInputInPlace(1, Mask))))
9572     if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9573             DL, MVT::v4i64, V1, V2, Mask, Subtarget, DAG))
9574       return Result;
9575
9576   // Otherwise fall back on generic blend lowering.
9577   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i64, V1, V2,
9578                                                     Mask, DAG);
9579 }
9580
9581 /// \brief Handle lowering of 8-lane 32-bit floating point shuffles.
9582 ///
9583 /// Also ends up handling lowering of 8-lane 32-bit integer shuffles when AVX2
9584 /// isn't available.
9585 static SDValue lowerV8F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9586                                        const X86Subtarget *Subtarget,
9587                                        SelectionDAG &DAG) {
9588   SDLoc DL(Op);
9589   assert(V1.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
9590   assert(V2.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
9591   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9592   ArrayRef<int> Mask = SVOp->getMask();
9593   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9594
9595   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8f32, V1, V2, Mask,
9596                                                 Subtarget, DAG))
9597     return Blend;
9598
9599   // Check for being able to broadcast a single element.
9600   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8f32, V1,
9601                                                         Mask, Subtarget, DAG))
9602     return Broadcast;
9603
9604   // If the shuffle mask is repeated in each 128-bit lane, we have many more
9605   // options to efficiently lower the shuffle.
9606   SmallVector<int, 4> RepeatedMask;
9607   if (is128BitLaneRepeatedShuffleMask(MVT::v8f32, Mask, RepeatedMask)) {
9608     assert(RepeatedMask.size() == 4 &&
9609            "Repeated masks must be half the mask width!");
9610
9611     // Use even/odd duplicate instructions for masks that match their pattern.
9612     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2, 4, 4, 6, 6}))
9613       return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v8f32, V1);
9614     if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3, 5, 5, 7, 7}))
9615       return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v8f32, V1);
9616
9617     if (isSingleInputShuffleMask(Mask))
9618       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v8f32, V1,
9619                          getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
9620
9621     // Use dedicated unpack instructions for masks that match their pattern.
9622     if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 4, 12, 5, 13}))
9623       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V1, V2);
9624     if (isShuffleEquivalent(V1, V2, Mask, {2, 10, 3, 11, 6, 14, 7, 15}))
9625       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V1, V2);
9626     if (isShuffleEquivalent(V1, V2, Mask, {8, 0, 9, 1, 12, 4, 13, 5}))
9627       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V2, V1);
9628     if (isShuffleEquivalent(V1, V2, Mask, {10, 2, 11, 3, 14, 6, 15, 7}))
9629       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V2, V1);
9630
9631     // Otherwise, fall back to a SHUFPS sequence. Here it is important that we
9632     // have already handled any direct blends. We also need to squash the
9633     // repeated mask into a simulated v4f32 mask.
9634     for (int i = 0; i < 4; ++i)
9635       if (RepeatedMask[i] >= 8)
9636         RepeatedMask[i] -= 4;
9637     return lowerVectorShuffleWithSHUFPS(DL, MVT::v8f32, RepeatedMask, V1, V2, DAG);
9638   }
9639
9640   // If we have a single input shuffle with different shuffle patterns in the
9641   // two 128-bit lanes use the variable mask to VPERMILPS.
9642   if (isSingleInputShuffleMask(Mask)) {
9643     SDValue VPermMask[8];
9644     for (int i = 0; i < 8; ++i)
9645       VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
9646                                  : DAG.getConstant(Mask[i], DL, MVT::i32);
9647     if (!is128BitLaneCrossingShuffleMask(MVT::v8f32, Mask))
9648       return DAG.getNode(
9649           X86ISD::VPERMILPV, DL, MVT::v8f32, V1,
9650           DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask));
9651
9652     if (Subtarget->hasAVX2())
9653       return DAG.getNode(X86ISD::VPERMV, DL, MVT::v8f32,
9654                          DAG.getNode(ISD::BITCAST, DL, MVT::v8f32,
9655                                      DAG.getNode(ISD::BUILD_VECTOR, DL,
9656                                                  MVT::v8i32, VPermMask)),
9657                          V1);
9658
9659     // Otherwise, fall back.
9660     return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v8f32, V1, V2, Mask,
9661                                                    DAG);
9662   }
9663
9664   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9665   // shuffle.
9666   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9667           DL, MVT::v8f32, V1, V2, Mask, Subtarget, DAG))
9668     return Result;
9669
9670   // If we have AVX2 then we always want to lower with a blend because at v8 we
9671   // can fully permute the elements.
9672   if (Subtarget->hasAVX2())
9673     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8f32, V1, V2,
9674                                                       Mask, DAG);
9675
9676   // Otherwise fall back on generic lowering.
9677   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v8f32, V1, V2, Mask, DAG);
9678 }
9679
9680 /// \brief Handle lowering of 8-lane 32-bit integer shuffles.
9681 ///
9682 /// This routine is only called when we have AVX2 and thus a reasonable
9683 /// instruction set for v8i32 shuffling..
9684 static SDValue lowerV8I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9685                                        const X86Subtarget *Subtarget,
9686                                        SelectionDAG &DAG) {
9687   SDLoc DL(Op);
9688   assert(V1.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
9689   assert(V2.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
9690   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9691   ArrayRef<int> Mask = SVOp->getMask();
9692   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9693   assert(Subtarget->hasAVX2() && "We can only lower v8i32 with AVX2!");
9694
9695   // Whenever we can lower this as a zext, that instruction is strictly faster
9696   // than any alternative. It also allows us to fold memory operands into the
9697   // shuffle in many cases.
9698   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v8i32, V1, V2,
9699                                                          Mask, Subtarget, DAG))
9700     return ZExt;
9701
9702   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i32, V1, V2, Mask,
9703                                                 Subtarget, DAG))
9704     return Blend;
9705
9706   // Check for being able to broadcast a single element.
9707   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i32, V1,
9708                                                         Mask, Subtarget, DAG))
9709     return Broadcast;
9710
9711   // If the shuffle mask is repeated in each 128-bit lane we can use more
9712   // efficient instructions that mirror the shuffles across the two 128-bit
9713   // lanes.
9714   SmallVector<int, 4> RepeatedMask;
9715   if (is128BitLaneRepeatedShuffleMask(MVT::v8i32, Mask, RepeatedMask)) {
9716     assert(RepeatedMask.size() == 4 && "Unexpected repeated mask size!");
9717     if (isSingleInputShuffleMask(Mask))
9718       return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32, V1,
9719                          getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
9720
9721     // Use dedicated unpack instructions for masks that match their pattern.
9722     if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 4, 12, 5, 13}))
9723       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V1, V2);
9724     if (isShuffleEquivalent(V1, V2, Mask, {2, 10, 3, 11, 6, 14, 7, 15}))
9725       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V1, V2);
9726     if (isShuffleEquivalent(V1, V2, Mask, {8, 0, 9, 1, 12, 4, 13, 5}))
9727       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V2, V1);
9728     if (isShuffleEquivalent(V1, V2, Mask, {10, 2, 11, 3, 14, 6, 15, 7}))
9729       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V2, V1);
9730   }
9731
9732   // Try to use shift instructions.
9733   if (SDValue Shift =
9734           lowerVectorShuffleAsShift(DL, MVT::v8i32, V1, V2, Mask, DAG))
9735     return Shift;
9736
9737   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9738           DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
9739     return Rotate;
9740
9741   // If the shuffle patterns aren't repeated but it is a single input, directly
9742   // generate a cross-lane VPERMD instruction.
9743   if (isSingleInputShuffleMask(Mask)) {
9744     SDValue VPermMask[8];
9745     for (int i = 0; i < 8; ++i)
9746       VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
9747                                  : DAG.getConstant(Mask[i], DL, MVT::i32);
9748     return DAG.getNode(
9749         X86ISD::VPERMV, DL, MVT::v8i32,
9750         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask), V1);
9751   }
9752
9753   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9754   // shuffle.
9755   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9756           DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
9757     return Result;
9758
9759   // Otherwise fall back on generic blend lowering.
9760   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i32, V1, V2,
9761                                                     Mask, DAG);
9762 }
9763
9764 /// \brief Handle lowering of 16-lane 16-bit integer shuffles.
9765 ///
9766 /// This routine is only called when we have AVX2 and thus a reasonable
9767 /// instruction set for v16i16 shuffling..
9768 static SDValue lowerV16I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9769                                         const X86Subtarget *Subtarget,
9770                                         SelectionDAG &DAG) {
9771   SDLoc DL(Op);
9772   assert(V1.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
9773   assert(V2.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
9774   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9775   ArrayRef<int> Mask = SVOp->getMask();
9776   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
9777   assert(Subtarget->hasAVX2() && "We can only lower v16i16 with AVX2!");
9778
9779   // Whenever we can lower this as a zext, that instruction is strictly faster
9780   // than any alternative. It also allows us to fold memory operands into the
9781   // shuffle in many cases.
9782   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v16i16, V1, V2,
9783                                                          Mask, Subtarget, DAG))
9784     return ZExt;
9785
9786   // Check for being able to broadcast a single element.
9787   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i16, V1,
9788                                                         Mask, Subtarget, DAG))
9789     return Broadcast;
9790
9791   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i16, V1, V2, Mask,
9792                                                 Subtarget, DAG))
9793     return Blend;
9794
9795   // Use dedicated unpack instructions for masks that match their pattern.
9796   if (isShuffleEquivalent(V1, V2, Mask,
9797                           {// First 128-bit lane:
9798                            0, 16, 1, 17, 2, 18, 3, 19,
9799                            // Second 128-bit lane:
9800                            8, 24, 9, 25, 10, 26, 11, 27}))
9801     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i16, V1, V2);
9802   if (isShuffleEquivalent(V1, V2, Mask,
9803                           {// First 128-bit lane:
9804                            4, 20, 5, 21, 6, 22, 7, 23,
9805                            // Second 128-bit lane:
9806                            12, 28, 13, 29, 14, 30, 15, 31}))
9807     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i16, V1, V2);
9808
9809   // Try to use shift instructions.
9810   if (SDValue Shift =
9811           lowerVectorShuffleAsShift(DL, MVT::v16i16, V1, V2, Mask, DAG))
9812     return Shift;
9813
9814   // Try to use byte rotation instructions.
9815   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9816           DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
9817     return Rotate;
9818
9819   if (isSingleInputShuffleMask(Mask)) {
9820     // There are no generalized cross-lane shuffle operations available on i16
9821     // element types.
9822     if (is128BitLaneCrossingShuffleMask(MVT::v16i16, Mask))
9823       return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v16i16, V1, V2,
9824                                                      Mask, DAG);
9825
9826     SmallVector<int, 8> RepeatedMask;
9827     if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
9828       // As this is a single-input shuffle, the repeated mask should be
9829       // a strictly valid v8i16 mask that we can pass through to the v8i16
9830       // lowering to handle even the v16 case.
9831       return lowerV8I16GeneralSingleInputVectorShuffle(
9832           DL, MVT::v16i16, V1, RepeatedMask, Subtarget, DAG);
9833     }
9834
9835     SDValue PSHUFBMask[32];
9836     for (int i = 0; i < 16; ++i) {
9837       if (Mask[i] == -1) {
9838         PSHUFBMask[2 * i] = PSHUFBMask[2 * i + 1] = DAG.getUNDEF(MVT::i8);
9839         continue;
9840       }
9841
9842       int M = i < 8 ? Mask[i] : Mask[i] - 8;
9843       assert(M >= 0 && M < 8 && "Invalid single-input mask!");
9844       PSHUFBMask[2 * i] = DAG.getConstant(2 * M, DL, MVT::i8);
9845       PSHUFBMask[2 * i + 1] = DAG.getConstant(2 * M + 1, DL, MVT::i8);
9846     }
9847     return DAG.getNode(
9848         ISD::BITCAST, DL, MVT::v16i16,
9849         DAG.getNode(
9850             X86ISD::PSHUFB, DL, MVT::v32i8,
9851             DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, V1),
9852             DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, PSHUFBMask)));
9853   }
9854
9855   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9856   // shuffle.
9857   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9858           DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
9859     return Result;
9860
9861   // Otherwise fall back on generic lowering.
9862   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v16i16, V1, V2, Mask, DAG);
9863 }
9864
9865 /// \brief Handle lowering of 32-lane 8-bit integer shuffles.
9866 ///
9867 /// This routine is only called when we have AVX2 and thus a reasonable
9868 /// instruction set for v32i8 shuffling..
9869 static SDValue lowerV32I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9870                                        const X86Subtarget *Subtarget,
9871                                        SelectionDAG &DAG) {
9872   SDLoc DL(Op);
9873   assert(V1.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
9874   assert(V2.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
9875   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9876   ArrayRef<int> Mask = SVOp->getMask();
9877   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
9878   assert(Subtarget->hasAVX2() && "We can only lower v32i8 with AVX2!");
9879
9880   // Whenever we can lower this as a zext, that instruction is strictly faster
9881   // than any alternative. It also allows us to fold memory operands into the
9882   // shuffle in many cases.
9883   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v32i8, V1, V2,
9884                                                          Mask, Subtarget, DAG))
9885     return ZExt;
9886
9887   // Check for being able to broadcast a single element.
9888   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v32i8, V1,
9889                                                         Mask, Subtarget, DAG))
9890     return Broadcast;
9891
9892   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v32i8, V1, V2, Mask,
9893                                                 Subtarget, DAG))
9894     return Blend;
9895
9896   // Use dedicated unpack instructions for masks that match their pattern.
9897   // Note that these are repeated 128-bit lane unpacks, not unpacks across all
9898   // 256-bit lanes.
9899   if (isShuffleEquivalent(
9900           V1, V2, Mask,
9901           {// First 128-bit lane:
9902            0, 32, 1, 33, 2, 34, 3, 35, 4, 36, 5, 37, 6, 38, 7, 39,
9903            // Second 128-bit lane:
9904            16, 48, 17, 49, 18, 50, 19, 51, 20, 52, 21, 53, 22, 54, 23, 55}))
9905     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v32i8, V1, V2);
9906   if (isShuffleEquivalent(
9907           V1, V2, Mask,
9908           {// First 128-bit lane:
9909            8, 40, 9, 41, 10, 42, 11, 43, 12, 44, 13, 45, 14, 46, 15, 47,
9910            // Second 128-bit lane:
9911            24, 56, 25, 57, 26, 58, 27, 59, 28, 60, 29, 61, 30, 62, 31, 63}))
9912     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v32i8, V1, V2);
9913
9914   // Try to use shift instructions.
9915   if (SDValue Shift =
9916           lowerVectorShuffleAsShift(DL, MVT::v32i8, V1, V2, Mask, DAG))
9917     return Shift;
9918
9919   // Try to use byte rotation instructions.
9920   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9921           DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
9922     return Rotate;
9923
9924   if (isSingleInputShuffleMask(Mask)) {
9925     // There are no generalized cross-lane shuffle operations available on i8
9926     // element types.
9927     if (is128BitLaneCrossingShuffleMask(MVT::v32i8, Mask))
9928       return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v32i8, V1, V2,
9929                                                      Mask, DAG);
9930
9931     SDValue PSHUFBMask[32];
9932     for (int i = 0; i < 32; ++i)
9933       PSHUFBMask[i] =
9934           Mask[i] < 0
9935               ? DAG.getUNDEF(MVT::i8)
9936               : DAG.getConstant(Mask[i] < 16 ? Mask[i] : Mask[i] - 16, DL,
9937                                 MVT::i8);
9938
9939     return DAG.getNode(
9940         X86ISD::PSHUFB, DL, MVT::v32i8, V1,
9941         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, PSHUFBMask));
9942   }
9943
9944   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9945   // shuffle.
9946   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9947           DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
9948     return Result;
9949
9950   // Otherwise fall back on generic lowering.
9951   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v32i8, V1, V2, Mask, DAG);
9952 }
9953
9954 /// \brief High-level routine to lower various 256-bit x86 vector shuffles.
9955 ///
9956 /// This routine either breaks down the specific type of a 256-bit x86 vector
9957 /// shuffle or splits it into two 128-bit shuffles and fuses the results back
9958 /// together based on the available instructions.
9959 static SDValue lower256BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9960                                         MVT VT, const X86Subtarget *Subtarget,
9961                                         SelectionDAG &DAG) {
9962   SDLoc DL(Op);
9963   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9964   ArrayRef<int> Mask = SVOp->getMask();
9965
9966   // If we have a single input to the zero element, insert that into V1 if we
9967   // can do so cheaply.
9968   int NumElts = VT.getVectorNumElements();
9969   int NumV2Elements = std::count_if(Mask.begin(), Mask.end(), [NumElts](int M) {
9970     return M >= NumElts;
9971   });
9972
9973   if (NumV2Elements == 1 && Mask[0] >= NumElts)
9974     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
9975                               DL, VT, V1, V2, Mask, Subtarget, DAG))
9976       return Insertion;
9977
9978   // There is a really nice hard cut-over between AVX1 and AVX2 that means we can
9979   // check for those subtargets here and avoid much of the subtarget querying in
9980   // the per-vector-type lowering routines. With AVX1 we have essentially *zero*
9981   // ability to manipulate a 256-bit vector with integer types. Since we'll use
9982   // floating point types there eventually, just immediately cast everything to
9983   // a float and operate entirely in that domain.
9984   if (VT.isInteger() && !Subtarget->hasAVX2()) {
9985     int ElementBits = VT.getScalarSizeInBits();
9986     if (ElementBits < 32)
9987       // No floating point type available, decompose into 128-bit vectors.
9988       return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9989
9990     MVT FpVT = MVT::getVectorVT(MVT::getFloatingPointVT(ElementBits),
9991                                 VT.getVectorNumElements());
9992     V1 = DAG.getNode(ISD::BITCAST, DL, FpVT, V1);
9993     V2 = DAG.getNode(ISD::BITCAST, DL, FpVT, V2);
9994     return DAG.getNode(ISD::BITCAST, DL, VT,
9995                        DAG.getVectorShuffle(FpVT, DL, V1, V2, Mask));
9996   }
9997
9998   switch (VT.SimpleTy) {
9999   case MVT::v4f64:
10000     return lowerV4F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10001   case MVT::v4i64:
10002     return lowerV4I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10003   case MVT::v8f32:
10004     return lowerV8F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10005   case MVT::v8i32:
10006     return lowerV8I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10007   case MVT::v16i16:
10008     return lowerV16I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
10009   case MVT::v32i8:
10010     return lowerV32I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
10011
10012   default:
10013     llvm_unreachable("Not a valid 256-bit x86 vector type!");
10014   }
10015 }
10016
10017 /// \brief Handle lowering of 8-lane 64-bit floating point shuffles.
10018 static SDValue lowerV8F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10019                                        const X86Subtarget *Subtarget,
10020                                        SelectionDAG &DAG) {
10021   SDLoc DL(Op);
10022   assert(V1.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
10023   assert(V2.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
10024   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10025   ArrayRef<int> Mask = SVOp->getMask();
10026   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10027
10028   // X86 has dedicated unpack instructions that can handle specific blend
10029   // operations: UNPCKH and UNPCKL.
10030   if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 2, 10, 4, 12, 6, 14}))
10031     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f64, V1, V2);
10032   if (isShuffleEquivalent(V1, V2, Mask, {1, 9, 3, 11, 5, 13, 7, 15}))
10033     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f64, V1, V2);
10034
10035   // FIXME: Implement direct support for this type!
10036   return splitAndLowerVectorShuffle(DL, MVT::v8f64, V1, V2, Mask, DAG);
10037 }
10038
10039 /// \brief Handle lowering of 16-lane 32-bit floating point shuffles.
10040 static SDValue lowerV16F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10041                                        const X86Subtarget *Subtarget,
10042                                        SelectionDAG &DAG) {
10043   SDLoc DL(Op);
10044   assert(V1.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
10045   assert(V2.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
10046   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10047   ArrayRef<int> Mask = SVOp->getMask();
10048   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10049
10050   // Use dedicated unpack instructions for masks that match their pattern.
10051   if (isShuffleEquivalent(V1, V2, Mask,
10052                           {// First 128-bit lane.
10053                            0, 16, 1, 17, 4, 20, 5, 21,
10054                            // Second 128-bit lane.
10055                            8, 24, 9, 25, 12, 28, 13, 29}))
10056     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16f32, V1, V2);
10057   if (isShuffleEquivalent(V1, V2, Mask,
10058                           {// First 128-bit lane.
10059                            2, 18, 3, 19, 6, 22, 7, 23,
10060                            // Second 128-bit lane.
10061                            10, 26, 11, 27, 14, 30, 15, 31}))
10062     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16f32, V1, V2);
10063
10064   // FIXME: Implement direct support for this type!
10065   return splitAndLowerVectorShuffle(DL, MVT::v16f32, V1, V2, Mask, DAG);
10066 }
10067
10068 /// \brief Handle lowering of 8-lane 64-bit integer shuffles.
10069 static SDValue lowerV8I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10070                                        const X86Subtarget *Subtarget,
10071                                        SelectionDAG &DAG) {
10072   SDLoc DL(Op);
10073   assert(V1.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
10074   assert(V2.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
10075   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10076   ArrayRef<int> Mask = SVOp->getMask();
10077   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10078
10079   // X86 has dedicated unpack instructions that can handle specific blend
10080   // operations: UNPCKH and UNPCKL.
10081   if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 2, 10, 4, 12, 6, 14}))
10082     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i64, V1, V2);
10083   if (isShuffleEquivalent(V1, V2, Mask, {1, 9, 3, 11, 5, 13, 7, 15}))
10084     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i64, V1, V2);
10085
10086   // FIXME: Implement direct support for this type!
10087   return splitAndLowerVectorShuffle(DL, MVT::v8i64, V1, V2, Mask, DAG);
10088 }
10089
10090 /// \brief Handle lowering of 16-lane 32-bit integer shuffles.
10091 static SDValue lowerV16I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10092                                        const X86Subtarget *Subtarget,
10093                                        SelectionDAG &DAG) {
10094   SDLoc DL(Op);
10095   assert(V1.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
10096   assert(V2.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
10097   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10098   ArrayRef<int> Mask = SVOp->getMask();
10099   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10100
10101   // Use dedicated unpack instructions for masks that match their pattern.
10102   if (isShuffleEquivalent(V1, V2, Mask,
10103                           {// First 128-bit lane.
10104                            0, 16, 1, 17, 4, 20, 5, 21,
10105                            // Second 128-bit lane.
10106                            8, 24, 9, 25, 12, 28, 13, 29}))
10107     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i32, V1, V2);
10108   if (isShuffleEquivalent(V1, V2, Mask,
10109                           {// First 128-bit lane.
10110                            2, 18, 3, 19, 6, 22, 7, 23,
10111                            // Second 128-bit lane.
10112                            10, 26, 11, 27, 14, 30, 15, 31}))
10113     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i32, V1, V2);
10114
10115   // FIXME: Implement direct support for this type!
10116   return splitAndLowerVectorShuffle(DL, MVT::v16i32, V1, V2, Mask, DAG);
10117 }
10118
10119 /// \brief Handle lowering of 32-lane 16-bit integer shuffles.
10120 static SDValue lowerV32I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10121                                         const X86Subtarget *Subtarget,
10122                                         SelectionDAG &DAG) {
10123   SDLoc DL(Op);
10124   assert(V1.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10125   assert(V2.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10126   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10127   ArrayRef<int> Mask = SVOp->getMask();
10128   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
10129   assert(Subtarget->hasBWI() && "We can only lower v32i16 with AVX-512-BWI!");
10130
10131   // FIXME: Implement direct support for this type!
10132   return splitAndLowerVectorShuffle(DL, MVT::v32i16, V1, V2, Mask, DAG);
10133 }
10134
10135 /// \brief Handle lowering of 64-lane 8-bit integer shuffles.
10136 static SDValue lowerV64I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10137                                        const X86Subtarget *Subtarget,
10138                                        SelectionDAG &DAG) {
10139   SDLoc DL(Op);
10140   assert(V1.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10141   assert(V2.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10142   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10143   ArrayRef<int> Mask = SVOp->getMask();
10144   assert(Mask.size() == 64 && "Unexpected mask size for v64 shuffle!");
10145   assert(Subtarget->hasBWI() && "We can only lower v64i8 with AVX-512-BWI!");
10146
10147   // FIXME: Implement direct support for this type!
10148   return splitAndLowerVectorShuffle(DL, MVT::v64i8, V1, V2, Mask, DAG);
10149 }
10150
10151 /// \brief High-level routine to lower various 512-bit x86 vector shuffles.
10152 ///
10153 /// This routine either breaks down the specific type of a 512-bit x86 vector
10154 /// shuffle or splits it into two 256-bit shuffles and fuses the results back
10155 /// together based on the available instructions.
10156 static SDValue lower512BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10157                                         MVT VT, const X86Subtarget *Subtarget,
10158                                         SelectionDAG &DAG) {
10159   SDLoc DL(Op);
10160   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10161   ArrayRef<int> Mask = SVOp->getMask();
10162   assert(Subtarget->hasAVX512() &&
10163          "Cannot lower 512-bit vectors w/ basic ISA!");
10164
10165   // Check for being able to broadcast a single element.
10166   if (SDValue Broadcast =
10167           lowerVectorShuffleAsBroadcast(DL, VT, V1, Mask, Subtarget, DAG))
10168     return Broadcast;
10169
10170   // Dispatch to each element type for lowering. If we don't have supprot for
10171   // specific element type shuffles at 512 bits, immediately split them and
10172   // lower them. Each lowering routine of a given type is allowed to assume that
10173   // the requisite ISA extensions for that element type are available.
10174   switch (VT.SimpleTy) {
10175   case MVT::v8f64:
10176     return lowerV8F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10177   case MVT::v16f32:
10178     return lowerV16F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10179   case MVT::v8i64:
10180     return lowerV8I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10181   case MVT::v16i32:
10182     return lowerV16I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10183   case MVT::v32i16:
10184     if (Subtarget->hasBWI())
10185       return lowerV32I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
10186     break;
10187   case MVT::v64i8:
10188     if (Subtarget->hasBWI())
10189       return lowerV64I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
10190     break;
10191
10192   default:
10193     llvm_unreachable("Not a valid 512-bit x86 vector type!");
10194   }
10195
10196   // Otherwise fall back on splitting.
10197   return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10198 }
10199
10200 /// \brief Top-level lowering for x86 vector shuffles.
10201 ///
10202 /// This handles decomposition, canonicalization, and lowering of all x86
10203 /// vector shuffles. Most of the specific lowering strategies are encapsulated
10204 /// above in helper routines. The canonicalization attempts to widen shuffles
10205 /// to involve fewer lanes of wider elements, consolidate symmetric patterns
10206 /// s.t. only one of the two inputs needs to be tested, etc.
10207 static SDValue lowerVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
10208                                   SelectionDAG &DAG) {
10209   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10210   ArrayRef<int> Mask = SVOp->getMask();
10211   SDValue V1 = Op.getOperand(0);
10212   SDValue V2 = Op.getOperand(1);
10213   MVT VT = Op.getSimpleValueType();
10214   int NumElements = VT.getVectorNumElements();
10215   SDLoc dl(Op);
10216
10217   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
10218
10219   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
10220   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
10221   if (V1IsUndef && V2IsUndef)
10222     return DAG.getUNDEF(VT);
10223
10224   // When we create a shuffle node we put the UNDEF node to second operand,
10225   // but in some cases the first operand may be transformed to UNDEF.
10226   // In this case we should just commute the node.
10227   if (V1IsUndef)
10228     return DAG.getCommutedVectorShuffle(*SVOp);
10229
10230   // Check for non-undef masks pointing at an undef vector and make the masks
10231   // undef as well. This makes it easier to match the shuffle based solely on
10232   // the mask.
10233   if (V2IsUndef)
10234     for (int M : Mask)
10235       if (M >= NumElements) {
10236         SmallVector<int, 8> NewMask(Mask.begin(), Mask.end());
10237         for (int &M : NewMask)
10238           if (M >= NumElements)
10239             M = -1;
10240         return DAG.getVectorShuffle(VT, dl, V1, V2, NewMask);
10241       }
10242
10243   // We actually see shuffles that are entirely re-arrangements of a set of
10244   // zero inputs. This mostly happens while decomposing complex shuffles into
10245   // simple ones. Directly lower these as a buildvector of zeros.
10246   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
10247   if (Zeroable.all())
10248     return getZeroVector(VT, Subtarget, DAG, dl);
10249
10250   // Try to collapse shuffles into using a vector type with fewer elements but
10251   // wider element types. We cap this to not form integers or floating point
10252   // elements wider than 64 bits, but it might be interesting to form i128
10253   // integers to handle flipping the low and high halves of AVX 256-bit vectors.
10254   SmallVector<int, 16> WidenedMask;
10255   if (VT.getScalarSizeInBits() < 64 &&
10256       canWidenShuffleElements(Mask, WidenedMask)) {
10257     MVT NewEltVT = VT.isFloatingPoint()
10258                        ? MVT::getFloatingPointVT(VT.getScalarSizeInBits() * 2)
10259                        : MVT::getIntegerVT(VT.getScalarSizeInBits() * 2);
10260     MVT NewVT = MVT::getVectorVT(NewEltVT, VT.getVectorNumElements() / 2);
10261     // Make sure that the new vector type is legal. For example, v2f64 isn't
10262     // legal on SSE1.
10263     if (DAG.getTargetLoweringInfo().isTypeLegal(NewVT)) {
10264       V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
10265       V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
10266       return DAG.getNode(ISD::BITCAST, dl, VT,
10267                          DAG.getVectorShuffle(NewVT, dl, V1, V2, WidenedMask));
10268     }
10269   }
10270
10271   int NumV1Elements = 0, NumUndefElements = 0, NumV2Elements = 0;
10272   for (int M : SVOp->getMask())
10273     if (M < 0)
10274       ++NumUndefElements;
10275     else if (M < NumElements)
10276       ++NumV1Elements;
10277     else
10278       ++NumV2Elements;
10279
10280   // Commute the shuffle as needed such that more elements come from V1 than
10281   // V2. This allows us to match the shuffle pattern strictly on how many
10282   // elements come from V1 without handling the symmetric cases.
10283   if (NumV2Elements > NumV1Elements)
10284     return DAG.getCommutedVectorShuffle(*SVOp);
10285
10286   // When the number of V1 and V2 elements are the same, try to minimize the
10287   // number of uses of V2 in the low half of the vector. When that is tied,
10288   // ensure that the sum of indices for V1 is equal to or lower than the sum
10289   // indices for V2. When those are equal, try to ensure that the number of odd
10290   // indices for V1 is lower than the number of odd indices for V2.
10291   if (NumV1Elements == NumV2Elements) {
10292     int LowV1Elements = 0, LowV2Elements = 0;
10293     for (int M : SVOp->getMask().slice(0, NumElements / 2))
10294       if (M >= NumElements)
10295         ++LowV2Elements;
10296       else if (M >= 0)
10297         ++LowV1Elements;
10298     if (LowV2Elements > LowV1Elements) {
10299       return DAG.getCommutedVectorShuffle(*SVOp);
10300     } else if (LowV2Elements == LowV1Elements) {
10301       int SumV1Indices = 0, SumV2Indices = 0;
10302       for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
10303         if (SVOp->getMask()[i] >= NumElements)
10304           SumV2Indices += i;
10305         else if (SVOp->getMask()[i] >= 0)
10306           SumV1Indices += i;
10307       if (SumV2Indices < SumV1Indices) {
10308         return DAG.getCommutedVectorShuffle(*SVOp);
10309       } else if (SumV2Indices == SumV1Indices) {
10310         int NumV1OddIndices = 0, NumV2OddIndices = 0;
10311         for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
10312           if (SVOp->getMask()[i] >= NumElements)
10313             NumV2OddIndices += i % 2;
10314           else if (SVOp->getMask()[i] >= 0)
10315             NumV1OddIndices += i % 2;
10316         if (NumV2OddIndices < NumV1OddIndices)
10317           return DAG.getCommutedVectorShuffle(*SVOp);
10318       }
10319     }
10320   }
10321
10322   // For each vector width, delegate to a specialized lowering routine.
10323   if (VT.getSizeInBits() == 128)
10324     return lower128BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10325
10326   if (VT.getSizeInBits() == 256)
10327     return lower256BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10328
10329   // Force AVX-512 vectors to be scalarized for now.
10330   // FIXME: Implement AVX-512 support!
10331   if (VT.getSizeInBits() == 512)
10332     return lower512BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10333
10334   llvm_unreachable("Unimplemented!");
10335 }
10336
10337 // This function assumes its argument is a BUILD_VECTOR of constants or
10338 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
10339 // true.
10340 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
10341                                     unsigned &MaskValue) {
10342   MaskValue = 0;
10343   unsigned NumElems = BuildVector->getNumOperands();
10344   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
10345   unsigned NumLanes = (NumElems - 1) / 8 + 1;
10346   unsigned NumElemsInLane = NumElems / NumLanes;
10347
10348   // Blend for v16i16 should be symetric for the both lanes.
10349   for (unsigned i = 0; i < NumElemsInLane; ++i) {
10350     SDValue EltCond = BuildVector->getOperand(i);
10351     SDValue SndLaneEltCond =
10352         (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
10353
10354     int Lane1Cond = -1, Lane2Cond = -1;
10355     if (isa<ConstantSDNode>(EltCond))
10356       Lane1Cond = !isZero(EltCond);
10357     if (isa<ConstantSDNode>(SndLaneEltCond))
10358       Lane2Cond = !isZero(SndLaneEltCond);
10359
10360     if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
10361       // Lane1Cond != 0, means we want the first argument.
10362       // Lane1Cond == 0, means we want the second argument.
10363       // The encoding of this argument is 0 for the first argument, 1
10364       // for the second. Therefore, invert the condition.
10365       MaskValue |= !Lane1Cond << i;
10366     else if (Lane1Cond < 0)
10367       MaskValue |= !Lane2Cond << i;
10368     else
10369       return false;
10370   }
10371   return true;
10372 }
10373
10374 /// \brief Try to lower a VSELECT instruction to a vector shuffle.
10375 static SDValue lowerVSELECTtoVectorShuffle(SDValue Op,
10376                                            const X86Subtarget *Subtarget,
10377                                            SelectionDAG &DAG) {
10378   SDValue Cond = Op.getOperand(0);
10379   SDValue LHS = Op.getOperand(1);
10380   SDValue RHS = Op.getOperand(2);
10381   SDLoc dl(Op);
10382   MVT VT = Op.getSimpleValueType();
10383
10384   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
10385     return SDValue();
10386   auto *CondBV = cast<BuildVectorSDNode>(Cond);
10387
10388   // Only non-legal VSELECTs reach this lowering, convert those into generic
10389   // shuffles and re-use the shuffle lowering path for blends.
10390   SmallVector<int, 32> Mask;
10391   for (int i = 0, Size = VT.getVectorNumElements(); i < Size; ++i) {
10392     SDValue CondElt = CondBV->getOperand(i);
10393     Mask.push_back(
10394         isa<ConstantSDNode>(CondElt) ? i + (isZero(CondElt) ? Size : 0) : -1);
10395   }
10396   return DAG.getVectorShuffle(VT, dl, LHS, RHS, Mask);
10397 }
10398
10399 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
10400   // A vselect where all conditions and data are constants can be optimized into
10401   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
10402   if (ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(0).getNode()) &&
10403       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(1).getNode()) &&
10404       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(2).getNode()))
10405     return SDValue();
10406
10407   // Try to lower this to a blend-style vector shuffle. This can handle all
10408   // constant condition cases.
10409   if (SDValue BlendOp = lowerVSELECTtoVectorShuffle(Op, Subtarget, DAG))
10410     return BlendOp;
10411
10412   // Variable blends are only legal from SSE4.1 onward.
10413   if (!Subtarget->hasSSE41())
10414     return SDValue();
10415
10416   // Only some types will be legal on some subtargets. If we can emit a legal
10417   // VSELECT-matching blend, return Op, and but if we need to expand, return
10418   // a null value.
10419   switch (Op.getSimpleValueType().SimpleTy) {
10420   default:
10421     // Most of the vector types have blends past SSE4.1.
10422     return Op;
10423
10424   case MVT::v32i8:
10425     // The byte blends for AVX vectors were introduced only in AVX2.
10426     if (Subtarget->hasAVX2())
10427       return Op;
10428
10429     return SDValue();
10430
10431   case MVT::v8i16:
10432   case MVT::v16i16:
10433     // AVX-512 BWI and VLX features support VSELECT with i16 elements.
10434     if (Subtarget->hasBWI() && Subtarget->hasVLX())
10435       return Op;
10436
10437     // FIXME: We should custom lower this by fixing the condition and using i8
10438     // blends.
10439     return SDValue();
10440   }
10441 }
10442
10443 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
10444   MVT VT = Op.getSimpleValueType();
10445   SDLoc dl(Op);
10446
10447   if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
10448     return SDValue();
10449
10450   if (VT.getSizeInBits() == 8) {
10451     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
10452                                   Op.getOperand(0), Op.getOperand(1));
10453     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
10454                                   DAG.getValueType(VT));
10455     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10456   }
10457
10458   if (VT.getSizeInBits() == 16) {
10459     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10460     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
10461     if (Idx == 0)
10462       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
10463                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10464                                      DAG.getNode(ISD::BITCAST, dl,
10465                                                  MVT::v4i32,
10466                                                  Op.getOperand(0)),
10467                                      Op.getOperand(1)));
10468     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
10469                                   Op.getOperand(0), Op.getOperand(1));
10470     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
10471                                   DAG.getValueType(VT));
10472     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10473   }
10474
10475   if (VT == MVT::f32) {
10476     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
10477     // the result back to FR32 register. It's only worth matching if the
10478     // result has a single use which is a store or a bitcast to i32.  And in
10479     // the case of a store, it's not worth it if the index is a constant 0,
10480     // because a MOVSSmr can be used instead, which is smaller and faster.
10481     if (!Op.hasOneUse())
10482       return SDValue();
10483     SDNode *User = *Op.getNode()->use_begin();
10484     if ((User->getOpcode() != ISD::STORE ||
10485          (isa<ConstantSDNode>(Op.getOperand(1)) &&
10486           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
10487         (User->getOpcode() != ISD::BITCAST ||
10488          User->getValueType(0) != MVT::i32))
10489       return SDValue();
10490     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10491                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
10492                                               Op.getOperand(0)),
10493                                               Op.getOperand(1));
10494     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
10495   }
10496
10497   if (VT == MVT::i32 || VT == MVT::i64) {
10498     // ExtractPS/pextrq works with constant index.
10499     if (isa<ConstantSDNode>(Op.getOperand(1)))
10500       return Op;
10501   }
10502   return SDValue();
10503 }
10504
10505 /// Extract one bit from mask vector, like v16i1 or v8i1.
10506 /// AVX-512 feature.
10507 SDValue
10508 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
10509   SDValue Vec = Op.getOperand(0);
10510   SDLoc dl(Vec);
10511   MVT VecVT = Vec.getSimpleValueType();
10512   SDValue Idx = Op.getOperand(1);
10513   MVT EltVT = Op.getSimpleValueType();
10514
10515   assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
10516   assert((VecVT.getVectorNumElements() <= 16 || Subtarget->hasBWI()) &&
10517          "Unexpected vector type in ExtractBitFromMaskVector");
10518
10519   // variable index can't be handled in mask registers,
10520   // extend vector to VR512
10521   if (!isa<ConstantSDNode>(Idx)) {
10522     MVT ExtVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
10523     SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
10524     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
10525                               ExtVT.getVectorElementType(), Ext, Idx);
10526     return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
10527   }
10528
10529   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10530   const TargetRegisterClass* rc = getRegClassFor(VecVT);
10531   if (!Subtarget->hasDQI() && (VecVT.getVectorNumElements() <= 8))
10532     rc = getRegClassFor(MVT::v16i1);
10533   unsigned MaxSift = rc->getSize()*8 - 1;
10534   Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
10535                     DAG.getConstant(MaxSift - IdxVal, dl, MVT::i8));
10536   Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
10537                     DAG.getConstant(MaxSift, dl, MVT::i8));
10538   return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
10539                        DAG.getIntPtrConstant(0, dl));
10540 }
10541
10542 SDValue
10543 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
10544                                            SelectionDAG &DAG) const {
10545   SDLoc dl(Op);
10546   SDValue Vec = Op.getOperand(0);
10547   MVT VecVT = Vec.getSimpleValueType();
10548   SDValue Idx = Op.getOperand(1);
10549
10550   if (Op.getSimpleValueType() == MVT::i1)
10551     return ExtractBitFromMaskVector(Op, DAG);
10552
10553   if (!isa<ConstantSDNode>(Idx)) {
10554     if (VecVT.is512BitVector() ||
10555         (VecVT.is256BitVector() && Subtarget->hasInt256() &&
10556          VecVT.getVectorElementType().getSizeInBits() == 32)) {
10557
10558       MVT MaskEltVT =
10559         MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
10560       MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
10561                                     MaskEltVT.getSizeInBits());
10562
10563       Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
10564       SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
10565                                 getZeroVector(MaskVT, Subtarget, DAG, dl),
10566                                 Idx, DAG.getConstant(0, dl, getPointerTy()));
10567       SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
10568       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(),
10569                         Perm, DAG.getConstant(0, dl, getPointerTy()));
10570     }
10571     return SDValue();
10572   }
10573
10574   // If this is a 256-bit vector result, first extract the 128-bit vector and
10575   // then extract the element from the 128-bit vector.
10576   if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
10577
10578     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10579     // Get the 128-bit vector.
10580     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
10581     MVT EltVT = VecVT.getVectorElementType();
10582
10583     unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
10584
10585     //if (IdxVal >= NumElems/2)
10586     //  IdxVal -= NumElems/2;
10587     IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
10588     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
10589                        DAG.getConstant(IdxVal, dl, MVT::i32));
10590   }
10591
10592   assert(VecVT.is128BitVector() && "Unexpected vector length");
10593
10594   if (Subtarget->hasSSE41()) {
10595     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
10596     if (Res.getNode())
10597       return Res;
10598   }
10599
10600   MVT VT = Op.getSimpleValueType();
10601   // TODO: handle v16i8.
10602   if (VT.getSizeInBits() == 16) {
10603     SDValue Vec = Op.getOperand(0);
10604     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10605     if (Idx == 0)
10606       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
10607                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10608                                      DAG.getNode(ISD::BITCAST, dl,
10609                                                  MVT::v4i32, Vec),
10610                                      Op.getOperand(1)));
10611     // Transform it so it match pextrw which produces a 32-bit result.
10612     MVT EltVT = MVT::i32;
10613     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
10614                                   Op.getOperand(0), Op.getOperand(1));
10615     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
10616                                   DAG.getValueType(VT));
10617     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10618   }
10619
10620   if (VT.getSizeInBits() == 32) {
10621     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10622     if (Idx == 0)
10623       return Op;
10624
10625     // SHUFPS the element to the lowest double word, then movss.
10626     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
10627     MVT VVT = Op.getOperand(0).getSimpleValueType();
10628     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
10629                                        DAG.getUNDEF(VVT), Mask);
10630     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
10631                        DAG.getIntPtrConstant(0, dl));
10632   }
10633
10634   if (VT.getSizeInBits() == 64) {
10635     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
10636     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
10637     //        to match extract_elt for f64.
10638     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10639     if (Idx == 0)
10640       return Op;
10641
10642     // UNPCKHPD the element to the lowest double word, then movsd.
10643     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
10644     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
10645     int Mask[2] = { 1, -1 };
10646     MVT VVT = Op.getOperand(0).getSimpleValueType();
10647     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
10648                                        DAG.getUNDEF(VVT), Mask);
10649     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
10650                        DAG.getIntPtrConstant(0, dl));
10651   }
10652
10653   return SDValue();
10654 }
10655
10656 /// Insert one bit to mask vector, like v16i1 or v8i1.
10657 /// AVX-512 feature.
10658 SDValue
10659 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
10660   SDLoc dl(Op);
10661   SDValue Vec = Op.getOperand(0);
10662   SDValue Elt = Op.getOperand(1);
10663   SDValue Idx = Op.getOperand(2);
10664   MVT VecVT = Vec.getSimpleValueType();
10665
10666   if (!isa<ConstantSDNode>(Idx)) {
10667     // Non constant index. Extend source and destination,
10668     // insert element and then truncate the result.
10669     MVT ExtVecVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
10670     MVT ExtEltVT = (VecVT == MVT::v8i1 ?  MVT::i64 : MVT::i32);
10671     SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT,
10672       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
10673       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
10674     return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
10675   }
10676
10677   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10678   SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
10679   if (Vec.getOpcode() == ISD::UNDEF)
10680     return DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
10681                        DAG.getConstant(IdxVal, dl, MVT::i8));
10682   const TargetRegisterClass* rc = getRegClassFor(VecVT);
10683   unsigned MaxSift = rc->getSize()*8 - 1;
10684   EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
10685                     DAG.getConstant(MaxSift, dl, MVT::i8));
10686   EltInVec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, EltInVec,
10687                     DAG.getConstant(MaxSift - IdxVal, dl, MVT::i8));
10688   return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
10689 }
10690
10691 SDValue X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
10692                                                   SelectionDAG &DAG) const {
10693   MVT VT = Op.getSimpleValueType();
10694   MVT EltVT = VT.getVectorElementType();
10695
10696   if (EltVT == MVT::i1)
10697     return InsertBitToMaskVector(Op, DAG);
10698
10699   SDLoc dl(Op);
10700   SDValue N0 = Op.getOperand(0);
10701   SDValue N1 = Op.getOperand(1);
10702   SDValue N2 = Op.getOperand(2);
10703   if (!isa<ConstantSDNode>(N2))
10704     return SDValue();
10705   auto *N2C = cast<ConstantSDNode>(N2);
10706   unsigned IdxVal = N2C->getZExtValue();
10707
10708   // If the vector is wider than 128 bits, extract the 128-bit subvector, insert
10709   // into that, and then insert the subvector back into the result.
10710   if (VT.is256BitVector() || VT.is512BitVector()) {
10711     // With a 256-bit vector, we can insert into the zero element efficiently
10712     // using a blend if we have AVX or AVX2 and the right data type.
10713     if (VT.is256BitVector() && IdxVal == 0) {
10714       // TODO: It is worthwhile to cast integer to floating point and back
10715       // and incur a domain crossing penalty if that's what we'll end up
10716       // doing anyway after extracting to a 128-bit vector.
10717       if ((Subtarget->hasAVX() && (EltVT == MVT::f64 || EltVT == MVT::f32)) ||
10718           (Subtarget->hasAVX2() && EltVT == MVT::i32)) {
10719         SDValue N1Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, N1);
10720         N2 = DAG.getIntPtrConstant(1, dl);
10721         return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1Vec, N2);
10722       }
10723     }
10724
10725     // Get the desired 128-bit vector chunk.
10726     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
10727
10728     // Insert the element into the desired chunk.
10729     unsigned NumEltsIn128 = 128 / EltVT.getSizeInBits();
10730     unsigned IdxIn128 = IdxVal - (IdxVal / NumEltsIn128) * NumEltsIn128;
10731
10732     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
10733                     DAG.getConstant(IdxIn128, dl, MVT::i32));
10734
10735     // Insert the changed part back into the bigger vector
10736     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
10737   }
10738   assert(VT.is128BitVector() && "Only 128-bit vector types should be left!");
10739
10740   if (Subtarget->hasSSE41()) {
10741     if (EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) {
10742       unsigned Opc;
10743       if (VT == MVT::v8i16) {
10744         Opc = X86ISD::PINSRW;
10745       } else {
10746         assert(VT == MVT::v16i8);
10747         Opc = X86ISD::PINSRB;
10748       }
10749
10750       // Transform it so it match pinsr{b,w} which expects a GR32 as its second
10751       // argument.
10752       if (N1.getValueType() != MVT::i32)
10753         N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
10754       if (N2.getValueType() != MVT::i32)
10755         N2 = DAG.getIntPtrConstant(IdxVal, dl);
10756       return DAG.getNode(Opc, dl, VT, N0, N1, N2);
10757     }
10758
10759     if (EltVT == MVT::f32) {
10760       // Bits [7:6] of the constant are the source select. This will always be
10761       //   zero here. The DAG Combiner may combine an extract_elt index into
10762       //   these bits. For example (insert (extract, 3), 2) could be matched by
10763       //   putting the '3' into bits [7:6] of X86ISD::INSERTPS.
10764       // Bits [5:4] of the constant are the destination select. This is the
10765       //   value of the incoming immediate.
10766       // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
10767       //   combine either bitwise AND or insert of float 0.0 to set these bits.
10768
10769       const Function *F = DAG.getMachineFunction().getFunction();
10770       bool MinSize = F->hasFnAttribute(Attribute::MinSize);
10771       if (IdxVal == 0 && (!MinSize || !MayFoldLoad(N1))) {
10772         // If this is an insertion of 32-bits into the low 32-bits of
10773         // a vector, we prefer to generate a blend with immediate rather
10774         // than an insertps. Blends are simpler operations in hardware and so
10775         // will always have equal or better performance than insertps.
10776         // But if optimizing for size and there's a load folding opportunity,
10777         // generate insertps because blendps does not have a 32-bit memory
10778         // operand form.
10779         N2 = DAG.getIntPtrConstant(1, dl);
10780         N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
10781         return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1, N2);
10782       }
10783       N2 = DAG.getIntPtrConstant(IdxVal << 4, dl);
10784       // Create this as a scalar to vector..
10785       N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
10786       return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
10787     }
10788
10789     if (EltVT == MVT::i32 || EltVT == MVT::i64) {
10790       // PINSR* works with constant index.
10791       return Op;
10792     }
10793   }
10794
10795   if (EltVT == MVT::i8)
10796     return SDValue();
10797
10798   if (EltVT.getSizeInBits() == 16) {
10799     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
10800     // as its second argument.
10801     if (N1.getValueType() != MVT::i32)
10802       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
10803     if (N2.getValueType() != MVT::i32)
10804       N2 = DAG.getIntPtrConstant(IdxVal, dl);
10805     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
10806   }
10807   return SDValue();
10808 }
10809
10810 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
10811   SDLoc dl(Op);
10812   MVT OpVT = Op.getSimpleValueType();
10813
10814   // If this is a 256-bit vector result, first insert into a 128-bit
10815   // vector and then insert into the 256-bit vector.
10816   if (!OpVT.is128BitVector()) {
10817     // Insert into a 128-bit vector.
10818     unsigned SizeFactor = OpVT.getSizeInBits()/128;
10819     MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
10820                                  OpVT.getVectorNumElements() / SizeFactor);
10821
10822     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
10823
10824     // Insert the 128-bit vector.
10825     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
10826   }
10827
10828   if (OpVT == MVT::v1i64 &&
10829       Op.getOperand(0).getValueType() == MVT::i64)
10830     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
10831
10832   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
10833   assert(OpVT.is128BitVector() && "Expected an SSE type!");
10834   return DAG.getNode(ISD::BITCAST, dl, OpVT,
10835                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
10836 }
10837
10838 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
10839 // a simple subregister reference or explicit instructions to grab
10840 // upper bits of a vector.
10841 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
10842                                       SelectionDAG &DAG) {
10843   SDLoc dl(Op);
10844   SDValue In =  Op.getOperand(0);
10845   SDValue Idx = Op.getOperand(1);
10846   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10847   MVT ResVT   = Op.getSimpleValueType();
10848   MVT InVT    = In.getSimpleValueType();
10849
10850   if (Subtarget->hasFp256()) {
10851     if (ResVT.is128BitVector() &&
10852         (InVT.is256BitVector() || InVT.is512BitVector()) &&
10853         isa<ConstantSDNode>(Idx)) {
10854       return Extract128BitVector(In, IdxVal, DAG, dl);
10855     }
10856     if (ResVT.is256BitVector() && InVT.is512BitVector() &&
10857         isa<ConstantSDNode>(Idx)) {
10858       return Extract256BitVector(In, IdxVal, DAG, dl);
10859     }
10860   }
10861   return SDValue();
10862 }
10863
10864 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
10865 // simple superregister reference or explicit instructions to insert
10866 // the upper bits of a vector.
10867 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
10868                                      SelectionDAG &DAG) {
10869   if (!Subtarget->hasAVX())
10870     return SDValue();
10871
10872   SDLoc dl(Op);
10873   SDValue Vec = Op.getOperand(0);
10874   SDValue SubVec = Op.getOperand(1);
10875   SDValue Idx = Op.getOperand(2);
10876
10877   if (!isa<ConstantSDNode>(Idx))
10878     return SDValue();
10879
10880   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10881   MVT OpVT = Op.getSimpleValueType();
10882   MVT SubVecVT = SubVec.getSimpleValueType();
10883
10884   // Fold two 16-byte subvector loads into one 32-byte load:
10885   // (insert_subvector (insert_subvector undef, (load addr), 0),
10886   //                   (load addr + 16), Elts/2)
10887   // --> load32 addr
10888   if ((IdxVal == OpVT.getVectorNumElements() / 2) &&
10889       Vec.getOpcode() == ISD::INSERT_SUBVECTOR &&
10890       OpVT.is256BitVector() && SubVecVT.is128BitVector() &&
10891       !Subtarget->isUnalignedMem32Slow()) {
10892     SDValue SubVec2 = Vec.getOperand(1);
10893     if (auto *Idx2 = dyn_cast<ConstantSDNode>(Vec.getOperand(2))) {
10894       if (Idx2->getZExtValue() == 0) {
10895         SDValue Ops[] = { SubVec2, SubVec };
10896         SDValue LD = EltsFromConsecutiveLoads(OpVT, Ops, dl, DAG, false);
10897         if (LD.getNode())
10898           return LD;
10899       }
10900     }
10901   }
10902
10903   if ((OpVT.is256BitVector() || OpVT.is512BitVector()) &&
10904       SubVecVT.is128BitVector())
10905     return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
10906
10907   if (OpVT.is512BitVector() && SubVecVT.is256BitVector())
10908     return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
10909
10910   if (OpVT.getVectorElementType() == MVT::i1) {
10911     if (IdxVal == 0  && Vec.getOpcode() == ISD::UNDEF) // the operation is legal
10912       return Op;
10913     SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
10914     SDValue Undef = DAG.getUNDEF(OpVT);
10915     unsigned NumElems = OpVT.getVectorNumElements();
10916     SDValue ShiftBits = DAG.getConstant(NumElems/2, dl, MVT::i8);
10917
10918     if (IdxVal == OpVT.getVectorNumElements() / 2) {
10919       // Zero upper bits of the Vec
10920       Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
10921       Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
10922
10923       SDValue Vec2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef,
10924                                  SubVec, ZeroIdx);
10925       Vec2 = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec2, ShiftBits);
10926       return DAG.getNode(ISD::OR, dl, OpVT, Vec, Vec2);
10927     }
10928     if (IdxVal == 0) {
10929       SDValue Vec2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef,
10930                                  SubVec, ZeroIdx);
10931       // Zero upper bits of the Vec2
10932       Vec2 = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec2, ShiftBits);
10933       Vec2 = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec2, ShiftBits);
10934       // Zero lower bits of the Vec
10935       Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
10936       Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
10937       // Merge them together
10938       return DAG.getNode(ISD::OR, dl, OpVT, Vec, Vec2);
10939     }
10940   }
10941   return SDValue();
10942 }
10943
10944 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
10945 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
10946 // one of the above mentioned nodes. It has to be wrapped because otherwise
10947 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
10948 // be used to form addressing mode. These wrapped nodes will be selected
10949 // into MOV32ri.
10950 SDValue
10951 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
10952   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
10953
10954   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10955   // global base reg.
10956   unsigned char OpFlag = 0;
10957   unsigned WrapperKind = X86ISD::Wrapper;
10958   CodeModel::Model M = DAG.getTarget().getCodeModel();
10959
10960   if (Subtarget->isPICStyleRIPRel() &&
10961       (M == CodeModel::Small || M == CodeModel::Kernel))
10962     WrapperKind = X86ISD::WrapperRIP;
10963   else if (Subtarget->isPICStyleGOT())
10964     OpFlag = X86II::MO_GOTOFF;
10965   else if (Subtarget->isPICStyleStubPIC())
10966     OpFlag = X86II::MO_PIC_BASE_OFFSET;
10967
10968   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
10969                                              CP->getAlignment(),
10970                                              CP->getOffset(), OpFlag);
10971   SDLoc DL(CP);
10972   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10973   // With PIC, the address is actually $g + Offset.
10974   if (OpFlag) {
10975     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10976                          DAG.getNode(X86ISD::GlobalBaseReg,
10977                                      SDLoc(), getPointerTy()),
10978                          Result);
10979   }
10980
10981   return Result;
10982 }
10983
10984 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
10985   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
10986
10987   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10988   // global base reg.
10989   unsigned char OpFlag = 0;
10990   unsigned WrapperKind = X86ISD::Wrapper;
10991   CodeModel::Model M = DAG.getTarget().getCodeModel();
10992
10993   if (Subtarget->isPICStyleRIPRel() &&
10994       (M == CodeModel::Small || M == CodeModel::Kernel))
10995     WrapperKind = X86ISD::WrapperRIP;
10996   else if (Subtarget->isPICStyleGOT())
10997     OpFlag = X86II::MO_GOTOFF;
10998   else if (Subtarget->isPICStyleStubPIC())
10999     OpFlag = X86II::MO_PIC_BASE_OFFSET;
11000
11001   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
11002                                           OpFlag);
11003   SDLoc DL(JT);
11004   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
11005
11006   // With PIC, the address is actually $g + Offset.
11007   if (OpFlag)
11008     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11009                          DAG.getNode(X86ISD::GlobalBaseReg,
11010                                      SDLoc(), getPointerTy()),
11011                          Result);
11012
11013   return Result;
11014 }
11015
11016 SDValue
11017 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
11018   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
11019
11020   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11021   // global base reg.
11022   unsigned char OpFlag = 0;
11023   unsigned WrapperKind = X86ISD::Wrapper;
11024   CodeModel::Model M = DAG.getTarget().getCodeModel();
11025
11026   if (Subtarget->isPICStyleRIPRel() &&
11027       (M == CodeModel::Small || M == CodeModel::Kernel)) {
11028     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
11029       OpFlag = X86II::MO_GOTPCREL;
11030     WrapperKind = X86ISD::WrapperRIP;
11031   } else if (Subtarget->isPICStyleGOT()) {
11032     OpFlag = X86II::MO_GOT;
11033   } else if (Subtarget->isPICStyleStubPIC()) {
11034     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
11035   } else if (Subtarget->isPICStyleStubNoDynamic()) {
11036     OpFlag = X86II::MO_DARWIN_NONLAZY;
11037   }
11038
11039   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
11040
11041   SDLoc DL(Op);
11042   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
11043
11044   // With PIC, the address is actually $g + Offset.
11045   if (DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
11046       !Subtarget->is64Bit()) {
11047     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11048                          DAG.getNode(X86ISD::GlobalBaseReg,
11049                                      SDLoc(), getPointerTy()),
11050                          Result);
11051   }
11052
11053   // For symbols that require a load from a stub to get the address, emit the
11054   // load.
11055   if (isGlobalStubReference(OpFlag))
11056     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
11057                          MachinePointerInfo::getGOT(), false, false, false, 0);
11058
11059   return Result;
11060 }
11061
11062 SDValue
11063 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
11064   // Create the TargetBlockAddressAddress node.
11065   unsigned char OpFlags =
11066     Subtarget->ClassifyBlockAddressReference();
11067   CodeModel::Model M = DAG.getTarget().getCodeModel();
11068   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
11069   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
11070   SDLoc dl(Op);
11071   SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
11072                                              OpFlags);
11073
11074   if (Subtarget->isPICStyleRIPRel() &&
11075       (M == CodeModel::Small || M == CodeModel::Kernel))
11076     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
11077   else
11078     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
11079
11080   // With PIC, the address is actually $g + Offset.
11081   if (isGlobalRelativeToPICBase(OpFlags)) {
11082     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
11083                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
11084                          Result);
11085   }
11086
11087   return Result;
11088 }
11089
11090 SDValue
11091 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
11092                                       int64_t Offset, SelectionDAG &DAG) const {
11093   // Create the TargetGlobalAddress node, folding in the constant
11094   // offset if it is legal.
11095   unsigned char OpFlags =
11096       Subtarget->ClassifyGlobalReference(GV, DAG.getTarget());
11097   CodeModel::Model M = DAG.getTarget().getCodeModel();
11098   SDValue Result;
11099   if (OpFlags == X86II::MO_NO_FLAG &&
11100       X86::isOffsetSuitableForCodeModel(Offset, M)) {
11101     // A direct static reference to a global.
11102     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
11103     Offset = 0;
11104   } else {
11105     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
11106   }
11107
11108   if (Subtarget->isPICStyleRIPRel() &&
11109       (M == CodeModel::Small || M == CodeModel::Kernel))
11110     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
11111   else
11112     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
11113
11114   // With PIC, the address is actually $g + Offset.
11115   if (isGlobalRelativeToPICBase(OpFlags)) {
11116     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
11117                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
11118                          Result);
11119   }
11120
11121   // For globals that require a load from a stub to get the address, emit the
11122   // load.
11123   if (isGlobalStubReference(OpFlags))
11124     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
11125                          MachinePointerInfo::getGOT(), false, false, false, 0);
11126
11127   // If there was a non-zero offset that we didn't fold, create an explicit
11128   // addition for it.
11129   if (Offset != 0)
11130     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
11131                          DAG.getConstant(Offset, dl, getPointerTy()));
11132
11133   return Result;
11134 }
11135
11136 SDValue
11137 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
11138   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
11139   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
11140   return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
11141 }
11142
11143 static SDValue
11144 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
11145            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
11146            unsigned char OperandFlags, bool LocalDynamic = false) {
11147   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11148   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11149   SDLoc dl(GA);
11150   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11151                                            GA->getValueType(0),
11152                                            GA->getOffset(),
11153                                            OperandFlags);
11154
11155   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
11156                                            : X86ISD::TLSADDR;
11157
11158   if (InFlag) {
11159     SDValue Ops[] = { Chain,  TGA, *InFlag };
11160     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11161   } else {
11162     SDValue Ops[]  = { Chain, TGA };
11163     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11164   }
11165
11166   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
11167   MFI->setAdjustsStack(true);
11168   MFI->setHasCalls(true);
11169
11170   SDValue Flag = Chain.getValue(1);
11171   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
11172 }
11173
11174 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
11175 static SDValue
11176 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11177                                 const EVT PtrVT) {
11178   SDValue InFlag;
11179   SDLoc dl(GA);  // ? function entry point might be better
11180   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
11181                                    DAG.getNode(X86ISD::GlobalBaseReg,
11182                                                SDLoc(), PtrVT), InFlag);
11183   InFlag = Chain.getValue(1);
11184
11185   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
11186 }
11187
11188 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
11189 static SDValue
11190 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11191                                 const EVT PtrVT) {
11192   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
11193                     X86::RAX, X86II::MO_TLSGD);
11194 }
11195
11196 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
11197                                            SelectionDAG &DAG,
11198                                            const EVT PtrVT,
11199                                            bool is64Bit) {
11200   SDLoc dl(GA);
11201
11202   // Get the start address of the TLS block for this module.
11203   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
11204       .getInfo<X86MachineFunctionInfo>();
11205   MFI->incNumLocalDynamicTLSAccesses();
11206
11207   SDValue Base;
11208   if (is64Bit) {
11209     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
11210                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
11211   } else {
11212     SDValue InFlag;
11213     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
11214         DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
11215     InFlag = Chain.getValue(1);
11216     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
11217                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
11218   }
11219
11220   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
11221   // of Base.
11222
11223   // Build x@dtpoff.
11224   unsigned char OperandFlags = X86II::MO_DTPOFF;
11225   unsigned WrapperKind = X86ISD::Wrapper;
11226   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11227                                            GA->getValueType(0),
11228                                            GA->getOffset(), OperandFlags);
11229   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
11230
11231   // Add x@dtpoff with the base.
11232   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
11233 }
11234
11235 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
11236 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11237                                    const EVT PtrVT, TLSModel::Model model,
11238                                    bool is64Bit, bool isPIC) {
11239   SDLoc dl(GA);
11240
11241   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
11242   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
11243                                                          is64Bit ? 257 : 256));
11244
11245   SDValue ThreadPointer =
11246       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0, dl),
11247                   MachinePointerInfo(Ptr), false, false, false, 0);
11248
11249   unsigned char OperandFlags = 0;
11250   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
11251   // initialexec.
11252   unsigned WrapperKind = X86ISD::Wrapper;
11253   if (model == TLSModel::LocalExec) {
11254     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
11255   } else if (model == TLSModel::InitialExec) {
11256     if (is64Bit) {
11257       OperandFlags = X86II::MO_GOTTPOFF;
11258       WrapperKind = X86ISD::WrapperRIP;
11259     } else {
11260       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
11261     }
11262   } else {
11263     llvm_unreachable("Unexpected model");
11264   }
11265
11266   // emit "addl x@ntpoff,%eax" (local exec)
11267   // or "addl x@indntpoff,%eax" (initial exec)
11268   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
11269   SDValue TGA =
11270       DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
11271                                  GA->getOffset(), OperandFlags);
11272   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
11273
11274   if (model == TLSModel::InitialExec) {
11275     if (isPIC && !is64Bit) {
11276       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
11277                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
11278                            Offset);
11279     }
11280
11281     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
11282                          MachinePointerInfo::getGOT(), false, false, false, 0);
11283   }
11284
11285   // The address of the thread local variable is the add of the thread
11286   // pointer with the offset of the variable.
11287   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
11288 }
11289
11290 SDValue
11291 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
11292
11293   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
11294   const GlobalValue *GV = GA->getGlobal();
11295
11296   if (Subtarget->isTargetELF()) {
11297     TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
11298
11299     switch (model) {
11300       case TLSModel::GeneralDynamic:
11301         if (Subtarget->is64Bit())
11302           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
11303         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
11304       case TLSModel::LocalDynamic:
11305         return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
11306                                            Subtarget->is64Bit());
11307       case TLSModel::InitialExec:
11308       case TLSModel::LocalExec:
11309         return LowerToTLSExecModel(
11310             GA, DAG, getPointerTy(), model, Subtarget->is64Bit(),
11311             DAG.getTarget().getRelocationModel() == Reloc::PIC_);
11312     }
11313     llvm_unreachable("Unknown TLS model.");
11314   }
11315
11316   if (Subtarget->isTargetDarwin()) {
11317     // Darwin only has one model of TLS.  Lower to that.
11318     unsigned char OpFlag = 0;
11319     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
11320                            X86ISD::WrapperRIP : X86ISD::Wrapper;
11321
11322     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11323     // global base reg.
11324     bool PIC32 = (DAG.getTarget().getRelocationModel() == Reloc::PIC_) &&
11325                  !Subtarget->is64Bit();
11326     if (PIC32)
11327       OpFlag = X86II::MO_TLVP_PIC_BASE;
11328     else
11329       OpFlag = X86II::MO_TLVP;
11330     SDLoc DL(Op);
11331     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
11332                                                 GA->getValueType(0),
11333                                                 GA->getOffset(), OpFlag);
11334     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
11335
11336     // With PIC32, the address is actually $g + Offset.
11337     if (PIC32)
11338       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11339                            DAG.getNode(X86ISD::GlobalBaseReg,
11340                                        SDLoc(), getPointerTy()),
11341                            Offset);
11342
11343     // Lowering the machine isd will make sure everything is in the right
11344     // location.
11345     SDValue Chain = DAG.getEntryNode();
11346     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11347     SDValue Args[] = { Chain, Offset };
11348     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
11349
11350     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
11351     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11352     MFI->setAdjustsStack(true);
11353
11354     // And our return value (tls address) is in the standard call return value
11355     // location.
11356     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
11357     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
11358                               Chain.getValue(1));
11359   }
11360
11361   if (Subtarget->isTargetKnownWindowsMSVC() ||
11362       Subtarget->isTargetWindowsGNU()) {
11363     // Just use the implicit TLS architecture
11364     // Need to generate someting similar to:
11365     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
11366     //                                  ; from TEB
11367     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
11368     //   mov     rcx, qword [rdx+rcx*8]
11369     //   mov     eax, .tls$:tlsvar
11370     //   [rax+rcx] contains the address
11371     // Windows 64bit: gs:0x58
11372     // Windows 32bit: fs:__tls_array
11373
11374     SDLoc dl(GA);
11375     SDValue Chain = DAG.getEntryNode();
11376
11377     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
11378     // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
11379     // use its literal value of 0x2C.
11380     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
11381                                         ? Type::getInt8PtrTy(*DAG.getContext(),
11382                                                              256)
11383                                         : Type::getInt32PtrTy(*DAG.getContext(),
11384                                                               257));
11385
11386     SDValue TlsArray =
11387         Subtarget->is64Bit()
11388             ? DAG.getIntPtrConstant(0x58, dl)
11389             : (Subtarget->isTargetWindowsGNU()
11390                    ? DAG.getIntPtrConstant(0x2C, dl)
11391                    : DAG.getExternalSymbol("_tls_array", getPointerTy()));
11392
11393     SDValue ThreadPointer =
11394         DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
11395                     MachinePointerInfo(Ptr), false, false, false, 0);
11396
11397     // Load the _tls_index variable
11398     SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
11399     if (Subtarget->is64Bit())
11400       IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
11401                            IDX, MachinePointerInfo(), MVT::i32,
11402                            false, false, false, 0);
11403     else
11404       IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
11405                         false, false, false, 0);
11406
11407     SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()), dl,
11408                                     getPointerTy());
11409     IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
11410
11411     SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
11412     res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
11413                       false, false, false, 0);
11414
11415     // Get the offset of start of .tls section
11416     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11417                                              GA->getValueType(0),
11418                                              GA->getOffset(), X86II::MO_SECREL);
11419     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
11420
11421     // The address of the thread local variable is the add of the thread
11422     // pointer with the offset of the variable.
11423     return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
11424   }
11425
11426   llvm_unreachable("TLS not implemented for this target.");
11427 }
11428
11429 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
11430 /// and take a 2 x i32 value to shift plus a shift amount.
11431 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
11432   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
11433   MVT VT = Op.getSimpleValueType();
11434   unsigned VTBits = VT.getSizeInBits();
11435   SDLoc dl(Op);
11436   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
11437   SDValue ShOpLo = Op.getOperand(0);
11438   SDValue ShOpHi = Op.getOperand(1);
11439   SDValue ShAmt  = Op.getOperand(2);
11440   // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
11441   // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
11442   // during isel.
11443   SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
11444                                   DAG.getConstant(VTBits - 1, dl, MVT::i8));
11445   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
11446                                      DAG.getConstant(VTBits - 1, dl, MVT::i8))
11447                        : DAG.getConstant(0, dl, VT);
11448
11449   SDValue Tmp2, Tmp3;
11450   if (Op.getOpcode() == ISD::SHL_PARTS) {
11451     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
11452     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
11453   } else {
11454     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
11455     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
11456   }
11457
11458   // If the shift amount is larger or equal than the width of a part we can't
11459   // rely on the results of shld/shrd. Insert a test and select the appropriate
11460   // values for large shift amounts.
11461   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
11462                                 DAG.getConstant(VTBits, dl, MVT::i8));
11463   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11464                              AndNode, DAG.getConstant(0, dl, MVT::i8));
11465
11466   SDValue Hi, Lo;
11467   SDValue CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
11468   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
11469   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
11470
11471   if (Op.getOpcode() == ISD::SHL_PARTS) {
11472     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
11473     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
11474   } else {
11475     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
11476     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
11477   }
11478
11479   SDValue Ops[2] = { Lo, Hi };
11480   return DAG.getMergeValues(Ops, dl);
11481 }
11482
11483 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
11484                                            SelectionDAG &DAG) const {
11485   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
11486   SDLoc dl(Op);
11487
11488   if (SrcVT.isVector()) {
11489     if (SrcVT.getVectorElementType() == MVT::i1) {
11490       MVT IntegerVT = MVT::getVectorVT(MVT::i32, SrcVT.getVectorNumElements());
11491       return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
11492                          DAG.getNode(ISD::SIGN_EXTEND, dl, IntegerVT,
11493                                      Op.getOperand(0)));
11494     }
11495     return SDValue();
11496   }
11497
11498   assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
11499          "Unknown SINT_TO_FP to lower!");
11500
11501   // These are really Legal; return the operand so the caller accepts it as
11502   // Legal.
11503   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
11504     return Op;
11505   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
11506       Subtarget->is64Bit()) {
11507     return Op;
11508   }
11509
11510   unsigned Size = SrcVT.getSizeInBits()/8;
11511   MachineFunction &MF = DAG.getMachineFunction();
11512   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
11513   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11514   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11515                                StackSlot,
11516                                MachinePointerInfo::getFixedStack(SSFI),
11517                                false, false, 0);
11518   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
11519 }
11520
11521 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
11522                                      SDValue StackSlot,
11523                                      SelectionDAG &DAG) const {
11524   // Build the FILD
11525   SDLoc DL(Op);
11526   SDVTList Tys;
11527   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
11528   if (useSSE)
11529     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
11530   else
11531     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
11532
11533   unsigned ByteSize = SrcVT.getSizeInBits()/8;
11534
11535   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
11536   MachineMemOperand *MMO;
11537   if (FI) {
11538     int SSFI = FI->getIndex();
11539     MMO =
11540       DAG.getMachineFunction()
11541       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11542                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
11543   } else {
11544     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
11545     StackSlot = StackSlot.getOperand(1);
11546   }
11547   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
11548   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
11549                                            X86ISD::FILD, DL,
11550                                            Tys, Ops, SrcVT, MMO);
11551
11552   if (useSSE) {
11553     Chain = Result.getValue(1);
11554     SDValue InFlag = Result.getValue(2);
11555
11556     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
11557     // shouldn't be necessary except that RFP cannot be live across
11558     // multiple blocks. When stackifier is fixed, they can be uncoupled.
11559     MachineFunction &MF = DAG.getMachineFunction();
11560     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
11561     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
11562     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11563     Tys = DAG.getVTList(MVT::Other);
11564     SDValue Ops[] = {
11565       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
11566     };
11567     MachineMemOperand *MMO =
11568       DAG.getMachineFunction()
11569       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11570                             MachineMemOperand::MOStore, SSFISize, SSFISize);
11571
11572     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
11573                                     Ops, Op.getValueType(), MMO);
11574     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
11575                          MachinePointerInfo::getFixedStack(SSFI),
11576                          false, false, false, 0);
11577   }
11578
11579   return Result;
11580 }
11581
11582 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
11583 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
11584                                                SelectionDAG &DAG) const {
11585   // This algorithm is not obvious. Here it is what we're trying to output:
11586   /*
11587      movq       %rax,  %xmm0
11588      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
11589      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
11590      #ifdef __SSE3__
11591        haddpd   %xmm0, %xmm0
11592      #else
11593        pshufd   $0x4e, %xmm0, %xmm1
11594        addpd    %xmm1, %xmm0
11595      #endif
11596   */
11597
11598   SDLoc dl(Op);
11599   LLVMContext *Context = DAG.getContext();
11600
11601   // Build some magic constants.
11602   static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
11603   Constant *C0 = ConstantDataVector::get(*Context, CV0);
11604   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
11605
11606   SmallVector<Constant*,2> CV1;
11607   CV1.push_back(
11608     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11609                                       APInt(64, 0x4330000000000000ULL))));
11610   CV1.push_back(
11611     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11612                                       APInt(64, 0x4530000000000000ULL))));
11613   Constant *C1 = ConstantVector::get(CV1);
11614   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
11615
11616   // Load the 64-bit value into an XMM register.
11617   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
11618                             Op.getOperand(0));
11619   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
11620                               MachinePointerInfo::getConstantPool(),
11621                               false, false, false, 16);
11622   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
11623                               DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
11624                               CLod0);
11625
11626   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
11627                               MachinePointerInfo::getConstantPool(),
11628                               false, false, false, 16);
11629   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
11630   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
11631   SDValue Result;
11632
11633   if (Subtarget->hasSSE3()) {
11634     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
11635     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
11636   } else {
11637     SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
11638     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
11639                                            S2F, 0x4E, DAG);
11640     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
11641                          DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
11642                          Sub);
11643   }
11644
11645   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
11646                      DAG.getIntPtrConstant(0, dl));
11647 }
11648
11649 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
11650 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
11651                                                SelectionDAG &DAG) const {
11652   SDLoc dl(Op);
11653   // FP constant to bias correct the final result.
11654   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
11655                                    MVT::f64);
11656
11657   // Load the 32-bit value into an XMM register.
11658   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
11659                              Op.getOperand(0));
11660
11661   // Zero out the upper parts of the register.
11662   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
11663
11664   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
11665                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
11666                      DAG.getIntPtrConstant(0, dl));
11667
11668   // Or the load with the bias.
11669   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
11670                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
11671                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
11672                                                    MVT::v2f64, Load)),
11673                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
11674                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
11675                                                    MVT::v2f64, Bias)));
11676   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
11677                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
11678                    DAG.getIntPtrConstant(0, dl));
11679
11680   // Subtract the bias.
11681   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
11682
11683   // Handle final rounding.
11684   EVT DestVT = Op.getValueType();
11685
11686   if (DestVT.bitsLT(MVT::f64))
11687     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
11688                        DAG.getIntPtrConstant(0, dl));
11689   if (DestVT.bitsGT(MVT::f64))
11690     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
11691
11692   // Handle final rounding.
11693   return Sub;
11694 }
11695
11696 static SDValue lowerUINT_TO_FP_vXi32(SDValue Op, SelectionDAG &DAG,
11697                                      const X86Subtarget &Subtarget) {
11698   // The algorithm is the following:
11699   // #ifdef __SSE4_1__
11700   //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
11701   //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
11702   //                                 (uint4) 0x53000000, 0xaa);
11703   // #else
11704   //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
11705   //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
11706   // #endif
11707   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
11708   //     return (float4) lo + fhi;
11709
11710   SDLoc DL(Op);
11711   SDValue V = Op->getOperand(0);
11712   EVT VecIntVT = V.getValueType();
11713   bool Is128 = VecIntVT == MVT::v4i32;
11714   EVT VecFloatVT = Is128 ? MVT::v4f32 : MVT::v8f32;
11715   // If we convert to something else than the supported type, e.g., to v4f64,
11716   // abort early.
11717   if (VecFloatVT != Op->getValueType(0))
11718     return SDValue();
11719
11720   unsigned NumElts = VecIntVT.getVectorNumElements();
11721   assert((VecIntVT == MVT::v4i32 || VecIntVT == MVT::v8i32) &&
11722          "Unsupported custom type");
11723   assert(NumElts <= 8 && "The size of the constant array must be fixed");
11724
11725   // In the #idef/#else code, we have in common:
11726   // - The vector of constants:
11727   // -- 0x4b000000
11728   // -- 0x53000000
11729   // - A shift:
11730   // -- v >> 16
11731
11732   // Create the splat vector for 0x4b000000.
11733   SDValue CstLow = DAG.getConstant(0x4b000000, DL, MVT::i32);
11734   SDValue CstLowArray[] = {CstLow, CstLow, CstLow, CstLow,
11735                            CstLow, CstLow, CstLow, CstLow};
11736   SDValue VecCstLow = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
11737                                   makeArrayRef(&CstLowArray[0], NumElts));
11738   // Create the splat vector for 0x53000000.
11739   SDValue CstHigh = DAG.getConstant(0x53000000, DL, MVT::i32);
11740   SDValue CstHighArray[] = {CstHigh, CstHigh, CstHigh, CstHigh,
11741                             CstHigh, CstHigh, CstHigh, CstHigh};
11742   SDValue VecCstHigh = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
11743                                    makeArrayRef(&CstHighArray[0], NumElts));
11744
11745   // Create the right shift.
11746   SDValue CstShift = DAG.getConstant(16, DL, MVT::i32);
11747   SDValue CstShiftArray[] = {CstShift, CstShift, CstShift, CstShift,
11748                              CstShift, CstShift, CstShift, CstShift};
11749   SDValue VecCstShift = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
11750                                     makeArrayRef(&CstShiftArray[0], NumElts));
11751   SDValue HighShift = DAG.getNode(ISD::SRL, DL, VecIntVT, V, VecCstShift);
11752
11753   SDValue Low, High;
11754   if (Subtarget.hasSSE41()) {
11755     EVT VecI16VT = Is128 ? MVT::v8i16 : MVT::v16i16;
11756     //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
11757     SDValue VecCstLowBitcast =
11758         DAG.getNode(ISD::BITCAST, DL, VecI16VT, VecCstLow);
11759     SDValue VecBitcast = DAG.getNode(ISD::BITCAST, DL, VecI16VT, V);
11760     // Low will be bitcasted right away, so do not bother bitcasting back to its
11761     // original type.
11762     Low = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecBitcast,
11763                       VecCstLowBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
11764     //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
11765     //                                 (uint4) 0x53000000, 0xaa);
11766     SDValue VecCstHighBitcast =
11767         DAG.getNode(ISD::BITCAST, DL, VecI16VT, VecCstHigh);
11768     SDValue VecShiftBitcast =
11769         DAG.getNode(ISD::BITCAST, DL, VecI16VT, HighShift);
11770     // High will be bitcasted right away, so do not bother bitcasting back to
11771     // its original type.
11772     High = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecShiftBitcast,
11773                        VecCstHighBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
11774   } else {
11775     SDValue CstMask = DAG.getConstant(0xffff, DL, MVT::i32);
11776     SDValue VecCstMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT, CstMask,
11777                                      CstMask, CstMask, CstMask);
11778     //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
11779     SDValue LowAnd = DAG.getNode(ISD::AND, DL, VecIntVT, V, VecCstMask);
11780     Low = DAG.getNode(ISD::OR, DL, VecIntVT, LowAnd, VecCstLow);
11781
11782     //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
11783     High = DAG.getNode(ISD::OR, DL, VecIntVT, HighShift, VecCstHigh);
11784   }
11785
11786   // Create the vector constant for -(0x1.0p39f + 0x1.0p23f).
11787   SDValue CstFAdd = DAG.getConstantFP(
11788       APFloat(APFloat::IEEEsingle, APInt(32, 0xD3000080)), DL, MVT::f32);
11789   SDValue CstFAddArray[] = {CstFAdd, CstFAdd, CstFAdd, CstFAdd,
11790                             CstFAdd, CstFAdd, CstFAdd, CstFAdd};
11791   SDValue VecCstFAdd = DAG.getNode(ISD::BUILD_VECTOR, DL, VecFloatVT,
11792                                    makeArrayRef(&CstFAddArray[0], NumElts));
11793
11794   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
11795   SDValue HighBitcast = DAG.getNode(ISD::BITCAST, DL, VecFloatVT, High);
11796   SDValue FHigh =
11797       DAG.getNode(ISD::FADD, DL, VecFloatVT, HighBitcast, VecCstFAdd);
11798   //     return (float4) lo + fhi;
11799   SDValue LowBitcast = DAG.getNode(ISD::BITCAST, DL, VecFloatVT, Low);
11800   return DAG.getNode(ISD::FADD, DL, VecFloatVT, LowBitcast, FHigh);
11801 }
11802
11803 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
11804                                                SelectionDAG &DAG) const {
11805   SDValue N0 = Op.getOperand(0);
11806   MVT SVT = N0.getSimpleValueType();
11807   SDLoc dl(Op);
11808
11809   switch (SVT.SimpleTy) {
11810   default:
11811     llvm_unreachable("Custom UINT_TO_FP is not supported!");
11812   case MVT::v4i8:
11813   case MVT::v4i16:
11814   case MVT::v8i8:
11815   case MVT::v8i16: {
11816     MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
11817     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
11818                        DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
11819   }
11820   case MVT::v4i32:
11821   case MVT::v8i32:
11822     return lowerUINT_TO_FP_vXi32(Op, DAG, *Subtarget);
11823   case MVT::v16i8:
11824   case MVT::v16i16:
11825     if (Subtarget->hasAVX512())
11826       return DAG.getNode(ISD::UINT_TO_FP, dl, Op.getValueType(),
11827                          DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v16i32, N0));
11828   }
11829   llvm_unreachable(nullptr);
11830 }
11831
11832 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
11833                                            SelectionDAG &DAG) const {
11834   SDValue N0 = Op.getOperand(0);
11835   SDLoc dl(Op);
11836
11837   if (Op.getValueType().isVector())
11838     return lowerUINT_TO_FP_vec(Op, DAG);
11839
11840   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
11841   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
11842   // the optimization here.
11843   if (DAG.SignBitIsZero(N0))
11844     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
11845
11846   MVT SrcVT = N0.getSimpleValueType();
11847   MVT DstVT = Op.getSimpleValueType();
11848   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
11849     return LowerUINT_TO_FP_i64(Op, DAG);
11850   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
11851     return LowerUINT_TO_FP_i32(Op, DAG);
11852   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
11853     return SDValue();
11854
11855   // Make a 64-bit buffer, and use it to build an FILD.
11856   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
11857   if (SrcVT == MVT::i32) {
11858     SDValue WordOff = DAG.getConstant(4, dl, getPointerTy());
11859     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
11860                                      getPointerTy(), StackSlot, WordOff);
11861     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11862                                   StackSlot, MachinePointerInfo(),
11863                                   false, false, 0);
11864     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, dl, MVT::i32),
11865                                   OffsetSlot, MachinePointerInfo(),
11866                                   false, false, 0);
11867     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
11868     return Fild;
11869   }
11870
11871   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
11872   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11873                                StackSlot, MachinePointerInfo(),
11874                                false, false, 0);
11875   // For i64 source, we need to add the appropriate power of 2 if the input
11876   // was negative.  This is the same as the optimization in
11877   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
11878   // we must be careful to do the computation in x87 extended precision, not
11879   // in SSE. (The generic code can't know it's OK to do this, or how to.)
11880   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
11881   MachineMemOperand *MMO =
11882     DAG.getMachineFunction()
11883     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11884                           MachineMemOperand::MOLoad, 8, 8);
11885
11886   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
11887   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
11888   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
11889                                          MVT::i64, MMO);
11890
11891   APInt FF(32, 0x5F800000ULL);
11892
11893   // Check whether the sign bit is set.
11894   SDValue SignSet = DAG.getSetCC(dl,
11895                                  getSetCCResultType(*DAG.getContext(), MVT::i64),
11896                                  Op.getOperand(0),
11897                                  DAG.getConstant(0, dl, MVT::i64), ISD::SETLT);
11898
11899   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
11900   SDValue FudgePtr = DAG.getConstantPool(
11901                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
11902                                          getPointerTy());
11903
11904   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
11905   SDValue Zero = DAG.getIntPtrConstant(0, dl);
11906   SDValue Four = DAG.getIntPtrConstant(4, dl);
11907   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
11908                                Zero, Four);
11909   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
11910
11911   // Load the value out, extending it from f32 to f80.
11912   // FIXME: Avoid the extend by constructing the right constant pool?
11913   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
11914                                  FudgePtr, MachinePointerInfo::getConstantPool(),
11915                                  MVT::f32, false, false, false, 4);
11916   // Extend everything to 80 bits to force it to be done on x87.
11917   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
11918   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add,
11919                      DAG.getIntPtrConstant(0, dl));
11920 }
11921
11922 std::pair<SDValue,SDValue>
11923 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
11924                                     bool IsSigned, bool IsReplace) const {
11925   SDLoc DL(Op);
11926
11927   EVT DstTy = Op.getValueType();
11928
11929   if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
11930     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
11931     DstTy = MVT::i64;
11932   }
11933
11934   assert(DstTy.getSimpleVT() <= MVT::i64 &&
11935          DstTy.getSimpleVT() >= MVT::i16 &&
11936          "Unknown FP_TO_INT to lower!");
11937
11938   // These are really Legal.
11939   if (DstTy == MVT::i32 &&
11940       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
11941     return std::make_pair(SDValue(), SDValue());
11942   if (Subtarget->is64Bit() &&
11943       DstTy == MVT::i64 &&
11944       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
11945     return std::make_pair(SDValue(), SDValue());
11946
11947   // We lower FP->int64 either into FISTP64 followed by a load from a temporary
11948   // stack slot, or into the FTOL runtime function.
11949   MachineFunction &MF = DAG.getMachineFunction();
11950   unsigned MemSize = DstTy.getSizeInBits()/8;
11951   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
11952   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11953
11954   unsigned Opc;
11955   if (!IsSigned && isIntegerTypeFTOL(DstTy))
11956     Opc = X86ISD::WIN_FTOL;
11957   else
11958     switch (DstTy.getSimpleVT().SimpleTy) {
11959     default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
11960     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
11961     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
11962     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
11963     }
11964
11965   SDValue Chain = DAG.getEntryNode();
11966   SDValue Value = Op.getOperand(0);
11967   EVT TheVT = Op.getOperand(0).getValueType();
11968   // FIXME This causes a redundant load/store if the SSE-class value is already
11969   // in memory, such as if it is on the callstack.
11970   if (isScalarFPTypeInSSEReg(TheVT)) {
11971     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
11972     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
11973                          MachinePointerInfo::getFixedStack(SSFI),
11974                          false, false, 0);
11975     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
11976     SDValue Ops[] = {
11977       Chain, StackSlot, DAG.getValueType(TheVT)
11978     };
11979
11980     MachineMemOperand *MMO =
11981       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11982                               MachineMemOperand::MOLoad, MemSize, MemSize);
11983     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
11984     Chain = Value.getValue(1);
11985     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
11986     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11987   }
11988
11989   MachineMemOperand *MMO =
11990     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11991                             MachineMemOperand::MOStore, MemSize, MemSize);
11992
11993   if (Opc != X86ISD::WIN_FTOL) {
11994     // Build the FP_TO_INT*_IN_MEM
11995     SDValue Ops[] = { Chain, Value, StackSlot };
11996     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
11997                                            Ops, DstTy, MMO);
11998     return std::make_pair(FIST, StackSlot);
11999   } else {
12000     SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
12001       DAG.getVTList(MVT::Other, MVT::Glue),
12002       Chain, Value);
12003     SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
12004       MVT::i32, ftol.getValue(1));
12005     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
12006       MVT::i32, eax.getValue(2));
12007     SDValue Ops[] = { eax, edx };
12008     SDValue pair = IsReplace
12009       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops)
12010       : DAG.getMergeValues(Ops, DL);
12011     return std::make_pair(pair, SDValue());
12012   }
12013 }
12014
12015 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
12016                               const X86Subtarget *Subtarget) {
12017   MVT VT = Op->getSimpleValueType(0);
12018   SDValue In = Op->getOperand(0);
12019   MVT InVT = In.getSimpleValueType();
12020   SDLoc dl(Op);
12021
12022   if (VT.is512BitVector() || InVT.getScalarType() == MVT::i1)
12023     return DAG.getNode(ISD::ZERO_EXTEND, dl, VT, In);
12024
12025   // Optimize vectors in AVX mode:
12026   //
12027   //   v8i16 -> v8i32
12028   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
12029   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
12030   //   Concat upper and lower parts.
12031   //
12032   //   v4i32 -> v4i64
12033   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
12034   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
12035   //   Concat upper and lower parts.
12036   //
12037
12038   if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
12039       ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
12040       ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
12041     return SDValue();
12042
12043   if (Subtarget->hasInt256())
12044     return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
12045
12046   SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
12047   SDValue Undef = DAG.getUNDEF(InVT);
12048   bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
12049   SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
12050   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
12051
12052   MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
12053                              VT.getVectorNumElements()/2);
12054
12055   OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
12056   OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
12057
12058   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
12059 }
12060
12061 static  SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
12062                                         SelectionDAG &DAG) {
12063   MVT VT = Op->getSimpleValueType(0);
12064   SDValue In = Op->getOperand(0);
12065   MVT InVT = In.getSimpleValueType();
12066   SDLoc DL(Op);
12067   unsigned int NumElts = VT.getVectorNumElements();
12068   if (NumElts != 8 && NumElts != 16)
12069     return SDValue();
12070
12071   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
12072     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
12073
12074   assert(InVT.getVectorElementType() == MVT::i1);
12075   MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
12076   SDValue One =
12077    DAG.getConstant(APInt(ExtVT.getScalarSizeInBits(), 1), DL, ExtVT);
12078   SDValue Zero =
12079    DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), DL, ExtVT);
12080
12081   SDValue V = DAG.getNode(ISD::VSELECT, DL, ExtVT, In, One, Zero);
12082   if (VT.is512BitVector())
12083     return V;
12084   return DAG.getNode(X86ISD::VTRUNC, DL, VT, V);
12085 }
12086
12087 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
12088                                SelectionDAG &DAG) {
12089   if (Subtarget->hasFp256()) {
12090     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
12091     if (Res.getNode())
12092       return Res;
12093   }
12094
12095   return SDValue();
12096 }
12097
12098 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
12099                                 SelectionDAG &DAG) {
12100   SDLoc DL(Op);
12101   MVT VT = Op.getSimpleValueType();
12102   SDValue In = Op.getOperand(0);
12103   MVT SVT = In.getSimpleValueType();
12104
12105   if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
12106     return LowerZERO_EXTEND_AVX512(Op, DAG);
12107
12108   if (Subtarget->hasFp256()) {
12109     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
12110     if (Res.getNode())
12111       return Res;
12112   }
12113
12114   assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
12115          VT.getVectorNumElements() != SVT.getVectorNumElements());
12116   return SDValue();
12117 }
12118
12119 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
12120   SDLoc DL(Op);
12121   MVT VT = Op.getSimpleValueType();
12122   SDValue In = Op.getOperand(0);
12123   MVT InVT = In.getSimpleValueType();
12124
12125   if (VT == MVT::i1) {
12126     assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
12127            "Invalid scalar TRUNCATE operation");
12128     if (InVT.getSizeInBits() >= 32)
12129       return SDValue();
12130     In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
12131     return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
12132   }
12133   assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
12134          "Invalid TRUNCATE operation");
12135
12136   // move vector to mask - truncate solution for SKX
12137   if (VT.getVectorElementType() == MVT::i1) {
12138     if (InVT.is512BitVector() && InVT.getScalarSizeInBits() <= 16 &&
12139         Subtarget->hasBWI())
12140       return Op; // legal, will go to VPMOVB2M, VPMOVW2M
12141     if ((InVT.is256BitVector() || InVT.is128BitVector()) 
12142         && InVT.getScalarSizeInBits() <= 16 &&
12143         Subtarget->hasBWI() && Subtarget->hasVLX())
12144       return Op; // legal, will go to VPMOVB2M, VPMOVW2M
12145     if (InVT.is512BitVector() && InVT.getScalarSizeInBits() >= 32 &&
12146         Subtarget->hasDQI())
12147       return Op; // legal, will go to VPMOVD2M, VPMOVQ2M
12148     if ((InVT.is256BitVector() || InVT.is128BitVector()) 
12149         && InVT.getScalarSizeInBits() >= 32 &&
12150         Subtarget->hasDQI() && Subtarget->hasVLX())
12151       return Op; // legal, will go to VPMOVB2M, VPMOVQ2M
12152   }
12153   if (InVT.is512BitVector() || VT.getVectorElementType() == MVT::i1) {
12154     if (VT.getVectorElementType().getSizeInBits() >=8)
12155       return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
12156
12157     assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
12158     unsigned NumElts = InVT.getVectorNumElements();
12159     assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
12160     if (InVT.getSizeInBits() < 512) {
12161       MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
12162       In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
12163       InVT = ExtVT;
12164     }
12165
12166     SDValue OneV =
12167      DAG.getConstant(APInt::getSignBit(InVT.getScalarSizeInBits()), DL, InVT);
12168     SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
12169     return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
12170   }
12171
12172   if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
12173     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
12174     if (Subtarget->hasInt256()) {
12175       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
12176       In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
12177       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
12178                                 ShufMask);
12179       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
12180                          DAG.getIntPtrConstant(0, DL));
12181     }
12182
12183     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12184                                DAG.getIntPtrConstant(0, DL));
12185     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12186                                DAG.getIntPtrConstant(2, DL));
12187     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
12188     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
12189     static const int ShufMask[] = {0, 2, 4, 6};
12190     return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
12191   }
12192
12193   if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
12194     // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
12195     if (Subtarget->hasInt256()) {
12196       In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
12197
12198       SmallVector<SDValue,32> pshufbMask;
12199       for (unsigned i = 0; i < 2; ++i) {
12200         pshufbMask.push_back(DAG.getConstant(0x0, DL, MVT::i8));
12201         pshufbMask.push_back(DAG.getConstant(0x1, DL, MVT::i8));
12202         pshufbMask.push_back(DAG.getConstant(0x4, DL, MVT::i8));
12203         pshufbMask.push_back(DAG.getConstant(0x5, DL, MVT::i8));
12204         pshufbMask.push_back(DAG.getConstant(0x8, DL, MVT::i8));
12205         pshufbMask.push_back(DAG.getConstant(0x9, DL, MVT::i8));
12206         pshufbMask.push_back(DAG.getConstant(0xc, DL, MVT::i8));
12207         pshufbMask.push_back(DAG.getConstant(0xd, DL, MVT::i8));
12208         for (unsigned j = 0; j < 8; ++j)
12209           pshufbMask.push_back(DAG.getConstant(0x80, DL, MVT::i8));
12210       }
12211       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
12212       In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
12213       In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
12214
12215       static const int ShufMask[] = {0,  2,  -1,  -1};
12216       In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, DAG.getUNDEF(MVT::v4i64),
12217                                 &ShufMask[0]);
12218       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12219                        DAG.getIntPtrConstant(0, DL));
12220       return DAG.getNode(ISD::BITCAST, DL, VT, In);
12221     }
12222
12223     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
12224                                DAG.getIntPtrConstant(0, DL));
12225
12226     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
12227                                DAG.getIntPtrConstant(4, DL));
12228
12229     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
12230     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
12231
12232     // The PSHUFB mask:
12233     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
12234                                    -1, -1, -1, -1, -1, -1, -1, -1};
12235
12236     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
12237     OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
12238     OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
12239
12240     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
12241     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
12242
12243     // The MOVLHPS Mask:
12244     static const int ShufMask2[] = {0, 1, 4, 5};
12245     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
12246     return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
12247   }
12248
12249   // Handle truncation of V256 to V128 using shuffles.
12250   if (!VT.is128BitVector() || !InVT.is256BitVector())
12251     return SDValue();
12252
12253   assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
12254
12255   unsigned NumElems = VT.getVectorNumElements();
12256   MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
12257
12258   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
12259   // Prepare truncation shuffle mask
12260   for (unsigned i = 0; i != NumElems; ++i)
12261     MaskVec[i] = i * 2;
12262   SDValue V = DAG.getVectorShuffle(NVT, DL,
12263                                    DAG.getNode(ISD::BITCAST, DL, NVT, In),
12264                                    DAG.getUNDEF(NVT), &MaskVec[0]);
12265   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
12266                      DAG.getIntPtrConstant(0, DL));
12267 }
12268
12269 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
12270                                            SelectionDAG &DAG) const {
12271   assert(!Op.getSimpleValueType().isVector());
12272
12273   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
12274     /*IsSigned=*/ true, /*IsReplace=*/ false);
12275   SDValue FIST = Vals.first, StackSlot = Vals.second;
12276   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
12277   if (!FIST.getNode()) return Op;
12278
12279   if (StackSlot.getNode())
12280     // Load the result.
12281     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
12282                        FIST, StackSlot, MachinePointerInfo(),
12283                        false, false, false, 0);
12284
12285   // The node is the result.
12286   return FIST;
12287 }
12288
12289 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
12290                                            SelectionDAG &DAG) const {
12291   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
12292     /*IsSigned=*/ false, /*IsReplace=*/ false);
12293   SDValue FIST = Vals.first, StackSlot = Vals.second;
12294   assert(FIST.getNode() && "Unexpected failure");
12295
12296   if (StackSlot.getNode())
12297     // Load the result.
12298     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
12299                        FIST, StackSlot, MachinePointerInfo(),
12300                        false, false, false, 0);
12301
12302   // The node is the result.
12303   return FIST;
12304 }
12305
12306 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
12307   SDLoc DL(Op);
12308   MVT VT = Op.getSimpleValueType();
12309   SDValue In = Op.getOperand(0);
12310   MVT SVT = In.getSimpleValueType();
12311
12312   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
12313
12314   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
12315                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
12316                                  In, DAG.getUNDEF(SVT)));
12317 }
12318
12319 /// The only differences between FABS and FNEG are the mask and the logic op.
12320 /// FNEG also has a folding opportunity for FNEG(FABS(x)).
12321 static SDValue LowerFABSorFNEG(SDValue Op, SelectionDAG &DAG) {
12322   assert((Op.getOpcode() == ISD::FABS || Op.getOpcode() == ISD::FNEG) &&
12323          "Wrong opcode for lowering FABS or FNEG.");
12324
12325   bool IsFABS = (Op.getOpcode() == ISD::FABS);
12326
12327   // If this is a FABS and it has an FNEG user, bail out to fold the combination
12328   // into an FNABS. We'll lower the FABS after that if it is still in use.
12329   if (IsFABS)
12330     for (SDNode *User : Op->uses())
12331       if (User->getOpcode() == ISD::FNEG)
12332         return Op;
12333
12334   SDValue Op0 = Op.getOperand(0);
12335   bool IsFNABS = !IsFABS && (Op0.getOpcode() == ISD::FABS);
12336
12337   SDLoc dl(Op);
12338   MVT VT = Op.getSimpleValueType();
12339   // Assume scalar op for initialization; update for vector if needed.
12340   // Note that there are no scalar bitwise logical SSE/AVX instructions, so we
12341   // generate a 16-byte vector constant and logic op even for the scalar case.
12342   // Using a 16-byte mask allows folding the load of the mask with
12343   // the logic op, so it can save (~4 bytes) on code size.
12344   MVT EltVT = VT;
12345   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
12346   // FIXME: Use function attribute "OptimizeForSize" and/or CodeGenOpt::Level to
12347   // decide if we should generate a 16-byte constant mask when we only need 4 or
12348   // 8 bytes for the scalar case.
12349   if (VT.isVector()) {
12350     EltVT = VT.getVectorElementType();
12351     NumElts = VT.getVectorNumElements();
12352   }
12353
12354   unsigned EltBits = EltVT.getSizeInBits();
12355   LLVMContext *Context = DAG.getContext();
12356   // For FABS, mask is 0x7f...; for FNEG, mask is 0x80...
12357   APInt MaskElt =
12358     IsFABS ? APInt::getSignedMaxValue(EltBits) : APInt::getSignBit(EltBits);
12359   Constant *C = ConstantInt::get(*Context, MaskElt);
12360   C = ConstantVector::getSplat(NumElts, C);
12361   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12362   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
12363   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
12364   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
12365                              MachinePointerInfo::getConstantPool(),
12366                              false, false, false, Alignment);
12367
12368   if (VT.isVector()) {
12369     // For a vector, cast operands to a vector type, perform the logic op,
12370     // and cast the result back to the original value type.
12371     MVT VecVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
12372     SDValue MaskCasted = DAG.getNode(ISD::BITCAST, dl, VecVT, Mask);
12373     SDValue Operand = IsFNABS ?
12374       DAG.getNode(ISD::BITCAST, dl, VecVT, Op0.getOperand(0)) :
12375       DAG.getNode(ISD::BITCAST, dl, VecVT, Op0);
12376     unsigned BitOp = IsFABS ? ISD::AND : IsFNABS ? ISD::OR : ISD::XOR;
12377     return DAG.getNode(ISD::BITCAST, dl, VT,
12378                        DAG.getNode(BitOp, dl, VecVT, Operand, MaskCasted));
12379   }
12380
12381   // If not vector, then scalar.
12382   unsigned BitOp = IsFABS ? X86ISD::FAND : IsFNABS ? X86ISD::FOR : X86ISD::FXOR;
12383   SDValue Operand = IsFNABS ? Op0.getOperand(0) : Op0;
12384   return DAG.getNode(BitOp, dl, VT, Operand, Mask);
12385 }
12386
12387 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
12388   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12389   LLVMContext *Context = DAG.getContext();
12390   SDValue Op0 = Op.getOperand(0);
12391   SDValue Op1 = Op.getOperand(1);
12392   SDLoc dl(Op);
12393   MVT VT = Op.getSimpleValueType();
12394   MVT SrcVT = Op1.getSimpleValueType();
12395
12396   // If second operand is smaller, extend it first.
12397   if (SrcVT.bitsLT(VT)) {
12398     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
12399     SrcVT = VT;
12400   }
12401   // And if it is bigger, shrink it first.
12402   if (SrcVT.bitsGT(VT)) {
12403     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1, dl));
12404     SrcVT = VT;
12405   }
12406
12407   // At this point the operands and the result should have the same
12408   // type, and that won't be f80 since that is not custom lowered.
12409
12410   const fltSemantics &Sem =
12411       VT == MVT::f64 ? APFloat::IEEEdouble : APFloat::IEEEsingle;
12412   const unsigned SizeInBits = VT.getSizeInBits();
12413
12414   SmallVector<Constant *, 4> CV(
12415       VT == MVT::f64 ? 2 : 4,
12416       ConstantFP::get(*Context, APFloat(Sem, APInt(SizeInBits, 0))));
12417
12418   // First, clear all bits but the sign bit from the second operand (sign).
12419   CV[0] = ConstantFP::get(*Context,
12420                           APFloat(Sem, APInt::getHighBitsSet(SizeInBits, 1)));
12421   Constant *C = ConstantVector::get(CV);
12422   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
12423   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
12424                               MachinePointerInfo::getConstantPool(),
12425                               false, false, false, 16);
12426   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
12427
12428   // Next, clear the sign bit from the first operand (magnitude).
12429   // If it's a constant, we can clear it here.
12430   if (ConstantFPSDNode *Op0CN = dyn_cast<ConstantFPSDNode>(Op0)) {
12431     APFloat APF = Op0CN->getValueAPF();
12432     // If the magnitude is a positive zero, the sign bit alone is enough.
12433     if (APF.isPosZero())
12434       return SignBit;
12435     APF.clearSign();
12436     CV[0] = ConstantFP::get(*Context, APF);
12437   } else {
12438     CV[0] = ConstantFP::get(
12439         *Context,
12440         APFloat(Sem, APInt::getLowBitsSet(SizeInBits, SizeInBits - 1)));
12441   }
12442   C = ConstantVector::get(CV);
12443   CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
12444   SDValue Val = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
12445                             MachinePointerInfo::getConstantPool(),
12446                             false, false, false, 16);
12447   // If the magnitude operand wasn't a constant, we need to AND out the sign.
12448   if (!isa<ConstantFPSDNode>(Op0))
12449     Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Val);
12450
12451   // OR the magnitude value with the sign bit.
12452   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
12453 }
12454
12455 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
12456   SDValue N0 = Op.getOperand(0);
12457   SDLoc dl(Op);
12458   MVT VT = Op.getSimpleValueType();
12459
12460   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
12461   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
12462                                   DAG.getConstant(1, dl, VT));
12463   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, dl, VT));
12464 }
12465
12466 // Check whether an OR'd tree is PTEST-able.
12467 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
12468                                       SelectionDAG &DAG) {
12469   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
12470
12471   if (!Subtarget->hasSSE41())
12472     return SDValue();
12473
12474   if (!Op->hasOneUse())
12475     return SDValue();
12476
12477   SDNode *N = Op.getNode();
12478   SDLoc DL(N);
12479
12480   SmallVector<SDValue, 8> Opnds;
12481   DenseMap<SDValue, unsigned> VecInMap;
12482   SmallVector<SDValue, 8> VecIns;
12483   EVT VT = MVT::Other;
12484
12485   // Recognize a special case where a vector is casted into wide integer to
12486   // test all 0s.
12487   Opnds.push_back(N->getOperand(0));
12488   Opnds.push_back(N->getOperand(1));
12489
12490   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
12491     SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
12492     // BFS traverse all OR'd operands.
12493     if (I->getOpcode() == ISD::OR) {
12494       Opnds.push_back(I->getOperand(0));
12495       Opnds.push_back(I->getOperand(1));
12496       // Re-evaluate the number of nodes to be traversed.
12497       e += 2; // 2 more nodes (LHS and RHS) are pushed.
12498       continue;
12499     }
12500
12501     // Quit if a non-EXTRACT_VECTOR_ELT
12502     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
12503       return SDValue();
12504
12505     // Quit if without a constant index.
12506     SDValue Idx = I->getOperand(1);
12507     if (!isa<ConstantSDNode>(Idx))
12508       return SDValue();
12509
12510     SDValue ExtractedFromVec = I->getOperand(0);
12511     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
12512     if (M == VecInMap.end()) {
12513       VT = ExtractedFromVec.getValueType();
12514       // Quit if not 128/256-bit vector.
12515       if (!VT.is128BitVector() && !VT.is256BitVector())
12516         return SDValue();
12517       // Quit if not the same type.
12518       if (VecInMap.begin() != VecInMap.end() &&
12519           VT != VecInMap.begin()->first.getValueType())
12520         return SDValue();
12521       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
12522       VecIns.push_back(ExtractedFromVec);
12523     }
12524     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
12525   }
12526
12527   assert((VT.is128BitVector() || VT.is256BitVector()) &&
12528          "Not extracted from 128-/256-bit vector.");
12529
12530   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
12531
12532   for (DenseMap<SDValue, unsigned>::const_iterator
12533         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
12534     // Quit if not all elements are used.
12535     if (I->second != FullMask)
12536       return SDValue();
12537   }
12538
12539   EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
12540
12541   // Cast all vectors into TestVT for PTEST.
12542   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
12543     VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
12544
12545   // If more than one full vectors are evaluated, OR them first before PTEST.
12546   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
12547     // Each iteration will OR 2 nodes and append the result until there is only
12548     // 1 node left, i.e. the final OR'd value of all vectors.
12549     SDValue LHS = VecIns[Slot];
12550     SDValue RHS = VecIns[Slot + 1];
12551     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
12552   }
12553
12554   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
12555                      VecIns.back(), VecIns.back());
12556 }
12557
12558 /// \brief return true if \c Op has a use that doesn't just read flags.
12559 static bool hasNonFlagsUse(SDValue Op) {
12560   for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
12561        ++UI) {
12562     SDNode *User = *UI;
12563     unsigned UOpNo = UI.getOperandNo();
12564     if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
12565       // Look pass truncate.
12566       UOpNo = User->use_begin().getOperandNo();
12567       User = *User->use_begin();
12568     }
12569
12570     if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
12571         !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
12572       return true;
12573   }
12574   return false;
12575 }
12576
12577 /// Emit nodes that will be selected as "test Op0,Op0", or something
12578 /// equivalent.
12579 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
12580                                     SelectionDAG &DAG) const {
12581   if (Op.getValueType() == MVT::i1) {
12582     SDValue ExtOp = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i8, Op);
12583     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, ExtOp,
12584                        DAG.getConstant(0, dl, MVT::i8));
12585   }
12586   // CF and OF aren't always set the way we want. Determine which
12587   // of these we need.
12588   bool NeedCF = false;
12589   bool NeedOF = false;
12590   switch (X86CC) {
12591   default: break;
12592   case X86::COND_A: case X86::COND_AE:
12593   case X86::COND_B: case X86::COND_BE:
12594     NeedCF = true;
12595     break;
12596   case X86::COND_G: case X86::COND_GE:
12597   case X86::COND_L: case X86::COND_LE:
12598   case X86::COND_O: case X86::COND_NO: {
12599     // Check if we really need to set the
12600     // Overflow flag. If NoSignedWrap is present
12601     // that is not actually needed.
12602     switch (Op->getOpcode()) {
12603     case ISD::ADD:
12604     case ISD::SUB:
12605     case ISD::MUL:
12606     case ISD::SHL: {
12607       const auto *BinNode = cast<BinaryWithFlagsSDNode>(Op.getNode());
12608       if (BinNode->Flags.hasNoSignedWrap())
12609         break;
12610     }
12611     default:
12612       NeedOF = true;
12613       break;
12614     }
12615     break;
12616   }
12617   }
12618   // See if we can use the EFLAGS value from the operand instead of
12619   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
12620   // we prove that the arithmetic won't overflow, we can't use OF or CF.
12621   if (Op.getResNo() != 0 || NeedOF || NeedCF) {
12622     // Emit a CMP with 0, which is the TEST pattern.
12623     //if (Op.getValueType() == MVT::i1)
12624     //  return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
12625     //                     DAG.getConstant(0, MVT::i1));
12626     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
12627                        DAG.getConstant(0, dl, Op.getValueType()));
12628   }
12629   unsigned Opcode = 0;
12630   unsigned NumOperands = 0;
12631
12632   // Truncate operations may prevent the merge of the SETCC instruction
12633   // and the arithmetic instruction before it. Attempt to truncate the operands
12634   // of the arithmetic instruction and use a reduced bit-width instruction.
12635   bool NeedTruncation = false;
12636   SDValue ArithOp = Op;
12637   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
12638     SDValue Arith = Op->getOperand(0);
12639     // Both the trunc and the arithmetic op need to have one user each.
12640     if (Arith->hasOneUse())
12641       switch (Arith.getOpcode()) {
12642         default: break;
12643         case ISD::ADD:
12644         case ISD::SUB:
12645         case ISD::AND:
12646         case ISD::OR:
12647         case ISD::XOR: {
12648           NeedTruncation = true;
12649           ArithOp = Arith;
12650         }
12651       }
12652   }
12653
12654   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
12655   // which may be the result of a CAST.  We use the variable 'Op', which is the
12656   // non-casted variable when we check for possible users.
12657   switch (ArithOp.getOpcode()) {
12658   case ISD::ADD:
12659     // Due to an isel shortcoming, be conservative if this add is likely to be
12660     // selected as part of a load-modify-store instruction. When the root node
12661     // in a match is a store, isel doesn't know how to remap non-chain non-flag
12662     // uses of other nodes in the match, such as the ADD in this case. This
12663     // leads to the ADD being left around and reselected, with the result being
12664     // two adds in the output.  Alas, even if none our users are stores, that
12665     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
12666     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
12667     // climbing the DAG back to the root, and it doesn't seem to be worth the
12668     // effort.
12669     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
12670          UE = Op.getNode()->use_end(); UI != UE; ++UI)
12671       if (UI->getOpcode() != ISD::CopyToReg &&
12672           UI->getOpcode() != ISD::SETCC &&
12673           UI->getOpcode() != ISD::STORE)
12674         goto default_case;
12675
12676     if (ConstantSDNode *C =
12677         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
12678       // An add of one will be selected as an INC.
12679       if (C->getAPIntValue() == 1 && !Subtarget->slowIncDec()) {
12680         Opcode = X86ISD::INC;
12681         NumOperands = 1;
12682         break;
12683       }
12684
12685       // An add of negative one (subtract of one) will be selected as a DEC.
12686       if (C->getAPIntValue().isAllOnesValue() && !Subtarget->slowIncDec()) {
12687         Opcode = X86ISD::DEC;
12688         NumOperands = 1;
12689         break;
12690       }
12691     }
12692
12693     // Otherwise use a regular EFLAGS-setting add.
12694     Opcode = X86ISD::ADD;
12695     NumOperands = 2;
12696     break;
12697   case ISD::SHL:
12698   case ISD::SRL:
12699     // If we have a constant logical shift that's only used in a comparison
12700     // against zero turn it into an equivalent AND. This allows turning it into
12701     // a TEST instruction later.
12702     if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
12703         isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
12704       EVT VT = Op.getValueType();
12705       unsigned BitWidth = VT.getSizeInBits();
12706       unsigned ShAmt = Op->getConstantOperandVal(1);
12707       if (ShAmt >= BitWidth) // Avoid undefined shifts.
12708         break;
12709       APInt Mask = ArithOp.getOpcode() == ISD::SRL
12710                        ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
12711                        : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
12712       if (!Mask.isSignedIntN(32)) // Avoid large immediates.
12713         break;
12714       SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
12715                                 DAG.getConstant(Mask, dl, VT));
12716       DAG.ReplaceAllUsesWith(Op, New);
12717       Op = New;
12718     }
12719     break;
12720
12721   case ISD::AND:
12722     // If the primary and result isn't used, don't bother using X86ISD::AND,
12723     // because a TEST instruction will be better.
12724     if (!hasNonFlagsUse(Op))
12725       break;
12726     // FALL THROUGH
12727   case ISD::SUB:
12728   case ISD::OR:
12729   case ISD::XOR:
12730     // Due to the ISEL shortcoming noted above, be conservative if this op is
12731     // likely to be selected as part of a load-modify-store instruction.
12732     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
12733            UE = Op.getNode()->use_end(); UI != UE; ++UI)
12734       if (UI->getOpcode() == ISD::STORE)
12735         goto default_case;
12736
12737     // Otherwise use a regular EFLAGS-setting instruction.
12738     switch (ArithOp.getOpcode()) {
12739     default: llvm_unreachable("unexpected operator!");
12740     case ISD::SUB: Opcode = X86ISD::SUB; break;
12741     case ISD::XOR: Opcode = X86ISD::XOR; break;
12742     case ISD::AND: Opcode = X86ISD::AND; break;
12743     case ISD::OR: {
12744       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
12745         SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
12746         if (EFLAGS.getNode())
12747           return EFLAGS;
12748       }
12749       Opcode = X86ISD::OR;
12750       break;
12751     }
12752     }
12753
12754     NumOperands = 2;
12755     break;
12756   case X86ISD::ADD:
12757   case X86ISD::SUB:
12758   case X86ISD::INC:
12759   case X86ISD::DEC:
12760   case X86ISD::OR:
12761   case X86ISD::XOR:
12762   case X86ISD::AND:
12763     return SDValue(Op.getNode(), 1);
12764   default:
12765   default_case:
12766     break;
12767   }
12768
12769   // If we found that truncation is beneficial, perform the truncation and
12770   // update 'Op'.
12771   if (NeedTruncation) {
12772     EVT VT = Op.getValueType();
12773     SDValue WideVal = Op->getOperand(0);
12774     EVT WideVT = WideVal.getValueType();
12775     unsigned ConvertedOp = 0;
12776     // Use a target machine opcode to prevent further DAGCombine
12777     // optimizations that may separate the arithmetic operations
12778     // from the setcc node.
12779     switch (WideVal.getOpcode()) {
12780       default: break;
12781       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
12782       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
12783       case ISD::AND: ConvertedOp = X86ISD::AND; break;
12784       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
12785       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
12786     }
12787
12788     if (ConvertedOp) {
12789       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12790       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
12791         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
12792         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
12793         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
12794       }
12795     }
12796   }
12797
12798   if (Opcode == 0)
12799     // Emit a CMP with 0, which is the TEST pattern.
12800     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
12801                        DAG.getConstant(0, dl, Op.getValueType()));
12802
12803   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
12804   SmallVector<SDValue, 4> Ops(Op->op_begin(), Op->op_begin() + NumOperands);
12805
12806   SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
12807   DAG.ReplaceAllUsesWith(Op, New);
12808   return SDValue(New.getNode(), 1);
12809 }
12810
12811 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
12812 /// equivalent.
12813 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
12814                                    SDLoc dl, SelectionDAG &DAG) const {
12815   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
12816     if (C->getAPIntValue() == 0)
12817       return EmitTest(Op0, X86CC, dl, DAG);
12818
12819      if (Op0.getValueType() == MVT::i1)
12820        llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
12821   }
12822
12823   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
12824        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
12825     // Do the comparison at i32 if it's smaller, besides the Atom case.
12826     // This avoids subregister aliasing issues. Keep the smaller reference
12827     // if we're optimizing for size, however, as that'll allow better folding
12828     // of memory operations.
12829     if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
12830         !DAG.getMachineFunction().getFunction()->hasFnAttribute(
12831             Attribute::MinSize) &&
12832         !Subtarget->isAtom()) {
12833       unsigned ExtendOp =
12834           isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
12835       Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
12836       Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
12837     }
12838     // Use SUB instead of CMP to enable CSE between SUB and CMP.
12839     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
12840     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
12841                               Op0, Op1);
12842     return SDValue(Sub.getNode(), 1);
12843   }
12844   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
12845 }
12846
12847 /// Convert a comparison if required by the subtarget.
12848 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
12849                                                  SelectionDAG &DAG) const {
12850   // If the subtarget does not support the FUCOMI instruction, floating-point
12851   // comparisons have to be converted.
12852   if (Subtarget->hasCMov() ||
12853       Cmp.getOpcode() != X86ISD::CMP ||
12854       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
12855       !Cmp.getOperand(1).getValueType().isFloatingPoint())
12856     return Cmp;
12857
12858   // The instruction selector will select an FUCOM instruction instead of
12859   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
12860   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
12861   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
12862   SDLoc dl(Cmp);
12863   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
12864   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
12865   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
12866                             DAG.getConstant(8, dl, MVT::i8));
12867   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
12868   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
12869 }
12870
12871 /// The minimum architected relative accuracy is 2^-12. We need one
12872 /// Newton-Raphson step to have a good float result (24 bits of precision).
12873 SDValue X86TargetLowering::getRsqrtEstimate(SDValue Op,
12874                                             DAGCombinerInfo &DCI,
12875                                             unsigned &RefinementSteps,
12876                                             bool &UseOneConstNR) const {
12877   // FIXME: We should use instruction latency models to calculate the cost of
12878   // each potential sequence, but this is very hard to do reliably because
12879   // at least Intel's Core* chips have variable timing based on the number of
12880   // significant digits in the divisor and/or sqrt operand.
12881   if (!Subtarget->useSqrtEst())
12882     return SDValue();
12883
12884   EVT VT = Op.getValueType();
12885
12886   // SSE1 has rsqrtss and rsqrtps.
12887   // TODO: Add support for AVX512 (v16f32).
12888   // It is likely not profitable to do this for f64 because a double-precision
12889   // rsqrt estimate with refinement on x86 prior to FMA requires at least 16
12890   // instructions: convert to single, rsqrtss, convert back to double, refine
12891   // (3 steps = at least 13 insts). If an 'rsqrtsd' variant was added to the ISA
12892   // along with FMA, this could be a throughput win.
12893   if ((Subtarget->hasSSE1() && (VT == MVT::f32 || VT == MVT::v4f32)) ||
12894       (Subtarget->hasAVX() && VT == MVT::v8f32)) {
12895     RefinementSteps = 1;
12896     UseOneConstNR = false;
12897     return DCI.DAG.getNode(X86ISD::FRSQRT, SDLoc(Op), VT, Op);
12898   }
12899   return SDValue();
12900 }
12901
12902 /// The minimum architected relative accuracy is 2^-12. We need one
12903 /// Newton-Raphson step to have a good float result (24 bits of precision).
12904 SDValue X86TargetLowering::getRecipEstimate(SDValue Op,
12905                                             DAGCombinerInfo &DCI,
12906                                             unsigned &RefinementSteps) const {
12907   // FIXME: We should use instruction latency models to calculate the cost of
12908   // each potential sequence, but this is very hard to do reliably because
12909   // at least Intel's Core* chips have variable timing based on the number of
12910   // significant digits in the divisor.
12911   if (!Subtarget->useReciprocalEst())
12912     return SDValue();
12913
12914   EVT VT = Op.getValueType();
12915
12916   // SSE1 has rcpss and rcpps. AVX adds a 256-bit variant for rcpps.
12917   // TODO: Add support for AVX512 (v16f32).
12918   // It is likely not profitable to do this for f64 because a double-precision
12919   // reciprocal estimate with refinement on x86 prior to FMA requires
12920   // 15 instructions: convert to single, rcpss, convert back to double, refine
12921   // (3 steps = 12 insts). If an 'rcpsd' variant was added to the ISA
12922   // along with FMA, this could be a throughput win.
12923   if ((Subtarget->hasSSE1() && (VT == MVT::f32 || VT == MVT::v4f32)) ||
12924       (Subtarget->hasAVX() && VT == MVT::v8f32)) {
12925     RefinementSteps = ReciprocalEstimateRefinementSteps;
12926     return DCI.DAG.getNode(X86ISD::FRCP, SDLoc(Op), VT, Op);
12927   }
12928   return SDValue();
12929 }
12930
12931 /// If we have at least two divisions that use the same divisor, convert to
12932 /// multplication by a reciprocal. This may need to be adjusted for a given
12933 /// CPU if a division's cost is not at least twice the cost of a multiplication.
12934 /// This is because we still need one division to calculate the reciprocal and
12935 /// then we need two multiplies by that reciprocal as replacements for the
12936 /// original divisions.
12937 bool X86TargetLowering::combineRepeatedFPDivisors(unsigned NumUsers) const {
12938   return NumUsers > 1;
12939 }
12940
12941 static bool isAllOnes(SDValue V) {
12942   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
12943   return C && C->isAllOnesValue();
12944 }
12945
12946 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
12947 /// if it's possible.
12948 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
12949                                      SDLoc dl, SelectionDAG &DAG) const {
12950   SDValue Op0 = And.getOperand(0);
12951   SDValue Op1 = And.getOperand(1);
12952   if (Op0.getOpcode() == ISD::TRUNCATE)
12953     Op0 = Op0.getOperand(0);
12954   if (Op1.getOpcode() == ISD::TRUNCATE)
12955     Op1 = Op1.getOperand(0);
12956
12957   SDValue LHS, RHS;
12958   if (Op1.getOpcode() == ISD::SHL)
12959     std::swap(Op0, Op1);
12960   if (Op0.getOpcode() == ISD::SHL) {
12961     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
12962       if (And00C->getZExtValue() == 1) {
12963         // If we looked past a truncate, check that it's only truncating away
12964         // known zeros.
12965         unsigned BitWidth = Op0.getValueSizeInBits();
12966         unsigned AndBitWidth = And.getValueSizeInBits();
12967         if (BitWidth > AndBitWidth) {
12968           APInt Zeros, Ones;
12969           DAG.computeKnownBits(Op0, Zeros, Ones);
12970           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
12971             return SDValue();
12972         }
12973         LHS = Op1;
12974         RHS = Op0.getOperand(1);
12975       }
12976   } else if (Op1.getOpcode() == ISD::Constant) {
12977     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
12978     uint64_t AndRHSVal = AndRHS->getZExtValue();
12979     SDValue AndLHS = Op0;
12980
12981     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
12982       LHS = AndLHS.getOperand(0);
12983       RHS = AndLHS.getOperand(1);
12984     }
12985
12986     // Use BT if the immediate can't be encoded in a TEST instruction.
12987     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
12988       LHS = AndLHS;
12989       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), dl, LHS.getValueType());
12990     }
12991   }
12992
12993   if (LHS.getNode()) {
12994     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
12995     // instruction.  Since the shift amount is in-range-or-undefined, we know
12996     // that doing a bittest on the i32 value is ok.  We extend to i32 because
12997     // the encoding for the i16 version is larger than the i32 version.
12998     // Also promote i16 to i32 for performance / code size reason.
12999     if (LHS.getValueType() == MVT::i8 ||
13000         LHS.getValueType() == MVT::i16)
13001       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
13002
13003     // If the operand types disagree, extend the shift amount to match.  Since
13004     // BT ignores high bits (like shifts) we can use anyextend.
13005     if (LHS.getValueType() != RHS.getValueType())
13006       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
13007
13008     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
13009     X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
13010     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13011                        DAG.getConstant(Cond, dl, MVT::i8), BT);
13012   }
13013
13014   return SDValue();
13015 }
13016
13017 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
13018 /// mask CMPs.
13019 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
13020                               SDValue &Op1) {
13021   unsigned SSECC;
13022   bool Swap = false;
13023
13024   // SSE Condition code mapping:
13025   //  0 - EQ
13026   //  1 - LT
13027   //  2 - LE
13028   //  3 - UNORD
13029   //  4 - NEQ
13030   //  5 - NLT
13031   //  6 - NLE
13032   //  7 - ORD
13033   switch (SetCCOpcode) {
13034   default: llvm_unreachable("Unexpected SETCC condition");
13035   case ISD::SETOEQ:
13036   case ISD::SETEQ:  SSECC = 0; break;
13037   case ISD::SETOGT:
13038   case ISD::SETGT:  Swap = true; // Fallthrough
13039   case ISD::SETLT:
13040   case ISD::SETOLT: SSECC = 1; break;
13041   case ISD::SETOGE:
13042   case ISD::SETGE:  Swap = true; // Fallthrough
13043   case ISD::SETLE:
13044   case ISD::SETOLE: SSECC = 2; break;
13045   case ISD::SETUO:  SSECC = 3; break;
13046   case ISD::SETUNE:
13047   case ISD::SETNE:  SSECC = 4; break;
13048   case ISD::SETULE: Swap = true; // Fallthrough
13049   case ISD::SETUGE: SSECC = 5; break;
13050   case ISD::SETULT: Swap = true; // Fallthrough
13051   case ISD::SETUGT: SSECC = 6; break;
13052   case ISD::SETO:   SSECC = 7; break;
13053   case ISD::SETUEQ:
13054   case ISD::SETONE: SSECC = 8; break;
13055   }
13056   if (Swap)
13057     std::swap(Op0, Op1);
13058
13059   return SSECC;
13060 }
13061
13062 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
13063 // ones, and then concatenate the result back.
13064 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
13065   MVT VT = Op.getSimpleValueType();
13066
13067   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
13068          "Unsupported value type for operation");
13069
13070   unsigned NumElems = VT.getVectorNumElements();
13071   SDLoc dl(Op);
13072   SDValue CC = Op.getOperand(2);
13073
13074   // Extract the LHS vectors
13075   SDValue LHS = Op.getOperand(0);
13076   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
13077   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
13078
13079   // Extract the RHS vectors
13080   SDValue RHS = Op.getOperand(1);
13081   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
13082   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
13083
13084   // Issue the operation on the smaller types and concatenate the result back
13085   MVT EltVT = VT.getVectorElementType();
13086   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13087   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
13088                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
13089                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
13090 }
13091
13092 static SDValue LowerBoolVSETCC_AVX512(SDValue Op, SelectionDAG &DAG) {
13093   SDValue Op0 = Op.getOperand(0);
13094   SDValue Op1 = Op.getOperand(1);
13095   SDValue CC = Op.getOperand(2);
13096   MVT VT = Op.getSimpleValueType();
13097   SDLoc dl(Op);
13098
13099   assert(Op0.getValueType().getVectorElementType() == MVT::i1 &&
13100          "Unexpected type for boolean compare operation");
13101   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13102   SDValue NotOp0 = DAG.getNode(ISD::XOR, dl, VT, Op0,
13103                                DAG.getConstant(-1, dl, VT));
13104   SDValue NotOp1 = DAG.getNode(ISD::XOR, dl, VT, Op1,
13105                                DAG.getConstant(-1, dl, VT));
13106   switch (SetCCOpcode) {
13107   default: llvm_unreachable("Unexpected SETCC condition");
13108   case ISD::SETNE:
13109     // (x != y) -> ~(x ^ y)
13110     return DAG.getNode(ISD::XOR, dl, VT,
13111                        DAG.getNode(ISD::XOR, dl, VT, Op0, Op1),
13112                        DAG.getConstant(-1, dl, VT));
13113   case ISD::SETEQ:
13114     // (x == y) -> (x ^ y)
13115     return DAG.getNode(ISD::XOR, dl, VT, Op0, Op1);
13116   case ISD::SETUGT:
13117   case ISD::SETGT:
13118     // (x > y) -> (x & ~y)
13119     return DAG.getNode(ISD::AND, dl, VT, Op0, NotOp1);
13120   case ISD::SETULT:
13121   case ISD::SETLT:
13122     // (x < y) -> (~x & y)
13123     return DAG.getNode(ISD::AND, dl, VT, NotOp0, Op1);
13124   case ISD::SETULE:
13125   case ISD::SETLE:
13126     // (x <= y) -> (~x | y)
13127     return DAG.getNode(ISD::OR, dl, VT, NotOp0, Op1);
13128   case ISD::SETUGE:
13129   case ISD::SETGE:
13130     // (x >=y) -> (x | ~y)
13131     return DAG.getNode(ISD::OR, dl, VT, Op0, NotOp1);
13132   }
13133 }
13134
13135 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
13136                                      const X86Subtarget *Subtarget) {
13137   SDValue Op0 = Op.getOperand(0);
13138   SDValue Op1 = Op.getOperand(1);
13139   SDValue CC = Op.getOperand(2);
13140   MVT VT = Op.getSimpleValueType();
13141   SDLoc dl(Op);
13142
13143   assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 8 &&
13144          Op.getValueType().getScalarType() == MVT::i1 &&
13145          "Cannot set masked compare for this operation");
13146
13147   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13148   unsigned  Opc = 0;
13149   bool Unsigned = false;
13150   bool Swap = false;
13151   unsigned SSECC;
13152   switch (SetCCOpcode) {
13153   default: llvm_unreachable("Unexpected SETCC condition");
13154   case ISD::SETNE:  SSECC = 4; break;
13155   case ISD::SETEQ:  Opc = X86ISD::PCMPEQM; break;
13156   case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
13157   case ISD::SETLT:  Swap = true; //fall-through
13158   case ISD::SETGT:  Opc = X86ISD::PCMPGTM; break;
13159   case ISD::SETULT: SSECC = 1; Unsigned = true; break;
13160   case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
13161   case ISD::SETGE:  Swap = true; SSECC = 2; break; // LE + swap
13162   case ISD::SETULE: Unsigned = true; //fall-through
13163   case ISD::SETLE:  SSECC = 2; break;
13164   }
13165
13166   if (Swap)
13167     std::swap(Op0, Op1);
13168   if (Opc)
13169     return DAG.getNode(Opc, dl, VT, Op0, Op1);
13170   Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
13171   return DAG.getNode(Opc, dl, VT, Op0, Op1,
13172                      DAG.getConstant(SSECC, dl, MVT::i8));
13173 }
13174
13175 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
13176 /// operand \p Op1.  If non-trivial (for example because it's not constant)
13177 /// return an empty value.
13178 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
13179 {
13180   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
13181   if (!BV)
13182     return SDValue();
13183
13184   MVT VT = Op1.getSimpleValueType();
13185   MVT EVT = VT.getVectorElementType();
13186   unsigned n = VT.getVectorNumElements();
13187   SmallVector<SDValue, 8> ULTOp1;
13188
13189   for (unsigned i = 0; i < n; ++i) {
13190     ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
13191     if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
13192       return SDValue();
13193
13194     // Avoid underflow.
13195     APInt Val = Elt->getAPIntValue();
13196     if (Val == 0)
13197       return SDValue();
13198
13199     ULTOp1.push_back(DAG.getConstant(Val - 1, dl, EVT));
13200   }
13201
13202   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
13203 }
13204
13205 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
13206                            SelectionDAG &DAG) {
13207   SDValue Op0 = Op.getOperand(0);
13208   SDValue Op1 = Op.getOperand(1);
13209   SDValue CC = Op.getOperand(2);
13210   MVT VT = Op.getSimpleValueType();
13211   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13212   bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
13213   SDLoc dl(Op);
13214
13215   if (isFP) {
13216 #ifndef NDEBUG
13217     MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
13218     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
13219 #endif
13220
13221     unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
13222     unsigned Opc = X86ISD::CMPP;
13223     if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
13224       assert(VT.getVectorNumElements() <= 16);
13225       Opc = X86ISD::CMPM;
13226     }
13227     // In the two special cases we can't handle, emit two comparisons.
13228     if (SSECC == 8) {
13229       unsigned CC0, CC1;
13230       unsigned CombineOpc;
13231       if (SetCCOpcode == ISD::SETUEQ) {
13232         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
13233       } else {
13234         assert(SetCCOpcode == ISD::SETONE);
13235         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
13236       }
13237
13238       SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
13239                                  DAG.getConstant(CC0, dl, MVT::i8));
13240       SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
13241                                  DAG.getConstant(CC1, dl, MVT::i8));
13242       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
13243     }
13244     // Handle all other FP comparisons here.
13245     return DAG.getNode(Opc, dl, VT, Op0, Op1,
13246                        DAG.getConstant(SSECC, dl, MVT::i8));
13247   }
13248
13249   // Break 256-bit integer vector compare into smaller ones.
13250   if (VT.is256BitVector() && !Subtarget->hasInt256())
13251     return Lower256IntVSETCC(Op, DAG);
13252
13253   EVT OpVT = Op1.getValueType();
13254   if (OpVT.getVectorElementType() == MVT::i1)
13255     return LowerBoolVSETCC_AVX512(Op, DAG);
13256
13257   bool MaskResult = (VT.getVectorElementType() == MVT::i1);
13258   if (Subtarget->hasAVX512()) {
13259     if (Op1.getValueType().is512BitVector() ||
13260         (Subtarget->hasBWI() && Subtarget->hasVLX()) ||
13261         (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
13262       return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
13263
13264     // In AVX-512 architecture setcc returns mask with i1 elements,
13265     // But there is no compare instruction for i8 and i16 elements in KNL.
13266     // We are not talking about 512-bit operands in this case, these
13267     // types are illegal.
13268     if (MaskResult &&
13269         (OpVT.getVectorElementType().getSizeInBits() < 32 &&
13270          OpVT.getVectorElementType().getSizeInBits() >= 8))
13271       return DAG.getNode(ISD::TRUNCATE, dl, VT,
13272                          DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
13273   }
13274
13275   // We are handling one of the integer comparisons here.  Since SSE only has
13276   // GT and EQ comparisons for integer, swapping operands and multiple
13277   // operations may be required for some comparisons.
13278   unsigned Opc;
13279   bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
13280   bool Subus = false;
13281
13282   switch (SetCCOpcode) {
13283   default: llvm_unreachable("Unexpected SETCC condition");
13284   case ISD::SETNE:  Invert = true;
13285   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
13286   case ISD::SETLT:  Swap = true;
13287   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
13288   case ISD::SETGE:  Swap = true;
13289   case ISD::SETLE:  Opc = X86ISD::PCMPGT;
13290                     Invert = true; break;
13291   case ISD::SETULT: Swap = true;
13292   case ISD::SETUGT: Opc = X86ISD::PCMPGT;
13293                     FlipSigns = true; break;
13294   case ISD::SETUGE: Swap = true;
13295   case ISD::SETULE: Opc = X86ISD::PCMPGT;
13296                     FlipSigns = true; Invert = true; break;
13297   }
13298
13299   // Special case: Use min/max operations for SETULE/SETUGE
13300   MVT VET = VT.getVectorElementType();
13301   bool hasMinMax =
13302        (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
13303     || (Subtarget->hasSSE2()  && (VET == MVT::i8));
13304
13305   if (hasMinMax) {
13306     switch (SetCCOpcode) {
13307     default: break;
13308     case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
13309     case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
13310     }
13311
13312     if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
13313   }
13314
13315   bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
13316   if (!MinMax && hasSubus) {
13317     // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
13318     // Op0 u<= Op1:
13319     //   t = psubus Op0, Op1
13320     //   pcmpeq t, <0..0>
13321     switch (SetCCOpcode) {
13322     default: break;
13323     case ISD::SETULT: {
13324       // If the comparison is against a constant we can turn this into a
13325       // setule.  With psubus, setule does not require a swap.  This is
13326       // beneficial because the constant in the register is no longer
13327       // destructed as the destination so it can be hoisted out of a loop.
13328       // Only do this pre-AVX since vpcmp* is no longer destructive.
13329       if (Subtarget->hasAVX())
13330         break;
13331       SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
13332       if (ULEOp1.getNode()) {
13333         Op1 = ULEOp1;
13334         Subus = true; Invert = false; Swap = false;
13335       }
13336       break;
13337     }
13338     // Psubus is better than flip-sign because it requires no inversion.
13339     case ISD::SETUGE: Subus = true; Invert = false; Swap = true;  break;
13340     case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
13341     }
13342
13343     if (Subus) {
13344       Opc = X86ISD::SUBUS;
13345       FlipSigns = false;
13346     }
13347   }
13348
13349   if (Swap)
13350     std::swap(Op0, Op1);
13351
13352   // Check that the operation in question is available (most are plain SSE2,
13353   // but PCMPGTQ and PCMPEQQ have different requirements).
13354   if (VT == MVT::v2i64) {
13355     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
13356       assert(Subtarget->hasSSE2() && "Don't know how to lower!");
13357
13358       // First cast everything to the right type.
13359       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
13360       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
13361
13362       // Since SSE has no unsigned integer comparisons, we need to flip the sign
13363       // bits of the inputs before performing those operations. The lower
13364       // compare is always unsigned.
13365       SDValue SB;
13366       if (FlipSigns) {
13367         SB = DAG.getConstant(0x80000000U, dl, MVT::v4i32);
13368       } else {
13369         SDValue Sign = DAG.getConstant(0x80000000U, dl, MVT::i32);
13370         SDValue Zero = DAG.getConstant(0x00000000U, dl, MVT::i32);
13371         SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
13372                          Sign, Zero, Sign, Zero);
13373       }
13374       Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
13375       Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
13376
13377       // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
13378       SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
13379       SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
13380
13381       // Create masks for only the low parts/high parts of the 64 bit integers.
13382       static const int MaskHi[] = { 1, 1, 3, 3 };
13383       static const int MaskLo[] = { 0, 0, 2, 2 };
13384       SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
13385       SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
13386       SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
13387
13388       SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
13389       Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
13390
13391       if (Invert)
13392         Result = DAG.getNOT(dl, Result, MVT::v4i32);
13393
13394       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
13395     }
13396
13397     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
13398       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
13399       // pcmpeqd + pshufd + pand.
13400       assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
13401
13402       // First cast everything to the right type.
13403       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
13404       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
13405
13406       // Do the compare.
13407       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
13408
13409       // Make sure the lower and upper halves are both all-ones.
13410       static const int Mask[] = { 1, 0, 3, 2 };
13411       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
13412       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
13413
13414       if (Invert)
13415         Result = DAG.getNOT(dl, Result, MVT::v4i32);
13416
13417       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
13418     }
13419   }
13420
13421   // Since SSE has no unsigned integer comparisons, we need to flip the sign
13422   // bits of the inputs before performing those operations.
13423   if (FlipSigns) {
13424     EVT EltVT = VT.getVectorElementType();
13425     SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), dl,
13426                                  VT);
13427     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
13428     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
13429   }
13430
13431   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
13432
13433   // If the logical-not of the result is required, perform that now.
13434   if (Invert)
13435     Result = DAG.getNOT(dl, Result, VT);
13436
13437   if (MinMax)
13438     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
13439
13440   if (Subus)
13441     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
13442                          getZeroVector(VT, Subtarget, DAG, dl));
13443
13444   return Result;
13445 }
13446
13447 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
13448
13449   MVT VT = Op.getSimpleValueType();
13450
13451   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
13452
13453   assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
13454          && "SetCC type must be 8-bit or 1-bit integer");
13455   SDValue Op0 = Op.getOperand(0);
13456   SDValue Op1 = Op.getOperand(1);
13457   SDLoc dl(Op);
13458   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
13459
13460   // Optimize to BT if possible.
13461   // Lower (X & (1 << N)) == 0 to BT(X, N).
13462   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
13463   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
13464   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
13465       Op1.getOpcode() == ISD::Constant &&
13466       cast<ConstantSDNode>(Op1)->isNullValue() &&
13467       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13468     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
13469     if (NewSetCC.getNode()) {
13470       if (VT == MVT::i1)
13471         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewSetCC);
13472       return NewSetCC;
13473     }
13474   }
13475
13476   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
13477   // these.
13478   if (Op1.getOpcode() == ISD::Constant &&
13479       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
13480        cast<ConstantSDNode>(Op1)->isNullValue()) &&
13481       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13482
13483     // If the input is a setcc, then reuse the input setcc or use a new one with
13484     // the inverted condition.
13485     if (Op0.getOpcode() == X86ISD::SETCC) {
13486       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
13487       bool Invert = (CC == ISD::SETNE) ^
13488         cast<ConstantSDNode>(Op1)->isNullValue();
13489       if (!Invert)
13490         return Op0;
13491
13492       CCode = X86::GetOppositeBranchCondition(CCode);
13493       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13494                                   DAG.getConstant(CCode, dl, MVT::i8),
13495                                   Op0.getOperand(1));
13496       if (VT == MVT::i1)
13497         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
13498       return SetCC;
13499     }
13500   }
13501   if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
13502       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
13503       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13504
13505     ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
13506     return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, dl, MVT::i1), NewCC);
13507   }
13508
13509   bool isFP = Op1.getSimpleValueType().isFloatingPoint();
13510   unsigned X86CC = TranslateX86CC(CC, dl, isFP, Op0, Op1, DAG);
13511   if (X86CC == X86::COND_INVALID)
13512     return SDValue();
13513
13514   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
13515   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
13516   SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13517                               DAG.getConstant(X86CC, dl, MVT::i8), EFLAGS);
13518   if (VT == MVT::i1)
13519     return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
13520   return SetCC;
13521 }
13522
13523 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
13524 static bool isX86LogicalCmp(SDValue Op) {
13525   unsigned Opc = Op.getNode()->getOpcode();
13526   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
13527       Opc == X86ISD::SAHF)
13528     return true;
13529   if (Op.getResNo() == 1 &&
13530       (Opc == X86ISD::ADD ||
13531        Opc == X86ISD::SUB ||
13532        Opc == X86ISD::ADC ||
13533        Opc == X86ISD::SBB ||
13534        Opc == X86ISD::SMUL ||
13535        Opc == X86ISD::UMUL ||
13536        Opc == X86ISD::INC ||
13537        Opc == X86ISD::DEC ||
13538        Opc == X86ISD::OR ||
13539        Opc == X86ISD::XOR ||
13540        Opc == X86ISD::AND))
13541     return true;
13542
13543   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
13544     return true;
13545
13546   return false;
13547 }
13548
13549 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
13550   if (V.getOpcode() != ISD::TRUNCATE)
13551     return false;
13552
13553   SDValue VOp0 = V.getOperand(0);
13554   unsigned InBits = VOp0.getValueSizeInBits();
13555   unsigned Bits = V.getValueSizeInBits();
13556   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
13557 }
13558
13559 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
13560   bool addTest = true;
13561   SDValue Cond  = Op.getOperand(0);
13562   SDValue Op1 = Op.getOperand(1);
13563   SDValue Op2 = Op.getOperand(2);
13564   SDLoc DL(Op);
13565   EVT VT = Op1.getValueType();
13566   SDValue CC;
13567
13568   // Lower FP selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
13569   // are available or VBLENDV if AVX is available.
13570   // Otherwise FP cmovs get lowered into a less efficient branch sequence later.
13571   if (Cond.getOpcode() == ISD::SETCC &&
13572       ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
13573        (Subtarget->hasSSE1() && VT == MVT::f32)) &&
13574       VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
13575     SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
13576     int SSECC = translateX86FSETCC(
13577         cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
13578
13579     if (SSECC != 8) {
13580       if (Subtarget->hasAVX512()) {
13581         SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
13582                                   DAG.getConstant(SSECC, DL, MVT::i8));
13583         return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
13584       }
13585
13586       SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
13587                                 DAG.getConstant(SSECC, DL, MVT::i8));
13588
13589       // If we have AVX, we can use a variable vector select (VBLENDV) instead
13590       // of 3 logic instructions for size savings and potentially speed.
13591       // Unfortunately, there is no scalar form of VBLENDV.
13592
13593       // If either operand is a constant, don't try this. We can expect to
13594       // optimize away at least one of the logic instructions later in that
13595       // case, so that sequence would be faster than a variable blend.
13596
13597       // BLENDV was introduced with SSE 4.1, but the 2 register form implicitly
13598       // uses XMM0 as the selection register. That may need just as many
13599       // instructions as the AND/ANDN/OR sequence due to register moves, so
13600       // don't bother.
13601
13602       if (Subtarget->hasAVX() &&
13603           !isa<ConstantFPSDNode>(Op1) && !isa<ConstantFPSDNode>(Op2)) {
13604
13605         // Convert to vectors, do a VSELECT, and convert back to scalar.
13606         // All of the conversions should be optimized away.
13607
13608         EVT VecVT = VT == MVT::f32 ? MVT::v4f32 : MVT::v2f64;
13609         SDValue VOp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op1);
13610         SDValue VOp2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op2);
13611         SDValue VCmp = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Cmp);
13612
13613         EVT VCmpVT = VT == MVT::f32 ? MVT::v4i32 : MVT::v2i64;
13614         VCmp = DAG.getNode(ISD::BITCAST, DL, VCmpVT, VCmp);
13615
13616         SDValue VSel = DAG.getNode(ISD::VSELECT, DL, VecVT, VCmp, VOp1, VOp2);
13617
13618         return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
13619                            VSel, DAG.getIntPtrConstant(0, DL));
13620       }
13621       SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
13622       SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
13623       return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
13624     }
13625   }
13626
13627   if (VT == MVT::v4i1 || VT == MVT::v2i1) {
13628     SDValue zeroConst = DAG.getIntPtrConstant(0, DL);
13629     Op1 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
13630                       DAG.getUNDEF(MVT::v8i1), Op1, zeroConst);
13631     Op2 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
13632                       DAG.getUNDEF(MVT::v8i1), Op2, zeroConst);
13633     SDValue newSelect = DAG.getNode(ISD::SELECT, DL, MVT::v8i1,
13634                                     Cond, Op1, Op2);
13635     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, newSelect, zeroConst);
13636   }
13637
13638   if (Cond.getOpcode() == ISD::SETCC) {
13639     SDValue NewCond = LowerSETCC(Cond, DAG);
13640     if (NewCond.getNode())
13641       Cond = NewCond;
13642   }
13643
13644   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
13645   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
13646   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
13647   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
13648   if (Cond.getOpcode() == X86ISD::SETCC &&
13649       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
13650       isZero(Cond.getOperand(1).getOperand(1))) {
13651     SDValue Cmp = Cond.getOperand(1);
13652
13653     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
13654
13655     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
13656         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
13657       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
13658
13659       SDValue CmpOp0 = Cmp.getOperand(0);
13660       // Apply further optimizations for special cases
13661       // (select (x != 0), -1, 0) -> neg & sbb
13662       // (select (x == 0), 0, -1) -> neg & sbb
13663       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
13664         if (YC->isNullValue() &&
13665             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
13666           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
13667           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
13668                                     DAG.getConstant(0, DL,
13669                                                     CmpOp0.getValueType()),
13670                                     CmpOp0);
13671           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
13672                                     DAG.getConstant(X86::COND_B, DL, MVT::i8),
13673                                     SDValue(Neg.getNode(), 1));
13674           return Res;
13675         }
13676
13677       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
13678                         CmpOp0, DAG.getConstant(1, DL, CmpOp0.getValueType()));
13679       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
13680
13681       SDValue Res =   // Res = 0 or -1.
13682         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
13683                     DAG.getConstant(X86::COND_B, DL, MVT::i8), Cmp);
13684
13685       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
13686         Res = DAG.getNOT(DL, Res, Res.getValueType());
13687
13688       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
13689       if (!N2C || !N2C->isNullValue())
13690         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
13691       return Res;
13692     }
13693   }
13694
13695   // Look past (and (setcc_carry (cmp ...)), 1).
13696   if (Cond.getOpcode() == ISD::AND &&
13697       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
13698     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
13699     if (C && C->getAPIntValue() == 1)
13700       Cond = Cond.getOperand(0);
13701   }
13702
13703   // If condition flag is set by a X86ISD::CMP, then use it as the condition
13704   // setting operand in place of the X86ISD::SETCC.
13705   unsigned CondOpcode = Cond.getOpcode();
13706   if (CondOpcode == X86ISD::SETCC ||
13707       CondOpcode == X86ISD::SETCC_CARRY) {
13708     CC = Cond.getOperand(0);
13709
13710     SDValue Cmp = Cond.getOperand(1);
13711     unsigned Opc = Cmp.getOpcode();
13712     MVT VT = Op.getSimpleValueType();
13713
13714     bool IllegalFPCMov = false;
13715     if (VT.isFloatingPoint() && !VT.isVector() &&
13716         !isScalarFPTypeInSSEReg(VT))  // FPStack?
13717       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
13718
13719     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
13720         Opc == X86ISD::BT) { // FIXME
13721       Cond = Cmp;
13722       addTest = false;
13723     }
13724   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
13725              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
13726              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
13727               Cond.getOperand(0).getValueType() != MVT::i8)) {
13728     SDValue LHS = Cond.getOperand(0);
13729     SDValue RHS = Cond.getOperand(1);
13730     unsigned X86Opcode;
13731     unsigned X86Cond;
13732     SDVTList VTs;
13733     switch (CondOpcode) {
13734     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
13735     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
13736     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
13737     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
13738     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
13739     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
13740     default: llvm_unreachable("unexpected overflowing operator");
13741     }
13742     if (CondOpcode == ISD::UMULO)
13743       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
13744                           MVT::i32);
13745     else
13746       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
13747
13748     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
13749
13750     if (CondOpcode == ISD::UMULO)
13751       Cond = X86Op.getValue(2);
13752     else
13753       Cond = X86Op.getValue(1);
13754
13755     CC = DAG.getConstant(X86Cond, DL, MVT::i8);
13756     addTest = false;
13757   }
13758
13759   if (addTest) {
13760     // Look pass the truncate if the high bits are known zero.
13761     if (isTruncWithZeroHighBitsInput(Cond, DAG))
13762         Cond = Cond.getOperand(0);
13763
13764     // We know the result of AND is compared against zero. Try to match
13765     // it to BT.
13766     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
13767       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
13768       if (NewSetCC.getNode()) {
13769         CC = NewSetCC.getOperand(0);
13770         Cond = NewSetCC.getOperand(1);
13771         addTest = false;
13772       }
13773     }
13774   }
13775
13776   if (addTest) {
13777     CC = DAG.getConstant(X86::COND_NE, DL, MVT::i8);
13778     Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
13779   }
13780
13781   // a <  b ? -1 :  0 -> RES = ~setcc_carry
13782   // a <  b ?  0 : -1 -> RES = setcc_carry
13783   // a >= b ? -1 :  0 -> RES = setcc_carry
13784   // a >= b ?  0 : -1 -> RES = ~setcc_carry
13785   if (Cond.getOpcode() == X86ISD::SUB) {
13786     Cond = ConvertCmpIfNecessary(Cond, DAG);
13787     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
13788
13789     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
13790         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
13791       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
13792                                 DAG.getConstant(X86::COND_B, DL, MVT::i8),
13793                                 Cond);
13794       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
13795         return DAG.getNOT(DL, Res, Res.getValueType());
13796       return Res;
13797     }
13798   }
13799
13800   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
13801   // widen the cmov and push the truncate through. This avoids introducing a new
13802   // branch during isel and doesn't add any extensions.
13803   if (Op.getValueType() == MVT::i8 &&
13804       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
13805     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
13806     if (T1.getValueType() == T2.getValueType() &&
13807         // Blacklist CopyFromReg to avoid partial register stalls.
13808         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
13809       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
13810       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
13811       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
13812     }
13813   }
13814
13815   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
13816   // condition is true.
13817   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
13818   SDValue Ops[] = { Op2, Op1, CC, Cond };
13819   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
13820 }
13821
13822 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op, const X86Subtarget *Subtarget,
13823                                        SelectionDAG &DAG) {
13824   MVT VT = Op->getSimpleValueType(0);
13825   SDValue In = Op->getOperand(0);
13826   MVT InVT = In.getSimpleValueType();
13827   MVT VTElt = VT.getVectorElementType();
13828   MVT InVTElt = InVT.getVectorElementType();
13829   SDLoc dl(Op);
13830
13831   // SKX processor
13832   if ((InVTElt == MVT::i1) &&
13833       (((Subtarget->hasBWI() && Subtarget->hasVLX() &&
13834         VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() <= 16)) ||
13835
13836        ((Subtarget->hasBWI() && VT.is512BitVector() &&
13837         VTElt.getSizeInBits() <= 16)) ||
13838
13839        ((Subtarget->hasDQI() && Subtarget->hasVLX() &&
13840         VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() >= 32)) ||
13841
13842        ((Subtarget->hasDQI() && VT.is512BitVector() &&
13843         VTElt.getSizeInBits() >= 32))))
13844     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
13845
13846   unsigned int NumElts = VT.getVectorNumElements();
13847
13848   if (NumElts != 8 && NumElts != 16)
13849     return SDValue();
13850
13851   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1) {
13852     if (In.getOpcode() == X86ISD::VSEXT || In.getOpcode() == X86ISD::VZEXT)
13853       return DAG.getNode(In.getOpcode(), dl, VT, In.getOperand(0));
13854     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
13855   }
13856
13857   assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
13858   MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
13859   SDValue NegOne =
13860    DAG.getConstant(APInt::getAllOnesValue(ExtVT.getScalarSizeInBits()), dl,
13861                    ExtVT);
13862   SDValue Zero =
13863    DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), dl, ExtVT);
13864
13865   SDValue V = DAG.getNode(ISD::VSELECT, dl, ExtVT, In, NegOne, Zero);
13866   if (VT.is512BitVector())
13867     return V;
13868   return DAG.getNode(X86ISD::VTRUNC, dl, VT, V);
13869 }
13870
13871 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
13872                                 SelectionDAG &DAG) {
13873   MVT VT = Op->getSimpleValueType(0);
13874   SDValue In = Op->getOperand(0);
13875   MVT InVT = In.getSimpleValueType();
13876   SDLoc dl(Op);
13877
13878   if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
13879     return LowerSIGN_EXTEND_AVX512(Op, Subtarget, DAG);
13880
13881   if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
13882       (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
13883       (VT != MVT::v16i16 || InVT != MVT::v16i8))
13884     return SDValue();
13885
13886   if (Subtarget->hasInt256())
13887     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
13888
13889   // Optimize vectors in AVX mode
13890   // Sign extend  v8i16 to v8i32 and
13891   //              v4i32 to v4i64
13892   //
13893   // Divide input vector into two parts
13894   // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
13895   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
13896   // concat the vectors to original VT
13897
13898   unsigned NumElems = InVT.getVectorNumElements();
13899   SDValue Undef = DAG.getUNDEF(InVT);
13900
13901   SmallVector<int,8> ShufMask1(NumElems, -1);
13902   for (unsigned i = 0; i != NumElems/2; ++i)
13903     ShufMask1[i] = i;
13904
13905   SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
13906
13907   SmallVector<int,8> ShufMask2(NumElems, -1);
13908   for (unsigned i = 0; i != NumElems/2; ++i)
13909     ShufMask2[i] = i + NumElems/2;
13910
13911   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
13912
13913   MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
13914                                 VT.getVectorNumElements()/2);
13915
13916   OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
13917   OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
13918
13919   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
13920 }
13921
13922 // Lower vector extended loads using a shuffle. If SSSE3 is not available we
13923 // may emit an illegal shuffle but the expansion is still better than scalar
13924 // code. We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise
13925 // we'll emit a shuffle and a arithmetic shift.
13926 // FIXME: Is the expansion actually better than scalar code? It doesn't seem so.
13927 // TODO: It is possible to support ZExt by zeroing the undef values during
13928 // the shuffle phase or after the shuffle.
13929 static SDValue LowerExtendedLoad(SDValue Op, const X86Subtarget *Subtarget,
13930                                  SelectionDAG &DAG) {
13931   MVT RegVT = Op.getSimpleValueType();
13932   assert(RegVT.isVector() && "We only custom lower vector sext loads.");
13933   assert(RegVT.isInteger() &&
13934          "We only custom lower integer vector sext loads.");
13935
13936   // Nothing useful we can do without SSE2 shuffles.
13937   assert(Subtarget->hasSSE2() && "We only custom lower sext loads with SSE2.");
13938
13939   LoadSDNode *Ld = cast<LoadSDNode>(Op.getNode());
13940   SDLoc dl(Ld);
13941   EVT MemVT = Ld->getMemoryVT();
13942   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13943   unsigned RegSz = RegVT.getSizeInBits();
13944
13945   ISD::LoadExtType Ext = Ld->getExtensionType();
13946
13947   assert((Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)
13948          && "Only anyext and sext are currently implemented.");
13949   assert(MemVT != RegVT && "Cannot extend to the same type");
13950   assert(MemVT.isVector() && "Must load a vector from memory");
13951
13952   unsigned NumElems = RegVT.getVectorNumElements();
13953   unsigned MemSz = MemVT.getSizeInBits();
13954   assert(RegSz > MemSz && "Register size must be greater than the mem size");
13955
13956   if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256()) {
13957     // The only way in which we have a legal 256-bit vector result but not the
13958     // integer 256-bit operations needed to directly lower a sextload is if we
13959     // have AVX1 but not AVX2. In that case, we can always emit a sextload to
13960     // a 128-bit vector and a normal sign_extend to 256-bits that should get
13961     // correctly legalized. We do this late to allow the canonical form of
13962     // sextload to persist throughout the rest of the DAG combiner -- it wants
13963     // to fold together any extensions it can, and so will fuse a sign_extend
13964     // of an sextload into a sextload targeting a wider value.
13965     SDValue Load;
13966     if (MemSz == 128) {
13967       // Just switch this to a normal load.
13968       assert(TLI.isTypeLegal(MemVT) && "If the memory type is a 128-bit type, "
13969                                        "it must be a legal 128-bit vector "
13970                                        "type!");
13971       Load = DAG.getLoad(MemVT, dl, Ld->getChain(), Ld->getBasePtr(),
13972                   Ld->getPointerInfo(), Ld->isVolatile(), Ld->isNonTemporal(),
13973                   Ld->isInvariant(), Ld->getAlignment());
13974     } else {
13975       assert(MemSz < 128 &&
13976              "Can't extend a type wider than 128 bits to a 256 bit vector!");
13977       // Do an sext load to a 128-bit vector type. We want to use the same
13978       // number of elements, but elements half as wide. This will end up being
13979       // recursively lowered by this routine, but will succeed as we definitely
13980       // have all the necessary features if we're using AVX1.
13981       EVT HalfEltVT =
13982           EVT::getIntegerVT(*DAG.getContext(), RegVT.getScalarSizeInBits() / 2);
13983       EVT HalfVecVT = EVT::getVectorVT(*DAG.getContext(), HalfEltVT, NumElems);
13984       Load =
13985           DAG.getExtLoad(Ext, dl, HalfVecVT, Ld->getChain(), Ld->getBasePtr(),
13986                          Ld->getPointerInfo(), MemVT, Ld->isVolatile(),
13987                          Ld->isNonTemporal(), Ld->isInvariant(),
13988                          Ld->getAlignment());
13989     }
13990
13991     // Replace chain users with the new chain.
13992     assert(Load->getNumValues() == 2 && "Loads must carry a chain!");
13993     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Load.getValue(1));
13994
13995     // Finally, do a normal sign-extend to the desired register.
13996     return DAG.getSExtOrTrunc(Load, dl, RegVT);
13997   }
13998
13999   // All sizes must be a power of two.
14000   assert(isPowerOf2_32(RegSz * MemSz * NumElems) &&
14001          "Non-power-of-two elements are not custom lowered!");
14002
14003   // Attempt to load the original value using scalar loads.
14004   // Find the largest scalar type that divides the total loaded size.
14005   MVT SclrLoadTy = MVT::i8;
14006   for (MVT Tp : MVT::integer_valuetypes()) {
14007     if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
14008       SclrLoadTy = Tp;
14009     }
14010   }
14011
14012   // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
14013   if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
14014       (64 <= MemSz))
14015     SclrLoadTy = MVT::f64;
14016
14017   // Calculate the number of scalar loads that we need to perform
14018   // in order to load our vector from memory.
14019   unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
14020
14021   assert((Ext != ISD::SEXTLOAD || NumLoads == 1) &&
14022          "Can only lower sext loads with a single scalar load!");
14023
14024   unsigned loadRegZize = RegSz;
14025   if (Ext == ISD::SEXTLOAD && RegSz >= 256)
14026     loadRegZize = 128;
14027
14028   // Represent our vector as a sequence of elements which are the
14029   // largest scalar that we can load.
14030   EVT LoadUnitVecVT = EVT::getVectorVT(
14031       *DAG.getContext(), SclrLoadTy, loadRegZize / SclrLoadTy.getSizeInBits());
14032
14033   // Represent the data using the same element type that is stored in
14034   // memory. In practice, we ''widen'' MemVT.
14035   EVT WideVecVT =
14036       EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
14037                        loadRegZize / MemVT.getScalarType().getSizeInBits());
14038
14039   assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
14040          "Invalid vector type");
14041
14042   // We can't shuffle using an illegal type.
14043   assert(TLI.isTypeLegal(WideVecVT) &&
14044          "We only lower types that form legal widened vector types");
14045
14046   SmallVector<SDValue, 8> Chains;
14047   SDValue Ptr = Ld->getBasePtr();
14048   SDValue Increment =
14049       DAG.getConstant(SclrLoadTy.getSizeInBits() / 8, dl, TLI.getPointerTy());
14050   SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
14051
14052   for (unsigned i = 0; i < NumLoads; ++i) {
14053     // Perform a single load.
14054     SDValue ScalarLoad =
14055         DAG.getLoad(SclrLoadTy, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
14056                     Ld->isVolatile(), Ld->isNonTemporal(), Ld->isInvariant(),
14057                     Ld->getAlignment());
14058     Chains.push_back(ScalarLoad.getValue(1));
14059     // Create the first element type using SCALAR_TO_VECTOR in order to avoid
14060     // another round of DAGCombining.
14061     if (i == 0)
14062       Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
14063     else
14064       Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
14065                         ScalarLoad, DAG.getIntPtrConstant(i, dl));
14066
14067     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
14068   }
14069
14070   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
14071
14072   // Bitcast the loaded value to a vector of the original element type, in
14073   // the size of the target vector type.
14074   SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
14075   unsigned SizeRatio = RegSz / MemSz;
14076
14077   if (Ext == ISD::SEXTLOAD) {
14078     // If we have SSE4.1, we can directly emit a VSEXT node.
14079     if (Subtarget->hasSSE41()) {
14080       SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
14081       DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14082       return Sext;
14083     }
14084
14085     // Otherwise we'll shuffle the small elements in the high bits of the
14086     // larger type and perform an arithmetic shift. If the shift is not legal
14087     // it's better to scalarize.
14088     assert(TLI.isOperationLegalOrCustom(ISD::SRA, RegVT) &&
14089            "We can't implement a sext load without an arithmetic right shift!");
14090
14091     // Redistribute the loaded elements into the different locations.
14092     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
14093     for (unsigned i = 0; i != NumElems; ++i)
14094       ShuffleVec[i * SizeRatio + SizeRatio - 1] = i;
14095
14096     SDValue Shuff = DAG.getVectorShuffle(
14097         WideVecVT, dl, SlicedVec, DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
14098
14099     Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
14100
14101     // Build the arithmetic shift.
14102     unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
14103                    MemVT.getVectorElementType().getSizeInBits();
14104     Shuff =
14105         DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
14106                     DAG.getConstant(Amt, dl, RegVT));
14107
14108     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14109     return Shuff;
14110   }
14111
14112   // Redistribute the loaded elements into the different locations.
14113   SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
14114   for (unsigned i = 0; i != NumElems; ++i)
14115     ShuffleVec[i * SizeRatio] = i;
14116
14117   SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
14118                                        DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
14119
14120   // Bitcast to the requested type.
14121   Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
14122   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14123   return Shuff;
14124 }
14125
14126 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
14127 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
14128 // from the AND / OR.
14129 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
14130   Opc = Op.getOpcode();
14131   if (Opc != ISD::OR && Opc != ISD::AND)
14132     return false;
14133   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
14134           Op.getOperand(0).hasOneUse() &&
14135           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
14136           Op.getOperand(1).hasOneUse());
14137 }
14138
14139 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
14140 // 1 and that the SETCC node has a single use.
14141 static bool isXor1OfSetCC(SDValue Op) {
14142   if (Op.getOpcode() != ISD::XOR)
14143     return false;
14144   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
14145   if (N1C && N1C->getAPIntValue() == 1) {
14146     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
14147       Op.getOperand(0).hasOneUse();
14148   }
14149   return false;
14150 }
14151
14152 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
14153   bool addTest = true;
14154   SDValue Chain = Op.getOperand(0);
14155   SDValue Cond  = Op.getOperand(1);
14156   SDValue Dest  = Op.getOperand(2);
14157   SDLoc dl(Op);
14158   SDValue CC;
14159   bool Inverted = false;
14160
14161   if (Cond.getOpcode() == ISD::SETCC) {
14162     // Check for setcc([su]{add,sub,mul}o == 0).
14163     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
14164         isa<ConstantSDNode>(Cond.getOperand(1)) &&
14165         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
14166         Cond.getOperand(0).getResNo() == 1 &&
14167         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
14168          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
14169          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
14170          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
14171          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
14172          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
14173       Inverted = true;
14174       Cond = Cond.getOperand(0);
14175     } else {
14176       SDValue NewCond = LowerSETCC(Cond, DAG);
14177       if (NewCond.getNode())
14178         Cond = NewCond;
14179     }
14180   }
14181 #if 0
14182   // FIXME: LowerXALUO doesn't handle these!!
14183   else if (Cond.getOpcode() == X86ISD::ADD  ||
14184            Cond.getOpcode() == X86ISD::SUB  ||
14185            Cond.getOpcode() == X86ISD::SMUL ||
14186            Cond.getOpcode() == X86ISD::UMUL)
14187     Cond = LowerXALUO(Cond, DAG);
14188 #endif
14189
14190   // Look pass (and (setcc_carry (cmp ...)), 1).
14191   if (Cond.getOpcode() == ISD::AND &&
14192       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
14193     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
14194     if (C && C->getAPIntValue() == 1)
14195       Cond = Cond.getOperand(0);
14196   }
14197
14198   // If condition flag is set by a X86ISD::CMP, then use it as the condition
14199   // setting operand in place of the X86ISD::SETCC.
14200   unsigned CondOpcode = Cond.getOpcode();
14201   if (CondOpcode == X86ISD::SETCC ||
14202       CondOpcode == X86ISD::SETCC_CARRY) {
14203     CC = Cond.getOperand(0);
14204
14205     SDValue Cmp = Cond.getOperand(1);
14206     unsigned Opc = Cmp.getOpcode();
14207     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
14208     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
14209       Cond = Cmp;
14210       addTest = false;
14211     } else {
14212       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
14213       default: break;
14214       case X86::COND_O:
14215       case X86::COND_B:
14216         // These can only come from an arithmetic instruction with overflow,
14217         // e.g. SADDO, UADDO.
14218         Cond = Cond.getNode()->getOperand(1);
14219         addTest = false;
14220         break;
14221       }
14222     }
14223   }
14224   CondOpcode = Cond.getOpcode();
14225   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
14226       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
14227       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
14228        Cond.getOperand(0).getValueType() != MVT::i8)) {
14229     SDValue LHS = Cond.getOperand(0);
14230     SDValue RHS = Cond.getOperand(1);
14231     unsigned X86Opcode;
14232     unsigned X86Cond;
14233     SDVTList VTs;
14234     // Keep this in sync with LowerXALUO, otherwise we might create redundant
14235     // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
14236     // X86ISD::INC).
14237     switch (CondOpcode) {
14238     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
14239     case ISD::SADDO:
14240       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
14241         if (C->isOne()) {
14242           X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
14243           break;
14244         }
14245       X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
14246     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
14247     case ISD::SSUBO:
14248       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
14249         if (C->isOne()) {
14250           X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
14251           break;
14252         }
14253       X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
14254     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
14255     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
14256     default: llvm_unreachable("unexpected overflowing operator");
14257     }
14258     if (Inverted)
14259       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
14260     if (CondOpcode == ISD::UMULO)
14261       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
14262                           MVT::i32);
14263     else
14264       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
14265
14266     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
14267
14268     if (CondOpcode == ISD::UMULO)
14269       Cond = X86Op.getValue(2);
14270     else
14271       Cond = X86Op.getValue(1);
14272
14273     CC = DAG.getConstant(X86Cond, dl, MVT::i8);
14274     addTest = false;
14275   } else {
14276     unsigned CondOpc;
14277     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
14278       SDValue Cmp = Cond.getOperand(0).getOperand(1);
14279       if (CondOpc == ISD::OR) {
14280         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
14281         // two branches instead of an explicit OR instruction with a
14282         // separate test.
14283         if (Cmp == Cond.getOperand(1).getOperand(1) &&
14284             isX86LogicalCmp(Cmp)) {
14285           CC = Cond.getOperand(0).getOperand(0);
14286           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14287                               Chain, Dest, CC, Cmp);
14288           CC = Cond.getOperand(1).getOperand(0);
14289           Cond = Cmp;
14290           addTest = false;
14291         }
14292       } else { // ISD::AND
14293         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
14294         // two branches instead of an explicit AND instruction with a
14295         // separate test. However, we only do this if this block doesn't
14296         // have a fall-through edge, because this requires an explicit
14297         // jmp when the condition is false.
14298         if (Cmp == Cond.getOperand(1).getOperand(1) &&
14299             isX86LogicalCmp(Cmp) &&
14300             Op.getNode()->hasOneUse()) {
14301           X86::CondCode CCode =
14302             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
14303           CCode = X86::GetOppositeBranchCondition(CCode);
14304           CC = DAG.getConstant(CCode, dl, MVT::i8);
14305           SDNode *User = *Op.getNode()->use_begin();
14306           // Look for an unconditional branch following this conditional branch.
14307           // We need this because we need to reverse the successors in order
14308           // to implement FCMP_OEQ.
14309           if (User->getOpcode() == ISD::BR) {
14310             SDValue FalseBB = User->getOperand(1);
14311             SDNode *NewBR =
14312               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14313             assert(NewBR == User);
14314             (void)NewBR;
14315             Dest = FalseBB;
14316
14317             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14318                                 Chain, Dest, CC, Cmp);
14319             X86::CondCode CCode =
14320               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
14321             CCode = X86::GetOppositeBranchCondition(CCode);
14322             CC = DAG.getConstant(CCode, dl, MVT::i8);
14323             Cond = Cmp;
14324             addTest = false;
14325           }
14326         }
14327       }
14328     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
14329       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
14330       // It should be transformed during dag combiner except when the condition
14331       // is set by a arithmetics with overflow node.
14332       X86::CondCode CCode =
14333         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
14334       CCode = X86::GetOppositeBranchCondition(CCode);
14335       CC = DAG.getConstant(CCode, dl, MVT::i8);
14336       Cond = Cond.getOperand(0).getOperand(1);
14337       addTest = false;
14338     } else if (Cond.getOpcode() == ISD::SETCC &&
14339                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
14340       // For FCMP_OEQ, we can emit
14341       // two branches instead of an explicit AND instruction with a
14342       // separate test. However, we only do this if this block doesn't
14343       // have a fall-through edge, because this requires an explicit
14344       // jmp when the condition is false.
14345       if (Op.getNode()->hasOneUse()) {
14346         SDNode *User = *Op.getNode()->use_begin();
14347         // Look for an unconditional branch following this conditional branch.
14348         // We need this because we need to reverse the successors in order
14349         // to implement FCMP_OEQ.
14350         if (User->getOpcode() == ISD::BR) {
14351           SDValue FalseBB = User->getOperand(1);
14352           SDNode *NewBR =
14353             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14354           assert(NewBR == User);
14355           (void)NewBR;
14356           Dest = FalseBB;
14357
14358           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
14359                                     Cond.getOperand(0), Cond.getOperand(1));
14360           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14361           CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
14362           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14363                               Chain, Dest, CC, Cmp);
14364           CC = DAG.getConstant(X86::COND_P, dl, MVT::i8);
14365           Cond = Cmp;
14366           addTest = false;
14367         }
14368       }
14369     } else if (Cond.getOpcode() == ISD::SETCC &&
14370                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
14371       // For FCMP_UNE, we can emit
14372       // two branches instead of an explicit AND instruction with a
14373       // separate test. However, we only do this if this block doesn't
14374       // have a fall-through edge, because this requires an explicit
14375       // jmp when the condition is false.
14376       if (Op.getNode()->hasOneUse()) {
14377         SDNode *User = *Op.getNode()->use_begin();
14378         // Look for an unconditional branch following this conditional branch.
14379         // We need this because we need to reverse the successors in order
14380         // to implement FCMP_UNE.
14381         if (User->getOpcode() == ISD::BR) {
14382           SDValue FalseBB = User->getOperand(1);
14383           SDNode *NewBR =
14384             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14385           assert(NewBR == User);
14386           (void)NewBR;
14387
14388           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
14389                                     Cond.getOperand(0), Cond.getOperand(1));
14390           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14391           CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
14392           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14393                               Chain, Dest, CC, Cmp);
14394           CC = DAG.getConstant(X86::COND_NP, dl, MVT::i8);
14395           Cond = Cmp;
14396           addTest = false;
14397           Dest = FalseBB;
14398         }
14399       }
14400     }
14401   }
14402
14403   if (addTest) {
14404     // Look pass the truncate if the high bits are known zero.
14405     if (isTruncWithZeroHighBitsInput(Cond, DAG))
14406         Cond = Cond.getOperand(0);
14407
14408     // We know the result of AND is compared against zero. Try to match
14409     // it to BT.
14410     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
14411       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
14412       if (NewSetCC.getNode()) {
14413         CC = NewSetCC.getOperand(0);
14414         Cond = NewSetCC.getOperand(1);
14415         addTest = false;
14416       }
14417     }
14418   }
14419
14420   if (addTest) {
14421     X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
14422     CC = DAG.getConstant(X86Cond, dl, MVT::i8);
14423     Cond = EmitTest(Cond, X86Cond, dl, DAG);
14424   }
14425   Cond = ConvertCmpIfNecessary(Cond, DAG);
14426   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14427                      Chain, Dest, CC, Cond);
14428 }
14429
14430 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
14431 // Calls to _alloca are needed to probe the stack when allocating more than 4k
14432 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
14433 // that the guard pages used by the OS virtual memory manager are allocated in
14434 // correct sequence.
14435 SDValue
14436 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
14437                                            SelectionDAG &DAG) const {
14438   MachineFunction &MF = DAG.getMachineFunction();
14439   bool SplitStack = MF.shouldSplitStack();
14440   bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMachO()) ||
14441                SplitStack;
14442   SDLoc dl(Op);
14443
14444   if (!Lower) {
14445     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14446     SDNode* Node = Op.getNode();
14447
14448     unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
14449     assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
14450         " not tell us which reg is the stack pointer!");
14451     EVT VT = Node->getValueType(0);
14452     SDValue Tmp1 = SDValue(Node, 0);
14453     SDValue Tmp2 = SDValue(Node, 1);
14454     SDValue Tmp3 = Node->getOperand(2);
14455     SDValue Chain = Tmp1.getOperand(0);
14456
14457     // Chain the dynamic stack allocation so that it doesn't modify the stack
14458     // pointer when other instructions are using the stack.
14459     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, dl, true),
14460         SDLoc(Node));
14461
14462     SDValue Size = Tmp2.getOperand(1);
14463     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
14464     Chain = SP.getValue(1);
14465     unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
14466     const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
14467     unsigned StackAlign = TFI.getStackAlignment();
14468     Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
14469     if (Align > StackAlign)
14470       Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
14471           DAG.getConstant(-(uint64_t)Align, dl, VT));
14472     Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
14473
14474     Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, dl, true),
14475         DAG.getIntPtrConstant(0, dl, true), SDValue(),
14476         SDLoc(Node));
14477
14478     SDValue Ops[2] = { Tmp1, Tmp2 };
14479     return DAG.getMergeValues(Ops, dl);
14480   }
14481
14482   // Get the inputs.
14483   SDValue Chain = Op.getOperand(0);
14484   SDValue Size  = Op.getOperand(1);
14485   unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
14486   EVT VT = Op.getNode()->getValueType(0);
14487
14488   bool Is64Bit = Subtarget->is64Bit();
14489   EVT SPTy = getPointerTy();
14490
14491   if (SplitStack) {
14492     MachineRegisterInfo &MRI = MF.getRegInfo();
14493
14494     if (Is64Bit) {
14495       // The 64 bit implementation of segmented stacks needs to clobber both r10
14496       // r11. This makes it impossible to use it along with nested parameters.
14497       const Function *F = MF.getFunction();
14498
14499       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
14500            I != E; ++I)
14501         if (I->hasNestAttr())
14502           report_fatal_error("Cannot use segmented stacks with functions that "
14503                              "have nested arguments.");
14504     }
14505
14506     const TargetRegisterClass *AddrRegClass =
14507       getRegClassFor(getPointerTy());
14508     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
14509     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
14510     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
14511                                 DAG.getRegister(Vreg, SPTy));
14512     SDValue Ops1[2] = { Value, Chain };
14513     return DAG.getMergeValues(Ops1, dl);
14514   } else {
14515     SDValue Flag;
14516     const unsigned Reg = (Subtarget->isTarget64BitLP64() ? X86::RAX : X86::EAX);
14517
14518     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
14519     Flag = Chain.getValue(1);
14520     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
14521
14522     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
14523
14524     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
14525     unsigned SPReg = RegInfo->getStackRegister();
14526     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
14527     Chain = SP.getValue(1);
14528
14529     if (Align) {
14530       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
14531                        DAG.getConstant(-(uint64_t)Align, dl, VT));
14532       Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
14533     }
14534
14535     SDValue Ops1[2] = { SP, Chain };
14536     return DAG.getMergeValues(Ops1, dl);
14537   }
14538 }
14539
14540 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
14541   MachineFunction &MF = DAG.getMachineFunction();
14542   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
14543
14544   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
14545   SDLoc DL(Op);
14546
14547   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
14548     // vastart just stores the address of the VarArgsFrameIndex slot into the
14549     // memory location argument.
14550     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
14551                                    getPointerTy());
14552     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
14553                         MachinePointerInfo(SV), false, false, 0);
14554   }
14555
14556   // __va_list_tag:
14557   //   gp_offset         (0 - 6 * 8)
14558   //   fp_offset         (48 - 48 + 8 * 16)
14559   //   overflow_arg_area (point to parameters coming in memory).
14560   //   reg_save_area
14561   SmallVector<SDValue, 8> MemOps;
14562   SDValue FIN = Op.getOperand(1);
14563   // Store gp_offset
14564   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
14565                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
14566                                                DL, MVT::i32),
14567                                FIN, MachinePointerInfo(SV), false, false, 0);
14568   MemOps.push_back(Store);
14569
14570   // Store fp_offset
14571   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
14572                     FIN, DAG.getIntPtrConstant(4, DL));
14573   Store = DAG.getStore(Op.getOperand(0), DL,
14574                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(), DL,
14575                                        MVT::i32),
14576                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
14577   MemOps.push_back(Store);
14578
14579   // Store ptr to overflow_arg_area
14580   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
14581                     FIN, DAG.getIntPtrConstant(4, DL));
14582   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
14583                                     getPointerTy());
14584   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
14585                        MachinePointerInfo(SV, 8),
14586                        false, false, 0);
14587   MemOps.push_back(Store);
14588
14589   // Store ptr to reg_save_area.
14590   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
14591                     FIN, DAG.getIntPtrConstant(8, DL));
14592   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
14593                                     getPointerTy());
14594   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
14595                        MachinePointerInfo(SV, 16), false, false, 0);
14596   MemOps.push_back(Store);
14597   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
14598 }
14599
14600 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
14601   assert(Subtarget->is64Bit() &&
14602          "LowerVAARG only handles 64-bit va_arg!");
14603   assert((Subtarget->isTargetLinux() ||
14604           Subtarget->isTargetDarwin()) &&
14605           "Unhandled target in LowerVAARG");
14606   assert(Op.getNode()->getNumOperands() == 4);
14607   SDValue Chain = Op.getOperand(0);
14608   SDValue SrcPtr = Op.getOperand(1);
14609   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
14610   unsigned Align = Op.getConstantOperandVal(3);
14611   SDLoc dl(Op);
14612
14613   EVT ArgVT = Op.getNode()->getValueType(0);
14614   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
14615   uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
14616   uint8_t ArgMode;
14617
14618   // Decide which area this value should be read from.
14619   // TODO: Implement the AMD64 ABI in its entirety. This simple
14620   // selection mechanism works only for the basic types.
14621   if (ArgVT == MVT::f80) {
14622     llvm_unreachable("va_arg for f80 not yet implemented");
14623   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
14624     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
14625   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
14626     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
14627   } else {
14628     llvm_unreachable("Unhandled argument type in LowerVAARG");
14629   }
14630
14631   if (ArgMode == 2) {
14632     // Sanity Check: Make sure using fp_offset makes sense.
14633     assert(!Subtarget->useSoftFloat() &&
14634            !(DAG.getMachineFunction().getFunction()->hasFnAttribute(
14635                Attribute::NoImplicitFloat)) &&
14636            Subtarget->hasSSE1());
14637   }
14638
14639   // Insert VAARG_64 node into the DAG
14640   // VAARG_64 returns two values: Variable Argument Address, Chain
14641   SDValue InstOps[] = {Chain, SrcPtr, DAG.getConstant(ArgSize, dl, MVT::i32),
14642                        DAG.getConstant(ArgMode, dl, MVT::i8),
14643                        DAG.getConstant(Align, dl, MVT::i32)};
14644   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
14645   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
14646                                           VTs, InstOps, MVT::i64,
14647                                           MachinePointerInfo(SV),
14648                                           /*Align=*/0,
14649                                           /*Volatile=*/false,
14650                                           /*ReadMem=*/true,
14651                                           /*WriteMem=*/true);
14652   Chain = VAARG.getValue(1);
14653
14654   // Load the next argument and return it
14655   return DAG.getLoad(ArgVT, dl,
14656                      Chain,
14657                      VAARG,
14658                      MachinePointerInfo(),
14659                      false, false, false, 0);
14660 }
14661
14662 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
14663                            SelectionDAG &DAG) {
14664   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
14665   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
14666   SDValue Chain = Op.getOperand(0);
14667   SDValue DstPtr = Op.getOperand(1);
14668   SDValue SrcPtr = Op.getOperand(2);
14669   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
14670   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
14671   SDLoc DL(Op);
14672
14673   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
14674                        DAG.getIntPtrConstant(24, DL), 8, /*isVolatile*/false,
14675                        false, false,
14676                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
14677 }
14678
14679 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
14680 // amount is a constant. Takes immediate version of shift as input.
14681 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
14682                                           SDValue SrcOp, uint64_t ShiftAmt,
14683                                           SelectionDAG &DAG) {
14684   MVT ElementType = VT.getVectorElementType();
14685
14686   // Fold this packed shift into its first operand if ShiftAmt is 0.
14687   if (ShiftAmt == 0)
14688     return SrcOp;
14689
14690   // Check for ShiftAmt >= element width
14691   if (ShiftAmt >= ElementType.getSizeInBits()) {
14692     if (Opc == X86ISD::VSRAI)
14693       ShiftAmt = ElementType.getSizeInBits() - 1;
14694     else
14695       return DAG.getConstant(0, dl, VT);
14696   }
14697
14698   assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
14699          && "Unknown target vector shift-by-constant node");
14700
14701   // Fold this packed vector shift into a build vector if SrcOp is a
14702   // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
14703   if (VT == SrcOp.getSimpleValueType() &&
14704       ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
14705     SmallVector<SDValue, 8> Elts;
14706     unsigned NumElts = SrcOp->getNumOperands();
14707     ConstantSDNode *ND;
14708
14709     switch(Opc) {
14710     default: llvm_unreachable(nullptr);
14711     case X86ISD::VSHLI:
14712       for (unsigned i=0; i!=NumElts; ++i) {
14713         SDValue CurrentOp = SrcOp->getOperand(i);
14714         if (CurrentOp->getOpcode() == ISD::UNDEF) {
14715           Elts.push_back(CurrentOp);
14716           continue;
14717         }
14718         ND = cast<ConstantSDNode>(CurrentOp);
14719         const APInt &C = ND->getAPIntValue();
14720         Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), dl, ElementType));
14721       }
14722       break;
14723     case X86ISD::VSRLI:
14724       for (unsigned i=0; i!=NumElts; ++i) {
14725         SDValue CurrentOp = SrcOp->getOperand(i);
14726         if (CurrentOp->getOpcode() == ISD::UNDEF) {
14727           Elts.push_back(CurrentOp);
14728           continue;
14729         }
14730         ND = cast<ConstantSDNode>(CurrentOp);
14731         const APInt &C = ND->getAPIntValue();
14732         Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), dl, ElementType));
14733       }
14734       break;
14735     case X86ISD::VSRAI:
14736       for (unsigned i=0; i!=NumElts; ++i) {
14737         SDValue CurrentOp = SrcOp->getOperand(i);
14738         if (CurrentOp->getOpcode() == ISD::UNDEF) {
14739           Elts.push_back(CurrentOp);
14740           continue;
14741         }
14742         ND = cast<ConstantSDNode>(CurrentOp);
14743         const APInt &C = ND->getAPIntValue();
14744         Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), dl, ElementType));
14745       }
14746       break;
14747     }
14748
14749     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
14750   }
14751
14752   return DAG.getNode(Opc, dl, VT, SrcOp,
14753                      DAG.getConstant(ShiftAmt, dl, MVT::i8));
14754 }
14755
14756 // getTargetVShiftNode - Handle vector element shifts where the shift amount
14757 // may or may not be a constant. Takes immediate version of shift as input.
14758 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
14759                                    SDValue SrcOp, SDValue ShAmt,
14760                                    SelectionDAG &DAG) {
14761   MVT SVT = ShAmt.getSimpleValueType();
14762   assert((SVT == MVT::i32 || SVT == MVT::i64) && "Unexpected value type!");
14763
14764   // Catch shift-by-constant.
14765   if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
14766     return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
14767                                       CShAmt->getZExtValue(), DAG);
14768
14769   // Change opcode to non-immediate version
14770   switch (Opc) {
14771     default: llvm_unreachable("Unknown target vector shift node");
14772     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
14773     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
14774     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
14775   }
14776
14777   const X86Subtarget &Subtarget =
14778       static_cast<const X86Subtarget &>(DAG.getSubtarget());
14779   if (Subtarget.hasSSE41() && ShAmt.getOpcode() == ISD::ZERO_EXTEND &&
14780       ShAmt.getOperand(0).getSimpleValueType() == MVT::i16) {
14781     // Let the shuffle legalizer expand this shift amount node.
14782     SDValue Op0 = ShAmt.getOperand(0);
14783     Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(Op0), MVT::v8i16, Op0);
14784     ShAmt = getShuffleVectorZeroOrUndef(Op0, 0, true, &Subtarget, DAG);
14785   } else {
14786     // Need to build a vector containing shift amount.
14787     // SSE/AVX packed shifts only use the lower 64-bit of the shift count.
14788     SmallVector<SDValue, 4> ShOps;
14789     ShOps.push_back(ShAmt);
14790     if (SVT == MVT::i32) {
14791       ShOps.push_back(DAG.getConstant(0, dl, SVT));
14792       ShOps.push_back(DAG.getUNDEF(SVT));
14793     }
14794     ShOps.push_back(DAG.getUNDEF(SVT));
14795
14796     MVT BVT = SVT == MVT::i32 ? MVT::v4i32 : MVT::v2i64;
14797     ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, BVT, ShOps);
14798   }
14799
14800   // The return type has to be a 128-bit type with the same element
14801   // type as the input type.
14802   MVT EltVT = VT.getVectorElementType();
14803   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
14804
14805   ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
14806   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
14807 }
14808
14809 /// \brief Return (and \p Op, \p Mask) for compare instructions or
14810 /// (vselect \p Mask, \p Op, \p PreservedSrc) for others along with the
14811 /// necessary casting for \p Mask when lowering masking intrinsics.
14812 static SDValue getVectorMaskingNode(SDValue Op, SDValue Mask,
14813                                     SDValue PreservedSrc,
14814                                     const X86Subtarget *Subtarget,
14815                                     SelectionDAG &DAG) {
14816     EVT VT = Op.getValueType();
14817     EVT MaskVT = EVT::getVectorVT(*DAG.getContext(),
14818                                   MVT::i1, VT.getVectorNumElements());
14819     EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
14820                                      Mask.getValueType().getSizeInBits());
14821     SDLoc dl(Op);
14822
14823     assert(MaskVT.isSimple() && "invalid mask type");
14824
14825     if (isAllOnes(Mask))
14826       return Op;
14827
14828     // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
14829     // are extracted by EXTRACT_SUBVECTOR.
14830     SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
14831                               DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
14832                               DAG.getIntPtrConstant(0, dl));
14833
14834     switch (Op.getOpcode()) {
14835       default: break;
14836       case X86ISD::PCMPEQM:
14837       case X86ISD::PCMPGTM:
14838       case X86ISD::CMPM:
14839       case X86ISD::CMPMU:
14840         return DAG.getNode(ISD::AND, dl, VT, Op, VMask);
14841     }
14842     if (PreservedSrc.getOpcode() == ISD::UNDEF)
14843       PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
14844     return DAG.getNode(ISD::VSELECT, dl, VT, VMask, Op, PreservedSrc);
14845 }
14846
14847 /// \brief Creates an SDNode for a predicated scalar operation.
14848 /// \returns (X86vselect \p Mask, \p Op, \p PreservedSrc).
14849 /// The mask is comming as MVT::i8 and it should be truncated
14850 /// to MVT::i1 while lowering masking intrinsics.
14851 /// The main difference between ScalarMaskingNode and VectorMaskingNode is using
14852 /// "X86select" instead of "vselect". We just can't create the "vselect" node for
14853 /// a scalar instruction.
14854 static SDValue getScalarMaskingNode(SDValue Op, SDValue Mask,
14855                                     SDValue PreservedSrc,
14856                                     const X86Subtarget *Subtarget,
14857                                     SelectionDAG &DAG) {
14858     if (isAllOnes(Mask))
14859       return Op;
14860
14861     EVT VT = Op.getValueType();
14862     SDLoc dl(Op);
14863     // The mask should be of type MVT::i1
14864     SDValue IMask = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Mask);
14865
14866     if (PreservedSrc.getOpcode() == ISD::UNDEF)
14867       PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
14868     return DAG.getNode(X86ISD::SELECT, dl, VT, IMask, Op, PreservedSrc);
14869 }
14870
14871 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
14872                                        SelectionDAG &DAG) {
14873   SDLoc dl(Op);
14874   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
14875   EVT VT = Op.getValueType();
14876   const IntrinsicData* IntrData = getIntrinsicWithoutChain(IntNo);
14877   if (IntrData) {
14878     switch(IntrData->Type) {
14879     case INTR_TYPE_1OP:
14880       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1));
14881     case INTR_TYPE_2OP:
14882       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
14883         Op.getOperand(2));
14884     case INTR_TYPE_3OP:
14885       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
14886         Op.getOperand(2), Op.getOperand(3));
14887     case INTR_TYPE_1OP_MASK_RM: {
14888       SDValue Src = Op.getOperand(1);
14889       SDValue Src0 = Op.getOperand(2);
14890       SDValue Mask = Op.getOperand(3);
14891       SDValue RoundingMode = Op.getOperand(4);
14892       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src,
14893                                               RoundingMode),
14894                                   Mask, Src0, Subtarget, DAG);
14895     }
14896     case INTR_TYPE_SCALAR_MASK_RM: {
14897       SDValue Src1 = Op.getOperand(1);
14898       SDValue Src2 = Op.getOperand(2);
14899       SDValue Src0 = Op.getOperand(3);
14900       SDValue Mask = Op.getOperand(4);
14901       // There are 2 kinds of intrinsics in this group:
14902       // (1) With supress-all-exceptions (sae) - 6 operands
14903       // (2) With rounding mode and sae - 7 operands.
14904       if (Op.getNumOperands() == 6) {
14905         SDValue Sae  = Op.getOperand(5);
14906         return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2,
14907                                                 Sae),
14908                                     Mask, Src0, Subtarget, DAG);
14909       }
14910       assert(Op.getNumOperands() == 7 && "Unexpected intrinsic form");
14911       SDValue RoundingMode  = Op.getOperand(5);
14912       SDValue Sae  = Op.getOperand(6);
14913       return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2,
14914                                               RoundingMode, Sae),
14915                                   Mask, Src0, Subtarget, DAG);
14916     }
14917     case INTR_TYPE_2OP_MASK: {
14918       SDValue Src1 = Op.getOperand(1);
14919       SDValue Src2 = Op.getOperand(2);
14920       SDValue PassThru = Op.getOperand(3);
14921       SDValue Mask = Op.getOperand(4);
14922       // We specify 2 possible opcodes for intrinsics with rounding modes.
14923       // First, we check if the intrinsic may have non-default rounding mode,
14924       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
14925       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
14926       if (IntrWithRoundingModeOpcode != 0) {
14927         SDValue Rnd = Op.getOperand(5);
14928         unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
14929         if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
14930           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
14931                                       dl, Op.getValueType(),
14932                                       Src1, Src2, Rnd),
14933                                       Mask, PassThru, Subtarget, DAG);
14934         }
14935       }
14936       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
14937                                               Src1,Src2),
14938                                   Mask, PassThru, Subtarget, DAG);
14939     }
14940     case FMA_OP_MASK: {
14941       SDValue Src1 = Op.getOperand(1);
14942       SDValue Src2 = Op.getOperand(2);
14943       SDValue Src3 = Op.getOperand(3);
14944       SDValue Mask = Op.getOperand(4);
14945       // We specify 2 possible opcodes for intrinsics with rounding modes.
14946       // First, we check if the intrinsic may have non-default rounding mode,
14947       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
14948       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
14949       if (IntrWithRoundingModeOpcode != 0) {
14950         SDValue Rnd = Op.getOperand(5);
14951         if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
14952             X86::STATIC_ROUNDING::CUR_DIRECTION)
14953           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
14954                                                   dl, Op.getValueType(),
14955                                                   Src1, Src2, Src3, Rnd),
14956                                       Mask, Src1, Subtarget, DAG);
14957       }
14958       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0,
14959                                               dl, Op.getValueType(),
14960                                               Src1, Src2, Src3),
14961                                   Mask, Src1, Subtarget, DAG);
14962     }
14963     case CMP_MASK:
14964     case CMP_MASK_CC: {
14965       // Comparison intrinsics with masks.
14966       // Example of transformation:
14967       // (i8 (int_x86_avx512_mask_pcmpeq_q_128
14968       //             (v2i64 %a), (v2i64 %b), (i8 %mask))) ->
14969       // (i8 (bitcast
14970       //   (v8i1 (insert_subvector undef,
14971       //           (v2i1 (and (PCMPEQM %a, %b),
14972       //                      (extract_subvector
14973       //                         (v8i1 (bitcast %mask)), 0))), 0))))
14974       EVT VT = Op.getOperand(1).getValueType();
14975       EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
14976                                     VT.getVectorNumElements());
14977       SDValue Mask = Op.getOperand((IntrData->Type == CMP_MASK_CC) ? 4 : 3);
14978       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
14979                                        Mask.getValueType().getSizeInBits());
14980       SDValue Cmp;
14981       if (IntrData->Type == CMP_MASK_CC) {
14982         SDValue CC = Op.getOperand(3);
14983         CC = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, CC);
14984         // We specify 2 possible opcodes for intrinsics with rounding modes.
14985         // First, we check if the intrinsic may have non-default rounding mode,
14986         // (IntrData->Opc1 != 0), then we check the rounding mode operand.
14987         if (IntrData->Opc1 != 0) {
14988           SDValue Rnd = Op.getOperand(5);
14989           if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
14990               X86::STATIC_ROUNDING::CUR_DIRECTION)
14991             Cmp = DAG.getNode(IntrData->Opc1, dl, MaskVT, Op.getOperand(1),
14992                               Op.getOperand(2), CC, Rnd);
14993         }
14994         //default rounding mode
14995         if(!Cmp.getNode())
14996             Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
14997                               Op.getOperand(2), CC);
14998
14999       } else {
15000         assert(IntrData->Type == CMP_MASK && "Unexpected intrinsic type!");
15001         Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
15002                           Op.getOperand(2));
15003       }
15004       SDValue CmpMask = getVectorMaskingNode(Cmp, Mask,
15005                                              DAG.getTargetConstant(0, dl,
15006                                                                    MaskVT),
15007                                              Subtarget, DAG);
15008       SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, BitcastVT,
15009                                 DAG.getUNDEF(BitcastVT), CmpMask,
15010                                 DAG.getIntPtrConstant(0, dl));
15011       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
15012     }
15013     case COMI: { // Comparison intrinsics
15014       ISD::CondCode CC = (ISD::CondCode)IntrData->Opc1;
15015       SDValue LHS = Op.getOperand(1);
15016       SDValue RHS = Op.getOperand(2);
15017       unsigned X86CC = TranslateX86CC(CC, dl, true, LHS, RHS, DAG);
15018       assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
15019       SDValue Cond = DAG.getNode(IntrData->Opc0, dl, MVT::i32, LHS, RHS);
15020       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15021                                   DAG.getConstant(X86CC, dl, MVT::i8), Cond);
15022       return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15023     }
15024     case VSHIFT:
15025       return getTargetVShiftNode(IntrData->Opc0, dl, Op.getSimpleValueType(),
15026                                  Op.getOperand(1), Op.getOperand(2), DAG);
15027     case VSHIFT_MASK:
15028       return getVectorMaskingNode(getTargetVShiftNode(IntrData->Opc0, dl,
15029                                                       Op.getSimpleValueType(),
15030                                                       Op.getOperand(1),
15031                                                       Op.getOperand(2), DAG),
15032                                   Op.getOperand(4), Op.getOperand(3), Subtarget,
15033                                   DAG);
15034     case COMPRESS_EXPAND_IN_REG: {
15035       SDValue Mask = Op.getOperand(3);
15036       SDValue DataToCompress = Op.getOperand(1);
15037       SDValue PassThru = Op.getOperand(2);
15038       if (isAllOnes(Mask)) // return data as is
15039         return Op.getOperand(1);
15040       EVT VT = Op.getValueType();
15041       EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15042                                     VT.getVectorNumElements());
15043       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15044                                        Mask.getValueType().getSizeInBits());
15045       SDLoc dl(Op);
15046       SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15047                                   DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
15048                                   DAG.getIntPtrConstant(0, dl));
15049
15050       return DAG.getNode(IntrData->Opc0, dl, VT, VMask, DataToCompress,
15051                          PassThru);
15052     }
15053     case BLEND: {
15054       SDValue Mask = Op.getOperand(3);
15055       EVT VT = Op.getValueType();
15056       EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15057                                     VT.getVectorNumElements());
15058       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15059                                        Mask.getValueType().getSizeInBits());
15060       SDLoc dl(Op);
15061       SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15062                                   DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
15063                                   DAG.getIntPtrConstant(0, dl));
15064       return DAG.getNode(IntrData->Opc0, dl, VT, VMask, Op.getOperand(1),
15065                          Op.getOperand(2));
15066     }
15067     default:
15068       break;
15069     }
15070   }
15071
15072   switch (IntNo) {
15073   default: return SDValue();    // Don't custom lower most intrinsics.
15074
15075   case Intrinsic::x86_avx2_permd:
15076   case Intrinsic::x86_avx2_permps:
15077     // Operands intentionally swapped. Mask is last operand to intrinsic,
15078     // but second operand for node/instruction.
15079     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
15080                        Op.getOperand(2), Op.getOperand(1));
15081
15082   case Intrinsic::x86_avx512_mask_valign_q_512:
15083   case Intrinsic::x86_avx512_mask_valign_d_512:
15084     // Vector source operands are swapped.
15085     return getVectorMaskingNode(DAG.getNode(X86ISD::VALIGN, dl,
15086                                             Op.getValueType(), Op.getOperand(2),
15087                                             Op.getOperand(1),
15088                                             Op.getOperand(3)),
15089                                 Op.getOperand(5), Op.getOperand(4),
15090                                 Subtarget, DAG);
15091
15092   // ptest and testp intrinsics. The intrinsic these come from are designed to
15093   // return an integer value, not just an instruction so lower it to the ptest
15094   // or testp pattern and a setcc for the result.
15095   case Intrinsic::x86_sse41_ptestz:
15096   case Intrinsic::x86_sse41_ptestc:
15097   case Intrinsic::x86_sse41_ptestnzc:
15098   case Intrinsic::x86_avx_ptestz_256:
15099   case Intrinsic::x86_avx_ptestc_256:
15100   case Intrinsic::x86_avx_ptestnzc_256:
15101   case Intrinsic::x86_avx_vtestz_ps:
15102   case Intrinsic::x86_avx_vtestc_ps:
15103   case Intrinsic::x86_avx_vtestnzc_ps:
15104   case Intrinsic::x86_avx_vtestz_pd:
15105   case Intrinsic::x86_avx_vtestc_pd:
15106   case Intrinsic::x86_avx_vtestnzc_pd:
15107   case Intrinsic::x86_avx_vtestz_ps_256:
15108   case Intrinsic::x86_avx_vtestc_ps_256:
15109   case Intrinsic::x86_avx_vtestnzc_ps_256:
15110   case Intrinsic::x86_avx_vtestz_pd_256:
15111   case Intrinsic::x86_avx_vtestc_pd_256:
15112   case Intrinsic::x86_avx_vtestnzc_pd_256: {
15113     bool IsTestPacked = false;
15114     unsigned X86CC;
15115     switch (IntNo) {
15116     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
15117     case Intrinsic::x86_avx_vtestz_ps:
15118     case Intrinsic::x86_avx_vtestz_pd:
15119     case Intrinsic::x86_avx_vtestz_ps_256:
15120     case Intrinsic::x86_avx_vtestz_pd_256:
15121       IsTestPacked = true; // Fallthrough
15122     case Intrinsic::x86_sse41_ptestz:
15123     case Intrinsic::x86_avx_ptestz_256:
15124       // ZF = 1
15125       X86CC = X86::COND_E;
15126       break;
15127     case Intrinsic::x86_avx_vtestc_ps:
15128     case Intrinsic::x86_avx_vtestc_pd:
15129     case Intrinsic::x86_avx_vtestc_ps_256:
15130     case Intrinsic::x86_avx_vtestc_pd_256:
15131       IsTestPacked = true; // Fallthrough
15132     case Intrinsic::x86_sse41_ptestc:
15133     case Intrinsic::x86_avx_ptestc_256:
15134       // CF = 1
15135       X86CC = X86::COND_B;
15136       break;
15137     case Intrinsic::x86_avx_vtestnzc_ps:
15138     case Intrinsic::x86_avx_vtestnzc_pd:
15139     case Intrinsic::x86_avx_vtestnzc_ps_256:
15140     case Intrinsic::x86_avx_vtestnzc_pd_256:
15141       IsTestPacked = true; // Fallthrough
15142     case Intrinsic::x86_sse41_ptestnzc:
15143     case Intrinsic::x86_avx_ptestnzc_256:
15144       // ZF and CF = 0
15145       X86CC = X86::COND_A;
15146       break;
15147     }
15148
15149     SDValue LHS = Op.getOperand(1);
15150     SDValue RHS = Op.getOperand(2);
15151     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
15152     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
15153     SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
15154     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
15155     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15156   }
15157   case Intrinsic::x86_avx512_kortestz_w:
15158   case Intrinsic::x86_avx512_kortestc_w: {
15159     unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
15160     SDValue LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(1));
15161     SDValue RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(2));
15162     SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
15163     SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
15164     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
15165     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15166   }
15167
15168   case Intrinsic::x86_sse42_pcmpistria128:
15169   case Intrinsic::x86_sse42_pcmpestria128:
15170   case Intrinsic::x86_sse42_pcmpistric128:
15171   case Intrinsic::x86_sse42_pcmpestric128:
15172   case Intrinsic::x86_sse42_pcmpistrio128:
15173   case Intrinsic::x86_sse42_pcmpestrio128:
15174   case Intrinsic::x86_sse42_pcmpistris128:
15175   case Intrinsic::x86_sse42_pcmpestris128:
15176   case Intrinsic::x86_sse42_pcmpistriz128:
15177   case Intrinsic::x86_sse42_pcmpestriz128: {
15178     unsigned Opcode;
15179     unsigned X86CC;
15180     switch (IntNo) {
15181     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
15182     case Intrinsic::x86_sse42_pcmpistria128:
15183       Opcode = X86ISD::PCMPISTRI;
15184       X86CC = X86::COND_A;
15185       break;
15186     case Intrinsic::x86_sse42_pcmpestria128:
15187       Opcode = X86ISD::PCMPESTRI;
15188       X86CC = X86::COND_A;
15189       break;
15190     case Intrinsic::x86_sse42_pcmpistric128:
15191       Opcode = X86ISD::PCMPISTRI;
15192       X86CC = X86::COND_B;
15193       break;
15194     case Intrinsic::x86_sse42_pcmpestric128:
15195       Opcode = X86ISD::PCMPESTRI;
15196       X86CC = X86::COND_B;
15197       break;
15198     case Intrinsic::x86_sse42_pcmpistrio128:
15199       Opcode = X86ISD::PCMPISTRI;
15200       X86CC = X86::COND_O;
15201       break;
15202     case Intrinsic::x86_sse42_pcmpestrio128:
15203       Opcode = X86ISD::PCMPESTRI;
15204       X86CC = X86::COND_O;
15205       break;
15206     case Intrinsic::x86_sse42_pcmpistris128:
15207       Opcode = X86ISD::PCMPISTRI;
15208       X86CC = X86::COND_S;
15209       break;
15210     case Intrinsic::x86_sse42_pcmpestris128:
15211       Opcode = X86ISD::PCMPESTRI;
15212       X86CC = X86::COND_S;
15213       break;
15214     case Intrinsic::x86_sse42_pcmpistriz128:
15215       Opcode = X86ISD::PCMPISTRI;
15216       X86CC = X86::COND_E;
15217       break;
15218     case Intrinsic::x86_sse42_pcmpestriz128:
15219       Opcode = X86ISD::PCMPESTRI;
15220       X86CC = X86::COND_E;
15221       break;
15222     }
15223     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
15224     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
15225     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
15226     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15227                                 DAG.getConstant(X86CC, dl, MVT::i8),
15228                                 SDValue(PCMP.getNode(), 1));
15229     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15230   }
15231
15232   case Intrinsic::x86_sse42_pcmpistri128:
15233   case Intrinsic::x86_sse42_pcmpestri128: {
15234     unsigned Opcode;
15235     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
15236       Opcode = X86ISD::PCMPISTRI;
15237     else
15238       Opcode = X86ISD::PCMPESTRI;
15239
15240     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
15241     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
15242     return DAG.getNode(Opcode, dl, VTs, NewOps);
15243   }
15244   }
15245 }
15246
15247 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15248                               SDValue Src, SDValue Mask, SDValue Base,
15249                               SDValue Index, SDValue ScaleOp, SDValue Chain,
15250                               const X86Subtarget * Subtarget) {
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   EVT MaskVT = MVT::getVectorVT(MVT::i1,
15256                              Index.getSimpleValueType().getVectorNumElements());
15257   SDValue MaskInReg;
15258   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15259   if (MaskC)
15260     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
15261   else
15262     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
15263   SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
15264   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
15265   SDValue Segment = DAG.getRegister(0, MVT::i32);
15266   if (Src.getOpcode() == ISD::UNDEF)
15267     Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
15268   SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
15269   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
15270   SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
15271   return DAG.getMergeValues(RetOps, dl);
15272 }
15273
15274 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15275                                SDValue Src, SDValue Mask, SDValue Base,
15276                                SDValue Index, SDValue ScaleOp, SDValue Chain) {
15277   SDLoc dl(Op);
15278   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15279   assert(C && "Invalid scale type");
15280   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
15281   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
15282   SDValue Segment = DAG.getRegister(0, MVT::i32);
15283   EVT MaskVT = MVT::getVectorVT(MVT::i1,
15284                              Index.getSimpleValueType().getVectorNumElements());
15285   SDValue MaskInReg;
15286   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15287   if (MaskC)
15288     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
15289   else
15290     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
15291   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
15292   SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
15293   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
15294   return SDValue(Res, 1);
15295 }
15296
15297 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15298                                SDValue Mask, SDValue Base, SDValue Index,
15299                                SDValue ScaleOp, SDValue Chain) {
15300   SDLoc dl(Op);
15301   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15302   assert(C && "Invalid scale type");
15303   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
15304   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
15305   SDValue Segment = DAG.getRegister(0, MVT::i32);
15306   EVT MaskVT =
15307     MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
15308   SDValue MaskInReg;
15309   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15310   if (MaskC)
15311     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
15312   else
15313     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
15314   //SDVTList VTs = DAG.getVTList(MVT::Other);
15315   SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
15316   SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
15317   return SDValue(Res, 0);
15318 }
15319
15320 // getReadPerformanceCounter - Handles the lowering of builtin intrinsics that
15321 // read performance monitor counters (x86_rdpmc).
15322 static void getReadPerformanceCounter(SDNode *N, SDLoc DL,
15323                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
15324                               SmallVectorImpl<SDValue> &Results) {
15325   assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
15326   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
15327   SDValue LO, HI;
15328
15329   // The ECX register is used to select the index of the performance counter
15330   // to read.
15331   SDValue Chain = DAG.getCopyToReg(N->getOperand(0), DL, X86::ECX,
15332                                    N->getOperand(2));
15333   SDValue rd = DAG.getNode(X86ISD::RDPMC_DAG, DL, Tys, Chain);
15334
15335   // Reads the content of a 64-bit performance counter and returns it in the
15336   // registers EDX:EAX.
15337   if (Subtarget->is64Bit()) {
15338     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
15339     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
15340                             LO.getValue(2));
15341   } else {
15342     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
15343     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
15344                             LO.getValue(2));
15345   }
15346   Chain = HI.getValue(1);
15347
15348   if (Subtarget->is64Bit()) {
15349     // The EAX register is loaded with the low-order 32 bits. The EDX register
15350     // is loaded with the supported high-order bits of the counter.
15351     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
15352                               DAG.getConstant(32, DL, MVT::i8));
15353     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
15354     Results.push_back(Chain);
15355     return;
15356   }
15357
15358   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
15359   SDValue Ops[] = { LO, HI };
15360   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
15361   Results.push_back(Pair);
15362   Results.push_back(Chain);
15363 }
15364
15365 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
15366 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
15367 // also used to custom lower READCYCLECOUNTER nodes.
15368 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
15369                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
15370                               SmallVectorImpl<SDValue> &Results) {
15371   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
15372   SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
15373   SDValue LO, HI;
15374
15375   // The processor's time-stamp counter (a 64-bit MSR) is stored into the
15376   // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
15377   // and the EAX register is loaded with the low-order 32 bits.
15378   if (Subtarget->is64Bit()) {
15379     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
15380     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
15381                             LO.getValue(2));
15382   } else {
15383     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
15384     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
15385                             LO.getValue(2));
15386   }
15387   SDValue Chain = HI.getValue(1);
15388
15389   if (Opcode == X86ISD::RDTSCP_DAG) {
15390     assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
15391
15392     // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
15393     // the ECX register. Add 'ecx' explicitly to the chain.
15394     SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
15395                                      HI.getValue(2));
15396     // Explicitly store the content of ECX at the location passed in input
15397     // to the 'rdtscp' intrinsic.
15398     Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
15399                          MachinePointerInfo(), false, false, 0);
15400   }
15401
15402   if (Subtarget->is64Bit()) {
15403     // The EDX register is loaded with the high-order 32 bits of the MSR, and
15404     // the EAX register is loaded with the low-order 32 bits.
15405     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
15406                               DAG.getConstant(32, DL, MVT::i8));
15407     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
15408     Results.push_back(Chain);
15409     return;
15410   }
15411
15412   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
15413   SDValue Ops[] = { LO, HI };
15414   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
15415   Results.push_back(Pair);
15416   Results.push_back(Chain);
15417 }
15418
15419 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
15420                                      SelectionDAG &DAG) {
15421   SmallVector<SDValue, 2> Results;
15422   SDLoc DL(Op);
15423   getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
15424                           Results);
15425   return DAG.getMergeValues(Results, DL);
15426 }
15427
15428
15429 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
15430                                       SelectionDAG &DAG) {
15431   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
15432
15433   const IntrinsicData* IntrData = getIntrinsicWithChain(IntNo);
15434   if (!IntrData)
15435     return SDValue();
15436
15437   SDLoc dl(Op);
15438   switch(IntrData->Type) {
15439   default:
15440     llvm_unreachable("Unknown Intrinsic Type");
15441     break;
15442   case RDSEED:
15443   case RDRAND: {
15444     // Emit the node with the right value type.
15445     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
15446     SDValue Result = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
15447
15448     // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
15449     // Otherwise return the value from Rand, which is always 0, casted to i32.
15450     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
15451                       DAG.getConstant(1, dl, Op->getValueType(1)),
15452                       DAG.getConstant(X86::COND_B, dl, MVT::i32),
15453                       SDValue(Result.getNode(), 1) };
15454     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
15455                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
15456                                   Ops);
15457
15458     // Return { result, isValid, chain }.
15459     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
15460                        SDValue(Result.getNode(), 2));
15461   }
15462   case GATHER: {
15463   //gather(v1, mask, index, base, scale);
15464     SDValue Chain = Op.getOperand(0);
15465     SDValue Src   = Op.getOperand(2);
15466     SDValue Base  = Op.getOperand(3);
15467     SDValue Index = Op.getOperand(4);
15468     SDValue Mask  = Op.getOperand(5);
15469     SDValue Scale = Op.getOperand(6);
15470     return getGatherNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index, Scale,
15471                          Chain, Subtarget);
15472   }
15473   case SCATTER: {
15474   //scatter(base, mask, index, v1, scale);
15475     SDValue Chain = Op.getOperand(0);
15476     SDValue Base  = Op.getOperand(2);
15477     SDValue Mask  = Op.getOperand(3);
15478     SDValue Index = Op.getOperand(4);
15479     SDValue Src   = Op.getOperand(5);
15480     SDValue Scale = Op.getOperand(6);
15481     return getScatterNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index,
15482                           Scale, Chain);
15483   }
15484   case PREFETCH: {
15485     SDValue Hint = Op.getOperand(6);
15486     unsigned HintVal = cast<ConstantSDNode>(Hint)->getZExtValue();
15487     assert(HintVal < 2 && "Wrong prefetch hint in intrinsic: should be 0 or 1");
15488     unsigned Opcode = (HintVal ? IntrData->Opc1 : IntrData->Opc0);
15489     SDValue Chain = Op.getOperand(0);
15490     SDValue Mask  = Op.getOperand(2);
15491     SDValue Index = Op.getOperand(3);
15492     SDValue Base  = Op.getOperand(4);
15493     SDValue Scale = Op.getOperand(5);
15494     return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
15495   }
15496   // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
15497   case RDTSC: {
15498     SmallVector<SDValue, 2> Results;
15499     getReadTimeStampCounter(Op.getNode(), dl, IntrData->Opc0, DAG, Subtarget,
15500                             Results);
15501     return DAG.getMergeValues(Results, dl);
15502   }
15503   // Read Performance Monitoring Counters.
15504   case RDPMC: {
15505     SmallVector<SDValue, 2> Results;
15506     getReadPerformanceCounter(Op.getNode(), dl, DAG, Subtarget, Results);
15507     return DAG.getMergeValues(Results, dl);
15508   }
15509   // XTEST intrinsics.
15510   case XTEST: {
15511     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
15512     SDValue InTrans = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
15513     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15514                                 DAG.getConstant(X86::COND_NE, dl, MVT::i8),
15515                                 InTrans);
15516     SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
15517     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
15518                        Ret, SDValue(InTrans.getNode(), 1));
15519   }
15520   // ADC/ADCX/SBB
15521   case ADX: {
15522     SmallVector<SDValue, 2> Results;
15523     SDVTList CFVTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
15524     SDVTList VTs = DAG.getVTList(Op.getOperand(3)->getValueType(0), MVT::Other);
15525     SDValue GenCF = DAG.getNode(X86ISD::ADD, dl, CFVTs, Op.getOperand(2),
15526                                 DAG.getConstant(-1, dl, MVT::i8));
15527     SDValue Res = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(3),
15528                               Op.getOperand(4), GenCF.getValue(1));
15529     SDValue Store = DAG.getStore(Op.getOperand(0), dl, Res.getValue(0),
15530                                  Op.getOperand(5), MachinePointerInfo(),
15531                                  false, false, 0);
15532     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15533                                 DAG.getConstant(X86::COND_B, dl, MVT::i8),
15534                                 Res.getValue(1));
15535     Results.push_back(SetCC);
15536     Results.push_back(Store);
15537     return DAG.getMergeValues(Results, dl);
15538   }
15539   case COMPRESS_TO_MEM: {
15540     SDLoc dl(Op);
15541     SDValue Mask = Op.getOperand(4);
15542     SDValue DataToCompress = Op.getOperand(3);
15543     SDValue Addr = Op.getOperand(2);
15544     SDValue Chain = Op.getOperand(0);
15545
15546     if (isAllOnes(Mask)) // return just a store
15547       return DAG.getStore(Chain, dl, DataToCompress, Addr,
15548                           MachinePointerInfo(), false, false, 0);
15549
15550     EVT VT = DataToCompress.getValueType();
15551     EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15552                                   VT.getVectorNumElements());
15553     EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15554                                      Mask.getValueType().getSizeInBits());
15555     SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15556                                 DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
15557                                 DAG.getIntPtrConstant(0, dl));
15558
15559     SDValue Compressed =  DAG.getNode(IntrData->Opc0, dl, VT, VMask,
15560                                       DataToCompress, DAG.getUNDEF(VT));
15561     return DAG.getStore(Chain, dl, Compressed, Addr,
15562                         MachinePointerInfo(), false, false, 0);
15563   }
15564   case EXPAND_FROM_MEM: {
15565     SDLoc dl(Op);
15566     SDValue Mask = Op.getOperand(4);
15567     SDValue PathThru = Op.getOperand(3);
15568     SDValue Addr = Op.getOperand(2);
15569     SDValue Chain = Op.getOperand(0);
15570     EVT VT = Op.getValueType();
15571
15572     if (isAllOnes(Mask)) // return just a load
15573       return DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(), false, false,
15574                          false, 0);
15575     EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15576                                   VT.getVectorNumElements());
15577     EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15578                                      Mask.getValueType().getSizeInBits());
15579     SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15580                                 DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
15581                                 DAG.getIntPtrConstant(0, dl));
15582
15583     SDValue DataToExpand = DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(),
15584                                    false, false, false, 0);
15585
15586     SDValue Results[] = {
15587         DAG.getNode(IntrData->Opc0, dl, VT, VMask, DataToExpand, PathThru),
15588         Chain};
15589     return DAG.getMergeValues(Results, dl);
15590   }
15591   }
15592 }
15593
15594 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
15595                                            SelectionDAG &DAG) const {
15596   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
15597   MFI->setReturnAddressIsTaken(true);
15598
15599   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
15600     return SDValue();
15601
15602   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15603   SDLoc dl(Op);
15604   EVT PtrVT = getPointerTy();
15605
15606   if (Depth > 0) {
15607     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
15608     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15609     SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), dl, PtrVT);
15610     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
15611                        DAG.getNode(ISD::ADD, dl, PtrVT,
15612                                    FrameAddr, Offset),
15613                        MachinePointerInfo(), false, false, false, 0);
15614   }
15615
15616   // Just load the return address.
15617   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
15618   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
15619                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
15620 }
15621
15622 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
15623   MachineFunction &MF = DAG.getMachineFunction();
15624   MachineFrameInfo *MFI = MF.getFrameInfo();
15625   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
15626   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15627   EVT VT = Op.getValueType();
15628
15629   MFI->setFrameAddressIsTaken(true);
15630
15631   if (MF.getTarget().getMCAsmInfo()->usesWindowsCFI()) {
15632     // Depth > 0 makes no sense on targets which use Windows unwind codes.  It
15633     // is not possible to crawl up the stack without looking at the unwind codes
15634     // simultaneously.
15635     int FrameAddrIndex = FuncInfo->getFAIndex();
15636     if (!FrameAddrIndex) {
15637       // Set up a frame object for the return address.
15638       unsigned SlotSize = RegInfo->getSlotSize();
15639       FrameAddrIndex = MF.getFrameInfo()->CreateFixedObject(
15640           SlotSize, /*Offset=*/0, /*IsImmutable=*/false);
15641       FuncInfo->setFAIndex(FrameAddrIndex);
15642     }
15643     return DAG.getFrameIndex(FrameAddrIndex, VT);
15644   }
15645
15646   unsigned FrameReg =
15647       RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
15648   SDLoc dl(Op);  // FIXME probably not meaningful
15649   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15650   assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
15651           (FrameReg == X86::EBP && VT == MVT::i32)) &&
15652          "Invalid Frame Register!");
15653   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
15654   while (Depth--)
15655     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
15656                             MachinePointerInfo(),
15657                             false, false, false, 0);
15658   return FrameAddr;
15659 }
15660
15661 // FIXME? Maybe this could be a TableGen attribute on some registers and
15662 // this table could be generated automatically from RegInfo.
15663 unsigned X86TargetLowering::getRegisterByName(const char* RegName,
15664                                               EVT VT) const {
15665   unsigned Reg = StringSwitch<unsigned>(RegName)
15666                        .Case("esp", X86::ESP)
15667                        .Case("rsp", X86::RSP)
15668                        .Default(0);
15669   if (Reg)
15670     return Reg;
15671   report_fatal_error("Invalid register name global variable");
15672 }
15673
15674 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
15675                                                      SelectionDAG &DAG) const {
15676   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15677   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize(), SDLoc(Op));
15678 }
15679
15680 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
15681   SDValue Chain     = Op.getOperand(0);
15682   SDValue Offset    = Op.getOperand(1);
15683   SDValue Handler   = Op.getOperand(2);
15684   SDLoc dl      (Op);
15685
15686   EVT PtrVT = getPointerTy();
15687   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15688   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
15689   assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
15690           (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
15691          "Invalid Frame Register!");
15692   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
15693   unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
15694
15695   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
15696                                  DAG.getIntPtrConstant(RegInfo->getSlotSize(),
15697                                                        dl));
15698   StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
15699   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
15700                        false, false, 0);
15701   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
15702
15703   return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
15704                      DAG.getRegister(StoreAddrReg, PtrVT));
15705 }
15706
15707 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
15708                                                SelectionDAG &DAG) const {
15709   SDLoc DL(Op);
15710   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
15711                      DAG.getVTList(MVT::i32, MVT::Other),
15712                      Op.getOperand(0), Op.getOperand(1));
15713 }
15714
15715 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
15716                                                 SelectionDAG &DAG) const {
15717   SDLoc DL(Op);
15718   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
15719                      Op.getOperand(0), Op.getOperand(1));
15720 }
15721
15722 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
15723   return Op.getOperand(0);
15724 }
15725
15726 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
15727                                                 SelectionDAG &DAG) const {
15728   SDValue Root = Op.getOperand(0);
15729   SDValue Trmp = Op.getOperand(1); // trampoline
15730   SDValue FPtr = Op.getOperand(2); // nested function
15731   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
15732   SDLoc dl (Op);
15733
15734   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
15735   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
15736
15737   if (Subtarget->is64Bit()) {
15738     SDValue OutChains[6];
15739
15740     // Large code-model.
15741     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
15742     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
15743
15744     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
15745     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
15746
15747     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
15748
15749     // Load the pointer to the nested function into R11.
15750     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
15751     SDValue Addr = Trmp;
15752     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
15753                                 Addr, MachinePointerInfo(TrmpAddr),
15754                                 false, false, 0);
15755
15756     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15757                        DAG.getConstant(2, dl, MVT::i64));
15758     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
15759                                 MachinePointerInfo(TrmpAddr, 2),
15760                                 false, false, 2);
15761
15762     // Load the 'nest' parameter value into R10.
15763     // R10 is specified in X86CallingConv.td
15764     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
15765     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15766                        DAG.getConstant(10, dl, MVT::i64));
15767     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
15768                                 Addr, MachinePointerInfo(TrmpAddr, 10),
15769                                 false, false, 0);
15770
15771     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15772                        DAG.getConstant(12, dl, MVT::i64));
15773     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
15774                                 MachinePointerInfo(TrmpAddr, 12),
15775                                 false, false, 2);
15776
15777     // Jump to the nested function.
15778     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
15779     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15780                        DAG.getConstant(20, dl, MVT::i64));
15781     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
15782                                 Addr, MachinePointerInfo(TrmpAddr, 20),
15783                                 false, false, 0);
15784
15785     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
15786     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15787                        DAG.getConstant(22, dl, MVT::i64));
15788     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, dl, MVT::i8),
15789                                 Addr, MachinePointerInfo(TrmpAddr, 22),
15790                                 false, false, 0);
15791
15792     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
15793   } else {
15794     const Function *Func =
15795       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
15796     CallingConv::ID CC = Func->getCallingConv();
15797     unsigned NestReg;
15798
15799     switch (CC) {
15800     default:
15801       llvm_unreachable("Unsupported calling convention");
15802     case CallingConv::C:
15803     case CallingConv::X86_StdCall: {
15804       // Pass 'nest' parameter in ECX.
15805       // Must be kept in sync with X86CallingConv.td
15806       NestReg = X86::ECX;
15807
15808       // Check that ECX wasn't needed by an 'inreg' parameter.
15809       FunctionType *FTy = Func->getFunctionType();
15810       const AttributeSet &Attrs = Func->getAttributes();
15811
15812       if (!Attrs.isEmpty() && !Func->isVarArg()) {
15813         unsigned InRegCount = 0;
15814         unsigned Idx = 1;
15815
15816         for (FunctionType::param_iterator I = FTy->param_begin(),
15817              E = FTy->param_end(); I != E; ++I, ++Idx)
15818           if (Attrs.hasAttribute(Idx, Attribute::InReg))
15819             // FIXME: should only count parameters that are lowered to integers.
15820             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
15821
15822         if (InRegCount > 2) {
15823           report_fatal_error("Nest register in use - reduce number of inreg"
15824                              " parameters!");
15825         }
15826       }
15827       break;
15828     }
15829     case CallingConv::X86_FastCall:
15830     case CallingConv::X86_ThisCall:
15831     case CallingConv::Fast:
15832       // Pass 'nest' parameter in EAX.
15833       // Must be kept in sync with X86CallingConv.td
15834       NestReg = X86::EAX;
15835       break;
15836     }
15837
15838     SDValue OutChains[4];
15839     SDValue Addr, Disp;
15840
15841     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15842                        DAG.getConstant(10, dl, MVT::i32));
15843     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
15844
15845     // This is storing the opcode for MOV32ri.
15846     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
15847     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
15848     OutChains[0] = DAG.getStore(Root, dl,
15849                                 DAG.getConstant(MOV32ri|N86Reg, dl, MVT::i8),
15850                                 Trmp, MachinePointerInfo(TrmpAddr),
15851                                 false, false, 0);
15852
15853     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15854                        DAG.getConstant(1, dl, MVT::i32));
15855     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
15856                                 MachinePointerInfo(TrmpAddr, 1),
15857                                 false, false, 1);
15858
15859     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
15860     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15861                        DAG.getConstant(5, dl, MVT::i32));
15862     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, dl, MVT::i8),
15863                                 Addr, MachinePointerInfo(TrmpAddr, 5),
15864                                 false, false, 1);
15865
15866     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15867                        DAG.getConstant(6, dl, MVT::i32));
15868     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
15869                                 MachinePointerInfo(TrmpAddr, 6),
15870                                 false, false, 1);
15871
15872     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
15873   }
15874 }
15875
15876 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
15877                                             SelectionDAG &DAG) const {
15878   /*
15879    The rounding mode is in bits 11:10 of FPSR, and has the following
15880    settings:
15881      00 Round to nearest
15882      01 Round to -inf
15883      10 Round to +inf
15884      11 Round to 0
15885
15886   FLT_ROUNDS, on the other hand, expects the following:
15887     -1 Undefined
15888      0 Round to 0
15889      1 Round to nearest
15890      2 Round to +inf
15891      3 Round to -inf
15892
15893   To perform the conversion, we do:
15894     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
15895   */
15896
15897   MachineFunction &MF = DAG.getMachineFunction();
15898   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
15899   unsigned StackAlignment = TFI.getStackAlignment();
15900   MVT VT = Op.getSimpleValueType();
15901   SDLoc DL(Op);
15902
15903   // Save FP Control Word to stack slot
15904   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
15905   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
15906
15907   MachineMemOperand *MMO =
15908    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
15909                            MachineMemOperand::MOStore, 2, 2);
15910
15911   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
15912   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
15913                                           DAG.getVTList(MVT::Other),
15914                                           Ops, MVT::i16, MMO);
15915
15916   // Load FP Control Word from stack slot
15917   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
15918                             MachinePointerInfo(), false, false, false, 0);
15919
15920   // Transform as necessary
15921   SDValue CWD1 =
15922     DAG.getNode(ISD::SRL, DL, MVT::i16,
15923                 DAG.getNode(ISD::AND, DL, MVT::i16,
15924                             CWD, DAG.getConstant(0x800, DL, MVT::i16)),
15925                 DAG.getConstant(11, DL, MVT::i8));
15926   SDValue CWD2 =
15927     DAG.getNode(ISD::SRL, DL, MVT::i16,
15928                 DAG.getNode(ISD::AND, DL, MVT::i16,
15929                             CWD, DAG.getConstant(0x400, DL, MVT::i16)),
15930                 DAG.getConstant(9, DL, MVT::i8));
15931
15932   SDValue RetVal =
15933     DAG.getNode(ISD::AND, DL, MVT::i16,
15934                 DAG.getNode(ISD::ADD, DL, MVT::i16,
15935                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
15936                             DAG.getConstant(1, DL, MVT::i16)),
15937                 DAG.getConstant(3, DL, MVT::i16));
15938
15939   return DAG.getNode((VT.getSizeInBits() < 16 ?
15940                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
15941 }
15942
15943 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
15944   MVT VT = Op.getSimpleValueType();
15945   EVT OpVT = VT;
15946   unsigned NumBits = VT.getSizeInBits();
15947   SDLoc dl(Op);
15948
15949   Op = Op.getOperand(0);
15950   if (VT == MVT::i8) {
15951     // Zero extend to i32 since there is not an i8 bsr.
15952     OpVT = MVT::i32;
15953     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
15954   }
15955
15956   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
15957   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
15958   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
15959
15960   // If src is zero (i.e. bsr sets ZF), returns NumBits.
15961   SDValue Ops[] = {
15962     Op,
15963     DAG.getConstant(NumBits + NumBits - 1, dl, OpVT),
15964     DAG.getConstant(X86::COND_E, dl, MVT::i8),
15965     Op.getValue(1)
15966   };
15967   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
15968
15969   // Finally 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 LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
15979   MVT VT = Op.getSimpleValueType();
15980   EVT OpVT = VT;
15981   unsigned NumBits = VT.getSizeInBits();
15982   SDLoc dl(Op);
15983
15984   Op = Op.getOperand(0);
15985   if (VT == MVT::i8) {
15986     // Zero extend to i32 since there is not an i8 bsr.
15987     OpVT = MVT::i32;
15988     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
15989   }
15990
15991   // Issue a bsr (scan bits in reverse).
15992   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
15993   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
15994
15995   // And xor with NumBits-1.
15996   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
15997                    DAG.getConstant(NumBits - 1, dl, OpVT));
15998
15999   if (VT == MVT::i8)
16000     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
16001   return Op;
16002 }
16003
16004 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
16005   MVT VT = Op.getSimpleValueType();
16006   unsigned NumBits = VT.getSizeInBits();
16007   SDLoc dl(Op);
16008   Op = Op.getOperand(0);
16009
16010   // Issue a bsf (scan bits forward) which also sets EFLAGS.
16011   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
16012   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
16013
16014   // If src is zero (i.e. bsf sets ZF), returns NumBits.
16015   SDValue Ops[] = {
16016     Op,
16017     DAG.getConstant(NumBits, dl, VT),
16018     DAG.getConstant(X86::COND_E, dl, MVT::i8),
16019     Op.getValue(1)
16020   };
16021   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
16022 }
16023
16024 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
16025 // ones, and then concatenate the result back.
16026 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
16027   MVT VT = Op.getSimpleValueType();
16028
16029   assert(VT.is256BitVector() && VT.isInteger() &&
16030          "Unsupported value type for operation");
16031
16032   unsigned NumElems = VT.getVectorNumElements();
16033   SDLoc dl(Op);
16034
16035   // Extract the LHS vectors
16036   SDValue LHS = Op.getOperand(0);
16037   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
16038   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
16039
16040   // Extract the RHS vectors
16041   SDValue RHS = Op.getOperand(1);
16042   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
16043   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
16044
16045   MVT EltVT = VT.getVectorElementType();
16046   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
16047
16048   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
16049                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
16050                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
16051 }
16052
16053 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
16054   assert(Op.getSimpleValueType().is256BitVector() &&
16055          Op.getSimpleValueType().isInteger() &&
16056          "Only handle AVX 256-bit vector integer operation");
16057   return Lower256IntArith(Op, DAG);
16058 }
16059
16060 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
16061   assert(Op.getSimpleValueType().is256BitVector() &&
16062          Op.getSimpleValueType().isInteger() &&
16063          "Only handle AVX 256-bit vector integer operation");
16064   return Lower256IntArith(Op, DAG);
16065 }
16066
16067 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
16068                         SelectionDAG &DAG) {
16069   SDLoc dl(Op);
16070   MVT VT = Op.getSimpleValueType();
16071
16072   // Decompose 256-bit ops into smaller 128-bit ops.
16073   if (VT.is256BitVector() && !Subtarget->hasInt256())
16074     return Lower256IntArith(Op, DAG);
16075
16076   SDValue A = Op.getOperand(0);
16077   SDValue B = Op.getOperand(1);
16078
16079   // Lower v16i8/v32i8 mul as promotion to v8i16/v16i16 vector
16080   // pairs, multiply and truncate.
16081   if (VT == MVT::v16i8 || VT == MVT::v32i8) {
16082     if (Subtarget->hasInt256()) {
16083       if (VT == MVT::v32i8) {
16084         MVT SubVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() / 2);
16085         SDValue Lo = DAG.getIntPtrConstant(0, dl);
16086         SDValue Hi = DAG.getIntPtrConstant(VT.getVectorNumElements() / 2, dl);
16087         SDValue ALo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Lo);
16088         SDValue BLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Lo);
16089         SDValue AHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Hi);
16090         SDValue BHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Hi);
16091         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
16092                            DAG.getNode(ISD::MUL, dl, SubVT, ALo, BLo),
16093                            DAG.getNode(ISD::MUL, dl, SubVT, AHi, BHi));
16094       }
16095
16096       MVT ExVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements());
16097       return DAG.getNode(
16098           ISD::TRUNCATE, dl, VT,
16099           DAG.getNode(ISD::MUL, dl, ExVT,
16100                       DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, A),
16101                       DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, B)));
16102     }
16103
16104     assert(VT == MVT::v16i8 &&
16105            "Pre-AVX2 support only supports v16i8 multiplication");
16106     MVT ExVT = MVT::v8i16;
16107
16108     // Extract the lo parts and sign extend to i16
16109     SDValue ALo, BLo;
16110     if (Subtarget->hasSSE41()) {
16111       ALo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, A);
16112       BLo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, B);
16113     } else {
16114       const int ShufMask[] = {-1, 0, -1, 1, -1, 2, -1, 3,
16115                               -1, 4, -1, 5, -1, 6, -1, 7};
16116       ALo = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
16117       BLo = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
16118       ALo = DAG.getNode(ISD::BITCAST, dl, ExVT, ALo);
16119       BLo = DAG.getNode(ISD::BITCAST, dl, ExVT, BLo);
16120       ALo = DAG.getNode(ISD::SRA, dl, ExVT, ALo, DAG.getConstant(8, dl, ExVT));
16121       BLo = DAG.getNode(ISD::SRA, dl, ExVT, BLo, DAG.getConstant(8, dl, ExVT));
16122     }
16123
16124     // Extract the hi parts and sign extend to i16
16125     SDValue AHi, BHi;
16126     if (Subtarget->hasSSE41()) {
16127       const int ShufMask[] = {8,  9,  10, 11, 12, 13, 14, 15,
16128                               -1, -1, -1, -1, -1, -1, -1, -1};
16129       AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
16130       BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
16131       AHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, AHi);
16132       BHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, BHi);
16133     } else {
16134       const int ShufMask[] = {-1, 8,  -1, 9,  -1, 10, -1, 11,
16135                               -1, 12, -1, 13, -1, 14, -1, 15};
16136       AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
16137       BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
16138       AHi = DAG.getNode(ISD::BITCAST, dl, ExVT, AHi);
16139       BHi = DAG.getNode(ISD::BITCAST, dl, ExVT, BHi);
16140       AHi = DAG.getNode(ISD::SRA, dl, ExVT, AHi, DAG.getConstant(8, dl, ExVT));
16141       BHi = DAG.getNode(ISD::SRA, dl, ExVT, BHi, DAG.getConstant(8, dl, ExVT));
16142     }
16143
16144     // Multiply, mask the lower 8bits of the lo/hi results and pack
16145     SDValue RLo = DAG.getNode(ISD::MUL, dl, ExVT, ALo, BLo);
16146     SDValue RHi = DAG.getNode(ISD::MUL, dl, ExVT, AHi, BHi);
16147     RLo = DAG.getNode(ISD::AND, dl, ExVT, RLo, DAG.getConstant(255, dl, ExVT));
16148     RHi = DAG.getNode(ISD::AND, dl, ExVT, RHi, DAG.getConstant(255, dl, ExVT));
16149     return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
16150   }
16151
16152   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
16153   if (VT == MVT::v4i32) {
16154     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
16155            "Should not custom lower when pmuldq is available!");
16156
16157     // Extract the odd parts.
16158     static const int UnpackMask[] = { 1, -1, 3, -1 };
16159     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
16160     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
16161
16162     // Multiply the even parts.
16163     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
16164     // Now multiply odd parts.
16165     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
16166
16167     Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
16168     Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
16169
16170     // Merge the two vectors back together with a shuffle. This expands into 2
16171     // shuffles.
16172     static const int ShufMask[] = { 0, 4, 2, 6 };
16173     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
16174   }
16175
16176   assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
16177          "Only know how to lower V2I64/V4I64/V8I64 multiply");
16178
16179   //  Ahi = psrlqi(a, 32);
16180   //  Bhi = psrlqi(b, 32);
16181   //
16182   //  AloBlo = pmuludq(a, b);
16183   //  AloBhi = pmuludq(a, Bhi);
16184   //  AhiBlo = pmuludq(Ahi, b);
16185
16186   //  AloBhi = psllqi(AloBhi, 32);
16187   //  AhiBlo = psllqi(AhiBlo, 32);
16188   //  return AloBlo + AloBhi + AhiBlo;
16189
16190   SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
16191   SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
16192
16193   // Bit cast to 32-bit vectors for MULUDQ
16194   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
16195                                   (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
16196   A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
16197   B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
16198   Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
16199   Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
16200
16201   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
16202   SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
16203   SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
16204
16205   AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
16206   AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
16207
16208   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
16209   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
16210 }
16211
16212 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
16213   assert(Subtarget->isTargetWin64() && "Unexpected target");
16214   EVT VT = Op.getValueType();
16215   assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
16216          "Unexpected return type for lowering");
16217
16218   RTLIB::Libcall LC;
16219   bool isSigned;
16220   switch (Op->getOpcode()) {
16221   default: llvm_unreachable("Unexpected request for libcall!");
16222   case ISD::SDIV:      isSigned = true;  LC = RTLIB::SDIV_I128;    break;
16223   case ISD::UDIV:      isSigned = false; LC = RTLIB::UDIV_I128;    break;
16224   case ISD::SREM:      isSigned = true;  LC = RTLIB::SREM_I128;    break;
16225   case ISD::UREM:      isSigned = false; LC = RTLIB::UREM_I128;    break;
16226   case ISD::SDIVREM:   isSigned = true;  LC = RTLIB::SDIVREM_I128; break;
16227   case ISD::UDIVREM:   isSigned = false; LC = RTLIB::UDIVREM_I128; break;
16228   }
16229
16230   SDLoc dl(Op);
16231   SDValue InChain = DAG.getEntryNode();
16232
16233   TargetLowering::ArgListTy Args;
16234   TargetLowering::ArgListEntry Entry;
16235   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
16236     EVT ArgVT = Op->getOperand(i).getValueType();
16237     assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
16238            "Unexpected argument type for lowering");
16239     SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
16240     Entry.Node = StackPtr;
16241     InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
16242                            false, false, 16);
16243     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
16244     Entry.Ty = PointerType::get(ArgTy,0);
16245     Entry.isSExt = false;
16246     Entry.isZExt = false;
16247     Args.push_back(Entry);
16248   }
16249
16250   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
16251                                          getPointerTy());
16252
16253   TargetLowering::CallLoweringInfo CLI(DAG);
16254   CLI.setDebugLoc(dl).setChain(InChain)
16255     .setCallee(getLibcallCallingConv(LC),
16256                static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
16257                Callee, std::move(Args), 0)
16258     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
16259
16260   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
16261   return DAG.getNode(ISD::BITCAST, dl, VT, CallInfo.first);
16262 }
16263
16264 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
16265                              SelectionDAG &DAG) {
16266   SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
16267   EVT VT = Op0.getValueType();
16268   SDLoc dl(Op);
16269
16270   assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
16271          (VT == MVT::v8i32 && Subtarget->hasInt256()));
16272
16273   // PMULxD operations multiply each even value (starting at 0) of LHS with
16274   // the related value of RHS and produce a widen result.
16275   // E.g., PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
16276   // => <2 x i64> <ae|cg>
16277   //
16278   // In other word, to have all the results, we need to perform two PMULxD:
16279   // 1. one with the even values.
16280   // 2. one with the odd values.
16281   // To achieve #2, with need to place the odd values at an even position.
16282   //
16283   // Place the odd value at an even position (basically, shift all values 1
16284   // step to the left):
16285   const int Mask[] = {1, -1, 3, -1, 5, -1, 7, -1};
16286   // <a|b|c|d> => <b|undef|d|undef>
16287   SDValue Odd0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
16288   // <e|f|g|h> => <f|undef|h|undef>
16289   SDValue Odd1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
16290
16291   // Emit two multiplies, one for the lower 2 ints and one for the higher 2
16292   // ints.
16293   MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
16294   bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
16295   unsigned Opcode =
16296       (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
16297   // PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
16298   // => <2 x i64> <ae|cg>
16299   SDValue Mul1 = DAG.getNode(ISD::BITCAST, dl, VT,
16300                              DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
16301   // PMULUDQ <4 x i32> <b|undef|d|undef>, <4 x i32> <f|undef|h|undef>
16302   // => <2 x i64> <bf|dh>
16303   SDValue Mul2 = DAG.getNode(ISD::BITCAST, dl, VT,
16304                              DAG.getNode(Opcode, dl, MulVT, Odd0, Odd1));
16305
16306   // Shuffle it back into the right order.
16307   SDValue Highs, Lows;
16308   if (VT == MVT::v8i32) {
16309     const int HighMask[] = {1, 9, 3, 11, 5, 13, 7, 15};
16310     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
16311     const int LowMask[] = {0, 8, 2, 10, 4, 12, 6, 14};
16312     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
16313   } else {
16314     const int HighMask[] = {1, 5, 3, 7};
16315     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
16316     const int LowMask[] = {0, 4, 2, 6};
16317     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
16318   }
16319
16320   // If we have a signed multiply but no PMULDQ fix up the high parts of a
16321   // unsigned multiply.
16322   if (IsSigned && !Subtarget->hasSSE41()) {
16323     SDValue ShAmt =
16324         DAG.getConstant(31, dl,
16325                         DAG.getTargetLoweringInfo().getShiftAmountTy(VT));
16326     SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
16327                              DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
16328     SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
16329                              DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
16330
16331     SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
16332     Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
16333   }
16334
16335   // The first result of MUL_LOHI is actually the low value, followed by the
16336   // high value.
16337   SDValue Ops[] = {Lows, Highs};
16338   return DAG.getMergeValues(Ops, dl);
16339 }
16340
16341 // Return true if the requred (according to Opcode) shift-imm form is natively
16342 // supported by the Subtarget
16343 static bool SupportedVectorShiftWithImm(MVT VT, const X86Subtarget *Subtarget, 
16344                                         unsigned Opcode) {
16345   if (VT.getScalarSizeInBits() < 16)
16346     return false;
16347  
16348   if (VT.is512BitVector() &&
16349       (VT.getScalarSizeInBits() > 16 || Subtarget->hasBWI()))
16350     return true;
16351
16352   bool LShift = VT.is128BitVector() || 
16353     (VT.is256BitVector() && Subtarget->hasInt256());
16354
16355   bool AShift = LShift && (Subtarget->hasVLX() ||
16356     (VT != MVT::v2i64 && VT != MVT::v4i64));
16357   return (Opcode == ISD::SRA) ? AShift : LShift;
16358 }
16359
16360 // The shift amount is a variable, but it is the same for all vector lanes.
16361 // These instrcutions are defined together with shift-immediate.
16362 static 
16363 bool SupportedVectorShiftWithBaseAmnt(MVT VT, const X86Subtarget *Subtarget, 
16364                                       unsigned Opcode) {
16365   return SupportedVectorShiftWithImm(VT, Subtarget, Opcode);
16366 }
16367
16368 // Return true if the requred (according to Opcode) variable-shift form is
16369 // natively supported by the Subtarget
16370 static bool SupportedVectorVarShift(MVT VT, const X86Subtarget *Subtarget, 
16371                                     unsigned Opcode) {
16372
16373   if (!Subtarget->hasInt256() || VT.getScalarSizeInBits() < 16)
16374     return false;
16375
16376   // vXi16 supported only on AVX-512, BWI
16377   if (VT.getScalarSizeInBits() == 16 && !Subtarget->hasBWI())
16378     return false;
16379
16380   if (VT.is512BitVector() || Subtarget->hasVLX())
16381     return true;
16382
16383   bool LShift = VT.is128BitVector() || VT.is256BitVector();
16384   bool AShift = LShift &&  VT != MVT::v2i64 && VT != MVT::v4i64;
16385   return (Opcode == ISD::SRA) ? AShift : LShift;
16386 }
16387
16388 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
16389                                          const X86Subtarget *Subtarget) {
16390   MVT VT = Op.getSimpleValueType();
16391   SDLoc dl(Op);
16392   SDValue R = Op.getOperand(0);
16393   SDValue Amt = Op.getOperand(1);
16394
16395   unsigned X86Opc = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHLI :
16396     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRLI : X86ISD::VSRAI;
16397
16398   // Optimize shl/srl/sra with constant shift amount.
16399   if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
16400     if (auto *ShiftConst = BVAmt->getConstantSplatNode()) {
16401       uint64_t ShiftAmt = ShiftConst->getZExtValue();
16402
16403       if (SupportedVectorShiftWithImm(VT, Subtarget, Op.getOpcode()))
16404         return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
16405
16406       if (VT == MVT::v16i8 || (Subtarget->hasInt256() && VT == MVT::v32i8)) {
16407         unsigned NumElts = VT.getVectorNumElements();
16408         MVT ShiftVT = MVT::getVectorVT(MVT::i16, NumElts / 2);
16409
16410         if (Op.getOpcode() == ISD::SHL) {
16411           // Make a large shift.
16412           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, ShiftVT,
16413                                                    R, ShiftAmt, DAG);
16414           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
16415           // Zero out the rightmost bits.
16416           SmallVector<SDValue, 32> V(
16417               NumElts, DAG.getConstant(uint8_t(-1U << ShiftAmt), dl, MVT::i8));
16418           return DAG.getNode(ISD::AND, dl, VT, SHL,
16419                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
16420         }
16421         if (Op.getOpcode() == ISD::SRL) {
16422           // Make a large shift.
16423           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ShiftVT,
16424                                                    R, ShiftAmt, DAG);
16425           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
16426           // Zero out the leftmost bits.
16427           SmallVector<SDValue, 32> V(
16428               NumElts, DAG.getConstant(uint8_t(-1U) >> ShiftAmt, dl, MVT::i8));
16429           return DAG.getNode(ISD::AND, dl, VT, SRL,
16430                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
16431         }
16432         if (Op.getOpcode() == ISD::SRA) {
16433           if (ShiftAmt == 7) {
16434             // R s>> 7  ===  R s< 0
16435             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
16436             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
16437           }
16438
16439           // R s>> a === ((R u>> a) ^ m) - m
16440           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
16441           SmallVector<SDValue, 32> V(NumElts,
16442                                      DAG.getConstant(128 >> ShiftAmt, dl,
16443                                                      MVT::i8));
16444           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
16445           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
16446           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
16447           return Res;
16448         }
16449         llvm_unreachable("Unknown shift opcode.");
16450       }
16451     }
16452   }
16453
16454   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
16455   if (!Subtarget->is64Bit() &&
16456       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
16457       Amt.getOpcode() == ISD::BITCAST &&
16458       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
16459     Amt = Amt.getOperand(0);
16460     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
16461                      VT.getVectorNumElements();
16462     unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
16463     uint64_t ShiftAmt = 0;
16464     for (unsigned i = 0; i != Ratio; ++i) {
16465       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
16466       if (!C)
16467         return SDValue();
16468       // 6 == Log2(64)
16469       ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
16470     }
16471     // Check remaining shift amounts.
16472     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
16473       uint64_t ShAmt = 0;
16474       for (unsigned j = 0; j != Ratio; ++j) {
16475         ConstantSDNode *C =
16476           dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
16477         if (!C)
16478           return SDValue();
16479         // 6 == Log2(64)
16480         ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
16481       }
16482       if (ShAmt != ShiftAmt)
16483         return SDValue();
16484     }
16485     return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
16486   }
16487
16488   return SDValue();
16489 }
16490
16491 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
16492                                         const X86Subtarget* Subtarget) {
16493   MVT VT = Op.getSimpleValueType();
16494   SDLoc dl(Op);
16495   SDValue R = Op.getOperand(0);
16496   SDValue Amt = Op.getOperand(1);
16497
16498   unsigned X86OpcI = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHLI :
16499     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRLI : X86ISD::VSRAI;
16500
16501   unsigned X86OpcV = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHL :
16502     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRL : X86ISD::VSRA;
16503
16504   if (SupportedVectorShiftWithBaseAmnt(VT, Subtarget, Op.getOpcode())) {
16505     SDValue BaseShAmt;
16506     EVT EltVT = VT.getVectorElementType();
16507
16508     if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Amt)) {
16509       // Check if this build_vector node is doing a splat.
16510       // If so, then set BaseShAmt equal to the splat value.
16511       BaseShAmt = BV->getSplatValue();
16512       if (BaseShAmt && BaseShAmt.getOpcode() == ISD::UNDEF)
16513         BaseShAmt = SDValue();
16514     } else {
16515       if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
16516         Amt = Amt.getOperand(0);
16517
16518       ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(Amt);
16519       if (SVN && SVN->isSplat()) {
16520         unsigned SplatIdx = (unsigned)SVN->getSplatIndex();
16521         SDValue InVec = Amt.getOperand(0);
16522         if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
16523           assert((SplatIdx < InVec.getValueType().getVectorNumElements()) &&
16524                  "Unexpected shuffle index found!");
16525           BaseShAmt = InVec.getOperand(SplatIdx);
16526         } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
16527            if (ConstantSDNode *C =
16528                dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
16529              if (C->getZExtValue() == SplatIdx)
16530                BaseShAmt = InVec.getOperand(1);
16531            }
16532         }
16533
16534         if (!BaseShAmt)
16535           // Avoid introducing an extract element from a shuffle.
16536           BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, InVec,
16537                                   DAG.getIntPtrConstant(SplatIdx, dl));
16538       }
16539     }
16540
16541     if (BaseShAmt.getNode()) {
16542       assert(EltVT.bitsLE(MVT::i64) && "Unexpected element type!");
16543       if (EltVT != MVT::i64 && EltVT.bitsGT(MVT::i32))
16544         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, BaseShAmt);
16545       else if (EltVT.bitsLT(MVT::i32))
16546         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
16547
16548       return getTargetVShiftNode(X86OpcI, dl, VT, R, BaseShAmt, DAG);
16549     }
16550   }
16551
16552   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
16553   if (!Subtarget->is64Bit() && VT == MVT::v2i64  &&
16554       Amt.getOpcode() == ISD::BITCAST &&
16555       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
16556     Amt = Amt.getOperand(0);
16557     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
16558                      VT.getVectorNumElements();
16559     std::vector<SDValue> Vals(Ratio);
16560     for (unsigned i = 0; i != Ratio; ++i)
16561       Vals[i] = Amt.getOperand(i);
16562     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
16563       for (unsigned j = 0; j != Ratio; ++j)
16564         if (Vals[j] != Amt.getOperand(i + j))
16565           return SDValue();
16566     }
16567     return DAG.getNode(X86OpcV, dl, VT, R, Op.getOperand(1));
16568   }
16569   return SDValue();
16570 }
16571
16572 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
16573                           SelectionDAG &DAG) {
16574   MVT VT = Op.getSimpleValueType();
16575   SDLoc dl(Op);
16576   SDValue R = Op.getOperand(0);
16577   SDValue Amt = Op.getOperand(1);
16578
16579   assert(VT.isVector() && "Custom lowering only for vector shifts!");
16580   assert(Subtarget->hasSSE2() && "Only custom lower when we have SSE2!");
16581
16582   if (SDValue V = LowerScalarImmediateShift(Op, DAG, Subtarget))
16583     return V;
16584
16585   if (SDValue V = LowerScalarVariableShift(Op, DAG, Subtarget))
16586       return V;
16587
16588   if (SupportedVectorVarShift(VT, Subtarget, Op.getOpcode()))
16589     return Op;
16590
16591   // 2i64 vector logical shifts can efficiently avoid scalarization - do the
16592   // shifts per-lane and then shuffle the partial results back together.
16593   if (VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) {
16594     // Splat the shift amounts so the scalar shifts above will catch it.
16595     SDValue Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {0, 0});
16596     SDValue Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {1, 1});
16597     SDValue R0 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt0);
16598     SDValue R1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt1);
16599     return DAG.getVectorShuffle(VT, dl, R0, R1, {0, 3});
16600   }
16601
16602   // If possible, lower this packed shift into a vector multiply instead of
16603   // expanding it into a sequence of scalar shifts.
16604   // Do this only if the vector shift count is a constant build_vector.
16605   if (Op.getOpcode() == ISD::SHL &&
16606       (VT == MVT::v8i16 || VT == MVT::v4i32 ||
16607        (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
16608       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
16609     SmallVector<SDValue, 8> Elts;
16610     EVT SVT = VT.getScalarType();
16611     unsigned SVTBits = SVT.getSizeInBits();
16612     const APInt &One = APInt(SVTBits, 1);
16613     unsigned NumElems = VT.getVectorNumElements();
16614
16615     for (unsigned i=0; i !=NumElems; ++i) {
16616       SDValue Op = Amt->getOperand(i);
16617       if (Op->getOpcode() == ISD::UNDEF) {
16618         Elts.push_back(Op);
16619         continue;
16620       }
16621
16622       ConstantSDNode *ND = cast<ConstantSDNode>(Op);
16623       const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
16624       uint64_t ShAmt = C.getZExtValue();
16625       if (ShAmt >= SVTBits) {
16626         Elts.push_back(DAG.getUNDEF(SVT));
16627         continue;
16628       }
16629       Elts.push_back(DAG.getConstant(One.shl(ShAmt), dl, SVT));
16630     }
16631     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
16632     return DAG.getNode(ISD::MUL, dl, VT, R, BV);
16633   }
16634
16635   // Lower SHL with variable shift amount.
16636   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
16637     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, dl, VT));
16638
16639     Op = DAG.getNode(ISD::ADD, dl, VT, Op,
16640                      DAG.getConstant(0x3f800000U, dl, VT));
16641     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
16642     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
16643     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
16644   }
16645
16646   // If possible, lower this shift as a sequence of two shifts by
16647   // constant plus a MOVSS/MOVSD instead of scalarizing it.
16648   // Example:
16649   //   (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
16650   //
16651   // Could be rewritten as:
16652   //   (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
16653   //
16654   // The advantage is that the two shifts from the example would be
16655   // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
16656   // the vector shift into four scalar shifts plus four pairs of vector
16657   // insert/extract.
16658   if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
16659       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
16660     unsigned TargetOpcode = X86ISD::MOVSS;
16661     bool CanBeSimplified;
16662     // The splat value for the first packed shift (the 'X' from the example).
16663     SDValue Amt1 = Amt->getOperand(0);
16664     // The splat value for the second packed shift (the 'Y' from the example).
16665     SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
16666                                         Amt->getOperand(2);
16667
16668     // See if it is possible to replace this node with a sequence of
16669     // two shifts followed by a MOVSS/MOVSD
16670     if (VT == MVT::v4i32) {
16671       // Check if it is legal to use a MOVSS.
16672       CanBeSimplified = Amt2 == Amt->getOperand(2) &&
16673                         Amt2 == Amt->getOperand(3);
16674       if (!CanBeSimplified) {
16675         // Otherwise, check if we can still simplify this node using a MOVSD.
16676         CanBeSimplified = Amt1 == Amt->getOperand(1) &&
16677                           Amt->getOperand(2) == Amt->getOperand(3);
16678         TargetOpcode = X86ISD::MOVSD;
16679         Amt2 = Amt->getOperand(2);
16680       }
16681     } else {
16682       // Do similar checks for the case where the machine value type
16683       // is MVT::v8i16.
16684       CanBeSimplified = Amt1 == Amt->getOperand(1);
16685       for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
16686         CanBeSimplified = Amt2 == Amt->getOperand(i);
16687
16688       if (!CanBeSimplified) {
16689         TargetOpcode = X86ISD::MOVSD;
16690         CanBeSimplified = true;
16691         Amt2 = Amt->getOperand(4);
16692         for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
16693           CanBeSimplified = Amt1 == Amt->getOperand(i);
16694         for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
16695           CanBeSimplified = Amt2 == Amt->getOperand(j);
16696       }
16697     }
16698
16699     if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
16700         isa<ConstantSDNode>(Amt2)) {
16701       // Replace this node with two shifts followed by a MOVSS/MOVSD.
16702       EVT CastVT = MVT::v4i32;
16703       SDValue Splat1 =
16704         DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), dl, VT);
16705       SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
16706       SDValue Splat2 =
16707         DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), dl, VT);
16708       SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
16709       if (TargetOpcode == X86ISD::MOVSD)
16710         CastVT = MVT::v2i64;
16711       SDValue BitCast1 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift1);
16712       SDValue BitCast2 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift2);
16713       SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
16714                                             BitCast1, DAG);
16715       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
16716     }
16717   }
16718
16719   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
16720     // Turn 'a' into a mask suitable for VSELECT: a = a << 5;
16721     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, dl, VT));
16722
16723     SDValue VSelM = DAG.getConstant(0x80, dl, VT);
16724     SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
16725     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
16726
16727     // r = VSELECT(r, shl(r, 4), a);
16728     SDValue M = DAG.getNode(ISD::SHL, dl, VT, R, DAG.getConstant(4, dl, VT));
16729     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
16730
16731     // a += a
16732     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
16733     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
16734     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
16735
16736     // r = VSELECT(r, shl(r, 2), a);
16737     M = DAG.getNode(ISD::SHL, dl, VT, R, DAG.getConstant(2, dl, VT));
16738     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
16739
16740     // a += a
16741     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
16742     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
16743     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
16744
16745     // return VSELECT(r, r+r, a);
16746     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
16747                     DAG.getNode(ISD::ADD, dl, VT, R, R), R);
16748     return R;
16749   }
16750
16751   // It's worth extending once and using the v8i32 shifts for 16-bit types, but
16752   // the extra overheads to get from v16i8 to v8i32 make the existing SSE
16753   // solution better.
16754   if (Subtarget->hasInt256() && VT == MVT::v8i16) {
16755     MVT NewVT = VT == MVT::v8i16 ? MVT::v8i32 : MVT::v16i16;
16756     unsigned ExtOpc =
16757         Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
16758     R = DAG.getNode(ExtOpc, dl, NewVT, R);
16759     Amt = DAG.getNode(ISD::ANY_EXTEND, dl, NewVT, Amt);
16760     return DAG.getNode(ISD::TRUNCATE, dl, VT,
16761                        DAG.getNode(Op.getOpcode(), dl, NewVT, R, Amt));
16762   }
16763
16764   // Decompose 256-bit shifts into smaller 128-bit shifts.
16765   if (VT.is256BitVector()) {
16766     unsigned NumElems = VT.getVectorNumElements();
16767     MVT EltVT = VT.getVectorElementType();
16768     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
16769
16770     // Extract the two vectors
16771     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
16772     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
16773
16774     // Recreate the shift amount vectors
16775     SDValue Amt1, Amt2;
16776     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
16777       // Constant shift amount
16778       SmallVector<SDValue, 8> Ops(Amt->op_begin(), Amt->op_begin() + NumElems);
16779       ArrayRef<SDValue> Amt1Csts = makeArrayRef(Ops).slice(0, NumElems / 2);
16780       ArrayRef<SDValue> Amt2Csts = makeArrayRef(Ops).slice(NumElems / 2);
16781
16782       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
16783       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
16784     } else {
16785       // Variable shift amount
16786       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
16787       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
16788     }
16789
16790     // Issue new vector shifts for the smaller types
16791     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
16792     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
16793
16794     // Concatenate the result back
16795     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
16796   }
16797
16798   return SDValue();
16799 }
16800
16801 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
16802   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
16803   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
16804   // looks for this combo and may remove the "setcc" instruction if the "setcc"
16805   // has only one use.
16806   SDNode *N = Op.getNode();
16807   SDValue LHS = N->getOperand(0);
16808   SDValue RHS = N->getOperand(1);
16809   unsigned BaseOp = 0;
16810   unsigned Cond = 0;
16811   SDLoc DL(Op);
16812   switch (Op.getOpcode()) {
16813   default: llvm_unreachable("Unknown ovf instruction!");
16814   case ISD::SADDO:
16815     // A subtract of one will be selected as a INC. Note that INC doesn't
16816     // set CF, so we can't do this for UADDO.
16817     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
16818       if (C->isOne()) {
16819         BaseOp = X86ISD::INC;
16820         Cond = X86::COND_O;
16821         break;
16822       }
16823     BaseOp = X86ISD::ADD;
16824     Cond = X86::COND_O;
16825     break;
16826   case ISD::UADDO:
16827     BaseOp = X86ISD::ADD;
16828     Cond = X86::COND_B;
16829     break;
16830   case ISD::SSUBO:
16831     // A subtract of one will be selected as a DEC. Note that DEC doesn't
16832     // set CF, so we can't do this for USUBO.
16833     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
16834       if (C->isOne()) {
16835         BaseOp = X86ISD::DEC;
16836         Cond = X86::COND_O;
16837         break;
16838       }
16839     BaseOp = X86ISD::SUB;
16840     Cond = X86::COND_O;
16841     break;
16842   case ISD::USUBO:
16843     BaseOp = X86ISD::SUB;
16844     Cond = X86::COND_B;
16845     break;
16846   case ISD::SMULO:
16847     BaseOp = N->getValueType(0) == MVT::i8 ? X86ISD::SMUL8 : X86ISD::SMUL;
16848     Cond = X86::COND_O;
16849     break;
16850   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
16851     if (N->getValueType(0) == MVT::i8) {
16852       BaseOp = X86ISD::UMUL8;
16853       Cond = X86::COND_O;
16854       break;
16855     }
16856     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
16857                                  MVT::i32);
16858     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
16859
16860     SDValue SetCC =
16861       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
16862                   DAG.getConstant(X86::COND_O, DL, MVT::i32),
16863                   SDValue(Sum.getNode(), 2));
16864
16865     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
16866   }
16867   }
16868
16869   // Also sets EFLAGS.
16870   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
16871   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
16872
16873   SDValue SetCC =
16874     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
16875                 DAG.getConstant(Cond, DL, MVT::i32),
16876                 SDValue(Sum.getNode(), 1));
16877
16878   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
16879 }
16880
16881 /// Returns true if the operand type is exactly twice the native width, and
16882 /// the corresponding cmpxchg8b or cmpxchg16b instruction is available.
16883 /// Used to know whether to use cmpxchg8/16b when expanding atomic operations
16884 /// (otherwise we leave them alone to become __sync_fetch_and_... calls).
16885 bool X86TargetLowering::needsCmpXchgNb(const Type *MemType) const {
16886   unsigned OpWidth = MemType->getPrimitiveSizeInBits();
16887
16888   if (OpWidth == 64)
16889     return !Subtarget->is64Bit(); // FIXME this should be Subtarget.hasCmpxchg8b
16890   else if (OpWidth == 128)
16891     return Subtarget->hasCmpxchg16b();
16892   else
16893     return false;
16894 }
16895
16896 bool X86TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
16897   return needsCmpXchgNb(SI->getValueOperand()->getType());
16898 }
16899
16900 // Note: this turns large loads into lock cmpxchg8b/16b.
16901 // FIXME: On 32 bits x86, fild/movq might be faster than lock cmpxchg8b.
16902 bool X86TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
16903   auto PTy = cast<PointerType>(LI->getPointerOperand()->getType());
16904   return needsCmpXchgNb(PTy->getElementType());
16905 }
16906
16907 TargetLoweringBase::AtomicRMWExpansionKind
16908 X86TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
16909   unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
16910   const Type *MemType = AI->getType();
16911
16912   // If the operand is too big, we must see if cmpxchg8/16b is available
16913   // and default to library calls otherwise.
16914   if (MemType->getPrimitiveSizeInBits() > NativeWidth) {
16915     return needsCmpXchgNb(MemType) ? AtomicRMWExpansionKind::CmpXChg
16916                                    : AtomicRMWExpansionKind::None;
16917   }
16918
16919   AtomicRMWInst::BinOp Op = AI->getOperation();
16920   switch (Op) {
16921   default:
16922     llvm_unreachable("Unknown atomic operation");
16923   case AtomicRMWInst::Xchg:
16924   case AtomicRMWInst::Add:
16925   case AtomicRMWInst::Sub:
16926     // It's better to use xadd, xsub or xchg for these in all cases.
16927     return AtomicRMWExpansionKind::None;
16928   case AtomicRMWInst::Or:
16929   case AtomicRMWInst::And:
16930   case AtomicRMWInst::Xor:
16931     // If the atomicrmw's result isn't actually used, we can just add a "lock"
16932     // prefix to a normal instruction for these operations.
16933     return !AI->use_empty() ? AtomicRMWExpansionKind::CmpXChg
16934                             : AtomicRMWExpansionKind::None;
16935   case AtomicRMWInst::Nand:
16936   case AtomicRMWInst::Max:
16937   case AtomicRMWInst::Min:
16938   case AtomicRMWInst::UMax:
16939   case AtomicRMWInst::UMin:
16940     // These always require a non-trivial set of data operations on x86. We must
16941     // use a cmpxchg loop.
16942     return AtomicRMWExpansionKind::CmpXChg;
16943   }
16944 }
16945
16946 static bool hasMFENCE(const X86Subtarget& Subtarget) {
16947   // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
16948   // no-sse2). There isn't any reason to disable it if the target processor
16949   // supports it.
16950   return Subtarget.hasSSE2() || Subtarget.is64Bit();
16951 }
16952
16953 LoadInst *
16954 X86TargetLowering::lowerIdempotentRMWIntoFencedLoad(AtomicRMWInst *AI) const {
16955   unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
16956   const Type *MemType = AI->getType();
16957   // Accesses larger than the native width are turned into cmpxchg/libcalls, so
16958   // there is no benefit in turning such RMWs into loads, and it is actually
16959   // harmful as it introduces a mfence.
16960   if (MemType->getPrimitiveSizeInBits() > NativeWidth)
16961     return nullptr;
16962
16963   auto Builder = IRBuilder<>(AI);
16964   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
16965   auto SynchScope = AI->getSynchScope();
16966   // We must restrict the ordering to avoid generating loads with Release or
16967   // ReleaseAcquire orderings.
16968   auto Order = AtomicCmpXchgInst::getStrongestFailureOrdering(AI->getOrdering());
16969   auto Ptr = AI->getPointerOperand();
16970
16971   // Before the load we need a fence. Here is an example lifted from
16972   // http://www.hpl.hp.com/techreports/2012/HPL-2012-68.pdf showing why a fence
16973   // is required:
16974   // Thread 0:
16975   //   x.store(1, relaxed);
16976   //   r1 = y.fetch_add(0, release);
16977   // Thread 1:
16978   //   y.fetch_add(42, acquire);
16979   //   r2 = x.load(relaxed);
16980   // r1 = r2 = 0 is impossible, but becomes possible if the idempotent rmw is
16981   // lowered to just a load without a fence. A mfence flushes the store buffer,
16982   // making the optimization clearly correct.
16983   // FIXME: it is required if isAtLeastRelease(Order) but it is not clear
16984   // otherwise, we might be able to be more agressive on relaxed idempotent
16985   // rmw. In practice, they do not look useful, so we don't try to be
16986   // especially clever.
16987   if (SynchScope == SingleThread) {
16988     // FIXME: we could just insert an X86ISD::MEMBARRIER here, except we are at
16989     // the IR level, so we must wrap it in an intrinsic.
16990     return nullptr;
16991   } else if (hasMFENCE(*Subtarget)) {
16992     Function *MFence = llvm::Intrinsic::getDeclaration(M,
16993             Intrinsic::x86_sse2_mfence);
16994     Builder.CreateCall(MFence);
16995   } else {
16996     // FIXME: it might make sense to use a locked operation here but on a
16997     // different cache-line to prevent cache-line bouncing. In practice it
16998     // is probably a small win, and x86 processors without mfence are rare
16999     // enough that we do not bother.
17000     return nullptr;
17001   }
17002
17003   // Finally we can emit the atomic load.
17004   LoadInst *Loaded = Builder.CreateAlignedLoad(Ptr,
17005           AI->getType()->getPrimitiveSizeInBits());
17006   Loaded->setAtomic(Order, SynchScope);
17007   AI->replaceAllUsesWith(Loaded);
17008   AI->eraseFromParent();
17009   return Loaded;
17010 }
17011
17012 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
17013                                  SelectionDAG &DAG) {
17014   SDLoc dl(Op);
17015   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
17016     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
17017   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
17018     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
17019
17020   // The only fence that needs an instruction is a sequentially-consistent
17021   // cross-thread fence.
17022   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
17023     if (hasMFENCE(*Subtarget))
17024       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
17025
17026     SDValue Chain = Op.getOperand(0);
17027     SDValue Zero = DAG.getConstant(0, dl, MVT::i32);
17028     SDValue Ops[] = {
17029       DAG.getRegister(X86::ESP, MVT::i32),     // Base
17030       DAG.getTargetConstant(1, dl, MVT::i8),   // Scale
17031       DAG.getRegister(0, MVT::i32),            // Index
17032       DAG.getTargetConstant(0, dl, MVT::i32),  // Disp
17033       DAG.getRegister(0, MVT::i32),            // Segment.
17034       Zero,
17035       Chain
17036     };
17037     SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
17038     return SDValue(Res, 0);
17039   }
17040
17041   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
17042   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
17043 }
17044
17045 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
17046                              SelectionDAG &DAG) {
17047   MVT T = Op.getSimpleValueType();
17048   SDLoc DL(Op);
17049   unsigned Reg = 0;
17050   unsigned size = 0;
17051   switch(T.SimpleTy) {
17052   default: llvm_unreachable("Invalid value type!");
17053   case MVT::i8:  Reg = X86::AL;  size = 1; break;
17054   case MVT::i16: Reg = X86::AX;  size = 2; break;
17055   case MVT::i32: Reg = X86::EAX; size = 4; break;
17056   case MVT::i64:
17057     assert(Subtarget->is64Bit() && "Node not type legal!");
17058     Reg = X86::RAX; size = 8;
17059     break;
17060   }
17061   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
17062                                   Op.getOperand(2), SDValue());
17063   SDValue Ops[] = { cpIn.getValue(0),
17064                     Op.getOperand(1),
17065                     Op.getOperand(3),
17066                     DAG.getTargetConstant(size, DL, MVT::i8),
17067                     cpIn.getValue(1) };
17068   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
17069   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
17070   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
17071                                            Ops, T, MMO);
17072
17073   SDValue cpOut =
17074     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
17075   SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
17076                                       MVT::i32, cpOut.getValue(2));
17077   SDValue Success = DAG.getNode(X86ISD::SETCC, DL, Op->getValueType(1),
17078                                 DAG.getConstant(X86::COND_E, DL, MVT::i8),
17079                                 EFLAGS);
17080
17081   DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), cpOut);
17082   DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
17083   DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), EFLAGS.getValue(1));
17084   return SDValue();
17085 }
17086
17087 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
17088                             SelectionDAG &DAG) {
17089   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
17090   MVT DstVT = Op.getSimpleValueType();
17091
17092   if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
17093     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
17094     if (DstVT != MVT::f64)
17095       // This conversion needs to be expanded.
17096       return SDValue();
17097
17098     SDValue InVec = Op->getOperand(0);
17099     SDLoc dl(Op);
17100     unsigned NumElts = SrcVT.getVectorNumElements();
17101     EVT SVT = SrcVT.getVectorElementType();
17102
17103     // Widen the vector in input in the case of MVT::v2i32.
17104     // Example: from MVT::v2i32 to MVT::v4i32.
17105     SmallVector<SDValue, 16> Elts;
17106     for (unsigned i = 0, e = NumElts; i != e; ++i)
17107       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
17108                                  DAG.getIntPtrConstant(i, dl)));
17109
17110     // Explicitly mark the extra elements as Undef.
17111     Elts.append(NumElts, DAG.getUNDEF(SVT));
17112
17113     EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
17114     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
17115     SDValue ToV2F64 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, BV);
17116     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
17117                        DAG.getIntPtrConstant(0, dl));
17118   }
17119
17120   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
17121          Subtarget->hasMMX() && "Unexpected custom BITCAST");
17122   assert((DstVT == MVT::i64 ||
17123           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
17124          "Unexpected custom BITCAST");
17125   // i64 <=> MMX conversions are Legal.
17126   if (SrcVT==MVT::i64 && DstVT.isVector())
17127     return Op;
17128   if (DstVT==MVT::i64 && SrcVT.isVector())
17129     return Op;
17130   // MMX <=> MMX conversions are Legal.
17131   if (SrcVT.isVector() && DstVT.isVector())
17132     return Op;
17133   // All other conversions need to be expanded.
17134   return SDValue();
17135 }
17136
17137 static SDValue LowerCTPOP(SDValue Op, const X86Subtarget *Subtarget,
17138                           SelectionDAG &DAG) {
17139   SDNode *Node = Op.getNode();
17140   SDLoc dl(Node);
17141
17142   Op = Op.getOperand(0);
17143   EVT VT = Op.getValueType();
17144   assert((VT.is128BitVector() || VT.is256BitVector()) &&
17145          "CTPOP lowering only implemented for 128/256-bit wide vector types");
17146
17147   unsigned NumElts = VT.getVectorNumElements();
17148   EVT EltVT = VT.getVectorElementType();
17149   unsigned Len = EltVT.getSizeInBits();
17150
17151   // This is the vectorized version of the "best" algorithm from
17152   // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
17153   // with a minor tweak to use a series of adds + shifts instead of vector
17154   // multiplications. Implemented for the v2i64, v4i64, v4i32, v8i32 types:
17155   //
17156   //  v2i64, v4i64, v4i32 => Only profitable w/ popcnt disabled
17157   //  v8i32 => Always profitable
17158   //
17159   // FIXME: There a couple of possible improvements:
17160   //
17161   // 1) Support for i8 and i16 vectors (needs measurements if popcnt enabled).
17162   // 2) Use strategies from http://wm.ite.pl/articles/sse-popcount.html
17163   //
17164   assert(EltVT.isInteger() && (Len == 32 || Len == 64) && Len % 8 == 0 &&
17165          "CTPOP not implemented for this vector element type.");
17166
17167   // X86 canonicalize ANDs to vXi64, generate the appropriate bitcasts to avoid
17168   // extra legalization.
17169   bool NeedsBitcast = EltVT == MVT::i32;
17170   MVT BitcastVT = VT.is256BitVector() ? MVT::v4i64 : MVT::v2i64;
17171
17172   SDValue Cst55 = DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x55)), dl,
17173                                   EltVT);
17174   SDValue Cst33 = DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x33)), dl,
17175                                   EltVT);
17176   SDValue Cst0F = DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x0F)), dl,
17177                                   EltVT);
17178
17179   // v = v - ((v >> 1) & 0x55555555...)
17180   SmallVector<SDValue, 8> Ones(NumElts, DAG.getConstant(1, dl, EltVT));
17181   SDValue OnesV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ones);
17182   SDValue Srl = DAG.getNode(ISD::SRL, dl, VT, Op, OnesV);
17183   if (NeedsBitcast)
17184     Srl = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Srl);
17185
17186   SmallVector<SDValue, 8> Mask55(NumElts, Cst55);
17187   SDValue M55 = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Mask55);
17188   if (NeedsBitcast)
17189     M55 = DAG.getNode(ISD::BITCAST, dl, BitcastVT, M55);
17190
17191   SDValue And = DAG.getNode(ISD::AND, dl, Srl.getValueType(), Srl, M55);
17192   if (VT != And.getValueType())
17193     And = DAG.getNode(ISD::BITCAST, dl, VT, And);
17194   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, Op, And);
17195
17196   // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...)
17197   SmallVector<SDValue, 8> Mask33(NumElts, Cst33);
17198   SDValue M33 = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Mask33);
17199   SmallVector<SDValue, 8> Twos(NumElts, DAG.getConstant(2, dl, EltVT));
17200   SDValue TwosV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Twos);
17201
17202   Srl = DAG.getNode(ISD::SRL, dl, VT, Sub, TwosV);
17203   if (NeedsBitcast) {
17204     Srl = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Srl);
17205     M33 = DAG.getNode(ISD::BITCAST, dl, BitcastVT, M33);
17206     Sub = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Sub);
17207   }
17208
17209   SDValue AndRHS = DAG.getNode(ISD::AND, dl, M33.getValueType(), Srl, M33);
17210   SDValue AndLHS = DAG.getNode(ISD::AND, dl, M33.getValueType(), Sub, M33);
17211   if (VT != AndRHS.getValueType()) {
17212     AndRHS = DAG.getNode(ISD::BITCAST, dl, VT, AndRHS);
17213     AndLHS = DAG.getNode(ISD::BITCAST, dl, VT, AndLHS);
17214   }
17215   SDValue Add = DAG.getNode(ISD::ADD, dl, VT, AndLHS, AndRHS);
17216
17217   // v = (v + (v >> 4)) & 0x0F0F0F0F...
17218   SmallVector<SDValue, 8> Fours(NumElts, DAG.getConstant(4, dl, EltVT));
17219   SDValue FoursV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Fours);
17220   Srl = DAG.getNode(ISD::SRL, dl, VT, Add, FoursV);
17221   Add = DAG.getNode(ISD::ADD, dl, VT, Add, Srl);
17222
17223   SmallVector<SDValue, 8> Mask0F(NumElts, Cst0F);
17224   SDValue M0F = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Mask0F);
17225   if (NeedsBitcast) {
17226     Add = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Add);
17227     M0F = DAG.getNode(ISD::BITCAST, dl, BitcastVT, M0F);
17228   }
17229   And = DAG.getNode(ISD::AND, dl, M0F.getValueType(), Add, M0F);
17230   if (VT != And.getValueType())
17231     And = DAG.getNode(ISD::BITCAST, dl, VT, And);
17232
17233   // The algorithm mentioned above uses:
17234   //    v = (v * 0x01010101...) >> (Len - 8)
17235   //
17236   // Change it to use vector adds + vector shifts which yield faster results on
17237   // Haswell than using vector integer multiplication.
17238   //
17239   // For i32 elements:
17240   //    v = v + (v >> 8)
17241   //    v = v + (v >> 16)
17242   //
17243   // For i64 elements:
17244   //    v = v + (v >> 8)
17245   //    v = v + (v >> 16)
17246   //    v = v + (v >> 32)
17247   //
17248   Add = And;
17249   SmallVector<SDValue, 8> Csts;
17250   for (unsigned i = 8; i <= Len/2; i *= 2) {
17251     Csts.assign(NumElts, DAG.getConstant(i, dl, EltVT));
17252     SDValue CstsV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Csts);
17253     Srl = DAG.getNode(ISD::SRL, dl, VT, Add, CstsV);
17254     Add = DAG.getNode(ISD::ADD, dl, VT, Add, Srl);
17255     Csts.clear();
17256   }
17257
17258   // The result is on the least significant 6-bits on i32 and 7-bits on i64.
17259   SDValue Cst3F = DAG.getConstant(APInt(Len, Len == 32 ? 0x3F : 0x7F), dl,
17260                                   EltVT);
17261   SmallVector<SDValue, 8> Cst3FV(NumElts, Cst3F);
17262   SDValue M3F = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Cst3FV);
17263   if (NeedsBitcast) {
17264     Add = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Add);
17265     M3F = DAG.getNode(ISD::BITCAST, dl, BitcastVT, M3F);
17266   }
17267   And = DAG.getNode(ISD::AND, dl, M3F.getValueType(), Add, M3F);
17268   if (VT != And.getValueType())
17269     And = DAG.getNode(ISD::BITCAST, dl, VT, And);
17270
17271   return And;
17272 }
17273
17274 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
17275   SDNode *Node = Op.getNode();
17276   SDLoc dl(Node);
17277   EVT T = Node->getValueType(0);
17278   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
17279                               DAG.getConstant(0, dl, T), Node->getOperand(2));
17280   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
17281                        cast<AtomicSDNode>(Node)->getMemoryVT(),
17282                        Node->getOperand(0),
17283                        Node->getOperand(1), negOp,
17284                        cast<AtomicSDNode>(Node)->getMemOperand(),
17285                        cast<AtomicSDNode>(Node)->getOrdering(),
17286                        cast<AtomicSDNode>(Node)->getSynchScope());
17287 }
17288
17289 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
17290   SDNode *Node = Op.getNode();
17291   SDLoc dl(Node);
17292   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
17293
17294   // Convert seq_cst store -> xchg
17295   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
17296   // FIXME: On 32-bit, store -> fist or movq would be more efficient
17297   //        (The only way to get a 16-byte store is cmpxchg16b)
17298   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
17299   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
17300       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
17301     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
17302                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
17303                                  Node->getOperand(0),
17304                                  Node->getOperand(1), Node->getOperand(2),
17305                                  cast<AtomicSDNode>(Node)->getMemOperand(),
17306                                  cast<AtomicSDNode>(Node)->getOrdering(),
17307                                  cast<AtomicSDNode>(Node)->getSynchScope());
17308     return Swap.getValue(1);
17309   }
17310   // Other atomic stores have a simple pattern.
17311   return Op;
17312 }
17313
17314 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
17315   EVT VT = Op.getNode()->getSimpleValueType(0);
17316
17317   // Let legalize expand this if it isn't a legal type yet.
17318   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
17319     return SDValue();
17320
17321   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
17322
17323   unsigned Opc;
17324   bool ExtraOp = false;
17325   switch (Op.getOpcode()) {
17326   default: llvm_unreachable("Invalid code");
17327   case ISD::ADDC: Opc = X86ISD::ADD; break;
17328   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
17329   case ISD::SUBC: Opc = X86ISD::SUB; break;
17330   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
17331   }
17332
17333   if (!ExtraOp)
17334     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
17335                        Op.getOperand(1));
17336   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
17337                      Op.getOperand(1), Op.getOperand(2));
17338 }
17339
17340 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
17341                             SelectionDAG &DAG) {
17342   assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
17343
17344   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
17345   // which returns the values as { float, float } (in XMM0) or
17346   // { double, double } (which is returned in XMM0, XMM1).
17347   SDLoc dl(Op);
17348   SDValue Arg = Op.getOperand(0);
17349   EVT ArgVT = Arg.getValueType();
17350   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
17351
17352   TargetLowering::ArgListTy Args;
17353   TargetLowering::ArgListEntry Entry;
17354
17355   Entry.Node = Arg;
17356   Entry.Ty = ArgTy;
17357   Entry.isSExt = false;
17358   Entry.isZExt = false;
17359   Args.push_back(Entry);
17360
17361   bool isF64 = ArgVT == MVT::f64;
17362   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
17363   // the small struct {f32, f32} is returned in (eax, edx). For f64,
17364   // the results are returned via SRet in memory.
17365   const char *LibcallName =  isF64 ? "__sincos_stret" : "__sincosf_stret";
17366   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17367   SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy());
17368
17369   Type *RetTy = isF64
17370     ? (Type*)StructType::get(ArgTy, ArgTy, nullptr)
17371     : (Type*)VectorType::get(ArgTy, 4);
17372
17373   TargetLowering::CallLoweringInfo CLI(DAG);
17374   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
17375     .setCallee(CallingConv::C, RetTy, Callee, std::move(Args), 0);
17376
17377   std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
17378
17379   if (isF64)
17380     // Returned in xmm0 and xmm1.
17381     return CallResult.first;
17382
17383   // Returned in bits 0:31 and 32:64 xmm0.
17384   SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
17385                                CallResult.first, DAG.getIntPtrConstant(0, dl));
17386   SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
17387                                CallResult.first, DAG.getIntPtrConstant(1, dl));
17388   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
17389   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
17390 }
17391
17392 static SDValue LowerMSCATTER(SDValue Op, const X86Subtarget *Subtarget,
17393                              SelectionDAG &DAG) {
17394   assert(Subtarget->hasAVX512() &&
17395          "MGATHER/MSCATTER are supported on AVX-512 arch only");
17396
17397   MaskedScatterSDNode *N = cast<MaskedScatterSDNode>(Op.getNode());
17398   EVT VT = N->getValue().getValueType();
17399   assert(VT.getScalarSizeInBits() >= 32 && "Unsupported scatter op");
17400   SDLoc dl(Op);
17401
17402   // X86 scatter kills mask register, so its type should be added to
17403   // the list of return values
17404   if (N->getNumValues() == 1) {
17405     SDValue Index = N->getIndex();
17406     if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
17407         !Index.getValueType().is512BitVector())
17408       Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
17409
17410     SDVTList VTs = DAG.getVTList(N->getMask().getValueType(), MVT::Other);
17411     SDValue Ops[] = { N->getOperand(0), N->getOperand(1),  N->getOperand(2),
17412                       N->getOperand(3), Index };
17413
17414     SDValue NewScatter = DAG.getMaskedScatter(VTs, VT, dl, Ops, N->getMemOperand());
17415     DAG.ReplaceAllUsesWith(Op, SDValue(NewScatter.getNode(), 1));
17416     return SDValue(NewScatter.getNode(), 0);
17417   }
17418   return Op;
17419 }
17420
17421 static SDValue LowerMGATHER(SDValue Op, const X86Subtarget *Subtarget,
17422                             SelectionDAG &DAG) {
17423   assert(Subtarget->hasAVX512() &&
17424          "MGATHER/MSCATTER are supported on AVX-512 arch only");
17425
17426   MaskedGatherSDNode *N = cast<MaskedGatherSDNode>(Op.getNode());
17427   EVT VT = Op.getValueType();
17428   assert(VT.getScalarSizeInBits() >= 32 && "Unsupported gather op");
17429   SDLoc dl(Op);
17430
17431   SDValue Index = N->getIndex();
17432   if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
17433       !Index.getValueType().is512BitVector()) {
17434     Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
17435     SDValue Ops[] = { N->getOperand(0), N->getOperand(1),  N->getOperand(2),
17436                       N->getOperand(3), Index };
17437     DAG.UpdateNodeOperands(N, Ops);
17438   }
17439   return Op;
17440 }
17441
17442 SDValue X86TargetLowering::LowerGC_TRANSITION_START(SDValue Op,
17443                                                     SelectionDAG &DAG) const {
17444   // TODO: Eventually, the lowering of these nodes should be informed by or
17445   // deferred to the GC strategy for the function in which they appear. For
17446   // now, however, they must be lowered to something. Since they are logically
17447   // no-ops in the case of a null GC strategy (or a GC strategy which does not
17448   // require special handling for these nodes), lower them as literal NOOPs for
17449   // the time being.
17450   SmallVector<SDValue, 2> Ops;
17451
17452   Ops.push_back(Op.getOperand(0));
17453   if (Op->getGluedNode())
17454     Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
17455
17456   SDLoc OpDL(Op);
17457   SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
17458   SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
17459
17460   return NOOP;
17461 }
17462
17463 SDValue X86TargetLowering::LowerGC_TRANSITION_END(SDValue Op,
17464                                                   SelectionDAG &DAG) const {
17465   // TODO: Eventually, the lowering of these nodes should be informed by or
17466   // deferred to the GC strategy for the function in which they appear. For
17467   // now, however, they must be lowered to something. Since they are logically
17468   // no-ops in the case of a null GC strategy (or a GC strategy which does not
17469   // require special handling for these nodes), lower them as literal NOOPs for
17470   // the time being.
17471   SmallVector<SDValue, 2> Ops;
17472
17473   Ops.push_back(Op.getOperand(0));
17474   if (Op->getGluedNode())
17475     Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
17476
17477   SDLoc OpDL(Op);
17478   SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
17479   SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
17480
17481   return NOOP;
17482 }
17483
17484 /// LowerOperation - Provide custom lowering hooks for some operations.
17485 ///
17486 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
17487   switch (Op.getOpcode()) {
17488   default: llvm_unreachable("Should not custom lower this!");
17489   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
17490   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
17491     return LowerCMP_SWAP(Op, Subtarget, DAG);
17492   case ISD::CTPOP:              return LowerCTPOP(Op, Subtarget, DAG);
17493   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
17494   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
17495   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
17496   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, Subtarget, DAG);
17497   case ISD::VECTOR_SHUFFLE:     return lowerVectorShuffle(Op, Subtarget, DAG);
17498   case ISD::VSELECT:            return LowerVSELECT(Op, DAG);
17499   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
17500   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
17501   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
17502   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
17503   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
17504   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
17505   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
17506   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
17507   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
17508   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
17509   case ISD::SHL_PARTS:
17510   case ISD::SRA_PARTS:
17511   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
17512   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
17513   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
17514   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
17515   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, Subtarget, DAG);
17516   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, Subtarget, DAG);
17517   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, Subtarget, DAG);
17518   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
17519   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
17520   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
17521   case ISD::LOAD:               return LowerExtendedLoad(Op, Subtarget, DAG);
17522   case ISD::FABS:
17523   case ISD::FNEG:               return LowerFABSorFNEG(Op, DAG);
17524   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
17525   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
17526   case ISD::SETCC:              return LowerSETCC(Op, DAG);
17527   case ISD::SELECT:             return LowerSELECT(Op, DAG);
17528   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
17529   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
17530   case ISD::VASTART:            return LowerVASTART(Op, DAG);
17531   case ISD::VAARG:              return LowerVAARG(Op, DAG);
17532   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
17533   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, Subtarget, DAG);
17534   case ISD::INTRINSIC_VOID:
17535   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
17536   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
17537   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
17538   case ISD::FRAME_TO_ARGS_OFFSET:
17539                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
17540   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
17541   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
17542   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
17543   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
17544   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
17545   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
17546   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
17547   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
17548   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
17549   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
17550   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
17551   case ISD::UMUL_LOHI:
17552   case ISD::SMUL_LOHI:          return LowerMUL_LOHI(Op, Subtarget, DAG);
17553   case ISD::SRA:
17554   case ISD::SRL:
17555   case ISD::SHL:                return LowerShift(Op, Subtarget, DAG);
17556   case ISD::SADDO:
17557   case ISD::UADDO:
17558   case ISD::SSUBO:
17559   case ISD::USUBO:
17560   case ISD::SMULO:
17561   case ISD::UMULO:              return LowerXALUO(Op, DAG);
17562   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
17563   case ISD::BITCAST:            return LowerBITCAST(Op, Subtarget, DAG);
17564   case ISD::ADDC:
17565   case ISD::ADDE:
17566   case ISD::SUBC:
17567   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
17568   case ISD::ADD:                return LowerADD(Op, DAG);
17569   case ISD::SUB:                return LowerSUB(Op, DAG);
17570   case ISD::FSINCOS:            return LowerFSINCOS(Op, Subtarget, DAG);
17571   case ISD::MGATHER:            return LowerMGATHER(Op, Subtarget, DAG);
17572   case ISD::MSCATTER:           return LowerMSCATTER(Op, Subtarget, DAG);
17573   case ISD::GC_TRANSITION_START:
17574                                 return LowerGC_TRANSITION_START(Op, DAG);
17575   case ISD::GC_TRANSITION_END:  return LowerGC_TRANSITION_END(Op, DAG);
17576   }
17577 }
17578
17579 /// ReplaceNodeResults - Replace a node with an illegal result type
17580 /// with a new node built out of custom code.
17581 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
17582                                            SmallVectorImpl<SDValue>&Results,
17583                                            SelectionDAG &DAG) const {
17584   SDLoc dl(N);
17585   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17586   switch (N->getOpcode()) {
17587   default:
17588     llvm_unreachable("Do not know how to custom type legalize this operation!");
17589   // We might have generated v2f32 FMIN/FMAX operations. Widen them to v4f32.
17590   case X86ISD::FMINC:
17591   case X86ISD::FMIN:
17592   case X86ISD::FMAXC:
17593   case X86ISD::FMAX: {
17594     EVT VT = N->getValueType(0);
17595     if (VT != MVT::v2f32)
17596       llvm_unreachable("Unexpected type (!= v2f32) on FMIN/FMAX.");
17597     SDValue UNDEF = DAG.getUNDEF(VT);
17598     SDValue LHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
17599                               N->getOperand(0), UNDEF);
17600     SDValue RHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
17601                               N->getOperand(1), UNDEF);
17602     Results.push_back(DAG.getNode(N->getOpcode(), dl, MVT::v4f32, LHS, RHS));
17603     return;
17604   }
17605   case ISD::SIGN_EXTEND_INREG:
17606   case ISD::ADDC:
17607   case ISD::ADDE:
17608   case ISD::SUBC:
17609   case ISD::SUBE:
17610     // We don't want to expand or promote these.
17611     return;
17612   case ISD::SDIV:
17613   case ISD::UDIV:
17614   case ISD::SREM:
17615   case ISD::UREM:
17616   case ISD::SDIVREM:
17617   case ISD::UDIVREM: {
17618     SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
17619     Results.push_back(V);
17620     return;
17621   }
17622   case ISD::FP_TO_SINT:
17623     // FP_TO_INT*_IN_MEM is not legal for f16 inputs.  Do not convert
17624     // (FP_TO_SINT (load f16)) to FP_TO_INT*.
17625     if (N->getOperand(0).getValueType() == MVT::f16)
17626       break;
17627     // fallthrough
17628   case ISD::FP_TO_UINT: {
17629     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
17630
17631     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
17632       return;
17633
17634     std::pair<SDValue,SDValue> Vals =
17635         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
17636     SDValue FIST = Vals.first, StackSlot = Vals.second;
17637     if (FIST.getNode()) {
17638       EVT VT = N->getValueType(0);
17639       // Return a load from the stack slot.
17640       if (StackSlot.getNode())
17641         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
17642                                       MachinePointerInfo(),
17643                                       false, false, false, 0));
17644       else
17645         Results.push_back(FIST);
17646     }
17647     return;
17648   }
17649   case ISD::UINT_TO_FP: {
17650     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
17651     if (N->getOperand(0).getValueType() != MVT::v2i32 ||
17652         N->getValueType(0) != MVT::v2f32)
17653       return;
17654     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
17655                                  N->getOperand(0));
17656     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
17657                                      MVT::f64);
17658     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
17659     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
17660                              DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
17661     Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
17662     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
17663     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
17664     return;
17665   }
17666   case ISD::FP_ROUND: {
17667     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
17668         return;
17669     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
17670     Results.push_back(V);
17671     return;
17672   }
17673   case ISD::FP_EXTEND: {
17674     // Right now, only MVT::v2f32 has OperationAction for FP_EXTEND.
17675     // No other ValueType for FP_EXTEND should reach this point.
17676     assert(N->getValueType(0) == MVT::v2f32 &&
17677            "Do not know how to legalize this Node");
17678     return;
17679   }
17680   case ISD::INTRINSIC_W_CHAIN: {
17681     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
17682     switch (IntNo) {
17683     default : llvm_unreachable("Do not know how to custom type "
17684                                "legalize this intrinsic operation!");
17685     case Intrinsic::x86_rdtsc:
17686       return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
17687                                      Results);
17688     case Intrinsic::x86_rdtscp:
17689       return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
17690                                      Results);
17691     case Intrinsic::x86_rdpmc:
17692       return getReadPerformanceCounter(N, dl, DAG, Subtarget, Results);
17693     }
17694   }
17695   case ISD::READCYCLECOUNTER: {
17696     return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
17697                                    Results);
17698   }
17699   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
17700     EVT T = N->getValueType(0);
17701     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
17702     bool Regs64bit = T == MVT::i128;
17703     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
17704     SDValue cpInL, cpInH;
17705     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
17706                         DAG.getConstant(0, dl, HalfT));
17707     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
17708                         DAG.getConstant(1, dl, HalfT));
17709     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
17710                              Regs64bit ? X86::RAX : X86::EAX,
17711                              cpInL, SDValue());
17712     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
17713                              Regs64bit ? X86::RDX : X86::EDX,
17714                              cpInH, cpInL.getValue(1));
17715     SDValue swapInL, swapInH;
17716     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
17717                           DAG.getConstant(0, dl, HalfT));
17718     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
17719                           DAG.getConstant(1, dl, HalfT));
17720     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
17721                                Regs64bit ? X86::RBX : X86::EBX,
17722                                swapInL, cpInH.getValue(1));
17723     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
17724                                Regs64bit ? X86::RCX : X86::ECX,
17725                                swapInH, swapInL.getValue(1));
17726     SDValue Ops[] = { swapInH.getValue(0),
17727                       N->getOperand(1),
17728                       swapInH.getValue(1) };
17729     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
17730     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
17731     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
17732                                   X86ISD::LCMPXCHG8_DAG;
17733     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
17734     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
17735                                         Regs64bit ? X86::RAX : X86::EAX,
17736                                         HalfT, Result.getValue(1));
17737     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
17738                                         Regs64bit ? X86::RDX : X86::EDX,
17739                                         HalfT, cpOutL.getValue(2));
17740     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
17741
17742     SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
17743                                         MVT::i32, cpOutH.getValue(2));
17744     SDValue Success =
17745         DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
17746                     DAG.getConstant(X86::COND_E, dl, MVT::i8), EFLAGS);
17747     Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
17748
17749     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
17750     Results.push_back(Success);
17751     Results.push_back(EFLAGS.getValue(1));
17752     return;
17753   }
17754   case ISD::ATOMIC_SWAP:
17755   case ISD::ATOMIC_LOAD_ADD:
17756   case ISD::ATOMIC_LOAD_SUB:
17757   case ISD::ATOMIC_LOAD_AND:
17758   case ISD::ATOMIC_LOAD_OR:
17759   case ISD::ATOMIC_LOAD_XOR:
17760   case ISD::ATOMIC_LOAD_NAND:
17761   case ISD::ATOMIC_LOAD_MIN:
17762   case ISD::ATOMIC_LOAD_MAX:
17763   case ISD::ATOMIC_LOAD_UMIN:
17764   case ISD::ATOMIC_LOAD_UMAX:
17765   case ISD::ATOMIC_LOAD: {
17766     // Delegate to generic TypeLegalization. Situations we can really handle
17767     // should have already been dealt with by AtomicExpandPass.cpp.
17768     break;
17769   }
17770   case ISD::BITCAST: {
17771     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
17772     EVT DstVT = N->getValueType(0);
17773     EVT SrcVT = N->getOperand(0)->getValueType(0);
17774
17775     if (SrcVT != MVT::f64 ||
17776         (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
17777       return;
17778
17779     unsigned NumElts = DstVT.getVectorNumElements();
17780     EVT SVT = DstVT.getVectorElementType();
17781     EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
17782     SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
17783                                    MVT::v2f64, N->getOperand(0));
17784     SDValue ToVecInt = DAG.getNode(ISD::BITCAST, dl, WiderVT, Expanded);
17785
17786     if (ExperimentalVectorWideningLegalization) {
17787       // If we are legalizing vectors by widening, we already have the desired
17788       // legal vector type, just return it.
17789       Results.push_back(ToVecInt);
17790       return;
17791     }
17792
17793     SmallVector<SDValue, 8> Elts;
17794     for (unsigned i = 0, e = NumElts; i != e; ++i)
17795       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
17796                                    ToVecInt, DAG.getIntPtrConstant(i, dl)));
17797
17798     Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
17799   }
17800   }
17801 }
17802
17803 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
17804   switch ((X86ISD::NodeType)Opcode) {
17805   case X86ISD::FIRST_NUMBER:       break;
17806   case X86ISD::BSF:                return "X86ISD::BSF";
17807   case X86ISD::BSR:                return "X86ISD::BSR";
17808   case X86ISD::SHLD:               return "X86ISD::SHLD";
17809   case X86ISD::SHRD:               return "X86ISD::SHRD";
17810   case X86ISD::FAND:               return "X86ISD::FAND";
17811   case X86ISD::FANDN:              return "X86ISD::FANDN";
17812   case X86ISD::FOR:                return "X86ISD::FOR";
17813   case X86ISD::FXOR:               return "X86ISD::FXOR";
17814   case X86ISD::FSRL:               return "X86ISD::FSRL";
17815   case X86ISD::FILD:               return "X86ISD::FILD";
17816   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
17817   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
17818   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
17819   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
17820   case X86ISD::FLD:                return "X86ISD::FLD";
17821   case X86ISD::FST:                return "X86ISD::FST";
17822   case X86ISD::CALL:               return "X86ISD::CALL";
17823   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
17824   case X86ISD::RDTSCP_DAG:         return "X86ISD::RDTSCP_DAG";
17825   case X86ISD::RDPMC_DAG:          return "X86ISD::RDPMC_DAG";
17826   case X86ISD::BT:                 return "X86ISD::BT";
17827   case X86ISD::CMP:                return "X86ISD::CMP";
17828   case X86ISD::COMI:               return "X86ISD::COMI";
17829   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
17830   case X86ISD::CMPM:               return "X86ISD::CMPM";
17831   case X86ISD::CMPMU:              return "X86ISD::CMPMU";
17832   case X86ISD::CMPM_RND:           return "X86ISD::CMPM_RND";
17833   case X86ISD::SETCC:              return "X86ISD::SETCC";
17834   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
17835   case X86ISD::FSETCC:             return "X86ISD::FSETCC";
17836   case X86ISD::FGETSIGNx86:        return "X86ISD::FGETSIGNx86";
17837   case X86ISD::CMOV:               return "X86ISD::CMOV";
17838   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
17839   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
17840   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
17841   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
17842   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
17843   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
17844   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
17845   case X86ISD::MOVDQ2Q:            return "X86ISD::MOVDQ2Q";
17846   case X86ISD::MMX_MOVD2W:         return "X86ISD::MMX_MOVD2W";
17847   case X86ISD::MMX_MOVW2D:         return "X86ISD::MMX_MOVW2D";
17848   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
17849   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
17850   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
17851   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
17852   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
17853   case X86ISD::MMX_PINSRW:         return "X86ISD::MMX_PINSRW";
17854   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
17855   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
17856   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
17857   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
17858   case X86ISD::SHRUNKBLEND:        return "X86ISD::SHRUNKBLEND";
17859   case X86ISD::ADDUS:              return "X86ISD::ADDUS";
17860   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
17861   case X86ISD::HADD:               return "X86ISD::HADD";
17862   case X86ISD::HSUB:               return "X86ISD::HSUB";
17863   case X86ISD::FHADD:              return "X86ISD::FHADD";
17864   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
17865   case X86ISD::UMAX:               return "X86ISD::UMAX";
17866   case X86ISD::UMIN:               return "X86ISD::UMIN";
17867   case X86ISD::SMAX:               return "X86ISD::SMAX";
17868   case X86ISD::SMIN:               return "X86ISD::SMIN";
17869   case X86ISD::FMAX:               return "X86ISD::FMAX";
17870   case X86ISD::FMAX_RND:           return "X86ISD::FMAX_RND";
17871   case X86ISD::FMIN:               return "X86ISD::FMIN";
17872   case X86ISD::FMIN_RND:           return "X86ISD::FMIN_RND";
17873   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
17874   case X86ISD::FMINC:              return "X86ISD::FMINC";
17875   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
17876   case X86ISD::FRCP:               return "X86ISD::FRCP";
17877   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
17878   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
17879   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
17880   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
17881   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
17882   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
17883   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
17884   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
17885   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
17886   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
17887   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
17888   case X86ISD::LCMPXCHG16_DAG:     return "X86ISD::LCMPXCHG16_DAG";
17889   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
17890   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
17891   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
17892   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
17893   case X86ISD::VTRUNC:             return "X86ISD::VTRUNC";
17894   case X86ISD::VTRUNCM:            return "X86ISD::VTRUNCM";
17895   case X86ISD::VINSERT:            return "X86ISD::VINSERT";
17896   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
17897   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
17898   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
17899   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
17900   case X86ISD::VSHL:               return "X86ISD::VSHL";
17901   case X86ISD::VSRL:               return "X86ISD::VSRL";
17902   case X86ISD::VSRA:               return "X86ISD::VSRA";
17903   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
17904   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
17905   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
17906   case X86ISD::CMPP:               return "X86ISD::CMPP";
17907   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
17908   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
17909   case X86ISD::PCMPEQM:            return "X86ISD::PCMPEQM";
17910   case X86ISD::PCMPGTM:            return "X86ISD::PCMPGTM";
17911   case X86ISD::ADD:                return "X86ISD::ADD";
17912   case X86ISD::SUB:                return "X86ISD::SUB";
17913   case X86ISD::ADC:                return "X86ISD::ADC";
17914   case X86ISD::SBB:                return "X86ISD::SBB";
17915   case X86ISD::SMUL:               return "X86ISD::SMUL";
17916   case X86ISD::UMUL:               return "X86ISD::UMUL";
17917   case X86ISD::SMUL8:              return "X86ISD::SMUL8";
17918   case X86ISD::UMUL8:              return "X86ISD::UMUL8";
17919   case X86ISD::SDIVREM8_SEXT_HREG: return "X86ISD::SDIVREM8_SEXT_HREG";
17920   case X86ISD::UDIVREM8_ZEXT_HREG: return "X86ISD::UDIVREM8_ZEXT_HREG";
17921   case X86ISD::INC:                return "X86ISD::INC";
17922   case X86ISD::DEC:                return "X86ISD::DEC";
17923   case X86ISD::OR:                 return "X86ISD::OR";
17924   case X86ISD::XOR:                return "X86ISD::XOR";
17925   case X86ISD::AND:                return "X86ISD::AND";
17926   case X86ISD::BEXTR:              return "X86ISD::BEXTR";
17927   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
17928   case X86ISD::PTEST:              return "X86ISD::PTEST";
17929   case X86ISD::TESTP:              return "X86ISD::TESTP";
17930   case X86ISD::TESTM:              return "X86ISD::TESTM";
17931   case X86ISD::TESTNM:             return "X86ISD::TESTNM";
17932   case X86ISD::KORTEST:            return "X86ISD::KORTEST";
17933   case X86ISD::PACKSS:             return "X86ISD::PACKSS";
17934   case X86ISD::PACKUS:             return "X86ISD::PACKUS";
17935   case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
17936   case X86ISD::VALIGN:             return "X86ISD::VALIGN";
17937   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
17938   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
17939   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
17940   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
17941   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
17942   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
17943   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
17944   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
17945   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
17946   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
17947   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
17948   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
17949   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
17950   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
17951   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
17952   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
17953   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
17954   case X86ISD::VEXTRACT:           return "X86ISD::VEXTRACT";
17955   case X86ISD::VPERMILPV:          return "X86ISD::VPERMILPV";
17956   case X86ISD::VPERMILPI:          return "X86ISD::VPERMILPI";
17957   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
17958   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
17959   case X86ISD::VPERMV3:            return "X86ISD::VPERMV3";
17960   case X86ISD::VPERMIV3:           return "X86ISD::VPERMIV3";
17961   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
17962   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
17963   case X86ISD::PMULDQ:             return "X86ISD::PMULDQ";
17964   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
17965   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
17966   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
17967   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
17968   case X86ISD::MFENCE:             return "X86ISD::MFENCE";
17969   case X86ISD::SFENCE:             return "X86ISD::SFENCE";
17970   case X86ISD::LFENCE:             return "X86ISD::LFENCE";
17971   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
17972   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
17973   case X86ISD::SAHF:               return "X86ISD::SAHF";
17974   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
17975   case X86ISD::RDSEED:             return "X86ISD::RDSEED";
17976   case X86ISD::FMADD:              return "X86ISD::FMADD";
17977   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
17978   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
17979   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
17980   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
17981   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
17982   case X86ISD::FMADD_RND:          return "X86ISD::FMADD_RND";
17983   case X86ISD::FNMADD_RND:         return "X86ISD::FNMADD_RND";
17984   case X86ISD::FMSUB_RND:          return "X86ISD::FMSUB_RND";
17985   case X86ISD::FNMSUB_RND:         return "X86ISD::FNMSUB_RND";
17986   case X86ISD::FMADDSUB_RND:       return "X86ISD::FMADDSUB_RND";
17987   case X86ISD::FMSUBADD_RND:       return "X86ISD::FMSUBADD_RND";
17988   case X86ISD::RNDSCALE:           return "X86ISD::RNDSCALE";
17989   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
17990   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
17991   case X86ISD::XTEST:              return "X86ISD::XTEST";
17992   case X86ISD::COMPRESS:           return "X86ISD::COMPRESS";
17993   case X86ISD::EXPAND:             return "X86ISD::EXPAND";
17994   case X86ISD::SELECT:             return "X86ISD::SELECT";
17995   case X86ISD::ADDSUB:             return "X86ISD::ADDSUB";
17996   case X86ISD::RCP28:              return "X86ISD::RCP28";
17997   case X86ISD::EXP2:               return "X86ISD::EXP2";
17998   case X86ISD::RSQRT28:            return "X86ISD::RSQRT28";
17999   case X86ISD::FADD_RND:           return "X86ISD::FADD_RND";
18000   case X86ISD::FSUB_RND:           return "X86ISD::FSUB_RND";
18001   case X86ISD::FMUL_RND:           return "X86ISD::FMUL_RND";
18002   case X86ISD::FDIV_RND:           return "X86ISD::FDIV_RND";
18003   case X86ISD::ADDS:               return "X86ISD::ADDS";
18004   case X86ISD::SUBS:               return "X86ISD::SUBS";
18005   }
18006   return nullptr;
18007 }
18008
18009 // isLegalAddressingMode - Return true if the addressing mode represented
18010 // by AM is legal for this target, for a load/store of the specified type.
18011 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
18012                                               Type *Ty) const {
18013   // X86 supports extremely general addressing modes.
18014   CodeModel::Model M = getTargetMachine().getCodeModel();
18015   Reloc::Model R = getTargetMachine().getRelocationModel();
18016
18017   // X86 allows a sign-extended 32-bit immediate field as a displacement.
18018   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
18019     return false;
18020
18021   if (AM.BaseGV) {
18022     unsigned GVFlags =
18023       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
18024
18025     // If a reference to this global requires an extra load, we can't fold it.
18026     if (isGlobalStubReference(GVFlags))
18027       return false;
18028
18029     // If BaseGV requires a register for the PIC base, we cannot also have a
18030     // BaseReg specified.
18031     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
18032       return false;
18033
18034     // If lower 4G is not available, then we must use rip-relative addressing.
18035     if ((M != CodeModel::Small || R != Reloc::Static) &&
18036         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
18037       return false;
18038   }
18039
18040   switch (AM.Scale) {
18041   case 0:
18042   case 1:
18043   case 2:
18044   case 4:
18045   case 8:
18046     // These scales always work.
18047     break;
18048   case 3:
18049   case 5:
18050   case 9:
18051     // These scales are formed with basereg+scalereg.  Only accept if there is
18052     // no basereg yet.
18053     if (AM.HasBaseReg)
18054       return false;
18055     break;
18056   default:  // Other stuff never works.
18057     return false;
18058   }
18059
18060   return true;
18061 }
18062
18063 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
18064   unsigned Bits = Ty->getScalarSizeInBits();
18065
18066   // 8-bit shifts are always expensive, but versions with a scalar amount aren't
18067   // particularly cheaper than those without.
18068   if (Bits == 8)
18069     return false;
18070
18071   // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
18072   // variable shifts just as cheap as scalar ones.
18073   if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
18074     return false;
18075
18076   // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
18077   // fully general vector.
18078   return true;
18079 }
18080
18081 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
18082   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
18083     return false;
18084   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
18085   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
18086   return NumBits1 > NumBits2;
18087 }
18088
18089 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
18090   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
18091     return false;
18092
18093   if (!isTypeLegal(EVT::getEVT(Ty1)))
18094     return false;
18095
18096   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
18097
18098   // Assuming the caller doesn't have a zeroext or signext return parameter,
18099   // truncation all the way down to i1 is valid.
18100   return true;
18101 }
18102
18103 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
18104   return isInt<32>(Imm);
18105 }
18106
18107 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
18108   // Can also use sub to handle negated immediates.
18109   return isInt<32>(Imm);
18110 }
18111
18112 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
18113   if (!VT1.isInteger() || !VT2.isInteger())
18114     return false;
18115   unsigned NumBits1 = VT1.getSizeInBits();
18116   unsigned NumBits2 = VT2.getSizeInBits();
18117   return NumBits1 > NumBits2;
18118 }
18119
18120 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
18121   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
18122   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
18123 }
18124
18125 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
18126   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
18127   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
18128 }
18129
18130 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
18131   EVT VT1 = Val.getValueType();
18132   if (isZExtFree(VT1, VT2))
18133     return true;
18134
18135   if (Val.getOpcode() != ISD::LOAD)
18136     return false;
18137
18138   if (!VT1.isSimple() || !VT1.isInteger() ||
18139       !VT2.isSimple() || !VT2.isInteger())
18140     return false;
18141
18142   switch (VT1.getSimpleVT().SimpleTy) {
18143   default: break;
18144   case MVT::i8:
18145   case MVT::i16:
18146   case MVT::i32:
18147     // X86 has 8, 16, and 32-bit zero-extending loads.
18148     return true;
18149   }
18150
18151   return false;
18152 }
18153
18154 bool X86TargetLowering::isVectorLoadExtDesirable(SDValue) const { return true; }
18155
18156 bool
18157 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
18158   if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
18159     return false;
18160
18161   VT = VT.getScalarType();
18162
18163   if (!VT.isSimple())
18164     return false;
18165
18166   switch (VT.getSimpleVT().SimpleTy) {
18167   case MVT::f32:
18168   case MVT::f64:
18169     return true;
18170   default:
18171     break;
18172   }
18173
18174   return false;
18175 }
18176
18177 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
18178   // i16 instructions are longer (0x66 prefix) and potentially slower.
18179   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
18180 }
18181
18182 /// isShuffleMaskLegal - Targets can use this to indicate that they only
18183 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
18184 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
18185 /// are assumed to be legal.
18186 bool
18187 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
18188                                       EVT VT) const {
18189   if (!VT.isSimple())
18190     return false;
18191
18192   // Not for i1 vectors
18193   if (VT.getScalarType() == MVT::i1)
18194     return false;
18195
18196   // Very little shuffling can be done for 64-bit vectors right now.
18197   if (VT.getSizeInBits() == 64)
18198     return false;
18199
18200   // We only care that the types being shuffled are legal. The lowering can
18201   // handle any possible shuffle mask that results.
18202   return isTypeLegal(VT.getSimpleVT());
18203 }
18204
18205 bool
18206 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
18207                                           EVT VT) const {
18208   // Just delegate to the generic legality, clear masks aren't special.
18209   return isShuffleMaskLegal(Mask, VT);
18210 }
18211
18212 //===----------------------------------------------------------------------===//
18213 //                           X86 Scheduler Hooks
18214 //===----------------------------------------------------------------------===//
18215
18216 /// Utility function to emit xbegin specifying the start of an RTM region.
18217 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
18218                                      const TargetInstrInfo *TII) {
18219   DebugLoc DL = MI->getDebugLoc();
18220
18221   const BasicBlock *BB = MBB->getBasicBlock();
18222   MachineFunction::iterator I = MBB;
18223   ++I;
18224
18225   // For the v = xbegin(), we generate
18226   //
18227   // thisMBB:
18228   //  xbegin sinkMBB
18229   //
18230   // mainMBB:
18231   //  eax = -1
18232   //
18233   // sinkMBB:
18234   //  v = eax
18235
18236   MachineBasicBlock *thisMBB = MBB;
18237   MachineFunction *MF = MBB->getParent();
18238   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
18239   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
18240   MF->insert(I, mainMBB);
18241   MF->insert(I, sinkMBB);
18242
18243   // Transfer the remainder of BB and its successor edges to sinkMBB.
18244   sinkMBB->splice(sinkMBB->begin(), MBB,
18245                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
18246   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
18247
18248   // thisMBB:
18249   //  xbegin sinkMBB
18250   //  # fallthrough to mainMBB
18251   //  # abortion to sinkMBB
18252   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
18253   thisMBB->addSuccessor(mainMBB);
18254   thisMBB->addSuccessor(sinkMBB);
18255
18256   // mainMBB:
18257   //  EAX = -1
18258   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
18259   mainMBB->addSuccessor(sinkMBB);
18260
18261   // sinkMBB:
18262   // EAX is live into the sinkMBB
18263   sinkMBB->addLiveIn(X86::EAX);
18264   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
18265           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
18266     .addReg(X86::EAX);
18267
18268   MI->eraseFromParent();
18269   return sinkMBB;
18270 }
18271
18272 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
18273 // or XMM0_V32I8 in AVX all of this code can be replaced with that
18274 // in the .td file.
18275 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
18276                                        const TargetInstrInfo *TII) {
18277   unsigned Opc;
18278   switch (MI->getOpcode()) {
18279   default: llvm_unreachable("illegal opcode!");
18280   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
18281   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
18282   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
18283   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
18284   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
18285   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
18286   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
18287   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
18288   }
18289
18290   DebugLoc dl = MI->getDebugLoc();
18291   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
18292
18293   unsigned NumArgs = MI->getNumOperands();
18294   for (unsigned i = 1; i < NumArgs; ++i) {
18295     MachineOperand &Op = MI->getOperand(i);
18296     if (!(Op.isReg() && Op.isImplicit()))
18297       MIB.addOperand(Op);
18298   }
18299   if (MI->hasOneMemOperand())
18300     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
18301
18302   BuildMI(*BB, MI, dl,
18303     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
18304     .addReg(X86::XMM0);
18305
18306   MI->eraseFromParent();
18307   return BB;
18308 }
18309
18310 // FIXME: Custom handling because TableGen doesn't support multiple implicit
18311 // defs in an instruction pattern
18312 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
18313                                        const TargetInstrInfo *TII) {
18314   unsigned Opc;
18315   switch (MI->getOpcode()) {
18316   default: llvm_unreachable("illegal opcode!");
18317   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
18318   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
18319   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
18320   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
18321   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
18322   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
18323   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
18324   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
18325   }
18326
18327   DebugLoc dl = MI->getDebugLoc();
18328   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
18329
18330   unsigned NumArgs = MI->getNumOperands(); // remove the results
18331   for (unsigned i = 1; i < NumArgs; ++i) {
18332     MachineOperand &Op = MI->getOperand(i);
18333     if (!(Op.isReg() && Op.isImplicit()))
18334       MIB.addOperand(Op);
18335   }
18336   if (MI->hasOneMemOperand())
18337     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
18338
18339   BuildMI(*BB, MI, dl,
18340     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
18341     .addReg(X86::ECX);
18342
18343   MI->eraseFromParent();
18344   return BB;
18345 }
18346
18347 static MachineBasicBlock *EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
18348                                       const X86Subtarget *Subtarget) {
18349   DebugLoc dl = MI->getDebugLoc();
18350   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18351   // Address into RAX/EAX, other two args into ECX, EDX.
18352   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
18353   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
18354   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
18355   for (int i = 0; i < X86::AddrNumOperands; ++i)
18356     MIB.addOperand(MI->getOperand(i));
18357
18358   unsigned ValOps = X86::AddrNumOperands;
18359   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
18360     .addReg(MI->getOperand(ValOps).getReg());
18361   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
18362     .addReg(MI->getOperand(ValOps+1).getReg());
18363
18364   // The instruction doesn't actually take any operands though.
18365   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
18366
18367   MI->eraseFromParent(); // The pseudo is gone now.
18368   return BB;
18369 }
18370
18371 MachineBasicBlock *
18372 X86TargetLowering::EmitVAARG64WithCustomInserter(MachineInstr *MI,
18373                                                  MachineBasicBlock *MBB) const {
18374   // Emit va_arg instruction on X86-64.
18375
18376   // Operands to this pseudo-instruction:
18377   // 0  ) Output        : destination address (reg)
18378   // 1-5) Input         : va_list address (addr, i64mem)
18379   // 6  ) ArgSize       : Size (in bytes) of vararg type
18380   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
18381   // 8  ) Align         : Alignment of type
18382   // 9  ) EFLAGS (implicit-def)
18383
18384   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
18385   static_assert(X86::AddrNumOperands == 5,
18386                 "VAARG_64 assumes 5 address operands");
18387
18388   unsigned DestReg = MI->getOperand(0).getReg();
18389   MachineOperand &Base = MI->getOperand(1);
18390   MachineOperand &Scale = MI->getOperand(2);
18391   MachineOperand &Index = MI->getOperand(3);
18392   MachineOperand &Disp = MI->getOperand(4);
18393   MachineOperand &Segment = MI->getOperand(5);
18394   unsigned ArgSize = MI->getOperand(6).getImm();
18395   unsigned ArgMode = MI->getOperand(7).getImm();
18396   unsigned Align = MI->getOperand(8).getImm();
18397
18398   // Memory Reference
18399   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
18400   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
18401   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
18402
18403   // Machine Information
18404   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18405   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
18406   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
18407   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
18408   DebugLoc DL = MI->getDebugLoc();
18409
18410   // struct va_list {
18411   //   i32   gp_offset
18412   //   i32   fp_offset
18413   //   i64   overflow_area (address)
18414   //   i64   reg_save_area (address)
18415   // }
18416   // sizeof(va_list) = 24
18417   // alignment(va_list) = 8
18418
18419   unsigned TotalNumIntRegs = 6;
18420   unsigned TotalNumXMMRegs = 8;
18421   bool UseGPOffset = (ArgMode == 1);
18422   bool UseFPOffset = (ArgMode == 2);
18423   unsigned MaxOffset = TotalNumIntRegs * 8 +
18424                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
18425
18426   /* Align ArgSize to a multiple of 8 */
18427   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
18428   bool NeedsAlign = (Align > 8);
18429
18430   MachineBasicBlock *thisMBB = MBB;
18431   MachineBasicBlock *overflowMBB;
18432   MachineBasicBlock *offsetMBB;
18433   MachineBasicBlock *endMBB;
18434
18435   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
18436   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
18437   unsigned OffsetReg = 0;
18438
18439   if (!UseGPOffset && !UseFPOffset) {
18440     // If we only pull from the overflow region, we don't create a branch.
18441     // We don't need to alter control flow.
18442     OffsetDestReg = 0; // unused
18443     OverflowDestReg = DestReg;
18444
18445     offsetMBB = nullptr;
18446     overflowMBB = thisMBB;
18447     endMBB = thisMBB;
18448   } else {
18449     // First emit code to check if gp_offset (or fp_offset) is below the bound.
18450     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
18451     // If not, pull from overflow_area. (branch to overflowMBB)
18452     //
18453     //       thisMBB
18454     //         |     .
18455     //         |        .
18456     //     offsetMBB   overflowMBB
18457     //         |        .
18458     //         |     .
18459     //        endMBB
18460
18461     // Registers for the PHI in endMBB
18462     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
18463     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
18464
18465     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
18466     MachineFunction *MF = MBB->getParent();
18467     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18468     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18469     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18470
18471     MachineFunction::iterator MBBIter = MBB;
18472     ++MBBIter;
18473
18474     // Insert the new basic blocks
18475     MF->insert(MBBIter, offsetMBB);
18476     MF->insert(MBBIter, overflowMBB);
18477     MF->insert(MBBIter, endMBB);
18478
18479     // Transfer the remainder of MBB and its successor edges to endMBB.
18480     endMBB->splice(endMBB->begin(), thisMBB,
18481                    std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
18482     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
18483
18484     // Make offsetMBB and overflowMBB successors of thisMBB
18485     thisMBB->addSuccessor(offsetMBB);
18486     thisMBB->addSuccessor(overflowMBB);
18487
18488     // endMBB is a successor of both offsetMBB and overflowMBB
18489     offsetMBB->addSuccessor(endMBB);
18490     overflowMBB->addSuccessor(endMBB);
18491
18492     // Load the offset value into a register
18493     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
18494     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
18495       .addOperand(Base)
18496       .addOperand(Scale)
18497       .addOperand(Index)
18498       .addDisp(Disp, UseFPOffset ? 4 : 0)
18499       .addOperand(Segment)
18500       .setMemRefs(MMOBegin, MMOEnd);
18501
18502     // Check if there is enough room left to pull this argument.
18503     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
18504       .addReg(OffsetReg)
18505       .addImm(MaxOffset + 8 - ArgSizeA8);
18506
18507     // Branch to "overflowMBB" if offset >= max
18508     // Fall through to "offsetMBB" otherwise
18509     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
18510       .addMBB(overflowMBB);
18511   }
18512
18513   // In offsetMBB, emit code to use the reg_save_area.
18514   if (offsetMBB) {
18515     assert(OffsetReg != 0);
18516
18517     // Read the reg_save_area address.
18518     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
18519     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
18520       .addOperand(Base)
18521       .addOperand(Scale)
18522       .addOperand(Index)
18523       .addDisp(Disp, 16)
18524       .addOperand(Segment)
18525       .setMemRefs(MMOBegin, MMOEnd);
18526
18527     // Zero-extend the offset
18528     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
18529       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
18530         .addImm(0)
18531         .addReg(OffsetReg)
18532         .addImm(X86::sub_32bit);
18533
18534     // Add the offset to the reg_save_area to get the final address.
18535     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
18536       .addReg(OffsetReg64)
18537       .addReg(RegSaveReg);
18538
18539     // Compute the offset for the next argument
18540     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
18541     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
18542       .addReg(OffsetReg)
18543       .addImm(UseFPOffset ? 16 : 8);
18544
18545     // Store it back into the va_list.
18546     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
18547       .addOperand(Base)
18548       .addOperand(Scale)
18549       .addOperand(Index)
18550       .addDisp(Disp, UseFPOffset ? 4 : 0)
18551       .addOperand(Segment)
18552       .addReg(NextOffsetReg)
18553       .setMemRefs(MMOBegin, MMOEnd);
18554
18555     // Jump to endMBB
18556     BuildMI(offsetMBB, DL, TII->get(X86::JMP_1))
18557       .addMBB(endMBB);
18558   }
18559
18560   //
18561   // Emit code to use overflow area
18562   //
18563
18564   // Load the overflow_area address into a register.
18565   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
18566   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
18567     .addOperand(Base)
18568     .addOperand(Scale)
18569     .addOperand(Index)
18570     .addDisp(Disp, 8)
18571     .addOperand(Segment)
18572     .setMemRefs(MMOBegin, MMOEnd);
18573
18574   // If we need to align it, do so. Otherwise, just copy the address
18575   // to OverflowDestReg.
18576   if (NeedsAlign) {
18577     // Align the overflow address
18578     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
18579     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
18580
18581     // aligned_addr = (addr + (align-1)) & ~(align-1)
18582     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
18583       .addReg(OverflowAddrReg)
18584       .addImm(Align-1);
18585
18586     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
18587       .addReg(TmpReg)
18588       .addImm(~(uint64_t)(Align-1));
18589   } else {
18590     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
18591       .addReg(OverflowAddrReg);
18592   }
18593
18594   // Compute the next overflow address after this argument.
18595   // (the overflow address should be kept 8-byte aligned)
18596   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
18597   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
18598     .addReg(OverflowDestReg)
18599     .addImm(ArgSizeA8);
18600
18601   // Store the new overflow address.
18602   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
18603     .addOperand(Base)
18604     .addOperand(Scale)
18605     .addOperand(Index)
18606     .addDisp(Disp, 8)
18607     .addOperand(Segment)
18608     .addReg(NextAddrReg)
18609     .setMemRefs(MMOBegin, MMOEnd);
18610
18611   // If we branched, emit the PHI to the front of endMBB.
18612   if (offsetMBB) {
18613     BuildMI(*endMBB, endMBB->begin(), DL,
18614             TII->get(X86::PHI), DestReg)
18615       .addReg(OffsetDestReg).addMBB(offsetMBB)
18616       .addReg(OverflowDestReg).addMBB(overflowMBB);
18617   }
18618
18619   // Erase the pseudo instruction
18620   MI->eraseFromParent();
18621
18622   return endMBB;
18623 }
18624
18625 MachineBasicBlock *
18626 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
18627                                                  MachineInstr *MI,
18628                                                  MachineBasicBlock *MBB) const {
18629   // Emit code to save XMM registers to the stack. The ABI says that the
18630   // number of registers to save is given in %al, so it's theoretically
18631   // possible to do an indirect jump trick to avoid saving all of them,
18632   // however this code takes a simpler approach and just executes all
18633   // of the stores if %al is non-zero. It's less code, and it's probably
18634   // easier on the hardware branch predictor, and stores aren't all that
18635   // expensive anyway.
18636
18637   // Create the new basic blocks. One block contains all the XMM stores,
18638   // and one block is the final destination regardless of whether any
18639   // stores were performed.
18640   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
18641   MachineFunction *F = MBB->getParent();
18642   MachineFunction::iterator MBBIter = MBB;
18643   ++MBBIter;
18644   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
18645   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
18646   F->insert(MBBIter, XMMSaveMBB);
18647   F->insert(MBBIter, EndMBB);
18648
18649   // Transfer the remainder of MBB and its successor edges to EndMBB.
18650   EndMBB->splice(EndMBB->begin(), MBB,
18651                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
18652   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
18653
18654   // The original block will now fall through to the XMM save block.
18655   MBB->addSuccessor(XMMSaveMBB);
18656   // The XMMSaveMBB will fall through to the end block.
18657   XMMSaveMBB->addSuccessor(EndMBB);
18658
18659   // Now add the instructions.
18660   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18661   DebugLoc DL = MI->getDebugLoc();
18662
18663   unsigned CountReg = MI->getOperand(0).getReg();
18664   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
18665   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
18666
18667   if (!Subtarget->isTargetWin64()) {
18668     // If %al is 0, branch around the XMM save block.
18669     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
18670     BuildMI(MBB, DL, TII->get(X86::JE_1)).addMBB(EndMBB);
18671     MBB->addSuccessor(EndMBB);
18672   }
18673
18674   // Make sure the last operand is EFLAGS, which gets clobbered by the branch
18675   // that was just emitted, but clearly shouldn't be "saved".
18676   assert((MI->getNumOperands() <= 3 ||
18677           !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
18678           MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
18679          && "Expected last argument to be EFLAGS");
18680   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
18681   // In the XMM save block, save all the XMM argument registers.
18682   for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
18683     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
18684     MachineMemOperand *MMO =
18685       F->getMachineMemOperand(
18686           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
18687         MachineMemOperand::MOStore,
18688         /*Size=*/16, /*Align=*/16);
18689     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
18690       .addFrameIndex(RegSaveFrameIndex)
18691       .addImm(/*Scale=*/1)
18692       .addReg(/*IndexReg=*/0)
18693       .addImm(/*Disp=*/Offset)
18694       .addReg(/*Segment=*/0)
18695       .addReg(MI->getOperand(i).getReg())
18696       .addMemOperand(MMO);
18697   }
18698
18699   MI->eraseFromParent();   // The pseudo instruction is gone now.
18700
18701   return EndMBB;
18702 }
18703
18704 // The EFLAGS operand of SelectItr might be missing a kill marker
18705 // because there were multiple uses of EFLAGS, and ISel didn't know
18706 // which to mark. Figure out whether SelectItr should have had a
18707 // kill marker, and set it if it should. Returns the correct kill
18708 // marker value.
18709 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
18710                                      MachineBasicBlock* BB,
18711                                      const TargetRegisterInfo* TRI) {
18712   // Scan forward through BB for a use/def of EFLAGS.
18713   MachineBasicBlock::iterator miI(std::next(SelectItr));
18714   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
18715     const MachineInstr& mi = *miI;
18716     if (mi.readsRegister(X86::EFLAGS))
18717       return false;
18718     if (mi.definesRegister(X86::EFLAGS))
18719       break; // Should have kill-flag - update below.
18720   }
18721
18722   // If we hit the end of the block, check whether EFLAGS is live into a
18723   // successor.
18724   if (miI == BB->end()) {
18725     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
18726                                           sEnd = BB->succ_end();
18727          sItr != sEnd; ++sItr) {
18728       MachineBasicBlock* succ = *sItr;
18729       if (succ->isLiveIn(X86::EFLAGS))
18730         return false;
18731     }
18732   }
18733
18734   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
18735   // out. SelectMI should have a kill flag on EFLAGS.
18736   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
18737   return true;
18738 }
18739
18740 MachineBasicBlock *
18741 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
18742                                      MachineBasicBlock *BB) const {
18743   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18744   DebugLoc DL = MI->getDebugLoc();
18745
18746   // To "insert" a SELECT_CC instruction, we actually have to insert the
18747   // diamond control-flow pattern.  The incoming instruction knows the
18748   // destination vreg to set, the condition code register to branch on, the
18749   // true/false values to select between, and a branch opcode to use.
18750   const BasicBlock *LLVM_BB = BB->getBasicBlock();
18751   MachineFunction::iterator It = BB;
18752   ++It;
18753
18754   //  thisMBB:
18755   //  ...
18756   //   TrueVal = ...
18757   //   cmpTY ccX, r1, r2
18758   //   bCC copy1MBB
18759   //   fallthrough --> copy0MBB
18760   MachineBasicBlock *thisMBB = BB;
18761   MachineFunction *F = BB->getParent();
18762
18763   // We also lower double CMOVs:
18764   //   (CMOV (CMOV F, T, cc1), T, cc2)
18765   // to two successives branches.  For that, we look for another CMOV as the
18766   // following instruction.
18767   //
18768   // Without this, we would add a PHI between the two jumps, which ends up
18769   // creating a few copies all around. For instance, for
18770   //
18771   //    (sitofp (zext (fcmp une)))
18772   //
18773   // we would generate:
18774   //
18775   //         ucomiss %xmm1, %xmm0
18776   //         movss  <1.0f>, %xmm0
18777   //         movaps  %xmm0, %xmm1
18778   //         jne     .LBB5_2
18779   //         xorps   %xmm1, %xmm1
18780   // .LBB5_2:
18781   //         jp      .LBB5_4
18782   //         movaps  %xmm1, %xmm0
18783   // .LBB5_4:
18784   //         retq
18785   //
18786   // because this custom-inserter would have generated:
18787   //
18788   //   A
18789   //   | \
18790   //   |  B
18791   //   | /
18792   //   C
18793   //   | \
18794   //   |  D
18795   //   | /
18796   //   E
18797   //
18798   // A: X = ...; Y = ...
18799   // B: empty
18800   // C: Z = PHI [X, A], [Y, B]
18801   // D: empty
18802   // E: PHI [X, C], [Z, D]
18803   //
18804   // If we lower both CMOVs in a single step, we can instead generate:
18805   //
18806   //   A
18807   //   | \
18808   //   |  C
18809   //   | /|
18810   //   |/ |
18811   //   |  |
18812   //   |  D
18813   //   | /
18814   //   E
18815   //
18816   // A: X = ...; Y = ...
18817   // D: empty
18818   // E: PHI [X, A], [X, C], [Y, D]
18819   //
18820   // Which, in our sitofp/fcmp example, gives us something like:
18821   //
18822   //         ucomiss %xmm1, %xmm0
18823   //         movss  <1.0f>, %xmm0
18824   //         jne     .LBB5_4
18825   //         jp      .LBB5_4
18826   //         xorps   %xmm0, %xmm0
18827   // .LBB5_4:
18828   //         retq
18829   //
18830   MachineInstr *NextCMOV = nullptr;
18831   MachineBasicBlock::iterator NextMIIt =
18832       std::next(MachineBasicBlock::iterator(MI));
18833   if (NextMIIt != BB->end() && NextMIIt->getOpcode() == MI->getOpcode() &&
18834       NextMIIt->getOperand(2).getReg() == MI->getOperand(2).getReg() &&
18835       NextMIIt->getOperand(1).getReg() == MI->getOperand(0).getReg())
18836     NextCMOV = &*NextMIIt;
18837
18838   MachineBasicBlock *jcc1MBB = nullptr;
18839
18840   // If we have a double CMOV, we lower it to two successive branches to
18841   // the same block.  EFLAGS is used by both, so mark it as live in the second.
18842   if (NextCMOV) {
18843     jcc1MBB = F->CreateMachineBasicBlock(LLVM_BB);
18844     F->insert(It, jcc1MBB);
18845     jcc1MBB->addLiveIn(X86::EFLAGS);
18846   }
18847
18848   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
18849   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
18850   F->insert(It, copy0MBB);
18851   F->insert(It, sinkMBB);
18852
18853   // If the EFLAGS register isn't dead in the terminator, then claim that it's
18854   // live into the sink and copy blocks.
18855   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
18856
18857   MachineInstr *LastEFLAGSUser = NextCMOV ? NextCMOV : MI;
18858   if (!LastEFLAGSUser->killsRegister(X86::EFLAGS) &&
18859       !checkAndUpdateEFLAGSKill(LastEFLAGSUser, BB, TRI)) {
18860     copy0MBB->addLiveIn(X86::EFLAGS);
18861     sinkMBB->addLiveIn(X86::EFLAGS);
18862   }
18863
18864   // Transfer the remainder of BB and its successor edges to sinkMBB.
18865   sinkMBB->splice(sinkMBB->begin(), BB,
18866                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
18867   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
18868
18869   // Add the true and fallthrough blocks as its successors.
18870   if (NextCMOV) {
18871     // The fallthrough block may be jcc1MBB, if we have a double CMOV.
18872     BB->addSuccessor(jcc1MBB);
18873
18874     // In that case, jcc1MBB will itself fallthrough the copy0MBB, and
18875     // jump to the sinkMBB.
18876     jcc1MBB->addSuccessor(copy0MBB);
18877     jcc1MBB->addSuccessor(sinkMBB);
18878   } else {
18879     BB->addSuccessor(copy0MBB);
18880   }
18881
18882   // The true block target of the first (or only) branch is always sinkMBB.
18883   BB->addSuccessor(sinkMBB);
18884
18885   // Create the conditional branch instruction.
18886   unsigned Opc =
18887     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
18888   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
18889
18890   if (NextCMOV) {
18891     unsigned Opc2 = X86::GetCondBranchFromCond(
18892         (X86::CondCode)NextCMOV->getOperand(3).getImm());
18893     BuildMI(jcc1MBB, DL, TII->get(Opc2)).addMBB(sinkMBB);
18894   }
18895
18896   //  copy0MBB:
18897   //   %FalseValue = ...
18898   //   # fallthrough to sinkMBB
18899   copy0MBB->addSuccessor(sinkMBB);
18900
18901   //  sinkMBB:
18902   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
18903   //  ...
18904   MachineInstrBuilder MIB =
18905       BuildMI(*sinkMBB, sinkMBB->begin(), DL, TII->get(X86::PHI),
18906               MI->getOperand(0).getReg())
18907           .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
18908           .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
18909
18910   // If we have a double CMOV, the second Jcc provides the same incoming
18911   // value as the first Jcc (the True operand of the SELECT_CC/CMOV nodes).
18912   if (NextCMOV) {
18913     MIB.addReg(MI->getOperand(2).getReg()).addMBB(jcc1MBB);
18914     // Copy the PHI result to the register defined by the second CMOV.
18915     BuildMI(*sinkMBB, std::next(MachineBasicBlock::iterator(MIB.getInstr())),
18916             DL, TII->get(TargetOpcode::COPY), NextCMOV->getOperand(0).getReg())
18917         .addReg(MI->getOperand(0).getReg());
18918     NextCMOV->eraseFromParent();
18919   }
18920
18921   MI->eraseFromParent();   // The pseudo instruction is gone now.
18922   return sinkMBB;
18923 }
18924
18925 MachineBasicBlock *
18926 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI,
18927                                         MachineBasicBlock *BB) const {
18928   MachineFunction *MF = BB->getParent();
18929   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18930   DebugLoc DL = MI->getDebugLoc();
18931   const BasicBlock *LLVM_BB = BB->getBasicBlock();
18932
18933   assert(MF->shouldSplitStack());
18934
18935   const bool Is64Bit = Subtarget->is64Bit();
18936   const bool IsLP64 = Subtarget->isTarget64BitLP64();
18937
18938   const unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
18939   const unsigned TlsOffset = IsLP64 ? 0x70 : Is64Bit ? 0x40 : 0x30;
18940
18941   // BB:
18942   //  ... [Till the alloca]
18943   // If stacklet is not large enough, jump to mallocMBB
18944   //
18945   // bumpMBB:
18946   //  Allocate by subtracting from RSP
18947   //  Jump to continueMBB
18948   //
18949   // mallocMBB:
18950   //  Allocate by call to runtime
18951   //
18952   // continueMBB:
18953   //  ...
18954   //  [rest of original BB]
18955   //
18956
18957   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18958   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18959   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18960
18961   MachineRegisterInfo &MRI = MF->getRegInfo();
18962   const TargetRegisterClass *AddrRegClass =
18963     getRegClassFor(getPointerTy());
18964
18965   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
18966     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
18967     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
18968     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
18969     sizeVReg = MI->getOperand(1).getReg(),
18970     physSPReg = IsLP64 || Subtarget->isTargetNaCl64() ? X86::RSP : X86::ESP;
18971
18972   MachineFunction::iterator MBBIter = BB;
18973   ++MBBIter;
18974
18975   MF->insert(MBBIter, bumpMBB);
18976   MF->insert(MBBIter, mallocMBB);
18977   MF->insert(MBBIter, continueMBB);
18978
18979   continueMBB->splice(continueMBB->begin(), BB,
18980                       std::next(MachineBasicBlock::iterator(MI)), BB->end());
18981   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
18982
18983   // Add code to the main basic block to check if the stack limit has been hit,
18984   // and if so, jump to mallocMBB otherwise to bumpMBB.
18985   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
18986   BuildMI(BB, DL, TII->get(IsLP64 ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
18987     .addReg(tmpSPVReg).addReg(sizeVReg);
18988   BuildMI(BB, DL, TII->get(IsLP64 ? X86::CMP64mr:X86::CMP32mr))
18989     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
18990     .addReg(SPLimitVReg);
18991   BuildMI(BB, DL, TII->get(X86::JG_1)).addMBB(mallocMBB);
18992
18993   // bumpMBB simply decreases the stack pointer, since we know the current
18994   // stacklet has enough space.
18995   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
18996     .addReg(SPLimitVReg);
18997   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
18998     .addReg(SPLimitVReg);
18999   BuildMI(bumpMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
19000
19001   // Calls into a routine in libgcc to allocate more space from the heap.
19002   const uint32_t *RegMask =
19003       Subtarget->getRegisterInfo()->getCallPreservedMask(*MF, CallingConv::C);
19004   if (IsLP64) {
19005     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
19006       .addReg(sizeVReg);
19007     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
19008       .addExternalSymbol("__morestack_allocate_stack_space")
19009       .addRegMask(RegMask)
19010       .addReg(X86::RDI, RegState::Implicit)
19011       .addReg(X86::RAX, RegState::ImplicitDefine);
19012   } else if (Is64Bit) {
19013     BuildMI(mallocMBB, DL, TII->get(X86::MOV32rr), X86::EDI)
19014       .addReg(sizeVReg);
19015     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
19016       .addExternalSymbol("__morestack_allocate_stack_space")
19017       .addRegMask(RegMask)
19018       .addReg(X86::EDI, RegState::Implicit)
19019       .addReg(X86::EAX, RegState::ImplicitDefine);
19020   } else {
19021     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
19022       .addImm(12);
19023     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
19024     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
19025       .addExternalSymbol("__morestack_allocate_stack_space")
19026       .addRegMask(RegMask)
19027       .addReg(X86::EAX, RegState::ImplicitDefine);
19028   }
19029
19030   if (!Is64Bit)
19031     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
19032       .addImm(16);
19033
19034   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
19035     .addReg(IsLP64 ? X86::RAX : X86::EAX);
19036   BuildMI(mallocMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
19037
19038   // Set up the CFG correctly.
19039   BB->addSuccessor(bumpMBB);
19040   BB->addSuccessor(mallocMBB);
19041   mallocMBB->addSuccessor(continueMBB);
19042   bumpMBB->addSuccessor(continueMBB);
19043
19044   // Take care of the PHI nodes.
19045   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
19046           MI->getOperand(0).getReg())
19047     .addReg(mallocPtrVReg).addMBB(mallocMBB)
19048     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
19049
19050   // Delete the original pseudo instruction.
19051   MI->eraseFromParent();
19052
19053   // And we're done.
19054   return continueMBB;
19055 }
19056
19057 MachineBasicBlock *
19058 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
19059                                         MachineBasicBlock *BB) const {
19060   DebugLoc DL = MI->getDebugLoc();
19061
19062   assert(!Subtarget->isTargetMachO());
19063
19064   X86FrameLowering::emitStackProbeCall(*BB->getParent(), *BB, MI, DL);
19065
19066   MI->eraseFromParent();   // The pseudo instruction is gone now.
19067   return BB;
19068 }
19069
19070 MachineBasicBlock *
19071 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
19072                                       MachineBasicBlock *BB) const {
19073   // This is pretty easy.  We're taking the value that we received from
19074   // our load from the relocation, sticking it in either RDI (x86-64)
19075   // or EAX and doing an indirect call.  The return value will then
19076   // be in the normal return register.
19077   MachineFunction *F = BB->getParent();
19078   const X86InstrInfo *TII = Subtarget->getInstrInfo();
19079   DebugLoc DL = MI->getDebugLoc();
19080
19081   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
19082   assert(MI->getOperand(3).isGlobal() && "This should be a global");
19083
19084   // Get a register mask for the lowered call.
19085   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
19086   // proper register mask.
19087   const uint32_t *RegMask =
19088       Subtarget->getRegisterInfo()->getCallPreservedMask(*F, CallingConv::C);
19089   if (Subtarget->is64Bit()) {
19090     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
19091                                       TII->get(X86::MOV64rm), X86::RDI)
19092     .addReg(X86::RIP)
19093     .addImm(0).addReg(0)
19094     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
19095                       MI->getOperand(3).getTargetFlags())
19096     .addReg(0);
19097     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
19098     addDirectMem(MIB, X86::RDI);
19099     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
19100   } else if (F->getTarget().getRelocationModel() != Reloc::PIC_) {
19101     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
19102                                       TII->get(X86::MOV32rm), X86::EAX)
19103     .addReg(0)
19104     .addImm(0).addReg(0)
19105     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
19106                       MI->getOperand(3).getTargetFlags())
19107     .addReg(0);
19108     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
19109     addDirectMem(MIB, X86::EAX);
19110     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
19111   } else {
19112     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
19113                                       TII->get(X86::MOV32rm), X86::EAX)
19114     .addReg(TII->getGlobalBaseReg(F))
19115     .addImm(0).addReg(0)
19116     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
19117                       MI->getOperand(3).getTargetFlags())
19118     .addReg(0);
19119     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
19120     addDirectMem(MIB, X86::EAX);
19121     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
19122   }
19123
19124   MI->eraseFromParent(); // The pseudo instruction is gone now.
19125   return BB;
19126 }
19127
19128 MachineBasicBlock *
19129 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
19130                                     MachineBasicBlock *MBB) const {
19131   DebugLoc DL = MI->getDebugLoc();
19132   MachineFunction *MF = MBB->getParent();
19133   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19134   MachineRegisterInfo &MRI = MF->getRegInfo();
19135
19136   const BasicBlock *BB = MBB->getBasicBlock();
19137   MachineFunction::iterator I = MBB;
19138   ++I;
19139
19140   // Memory Reference
19141   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
19142   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
19143
19144   unsigned DstReg;
19145   unsigned MemOpndSlot = 0;
19146
19147   unsigned CurOp = 0;
19148
19149   DstReg = MI->getOperand(CurOp++).getReg();
19150   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
19151   assert(RC->hasType(MVT::i32) && "Invalid destination!");
19152   unsigned mainDstReg = MRI.createVirtualRegister(RC);
19153   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
19154
19155   MemOpndSlot = CurOp;
19156
19157   MVT PVT = getPointerTy();
19158   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
19159          "Invalid Pointer Size!");
19160
19161   // For v = setjmp(buf), we generate
19162   //
19163   // thisMBB:
19164   //  buf[LabelOffset] = restoreMBB
19165   //  SjLjSetup restoreMBB
19166   //
19167   // mainMBB:
19168   //  v_main = 0
19169   //
19170   // sinkMBB:
19171   //  v = phi(main, restore)
19172   //
19173   // restoreMBB:
19174   //  if base pointer being used, load it from frame
19175   //  v_restore = 1
19176
19177   MachineBasicBlock *thisMBB = MBB;
19178   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
19179   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
19180   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
19181   MF->insert(I, mainMBB);
19182   MF->insert(I, sinkMBB);
19183   MF->push_back(restoreMBB);
19184
19185   MachineInstrBuilder MIB;
19186
19187   // Transfer the remainder of BB and its successor edges to sinkMBB.
19188   sinkMBB->splice(sinkMBB->begin(), MBB,
19189                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
19190   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
19191
19192   // thisMBB:
19193   unsigned PtrStoreOpc = 0;
19194   unsigned LabelReg = 0;
19195   const int64_t LabelOffset = 1 * PVT.getStoreSize();
19196   Reloc::Model RM = MF->getTarget().getRelocationModel();
19197   bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
19198                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
19199
19200   // Prepare IP either in reg or imm.
19201   if (!UseImmLabel) {
19202     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
19203     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
19204     LabelReg = MRI.createVirtualRegister(PtrRC);
19205     if (Subtarget->is64Bit()) {
19206       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
19207               .addReg(X86::RIP)
19208               .addImm(0)
19209               .addReg(0)
19210               .addMBB(restoreMBB)
19211               .addReg(0);
19212     } else {
19213       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
19214       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
19215               .addReg(XII->getGlobalBaseReg(MF))
19216               .addImm(0)
19217               .addReg(0)
19218               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
19219               .addReg(0);
19220     }
19221   } else
19222     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
19223   // Store IP
19224   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
19225   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
19226     if (i == X86::AddrDisp)
19227       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
19228     else
19229       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
19230   }
19231   if (!UseImmLabel)
19232     MIB.addReg(LabelReg);
19233   else
19234     MIB.addMBB(restoreMBB);
19235   MIB.setMemRefs(MMOBegin, MMOEnd);
19236   // Setup
19237   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
19238           .addMBB(restoreMBB);
19239
19240   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
19241   MIB.addRegMask(RegInfo->getNoPreservedMask());
19242   thisMBB->addSuccessor(mainMBB);
19243   thisMBB->addSuccessor(restoreMBB);
19244
19245   // mainMBB:
19246   //  EAX = 0
19247   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
19248   mainMBB->addSuccessor(sinkMBB);
19249
19250   // sinkMBB:
19251   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
19252           TII->get(X86::PHI), DstReg)
19253     .addReg(mainDstReg).addMBB(mainMBB)
19254     .addReg(restoreDstReg).addMBB(restoreMBB);
19255
19256   // restoreMBB:
19257   if (RegInfo->hasBasePointer(*MF)) {
19258     const bool Uses64BitFramePtr =
19259         Subtarget->isTarget64BitLP64() || Subtarget->isTargetNaCl64();
19260     X86MachineFunctionInfo *X86FI = MF->getInfo<X86MachineFunctionInfo>();
19261     X86FI->setRestoreBasePointer(MF);
19262     unsigned FramePtr = RegInfo->getFrameRegister(*MF);
19263     unsigned BasePtr = RegInfo->getBaseRegister();
19264     unsigned Opm = Uses64BitFramePtr ? X86::MOV64rm : X86::MOV32rm;
19265     addRegOffset(BuildMI(restoreMBB, DL, TII->get(Opm), BasePtr),
19266                  FramePtr, true, X86FI->getRestoreBasePointerOffset())
19267       .setMIFlag(MachineInstr::FrameSetup);
19268   }
19269   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
19270   BuildMI(restoreMBB, DL, TII->get(X86::JMP_1)).addMBB(sinkMBB);
19271   restoreMBB->addSuccessor(sinkMBB);
19272
19273   MI->eraseFromParent();
19274   return sinkMBB;
19275 }
19276
19277 MachineBasicBlock *
19278 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
19279                                      MachineBasicBlock *MBB) const {
19280   DebugLoc DL = MI->getDebugLoc();
19281   MachineFunction *MF = MBB->getParent();
19282   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19283   MachineRegisterInfo &MRI = MF->getRegInfo();
19284
19285   // Memory Reference
19286   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
19287   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
19288
19289   MVT PVT = getPointerTy();
19290   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
19291          "Invalid Pointer Size!");
19292
19293   const TargetRegisterClass *RC =
19294     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
19295   unsigned Tmp = MRI.createVirtualRegister(RC);
19296   // Since FP is only updated here but NOT referenced, it's treated as GPR.
19297   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
19298   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
19299   unsigned SP = RegInfo->getStackRegister();
19300
19301   MachineInstrBuilder MIB;
19302
19303   const int64_t LabelOffset = 1 * PVT.getStoreSize();
19304   const int64_t SPOffset = 2 * PVT.getStoreSize();
19305
19306   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
19307   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
19308
19309   // Reload FP
19310   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
19311   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
19312     MIB.addOperand(MI->getOperand(i));
19313   MIB.setMemRefs(MMOBegin, MMOEnd);
19314   // Reload IP
19315   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
19316   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
19317     if (i == X86::AddrDisp)
19318       MIB.addDisp(MI->getOperand(i), LabelOffset);
19319     else
19320       MIB.addOperand(MI->getOperand(i));
19321   }
19322   MIB.setMemRefs(MMOBegin, MMOEnd);
19323   // Reload SP
19324   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
19325   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
19326     if (i == X86::AddrDisp)
19327       MIB.addDisp(MI->getOperand(i), SPOffset);
19328     else
19329       MIB.addOperand(MI->getOperand(i));
19330   }
19331   MIB.setMemRefs(MMOBegin, MMOEnd);
19332   // Jump
19333   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
19334
19335   MI->eraseFromParent();
19336   return MBB;
19337 }
19338
19339 // Replace 213-type (isel default) FMA3 instructions with 231-type for
19340 // accumulator loops. Writing back to the accumulator allows the coalescer
19341 // to remove extra copies in the loop.
19342 MachineBasicBlock *
19343 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
19344                                  MachineBasicBlock *MBB) const {
19345   MachineOperand &AddendOp = MI->getOperand(3);
19346
19347   // Bail out early if the addend isn't a register - we can't switch these.
19348   if (!AddendOp.isReg())
19349     return MBB;
19350
19351   MachineFunction &MF = *MBB->getParent();
19352   MachineRegisterInfo &MRI = MF.getRegInfo();
19353
19354   // Check whether the addend is defined by a PHI:
19355   assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
19356   MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
19357   if (!AddendDef.isPHI())
19358     return MBB;
19359
19360   // Look for the following pattern:
19361   // loop:
19362   //   %addend = phi [%entry, 0], [%loop, %result]
19363   //   ...
19364   //   %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
19365
19366   // Replace with:
19367   //   loop:
19368   //   %addend = phi [%entry, 0], [%loop, %result]
19369   //   ...
19370   //   %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
19371
19372   for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
19373     assert(AddendDef.getOperand(i).isReg());
19374     MachineOperand PHISrcOp = AddendDef.getOperand(i);
19375     MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
19376     if (&PHISrcInst == MI) {
19377       // Found a matching instruction.
19378       unsigned NewFMAOpc = 0;
19379       switch (MI->getOpcode()) {
19380         case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
19381         case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
19382         case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
19383         case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
19384         case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
19385         case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
19386         case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
19387         case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
19388         case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
19389         case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
19390         case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
19391         case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
19392         case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
19393         case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
19394         case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
19395         case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
19396         case X86::VFMADDSUBPDr213r: NewFMAOpc = X86::VFMADDSUBPDr231r; break;
19397         case X86::VFMADDSUBPSr213r: NewFMAOpc = X86::VFMADDSUBPSr231r; break;
19398         case X86::VFMSUBADDPDr213r: NewFMAOpc = X86::VFMSUBADDPDr231r; break;
19399         case X86::VFMSUBADDPSr213r: NewFMAOpc = X86::VFMSUBADDPSr231r; break;
19400
19401         case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
19402         case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
19403         case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
19404         case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
19405         case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
19406         case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
19407         case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
19408         case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
19409         case X86::VFMADDSUBPDr213rY: NewFMAOpc = X86::VFMADDSUBPDr231rY; break;
19410         case X86::VFMADDSUBPSr213rY: NewFMAOpc = X86::VFMADDSUBPSr231rY; break;
19411         case X86::VFMSUBADDPDr213rY: NewFMAOpc = X86::VFMSUBADDPDr231rY; break;
19412         case X86::VFMSUBADDPSr213rY: NewFMAOpc = X86::VFMSUBADDPSr231rY; break;
19413         default: llvm_unreachable("Unrecognized FMA variant.");
19414       }
19415
19416       const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
19417       MachineInstrBuilder MIB =
19418         BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
19419         .addOperand(MI->getOperand(0))
19420         .addOperand(MI->getOperand(3))
19421         .addOperand(MI->getOperand(2))
19422         .addOperand(MI->getOperand(1));
19423       MBB->insert(MachineBasicBlock::iterator(MI), MIB);
19424       MI->eraseFromParent();
19425     }
19426   }
19427
19428   return MBB;
19429 }
19430
19431 MachineBasicBlock *
19432 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
19433                                                MachineBasicBlock *BB) const {
19434   switch (MI->getOpcode()) {
19435   default: llvm_unreachable("Unexpected instr type to insert");
19436   case X86::TAILJMPd64:
19437   case X86::TAILJMPr64:
19438   case X86::TAILJMPm64:
19439   case X86::TAILJMPd64_REX:
19440   case X86::TAILJMPr64_REX:
19441   case X86::TAILJMPm64_REX:
19442     llvm_unreachable("TAILJMP64 would not be touched here.");
19443   case X86::TCRETURNdi64:
19444   case X86::TCRETURNri64:
19445   case X86::TCRETURNmi64:
19446     return BB;
19447   case X86::WIN_ALLOCA:
19448     return EmitLoweredWinAlloca(MI, BB);
19449   case X86::SEG_ALLOCA_32:
19450   case X86::SEG_ALLOCA_64:
19451     return EmitLoweredSegAlloca(MI, BB);
19452   case X86::TLSCall_32:
19453   case X86::TLSCall_64:
19454     return EmitLoweredTLSCall(MI, BB);
19455   case X86::CMOV_GR8:
19456   case X86::CMOV_FR32:
19457   case X86::CMOV_FR64:
19458   case X86::CMOV_V4F32:
19459   case X86::CMOV_V2F64:
19460   case X86::CMOV_V2I64:
19461   case X86::CMOV_V8F32:
19462   case X86::CMOV_V4F64:
19463   case X86::CMOV_V4I64:
19464   case X86::CMOV_V16F32:
19465   case X86::CMOV_V8F64:
19466   case X86::CMOV_V8I64:
19467   case X86::CMOV_GR16:
19468   case X86::CMOV_GR32:
19469   case X86::CMOV_RFP32:
19470   case X86::CMOV_RFP64:
19471   case X86::CMOV_RFP80:
19472   case X86::CMOV_V8I1:
19473   case X86::CMOV_V16I1:
19474   case X86::CMOV_V32I1:
19475   case X86::CMOV_V64I1:
19476     return EmitLoweredSelect(MI, BB);
19477
19478   case X86::FP32_TO_INT16_IN_MEM:
19479   case X86::FP32_TO_INT32_IN_MEM:
19480   case X86::FP32_TO_INT64_IN_MEM:
19481   case X86::FP64_TO_INT16_IN_MEM:
19482   case X86::FP64_TO_INT32_IN_MEM:
19483   case X86::FP64_TO_INT64_IN_MEM:
19484   case X86::FP80_TO_INT16_IN_MEM:
19485   case X86::FP80_TO_INT32_IN_MEM:
19486   case X86::FP80_TO_INT64_IN_MEM: {
19487     MachineFunction *F = BB->getParent();
19488     const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19489     DebugLoc DL = MI->getDebugLoc();
19490
19491     // Change the floating point control register to use "round towards zero"
19492     // mode when truncating to an integer value.
19493     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
19494     addFrameReference(BuildMI(*BB, MI, DL,
19495                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
19496
19497     // Load the old value of the high byte of the control word...
19498     unsigned OldCW =
19499       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
19500     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
19501                       CWFrameIdx);
19502
19503     // Set the high part to be round to zero...
19504     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
19505       .addImm(0xC7F);
19506
19507     // Reload the modified control word now...
19508     addFrameReference(BuildMI(*BB, MI, DL,
19509                               TII->get(X86::FLDCW16m)), CWFrameIdx);
19510
19511     // Restore the memory image of control word to original value
19512     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
19513       .addReg(OldCW);
19514
19515     // Get the X86 opcode to use.
19516     unsigned Opc;
19517     switch (MI->getOpcode()) {
19518     default: llvm_unreachable("illegal opcode!");
19519     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
19520     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
19521     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
19522     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
19523     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
19524     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
19525     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
19526     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
19527     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
19528     }
19529
19530     X86AddressMode AM;
19531     MachineOperand &Op = MI->getOperand(0);
19532     if (Op.isReg()) {
19533       AM.BaseType = X86AddressMode::RegBase;
19534       AM.Base.Reg = Op.getReg();
19535     } else {
19536       AM.BaseType = X86AddressMode::FrameIndexBase;
19537       AM.Base.FrameIndex = Op.getIndex();
19538     }
19539     Op = MI->getOperand(1);
19540     if (Op.isImm())
19541       AM.Scale = Op.getImm();
19542     Op = MI->getOperand(2);
19543     if (Op.isImm())
19544       AM.IndexReg = Op.getImm();
19545     Op = MI->getOperand(3);
19546     if (Op.isGlobal()) {
19547       AM.GV = Op.getGlobal();
19548     } else {
19549       AM.Disp = Op.getImm();
19550     }
19551     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
19552                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
19553
19554     // Reload the original control word now.
19555     addFrameReference(BuildMI(*BB, MI, DL,
19556                               TII->get(X86::FLDCW16m)), CWFrameIdx);
19557
19558     MI->eraseFromParent();   // The pseudo instruction is gone now.
19559     return BB;
19560   }
19561     // String/text processing lowering.
19562   case X86::PCMPISTRM128REG:
19563   case X86::VPCMPISTRM128REG:
19564   case X86::PCMPISTRM128MEM:
19565   case X86::VPCMPISTRM128MEM:
19566   case X86::PCMPESTRM128REG:
19567   case X86::VPCMPESTRM128REG:
19568   case X86::PCMPESTRM128MEM:
19569   case X86::VPCMPESTRM128MEM:
19570     assert(Subtarget->hasSSE42() &&
19571            "Target must have SSE4.2 or AVX features enabled");
19572     return EmitPCMPSTRM(MI, BB, Subtarget->getInstrInfo());
19573
19574   // String/text processing lowering.
19575   case X86::PCMPISTRIREG:
19576   case X86::VPCMPISTRIREG:
19577   case X86::PCMPISTRIMEM:
19578   case X86::VPCMPISTRIMEM:
19579   case X86::PCMPESTRIREG:
19580   case X86::VPCMPESTRIREG:
19581   case X86::PCMPESTRIMEM:
19582   case X86::VPCMPESTRIMEM:
19583     assert(Subtarget->hasSSE42() &&
19584            "Target must have SSE4.2 or AVX features enabled");
19585     return EmitPCMPSTRI(MI, BB, Subtarget->getInstrInfo());
19586
19587   // Thread synchronization.
19588   case X86::MONITOR:
19589     return EmitMonitor(MI, BB, Subtarget);
19590
19591   // xbegin
19592   case X86::XBEGIN:
19593     return EmitXBegin(MI, BB, Subtarget->getInstrInfo());
19594
19595   case X86::VASTART_SAVE_XMM_REGS:
19596     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
19597
19598   case X86::VAARG_64:
19599     return EmitVAARG64WithCustomInserter(MI, BB);
19600
19601   case X86::EH_SjLj_SetJmp32:
19602   case X86::EH_SjLj_SetJmp64:
19603     return emitEHSjLjSetJmp(MI, BB);
19604
19605   case X86::EH_SjLj_LongJmp32:
19606   case X86::EH_SjLj_LongJmp64:
19607     return emitEHSjLjLongJmp(MI, BB);
19608
19609   case TargetOpcode::STATEPOINT:
19610     // As an implementation detail, STATEPOINT shares the STACKMAP format at
19611     // this point in the process.  We diverge later.
19612     return emitPatchPoint(MI, BB);
19613
19614   case TargetOpcode::STACKMAP:
19615   case TargetOpcode::PATCHPOINT:
19616     return emitPatchPoint(MI, BB);
19617
19618   case X86::VFMADDPDr213r:
19619   case X86::VFMADDPSr213r:
19620   case X86::VFMADDSDr213r:
19621   case X86::VFMADDSSr213r:
19622   case X86::VFMSUBPDr213r:
19623   case X86::VFMSUBPSr213r:
19624   case X86::VFMSUBSDr213r:
19625   case X86::VFMSUBSSr213r:
19626   case X86::VFNMADDPDr213r:
19627   case X86::VFNMADDPSr213r:
19628   case X86::VFNMADDSDr213r:
19629   case X86::VFNMADDSSr213r:
19630   case X86::VFNMSUBPDr213r:
19631   case X86::VFNMSUBPSr213r:
19632   case X86::VFNMSUBSDr213r:
19633   case X86::VFNMSUBSSr213r:
19634   case X86::VFMADDSUBPDr213r:
19635   case X86::VFMADDSUBPSr213r:
19636   case X86::VFMSUBADDPDr213r:
19637   case X86::VFMSUBADDPSr213r:
19638   case X86::VFMADDPDr213rY:
19639   case X86::VFMADDPSr213rY:
19640   case X86::VFMSUBPDr213rY:
19641   case X86::VFMSUBPSr213rY:
19642   case X86::VFNMADDPDr213rY:
19643   case X86::VFNMADDPSr213rY:
19644   case X86::VFNMSUBPDr213rY:
19645   case X86::VFNMSUBPSr213rY:
19646   case X86::VFMADDSUBPDr213rY:
19647   case X86::VFMADDSUBPSr213rY:
19648   case X86::VFMSUBADDPDr213rY:
19649   case X86::VFMSUBADDPSr213rY:
19650     return emitFMA3Instr(MI, BB);
19651   }
19652 }
19653
19654 //===----------------------------------------------------------------------===//
19655 //                           X86 Optimization Hooks
19656 //===----------------------------------------------------------------------===//
19657
19658 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
19659                                                       APInt &KnownZero,
19660                                                       APInt &KnownOne,
19661                                                       const SelectionDAG &DAG,
19662                                                       unsigned Depth) const {
19663   unsigned BitWidth = KnownZero.getBitWidth();
19664   unsigned Opc = Op.getOpcode();
19665   assert((Opc >= ISD::BUILTIN_OP_END ||
19666           Opc == ISD::INTRINSIC_WO_CHAIN ||
19667           Opc == ISD::INTRINSIC_W_CHAIN ||
19668           Opc == ISD::INTRINSIC_VOID) &&
19669          "Should use MaskedValueIsZero if you don't know whether Op"
19670          " is a target node!");
19671
19672   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
19673   switch (Opc) {
19674   default: break;
19675   case X86ISD::ADD:
19676   case X86ISD::SUB:
19677   case X86ISD::ADC:
19678   case X86ISD::SBB:
19679   case X86ISD::SMUL:
19680   case X86ISD::UMUL:
19681   case X86ISD::INC:
19682   case X86ISD::DEC:
19683   case X86ISD::OR:
19684   case X86ISD::XOR:
19685   case X86ISD::AND:
19686     // These nodes' second result is a boolean.
19687     if (Op.getResNo() == 0)
19688       break;
19689     // Fallthrough
19690   case X86ISD::SETCC:
19691     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
19692     break;
19693   case ISD::INTRINSIC_WO_CHAIN: {
19694     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
19695     unsigned NumLoBits = 0;
19696     switch (IntId) {
19697     default: break;
19698     case Intrinsic::x86_sse_movmsk_ps:
19699     case Intrinsic::x86_avx_movmsk_ps_256:
19700     case Intrinsic::x86_sse2_movmsk_pd:
19701     case Intrinsic::x86_avx_movmsk_pd_256:
19702     case Intrinsic::x86_mmx_pmovmskb:
19703     case Intrinsic::x86_sse2_pmovmskb_128:
19704     case Intrinsic::x86_avx2_pmovmskb: {
19705       // High bits of movmskp{s|d}, pmovmskb are known zero.
19706       switch (IntId) {
19707         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
19708         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
19709         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
19710         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
19711         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
19712         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
19713         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
19714         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
19715       }
19716       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
19717       break;
19718     }
19719     }
19720     break;
19721   }
19722   }
19723 }
19724
19725 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
19726   SDValue Op,
19727   const SelectionDAG &,
19728   unsigned Depth) const {
19729   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
19730   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
19731     return Op.getValueType().getScalarType().getSizeInBits();
19732
19733   // Fallback case.
19734   return 1;
19735 }
19736
19737 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
19738 /// node is a GlobalAddress + offset.
19739 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
19740                                        const GlobalValue* &GA,
19741                                        int64_t &Offset) const {
19742   if (N->getOpcode() == X86ISD::Wrapper) {
19743     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
19744       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
19745       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
19746       return true;
19747     }
19748   }
19749   return TargetLowering::isGAPlusOffset(N, GA, Offset);
19750 }
19751
19752 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
19753 /// same as extracting the high 128-bit part of 256-bit vector and then
19754 /// inserting the result into the low part of a new 256-bit vector
19755 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
19756   EVT VT = SVOp->getValueType(0);
19757   unsigned NumElems = VT.getVectorNumElements();
19758
19759   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
19760   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
19761     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
19762         SVOp->getMaskElt(j) >= 0)
19763       return false;
19764
19765   return true;
19766 }
19767
19768 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
19769 /// same as extracting the low 128-bit part of 256-bit vector and then
19770 /// inserting the result into the high part of a new 256-bit vector
19771 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
19772   EVT VT = SVOp->getValueType(0);
19773   unsigned NumElems = VT.getVectorNumElements();
19774
19775   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
19776   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
19777     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
19778         SVOp->getMaskElt(j) >= 0)
19779       return false;
19780
19781   return true;
19782 }
19783
19784 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
19785 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
19786                                         TargetLowering::DAGCombinerInfo &DCI,
19787                                         const X86Subtarget* Subtarget) {
19788   SDLoc dl(N);
19789   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
19790   SDValue V1 = SVOp->getOperand(0);
19791   SDValue V2 = SVOp->getOperand(1);
19792   EVT VT = SVOp->getValueType(0);
19793   unsigned NumElems = VT.getVectorNumElements();
19794
19795   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
19796       V2.getOpcode() == ISD::CONCAT_VECTORS) {
19797     //
19798     //                   0,0,0,...
19799     //                      |
19800     //    V      UNDEF    BUILD_VECTOR    UNDEF
19801     //     \      /           \           /
19802     //  CONCAT_VECTOR         CONCAT_VECTOR
19803     //         \                  /
19804     //          \                /
19805     //          RESULT: V + zero extended
19806     //
19807     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
19808         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
19809         V1.getOperand(1).getOpcode() != ISD::UNDEF)
19810       return SDValue();
19811
19812     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
19813       return SDValue();
19814
19815     // To match the shuffle mask, the first half of the mask should
19816     // be exactly the first vector, and all the rest a splat with the
19817     // first element of the second one.
19818     for (unsigned i = 0; i != NumElems/2; ++i)
19819       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
19820           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
19821         return SDValue();
19822
19823     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
19824     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
19825       if (Ld->hasNUsesOfValue(1, 0)) {
19826         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
19827         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
19828         SDValue ResNode =
19829           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
19830                                   Ld->getMemoryVT(),
19831                                   Ld->getPointerInfo(),
19832                                   Ld->getAlignment(),
19833                                   false/*isVolatile*/, true/*ReadMem*/,
19834                                   false/*WriteMem*/);
19835
19836         // Make sure the newly-created LOAD is in the same position as Ld in
19837         // terms of dependency. We create a TokenFactor for Ld and ResNode,
19838         // and update uses of Ld's output chain to use the TokenFactor.
19839         if (Ld->hasAnyUseOfValue(1)) {
19840           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
19841                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
19842           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
19843           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
19844                                  SDValue(ResNode.getNode(), 1));
19845         }
19846
19847         return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
19848       }
19849     }
19850
19851     // Emit a zeroed vector and insert the desired subvector on its
19852     // first half.
19853     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
19854     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
19855     return DCI.CombineTo(N, InsV);
19856   }
19857
19858   //===--------------------------------------------------------------------===//
19859   // Combine some shuffles into subvector extracts and inserts:
19860   //
19861
19862   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
19863   if (isShuffleHigh128VectorInsertLow(SVOp)) {
19864     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
19865     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
19866     return DCI.CombineTo(N, InsV);
19867   }
19868
19869   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
19870   if (isShuffleLow128VectorInsertHigh(SVOp)) {
19871     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
19872     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
19873     return DCI.CombineTo(N, InsV);
19874   }
19875
19876   return SDValue();
19877 }
19878
19879 /// \brief Combine an arbitrary chain of shuffles into a single instruction if
19880 /// possible.
19881 ///
19882 /// This is the leaf of the recursive combinine below. When we have found some
19883 /// chain of single-use x86 shuffle instructions and accumulated the combined
19884 /// shuffle mask represented by them, this will try to pattern match that mask
19885 /// into either a single instruction if there is a special purpose instruction
19886 /// for this operation, or into a PSHUFB instruction which is a fully general
19887 /// instruction but should only be used to replace chains over a certain depth.
19888 static bool combineX86ShuffleChain(SDValue Op, SDValue Root, ArrayRef<int> Mask,
19889                                    int Depth, bool HasPSHUFB, SelectionDAG &DAG,
19890                                    TargetLowering::DAGCombinerInfo &DCI,
19891                                    const X86Subtarget *Subtarget) {
19892   assert(!Mask.empty() && "Cannot combine an empty shuffle mask!");
19893
19894   // Find the operand that enters the chain. Note that multiple uses are OK
19895   // here, we're not going to remove the operand we find.
19896   SDValue Input = Op.getOperand(0);
19897   while (Input.getOpcode() == ISD::BITCAST)
19898     Input = Input.getOperand(0);
19899
19900   MVT VT = Input.getSimpleValueType();
19901   MVT RootVT = Root.getSimpleValueType();
19902   SDLoc DL(Root);
19903
19904   // Just remove no-op shuffle masks.
19905   if (Mask.size() == 1) {
19906     DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Input),
19907                   /*AddTo*/ true);
19908     return true;
19909   }
19910
19911   // Use the float domain if the operand type is a floating point type.
19912   bool FloatDomain = VT.isFloatingPoint();
19913
19914   // For floating point shuffles, we don't have free copies in the shuffle
19915   // instructions or the ability to load as part of the instruction, so
19916   // canonicalize their shuffles to UNPCK or MOV variants.
19917   //
19918   // Note that even with AVX we prefer the PSHUFD form of shuffle for integer
19919   // vectors because it can have a load folded into it that UNPCK cannot. This
19920   // doesn't preclude something switching to the shorter encoding post-RA.
19921   //
19922   // FIXME: Should teach these routines about AVX vector widths.
19923   if (FloatDomain && VT.getSizeInBits() == 128) {
19924     if (Mask.equals({0, 0}) || Mask.equals({1, 1})) {
19925       bool Lo = Mask.equals({0, 0});
19926       unsigned Shuffle;
19927       MVT ShuffleVT;
19928       // Check if we have SSE3 which will let us use MOVDDUP. That instruction
19929       // is no slower than UNPCKLPD but has the option to fold the input operand
19930       // into even an unaligned memory load.
19931       if (Lo && Subtarget->hasSSE3()) {
19932         Shuffle = X86ISD::MOVDDUP;
19933         ShuffleVT = MVT::v2f64;
19934       } else {
19935         // We have MOVLHPS and MOVHLPS throughout SSE and they encode smaller
19936         // than the UNPCK variants.
19937         Shuffle = Lo ? X86ISD::MOVLHPS : X86ISD::MOVHLPS;
19938         ShuffleVT = MVT::v4f32;
19939       }
19940       if (Depth == 1 && Root->getOpcode() == Shuffle)
19941         return false; // Nothing to do!
19942       Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
19943       DCI.AddToWorklist(Op.getNode());
19944       if (Shuffle == X86ISD::MOVDDUP)
19945         Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
19946       else
19947         Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
19948       DCI.AddToWorklist(Op.getNode());
19949       DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
19950                     /*AddTo*/ true);
19951       return true;
19952     }
19953     if (Subtarget->hasSSE3() &&
19954         (Mask.equals({0, 0, 2, 2}) || Mask.equals({1, 1, 3, 3}))) {
19955       bool Lo = Mask.equals({0, 0, 2, 2});
19956       unsigned Shuffle = Lo ? X86ISD::MOVSLDUP : X86ISD::MOVSHDUP;
19957       MVT ShuffleVT = MVT::v4f32;
19958       if (Depth == 1 && Root->getOpcode() == Shuffle)
19959         return false; // Nothing to do!
19960       Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
19961       DCI.AddToWorklist(Op.getNode());
19962       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
19963       DCI.AddToWorklist(Op.getNode());
19964       DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
19965                     /*AddTo*/ true);
19966       return true;
19967     }
19968     if (Mask.equals({0, 0, 1, 1}) || Mask.equals({2, 2, 3, 3})) {
19969       bool Lo = Mask.equals({0, 0, 1, 1});
19970       unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
19971       MVT ShuffleVT = MVT::v4f32;
19972       if (Depth == 1 && Root->getOpcode() == Shuffle)
19973         return false; // Nothing to do!
19974       Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
19975       DCI.AddToWorklist(Op.getNode());
19976       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
19977       DCI.AddToWorklist(Op.getNode());
19978       DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
19979                     /*AddTo*/ true);
19980       return true;
19981     }
19982   }
19983
19984   // We always canonicalize the 8 x i16 and 16 x i8 shuffles into their UNPCK
19985   // variants as none of these have single-instruction variants that are
19986   // superior to the UNPCK formulation.
19987   if (!FloatDomain && VT.getSizeInBits() == 128 &&
19988       (Mask.equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
19989        Mask.equals({4, 4, 5, 5, 6, 6, 7, 7}) ||
19990        Mask.equals({0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7}) ||
19991        Mask.equals(
19992            {8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15, 15}))) {
19993     bool Lo = Mask[0] == 0;
19994     unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
19995     if (Depth == 1 && Root->getOpcode() == Shuffle)
19996       return false; // Nothing to do!
19997     MVT ShuffleVT;
19998     switch (Mask.size()) {
19999     case 8:
20000       ShuffleVT = MVT::v8i16;
20001       break;
20002     case 16:
20003       ShuffleVT = MVT::v16i8;
20004       break;
20005     default:
20006       llvm_unreachable("Impossible mask size!");
20007     };
20008     Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
20009     DCI.AddToWorklist(Op.getNode());
20010     Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
20011     DCI.AddToWorklist(Op.getNode());
20012     DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
20013                   /*AddTo*/ true);
20014     return true;
20015   }
20016
20017   // Don't try to re-form single instruction chains under any circumstances now
20018   // that we've done encoding canonicalization for them.
20019   if (Depth < 2)
20020     return false;
20021
20022   // If we have 3 or more shuffle instructions or a chain involving PSHUFB, we
20023   // can replace them with a single PSHUFB instruction profitably. Intel's
20024   // manuals suggest only using PSHUFB if doing so replacing 5 instructions, but
20025   // in practice PSHUFB tends to be *very* fast so we're more aggressive.
20026   if ((Depth >= 3 || HasPSHUFB) && Subtarget->hasSSSE3()) {
20027     SmallVector<SDValue, 16> PSHUFBMask;
20028     int NumBytes = VT.getSizeInBits() / 8;
20029     int Ratio = NumBytes / Mask.size();
20030     for (int i = 0; i < NumBytes; ++i) {
20031       if (Mask[i / Ratio] == SM_SentinelUndef) {
20032         PSHUFBMask.push_back(DAG.getUNDEF(MVT::i8));
20033         continue;
20034       }
20035       int M = Mask[i / Ratio] != SM_SentinelZero
20036                   ? Ratio * Mask[i / Ratio] + i % Ratio
20037                   : 255;
20038       PSHUFBMask.push_back(DAG.getConstant(M, DL, MVT::i8));
20039     }
20040     MVT ByteVT = MVT::getVectorVT(MVT::i8, NumBytes);
20041     Op = DAG.getNode(ISD::BITCAST, DL, ByteVT, Input);
20042     DCI.AddToWorklist(Op.getNode());
20043     SDValue PSHUFBMaskOp =
20044         DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVT, PSHUFBMask);
20045     DCI.AddToWorklist(PSHUFBMaskOp.getNode());
20046     Op = DAG.getNode(X86ISD::PSHUFB, DL, ByteVT, Op, PSHUFBMaskOp);
20047     DCI.AddToWorklist(Op.getNode());
20048     DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
20049                   /*AddTo*/ true);
20050     return true;
20051   }
20052
20053   // Failed to find any combines.
20054   return false;
20055 }
20056
20057 /// \brief Fully generic combining of x86 shuffle instructions.
20058 ///
20059 /// This should be the last combine run over the x86 shuffle instructions. Once
20060 /// they have been fully optimized, this will recursively consider all chains
20061 /// of single-use shuffle instructions, build a generic model of the cumulative
20062 /// shuffle operation, and check for simpler instructions which implement this
20063 /// operation. We use this primarily for two purposes:
20064 ///
20065 /// 1) Collapse generic shuffles to specialized single instructions when
20066 ///    equivalent. In most cases, this is just an encoding size win, but
20067 ///    sometimes we will collapse multiple generic shuffles into a single
20068 ///    special-purpose shuffle.
20069 /// 2) Look for sequences of shuffle instructions with 3 or more total
20070 ///    instructions, and replace them with the slightly more expensive SSSE3
20071 ///    PSHUFB instruction if available. We do this as the last combining step
20072 ///    to ensure we avoid using PSHUFB if we can implement the shuffle with
20073 ///    a suitable short sequence of other instructions. The PHUFB will either
20074 ///    use a register or have to read from memory and so is slightly (but only
20075 ///    slightly) more expensive than the other shuffle instructions.
20076 ///
20077 /// Because this is inherently a quadratic operation (for each shuffle in
20078 /// a chain, we recurse up the chain), the depth is limited to 8 instructions.
20079 /// This should never be an issue in practice as the shuffle lowering doesn't
20080 /// produce sequences of more than 8 instructions.
20081 ///
20082 /// FIXME: We will currently miss some cases where the redundant shuffling
20083 /// would simplify under the threshold for PSHUFB formation because of
20084 /// combine-ordering. To fix this, we should do the redundant instruction
20085 /// combining in this recursive walk.
20086 static bool combineX86ShufflesRecursively(SDValue Op, SDValue Root,
20087                                           ArrayRef<int> RootMask,
20088                                           int Depth, bool HasPSHUFB,
20089                                           SelectionDAG &DAG,
20090                                           TargetLowering::DAGCombinerInfo &DCI,
20091                                           const X86Subtarget *Subtarget) {
20092   // Bound the depth of our recursive combine because this is ultimately
20093   // quadratic in nature.
20094   if (Depth > 8)
20095     return false;
20096
20097   // Directly rip through bitcasts to find the underlying operand.
20098   while (Op.getOpcode() == ISD::BITCAST && Op.getOperand(0).hasOneUse())
20099     Op = Op.getOperand(0);
20100
20101   MVT VT = Op.getSimpleValueType();
20102   if (!VT.isVector())
20103     return false; // Bail if we hit a non-vector.
20104
20105   assert(Root.getSimpleValueType().isVector() &&
20106          "Shuffles operate on vector types!");
20107   assert(VT.getSizeInBits() == Root.getSimpleValueType().getSizeInBits() &&
20108          "Can only combine shuffles of the same vector register size.");
20109
20110   if (!isTargetShuffle(Op.getOpcode()))
20111     return false;
20112   SmallVector<int, 16> OpMask;
20113   bool IsUnary;
20114   bool HaveMask = getTargetShuffleMask(Op.getNode(), VT, OpMask, IsUnary);
20115   // We only can combine unary shuffles which we can decode the mask for.
20116   if (!HaveMask || !IsUnary)
20117     return false;
20118
20119   assert(VT.getVectorNumElements() == OpMask.size() &&
20120          "Different mask size from vector size!");
20121   assert(((RootMask.size() > OpMask.size() &&
20122            RootMask.size() % OpMask.size() == 0) ||
20123           (OpMask.size() > RootMask.size() &&
20124            OpMask.size() % RootMask.size() == 0) ||
20125           OpMask.size() == RootMask.size()) &&
20126          "The smaller number of elements must divide the larger.");
20127   int RootRatio = std::max<int>(1, OpMask.size() / RootMask.size());
20128   int OpRatio = std::max<int>(1, RootMask.size() / OpMask.size());
20129   assert(((RootRatio == 1 && OpRatio == 1) ||
20130           (RootRatio == 1) != (OpRatio == 1)) &&
20131          "Must not have a ratio for both incoming and op masks!");
20132
20133   SmallVector<int, 16> Mask;
20134   Mask.reserve(std::max(OpMask.size(), RootMask.size()));
20135
20136   // Merge this shuffle operation's mask into our accumulated mask. Note that
20137   // this shuffle's mask will be the first applied to the input, followed by the
20138   // root mask to get us all the way to the root value arrangement. The reason
20139   // for this order is that we are recursing up the operation chain.
20140   for (int i = 0, e = std::max(OpMask.size(), RootMask.size()); i < e; ++i) {
20141     int RootIdx = i / RootRatio;
20142     if (RootMask[RootIdx] < 0) {
20143       // This is a zero or undef lane, we're done.
20144       Mask.push_back(RootMask[RootIdx]);
20145       continue;
20146     }
20147
20148     int RootMaskedIdx = RootMask[RootIdx] * RootRatio + i % RootRatio;
20149     int OpIdx = RootMaskedIdx / OpRatio;
20150     if (OpMask[OpIdx] < 0) {
20151       // The incoming lanes are zero or undef, it doesn't matter which ones we
20152       // are using.
20153       Mask.push_back(OpMask[OpIdx]);
20154       continue;
20155     }
20156
20157     // Ok, we have non-zero lanes, map them through.
20158     Mask.push_back(OpMask[OpIdx] * OpRatio +
20159                    RootMaskedIdx % OpRatio);
20160   }
20161
20162   // See if we can recurse into the operand to combine more things.
20163   switch (Op.getOpcode()) {
20164     case X86ISD::PSHUFB:
20165       HasPSHUFB = true;
20166     case X86ISD::PSHUFD:
20167     case X86ISD::PSHUFHW:
20168     case X86ISD::PSHUFLW:
20169       if (Op.getOperand(0).hasOneUse() &&
20170           combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
20171                                         HasPSHUFB, DAG, DCI, Subtarget))
20172         return true;
20173       break;
20174
20175     case X86ISD::UNPCKL:
20176     case X86ISD::UNPCKH:
20177       assert(Op.getOperand(0) == Op.getOperand(1) && "We only combine unary shuffles!");
20178       // We can't check for single use, we have to check that this shuffle is the only user.
20179       if (Op->isOnlyUserOf(Op.getOperand(0).getNode()) &&
20180           combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
20181                                         HasPSHUFB, DAG, DCI, Subtarget))
20182           return true;
20183       break;
20184   }
20185
20186   // Minor canonicalization of the accumulated shuffle mask to make it easier
20187   // to match below. All this does is detect masks with squential pairs of
20188   // elements, and shrink them to the half-width mask. It does this in a loop
20189   // so it will reduce the size of the mask to the minimal width mask which
20190   // performs an equivalent shuffle.
20191   SmallVector<int, 16> WidenedMask;
20192   while (Mask.size() > 1 && canWidenShuffleElements(Mask, WidenedMask)) {
20193     Mask = std::move(WidenedMask);
20194     WidenedMask.clear();
20195   }
20196
20197   return combineX86ShuffleChain(Op, Root, Mask, Depth, HasPSHUFB, DAG, DCI,
20198                                 Subtarget);
20199 }
20200
20201 /// \brief Get the PSHUF-style mask from PSHUF node.
20202 ///
20203 /// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
20204 /// PSHUF-style masks that can be reused with such instructions.
20205 static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
20206   MVT VT = N.getSimpleValueType();
20207   SmallVector<int, 4> Mask;
20208   bool IsUnary;
20209   bool HaveMask = getTargetShuffleMask(N.getNode(), VT, Mask, IsUnary);
20210   (void)HaveMask;
20211   assert(HaveMask);
20212
20213   // If we have more than 128-bits, only the low 128-bits of shuffle mask
20214   // matter. Check that the upper masks are repeats and remove them.
20215   if (VT.getSizeInBits() > 128) {
20216     int LaneElts = 128 / VT.getScalarSizeInBits();
20217 #ifndef NDEBUG
20218     for (int i = 1, NumLanes = VT.getSizeInBits() / 128; i < NumLanes; ++i)
20219       for (int j = 0; j < LaneElts; ++j)
20220         assert(Mask[j] == Mask[i * LaneElts + j] - LaneElts &&
20221                "Mask doesn't repeat in high 128-bit lanes!");
20222 #endif
20223     Mask.resize(LaneElts);
20224   }
20225
20226   switch (N.getOpcode()) {
20227   case X86ISD::PSHUFD:
20228     return Mask;
20229   case X86ISD::PSHUFLW:
20230     Mask.resize(4);
20231     return Mask;
20232   case X86ISD::PSHUFHW:
20233     Mask.erase(Mask.begin(), Mask.begin() + 4);
20234     for (int &M : Mask)
20235       M -= 4;
20236     return Mask;
20237   default:
20238     llvm_unreachable("No valid shuffle instruction found!");
20239   }
20240 }
20241
20242 /// \brief Search for a combinable shuffle across a chain ending in pshufd.
20243 ///
20244 /// We walk up the chain and look for a combinable shuffle, skipping over
20245 /// shuffles that we could hoist this shuffle's transformation past without
20246 /// altering anything.
20247 static SDValue
20248 combineRedundantDWordShuffle(SDValue N, MutableArrayRef<int> Mask,
20249                              SelectionDAG &DAG,
20250                              TargetLowering::DAGCombinerInfo &DCI) {
20251   assert(N.getOpcode() == X86ISD::PSHUFD &&
20252          "Called with something other than an x86 128-bit half shuffle!");
20253   SDLoc DL(N);
20254
20255   // Walk up a single-use chain looking for a combinable shuffle. Keep a stack
20256   // of the shuffles in the chain so that we can form a fresh chain to replace
20257   // this one.
20258   SmallVector<SDValue, 8> Chain;
20259   SDValue V = N.getOperand(0);
20260   for (; V.hasOneUse(); V = V.getOperand(0)) {
20261     switch (V.getOpcode()) {
20262     default:
20263       return SDValue(); // Nothing combined!
20264
20265     case ISD::BITCAST:
20266       // Skip bitcasts as we always know the type for the target specific
20267       // instructions.
20268       continue;
20269
20270     case X86ISD::PSHUFD:
20271       // Found another dword shuffle.
20272       break;
20273
20274     case X86ISD::PSHUFLW:
20275       // Check that the low words (being shuffled) are the identity in the
20276       // dword shuffle, and the high words are self-contained.
20277       if (Mask[0] != 0 || Mask[1] != 1 ||
20278           !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
20279         return SDValue();
20280
20281       Chain.push_back(V);
20282       continue;
20283
20284     case X86ISD::PSHUFHW:
20285       // Check that the high words (being shuffled) are the identity in the
20286       // dword shuffle, and the low words are self-contained.
20287       if (Mask[2] != 2 || Mask[3] != 3 ||
20288           !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
20289         return SDValue();
20290
20291       Chain.push_back(V);
20292       continue;
20293
20294     case X86ISD::UNPCKL:
20295     case X86ISD::UNPCKH:
20296       // For either i8 -> i16 or i16 -> i32 unpacks, we can combine a dword
20297       // shuffle into a preceding word shuffle.
20298       if (V.getSimpleValueType().getScalarType() != MVT::i8 &&
20299           V.getSimpleValueType().getScalarType() != MVT::i16)
20300         return SDValue();
20301
20302       // Search for a half-shuffle which we can combine with.
20303       unsigned CombineOp =
20304           V.getOpcode() == X86ISD::UNPCKL ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
20305       if (V.getOperand(0) != V.getOperand(1) ||
20306           !V->isOnlyUserOf(V.getOperand(0).getNode()))
20307         return SDValue();
20308       Chain.push_back(V);
20309       V = V.getOperand(0);
20310       do {
20311         switch (V.getOpcode()) {
20312         default:
20313           return SDValue(); // Nothing to combine.
20314
20315         case X86ISD::PSHUFLW:
20316         case X86ISD::PSHUFHW:
20317           if (V.getOpcode() == CombineOp)
20318             break;
20319
20320           Chain.push_back(V);
20321
20322           // Fallthrough!
20323         case ISD::BITCAST:
20324           V = V.getOperand(0);
20325           continue;
20326         }
20327         break;
20328       } while (V.hasOneUse());
20329       break;
20330     }
20331     // Break out of the loop if we break out of the switch.
20332     break;
20333   }
20334
20335   if (!V.hasOneUse())
20336     // We fell out of the loop without finding a viable combining instruction.
20337     return SDValue();
20338
20339   // Merge this node's mask and our incoming mask.
20340   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
20341   for (int &M : Mask)
20342     M = VMask[M];
20343   V = DAG.getNode(V.getOpcode(), DL, V.getValueType(), V.getOperand(0),
20344                   getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
20345
20346   // Rebuild the chain around this new shuffle.
20347   while (!Chain.empty()) {
20348     SDValue W = Chain.pop_back_val();
20349
20350     if (V.getValueType() != W.getOperand(0).getValueType())
20351       V = DAG.getNode(ISD::BITCAST, DL, W.getOperand(0).getValueType(), V);
20352
20353     switch (W.getOpcode()) {
20354     default:
20355       llvm_unreachable("Only PSHUF and UNPCK instructions get here!");
20356
20357     case X86ISD::UNPCKL:
20358     case X86ISD::UNPCKH:
20359       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, V);
20360       break;
20361
20362     case X86ISD::PSHUFD:
20363     case X86ISD::PSHUFLW:
20364     case X86ISD::PSHUFHW:
20365       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, W.getOperand(1));
20366       break;
20367     }
20368   }
20369   if (V.getValueType() != N.getValueType())
20370     V = DAG.getNode(ISD::BITCAST, DL, N.getValueType(), V);
20371
20372   // Return the new chain to replace N.
20373   return V;
20374 }
20375
20376 /// \brief Search for a combinable shuffle across a chain ending in pshuflw or pshufhw.
20377 ///
20378 /// We walk up the chain, skipping shuffles of the other half and looking
20379 /// through shuffles which switch halves trying to find a shuffle of the same
20380 /// pair of dwords.
20381 static bool combineRedundantHalfShuffle(SDValue N, MutableArrayRef<int> Mask,
20382                                         SelectionDAG &DAG,
20383                                         TargetLowering::DAGCombinerInfo &DCI) {
20384   assert(
20385       (N.getOpcode() == X86ISD::PSHUFLW || N.getOpcode() == X86ISD::PSHUFHW) &&
20386       "Called with something other than an x86 128-bit half shuffle!");
20387   SDLoc DL(N);
20388   unsigned CombineOpcode = N.getOpcode();
20389
20390   // Walk up a single-use chain looking for a combinable shuffle.
20391   SDValue V = N.getOperand(0);
20392   for (; V.hasOneUse(); V = V.getOperand(0)) {
20393     switch (V.getOpcode()) {
20394     default:
20395       return false; // Nothing combined!
20396
20397     case ISD::BITCAST:
20398       // Skip bitcasts as we always know the type for the target specific
20399       // instructions.
20400       continue;
20401
20402     case X86ISD::PSHUFLW:
20403     case X86ISD::PSHUFHW:
20404       if (V.getOpcode() == CombineOpcode)
20405         break;
20406
20407       // Other-half shuffles are no-ops.
20408       continue;
20409     }
20410     // Break out of the loop if we break out of the switch.
20411     break;
20412   }
20413
20414   if (!V.hasOneUse())
20415     // We fell out of the loop without finding a viable combining instruction.
20416     return false;
20417
20418   // Combine away the bottom node as its shuffle will be accumulated into
20419   // a preceding shuffle.
20420   DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
20421
20422   // Record the old value.
20423   SDValue Old = V;
20424
20425   // Merge this node's mask and our incoming mask (adjusted to account for all
20426   // the pshufd instructions encountered).
20427   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
20428   for (int &M : Mask)
20429     M = VMask[M];
20430   V = DAG.getNode(V.getOpcode(), DL, MVT::v8i16, V.getOperand(0),
20431                   getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
20432
20433   // Check that the shuffles didn't cancel each other out. If not, we need to
20434   // combine to the new one.
20435   if (Old != V)
20436     // Replace the combinable shuffle with the combined one, updating all users
20437     // so that we re-evaluate the chain here.
20438     DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
20439
20440   return true;
20441 }
20442
20443 /// \brief Try to combine x86 target specific shuffles.
20444 static SDValue PerformTargetShuffleCombine(SDValue N, SelectionDAG &DAG,
20445                                            TargetLowering::DAGCombinerInfo &DCI,
20446                                            const X86Subtarget *Subtarget) {
20447   SDLoc DL(N);
20448   MVT VT = N.getSimpleValueType();
20449   SmallVector<int, 4> Mask;
20450
20451   switch (N.getOpcode()) {
20452   case X86ISD::PSHUFD:
20453   case X86ISD::PSHUFLW:
20454   case X86ISD::PSHUFHW:
20455     Mask = getPSHUFShuffleMask(N);
20456     assert(Mask.size() == 4);
20457     break;
20458   default:
20459     return SDValue();
20460   }
20461
20462   // Nuke no-op shuffles that show up after combining.
20463   if (isNoopShuffleMask(Mask))
20464     return DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
20465
20466   // Look for simplifications involving one or two shuffle instructions.
20467   SDValue V = N.getOperand(0);
20468   switch (N.getOpcode()) {
20469   default:
20470     break;
20471   case X86ISD::PSHUFLW:
20472   case X86ISD::PSHUFHW:
20473     assert(VT.getScalarType() == MVT::i16 && "Bad word shuffle type!");
20474
20475     if (combineRedundantHalfShuffle(N, Mask, DAG, DCI))
20476       return SDValue(); // We combined away this shuffle, so we're done.
20477
20478     // See if this reduces to a PSHUFD which is no more expensive and can
20479     // combine with more operations. Note that it has to at least flip the
20480     // dwords as otherwise it would have been removed as a no-op.
20481     if (makeArrayRef(Mask).equals({2, 3, 0, 1})) {
20482       int DMask[] = {0, 1, 2, 3};
20483       int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
20484       DMask[DOffset + 0] = DOffset + 1;
20485       DMask[DOffset + 1] = DOffset + 0;
20486       MVT DVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
20487       V = DAG.getNode(ISD::BITCAST, DL, DVT, V);
20488       DCI.AddToWorklist(V.getNode());
20489       V = DAG.getNode(X86ISD::PSHUFD, DL, DVT, V,
20490                       getV4X86ShuffleImm8ForMask(DMask, DL, DAG));
20491       DCI.AddToWorklist(V.getNode());
20492       return DAG.getNode(ISD::BITCAST, DL, VT, V);
20493     }
20494
20495     // Look for shuffle patterns which can be implemented as a single unpack.
20496     // FIXME: This doesn't handle the location of the PSHUFD generically, and
20497     // only works when we have a PSHUFD followed by two half-shuffles.
20498     if (Mask[0] == Mask[1] && Mask[2] == Mask[3] &&
20499         (V.getOpcode() == X86ISD::PSHUFLW ||
20500          V.getOpcode() == X86ISD::PSHUFHW) &&
20501         V.getOpcode() != N.getOpcode() &&
20502         V.hasOneUse()) {
20503       SDValue D = V.getOperand(0);
20504       while (D.getOpcode() == ISD::BITCAST && D.hasOneUse())
20505         D = D.getOperand(0);
20506       if (D.getOpcode() == X86ISD::PSHUFD && D.hasOneUse()) {
20507         SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
20508         SmallVector<int, 4> DMask = getPSHUFShuffleMask(D);
20509         int NOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
20510         int VOffset = V.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
20511         int WordMask[8];
20512         for (int i = 0; i < 4; ++i) {
20513           WordMask[i + NOffset] = Mask[i] + NOffset;
20514           WordMask[i + VOffset] = VMask[i] + VOffset;
20515         }
20516         // Map the word mask through the DWord mask.
20517         int MappedMask[8];
20518         for (int i = 0; i < 8; ++i)
20519           MappedMask[i] = 2 * DMask[WordMask[i] / 2] + WordMask[i] % 2;
20520         if (makeArrayRef(MappedMask).equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
20521             makeArrayRef(MappedMask).equals({4, 4, 5, 5, 6, 6, 7, 7})) {
20522           // We can replace all three shuffles with an unpack.
20523           V = DAG.getNode(ISD::BITCAST, DL, VT, D.getOperand(0));
20524           DCI.AddToWorklist(V.getNode());
20525           return DAG.getNode(MappedMask[0] == 0 ? X86ISD::UNPCKL
20526                                                 : X86ISD::UNPCKH,
20527                              DL, VT, V, V);
20528         }
20529       }
20530     }
20531
20532     break;
20533
20534   case X86ISD::PSHUFD:
20535     if (SDValue NewN = combineRedundantDWordShuffle(N, Mask, DAG, DCI))
20536       return NewN;
20537
20538     break;
20539   }
20540
20541   return SDValue();
20542 }
20543
20544 /// \brief Try to combine a shuffle into a target-specific add-sub node.
20545 ///
20546 /// We combine this directly on the abstract vector shuffle nodes so it is
20547 /// easier to generically match. We also insert dummy vector shuffle nodes for
20548 /// the operands which explicitly discard the lanes which are unused by this
20549 /// operation to try to flow through the rest of the combiner the fact that
20550 /// they're unused.
20551 static SDValue combineShuffleToAddSub(SDNode *N, SelectionDAG &DAG) {
20552   SDLoc DL(N);
20553   EVT VT = N->getValueType(0);
20554
20555   // We only handle target-independent shuffles.
20556   // FIXME: It would be easy and harmless to use the target shuffle mask
20557   // extraction tool to support more.
20558   if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
20559     return SDValue();
20560
20561   auto *SVN = cast<ShuffleVectorSDNode>(N);
20562   ArrayRef<int> Mask = SVN->getMask();
20563   SDValue V1 = N->getOperand(0);
20564   SDValue V2 = N->getOperand(1);
20565
20566   // We require the first shuffle operand to be the SUB node, and the second to
20567   // be the ADD node.
20568   // FIXME: We should support the commuted patterns.
20569   if (V1->getOpcode() != ISD::FSUB || V2->getOpcode() != ISD::FADD)
20570     return SDValue();
20571
20572   // If there are other uses of these operations we can't fold them.
20573   if (!V1->hasOneUse() || !V2->hasOneUse())
20574     return SDValue();
20575
20576   // Ensure that both operations have the same operands. Note that we can
20577   // commute the FADD operands.
20578   SDValue LHS = V1->getOperand(0), RHS = V1->getOperand(1);
20579   if ((V2->getOperand(0) != LHS || V2->getOperand(1) != RHS) &&
20580       (V2->getOperand(0) != RHS || V2->getOperand(1) != LHS))
20581     return SDValue();
20582
20583   // We're looking for blends between FADD and FSUB nodes. We insist on these
20584   // nodes being lined up in a specific expected pattern.
20585   if (!(isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
20586         isShuffleEquivalent(V1, V2, Mask, {0, 5, 2, 7}) ||
20587         isShuffleEquivalent(V1, V2, Mask, {0, 9, 2, 11, 4, 13, 6, 15})))
20588     return SDValue();
20589
20590   // Only specific types are legal at this point, assert so we notice if and
20591   // when these change.
20592   assert((VT == MVT::v4f32 || VT == MVT::v2f64 || VT == MVT::v8f32 ||
20593           VT == MVT::v4f64) &&
20594          "Unknown vector type encountered!");
20595
20596   return DAG.getNode(X86ISD::ADDSUB, DL, VT, LHS, RHS);
20597 }
20598
20599 /// PerformShuffleCombine - Performs several different shuffle combines.
20600 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
20601                                      TargetLowering::DAGCombinerInfo &DCI,
20602                                      const X86Subtarget *Subtarget) {
20603   SDLoc dl(N);
20604   SDValue N0 = N->getOperand(0);
20605   SDValue N1 = N->getOperand(1);
20606   EVT VT = N->getValueType(0);
20607
20608   // Don't create instructions with illegal types after legalize types has run.
20609   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20610   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
20611     return SDValue();
20612
20613   // If we have legalized the vector types, look for blends of FADD and FSUB
20614   // nodes that we can fuse into an ADDSUB node.
20615   if (TLI.isTypeLegal(VT) && Subtarget->hasSSE3())
20616     if (SDValue AddSub = combineShuffleToAddSub(N, DAG))
20617       return AddSub;
20618
20619   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
20620   if (Subtarget->hasFp256() && VT.is256BitVector() &&
20621       N->getOpcode() == ISD::VECTOR_SHUFFLE)
20622     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
20623
20624   // During Type Legalization, when promoting illegal vector types,
20625   // the backend might introduce new shuffle dag nodes and bitcasts.
20626   //
20627   // This code performs the following transformation:
20628   // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
20629   //       (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
20630   //
20631   // We do this only if both the bitcast and the BINOP dag nodes have
20632   // one use. Also, perform this transformation only if the new binary
20633   // operation is legal. This is to avoid introducing dag nodes that
20634   // potentially need to be further expanded (or custom lowered) into a
20635   // less optimal sequence of dag nodes.
20636   if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
20637       N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
20638       N0.getOpcode() == ISD::BITCAST) {
20639     SDValue BC0 = N0.getOperand(0);
20640     EVT SVT = BC0.getValueType();
20641     unsigned Opcode = BC0.getOpcode();
20642     unsigned NumElts = VT.getVectorNumElements();
20643
20644     if (BC0.hasOneUse() && SVT.isVector() &&
20645         SVT.getVectorNumElements() * 2 == NumElts &&
20646         TLI.isOperationLegal(Opcode, VT)) {
20647       bool CanFold = false;
20648       switch (Opcode) {
20649       default : break;
20650       case ISD::ADD :
20651       case ISD::FADD :
20652       case ISD::SUB :
20653       case ISD::FSUB :
20654       case ISD::MUL :
20655       case ISD::FMUL :
20656         CanFold = true;
20657       }
20658
20659       unsigned SVTNumElts = SVT.getVectorNumElements();
20660       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
20661       for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
20662         CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
20663       for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
20664         CanFold = SVOp->getMaskElt(i) < 0;
20665
20666       if (CanFold) {
20667         SDValue BC00 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(0));
20668         SDValue BC01 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(1));
20669         SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
20670         return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
20671       }
20672     }
20673   }
20674
20675   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
20676   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
20677   // consecutive, non-overlapping, and in the right order.
20678   SmallVector<SDValue, 16> Elts;
20679   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
20680     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
20681
20682   SDValue LD = EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true);
20683   if (LD.getNode())
20684     return LD;
20685
20686   if (isTargetShuffle(N->getOpcode())) {
20687     SDValue Shuffle =
20688         PerformTargetShuffleCombine(SDValue(N, 0), DAG, DCI, Subtarget);
20689     if (Shuffle.getNode())
20690       return Shuffle;
20691
20692     // Try recursively combining arbitrary sequences of x86 shuffle
20693     // instructions into higher-order shuffles. We do this after combining
20694     // specific PSHUF instruction sequences into their minimal form so that we
20695     // can evaluate how many specialized shuffle instructions are involved in
20696     // a particular chain.
20697     SmallVector<int, 1> NonceMask; // Just a placeholder.
20698     NonceMask.push_back(0);
20699     if (combineX86ShufflesRecursively(SDValue(N, 0), SDValue(N, 0), NonceMask,
20700                                       /*Depth*/ 1, /*HasPSHUFB*/ false, DAG,
20701                                       DCI, Subtarget))
20702       return SDValue(); // This routine will use CombineTo to replace N.
20703   }
20704
20705   return SDValue();
20706 }
20707
20708 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
20709 /// specific shuffle of a load can be folded into a single element load.
20710 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
20711 /// shuffles have been custom lowered so we need to handle those here.
20712 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
20713                                          TargetLowering::DAGCombinerInfo &DCI) {
20714   if (DCI.isBeforeLegalizeOps())
20715     return SDValue();
20716
20717   SDValue InVec = N->getOperand(0);
20718   SDValue EltNo = N->getOperand(1);
20719
20720   if (!isa<ConstantSDNode>(EltNo))
20721     return SDValue();
20722
20723   EVT OriginalVT = InVec.getValueType();
20724
20725   if (InVec.getOpcode() == ISD::BITCAST) {
20726     // Don't duplicate a load with other uses.
20727     if (!InVec.hasOneUse())
20728       return SDValue();
20729     EVT BCVT = InVec.getOperand(0).getValueType();
20730     if (BCVT.getVectorNumElements() != OriginalVT.getVectorNumElements())
20731       return SDValue();
20732     InVec = InVec.getOperand(0);
20733   }
20734
20735   EVT CurrentVT = InVec.getValueType();
20736
20737   if (!isTargetShuffle(InVec.getOpcode()))
20738     return SDValue();
20739
20740   // Don't duplicate a load with other uses.
20741   if (!InVec.hasOneUse())
20742     return SDValue();
20743
20744   SmallVector<int, 16> ShuffleMask;
20745   bool UnaryShuffle;
20746   if (!getTargetShuffleMask(InVec.getNode(), CurrentVT.getSimpleVT(),
20747                             ShuffleMask, UnaryShuffle))
20748     return SDValue();
20749
20750   // Select the input vector, guarding against out of range extract vector.
20751   unsigned NumElems = CurrentVT.getVectorNumElements();
20752   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
20753   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
20754   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
20755                                          : InVec.getOperand(1);
20756
20757   // If inputs to shuffle are the same for both ops, then allow 2 uses
20758   unsigned AllowedUses = InVec.getNumOperands() > 1 &&
20759                          InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
20760
20761   if (LdNode.getOpcode() == ISD::BITCAST) {
20762     // Don't duplicate a load with other uses.
20763     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
20764       return SDValue();
20765
20766     AllowedUses = 1; // only allow 1 load use if we have a bitcast
20767     LdNode = LdNode.getOperand(0);
20768   }
20769
20770   if (!ISD::isNormalLoad(LdNode.getNode()))
20771     return SDValue();
20772
20773   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
20774
20775   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
20776     return SDValue();
20777
20778   EVT EltVT = N->getValueType(0);
20779   // If there's a bitcast before the shuffle, check if the load type and
20780   // alignment is valid.
20781   unsigned Align = LN0->getAlignment();
20782   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20783   unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment(
20784       EltVT.getTypeForEVT(*DAG.getContext()));
20785
20786   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, EltVT))
20787     return SDValue();
20788
20789   // All checks match so transform back to vector_shuffle so that DAG combiner
20790   // can finish the job
20791   SDLoc dl(N);
20792
20793   // Create shuffle node taking into account the case that its a unary shuffle
20794   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(CurrentVT)
20795                                    : InVec.getOperand(1);
20796   Shuffle = DAG.getVectorShuffle(CurrentVT, dl,
20797                                  InVec.getOperand(0), Shuffle,
20798                                  &ShuffleMask[0]);
20799   Shuffle = DAG.getNode(ISD::BITCAST, dl, OriginalVT, Shuffle);
20800   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
20801                      EltNo);
20802 }
20803
20804 /// \brief Detect bitcasts between i32 to x86mmx low word. Since MMX types are
20805 /// special and don't usually play with other vector types, it's better to
20806 /// handle them early to be sure we emit efficient code by avoiding
20807 /// store-load conversions.
20808 static SDValue PerformBITCASTCombine(SDNode *N, SelectionDAG &DAG) {
20809   if (N->getValueType(0) != MVT::x86mmx ||
20810       N->getOperand(0)->getOpcode() != ISD::BUILD_VECTOR ||
20811       N->getOperand(0)->getValueType(0) != MVT::v2i32)
20812     return SDValue();
20813
20814   SDValue V = N->getOperand(0);
20815   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V.getOperand(1));
20816   if (C && C->getZExtValue() == 0 && V.getOperand(0).getValueType() == MVT::i32)
20817     return DAG.getNode(X86ISD::MMX_MOVW2D, SDLoc(V.getOperand(0)),
20818                        N->getValueType(0), V.getOperand(0));
20819
20820   return SDValue();
20821 }
20822
20823 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
20824 /// generation and convert it from being a bunch of shuffles and extracts
20825 /// into a somewhat faster sequence. For i686, the best sequence is apparently
20826 /// storing the value and loading scalars back, while for x64 we should
20827 /// use 64-bit extracts and shifts.
20828 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
20829                                          TargetLowering::DAGCombinerInfo &DCI) {
20830   SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
20831   if (NewOp.getNode())
20832     return NewOp;
20833
20834   SDValue InputVector = N->getOperand(0);
20835
20836   // Detect mmx to i32 conversion through a v2i32 elt extract.
20837   if (InputVector.getOpcode() == ISD::BITCAST && InputVector.hasOneUse() &&
20838       N->getValueType(0) == MVT::i32 &&
20839       InputVector.getValueType() == MVT::v2i32) {
20840
20841     // The bitcast source is a direct mmx result.
20842     SDValue MMXSrc = InputVector.getNode()->getOperand(0);
20843     if (MMXSrc.getValueType() == MVT::x86mmx)
20844       return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
20845                          N->getValueType(0),
20846                          InputVector.getNode()->getOperand(0));
20847
20848     // The mmx is indirect: (i64 extract_elt (v1i64 bitcast (x86mmx ...))).
20849     SDValue MMXSrcOp = MMXSrc.getOperand(0);
20850     if (MMXSrc.getOpcode() == ISD::EXTRACT_VECTOR_ELT && MMXSrc.hasOneUse() &&
20851         MMXSrc.getValueType() == MVT::i64 && MMXSrcOp.hasOneUse() &&
20852         MMXSrcOp.getOpcode() == ISD::BITCAST &&
20853         MMXSrcOp.getValueType() == MVT::v1i64 &&
20854         MMXSrcOp.getOperand(0).getValueType() == MVT::x86mmx)
20855       return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
20856                          N->getValueType(0),
20857                          MMXSrcOp.getOperand(0));
20858   }
20859
20860   // Only operate on vectors of 4 elements, where the alternative shuffling
20861   // gets to be more expensive.
20862   if (InputVector.getValueType() != MVT::v4i32)
20863     return SDValue();
20864
20865   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
20866   // single use which is a sign-extend or zero-extend, and all elements are
20867   // used.
20868   SmallVector<SDNode *, 4> Uses;
20869   unsigned ExtractedElements = 0;
20870   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
20871        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
20872     if (UI.getUse().getResNo() != InputVector.getResNo())
20873       return SDValue();
20874
20875     SDNode *Extract = *UI;
20876     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
20877       return SDValue();
20878
20879     if (Extract->getValueType(0) != MVT::i32)
20880       return SDValue();
20881     if (!Extract->hasOneUse())
20882       return SDValue();
20883     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
20884         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
20885       return SDValue();
20886     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
20887       return SDValue();
20888
20889     // Record which element was extracted.
20890     ExtractedElements |=
20891       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
20892
20893     Uses.push_back(Extract);
20894   }
20895
20896   // If not all the elements were used, this may not be worthwhile.
20897   if (ExtractedElements != 15)
20898     return SDValue();
20899
20900   // Ok, we've now decided to do the transformation.
20901   // If 64-bit shifts are legal, use the extract-shift sequence,
20902   // otherwise bounce the vector off the cache.
20903   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20904   SDValue Vals[4];
20905   SDLoc dl(InputVector);
20906
20907   if (TLI.isOperationLegal(ISD::SRA, MVT::i64)) {
20908     SDValue Cst = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, InputVector);
20909     EVT VecIdxTy = DAG.getTargetLoweringInfo().getVectorIdxTy();
20910     SDValue BottomHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
20911       DAG.getConstant(0, dl, VecIdxTy));
20912     SDValue TopHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
20913       DAG.getConstant(1, dl, VecIdxTy));
20914
20915     SDValue ShAmt = DAG.getConstant(32, dl,
20916       DAG.getTargetLoweringInfo().getShiftAmountTy(MVT::i64));
20917     Vals[0] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BottomHalf);
20918     Vals[1] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
20919       DAG.getNode(ISD::SRA, dl, MVT::i64, BottomHalf, ShAmt));
20920     Vals[2] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, TopHalf);
20921     Vals[3] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
20922       DAG.getNode(ISD::SRA, dl, MVT::i64, TopHalf, ShAmt));
20923   } else {
20924     // Store the value to a temporary stack slot.
20925     SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
20926     SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
20927       MachinePointerInfo(), false, false, 0);
20928
20929     EVT ElementType = InputVector.getValueType().getVectorElementType();
20930     unsigned EltSize = ElementType.getSizeInBits() / 8;
20931
20932     // Replace each use (extract) with a load of the appropriate element.
20933     for (unsigned i = 0; i < 4; ++i) {
20934       uint64_t Offset = EltSize * i;
20935       SDValue OffsetVal = DAG.getConstant(Offset, dl, TLI.getPointerTy());
20936
20937       SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
20938                                        StackPtr, OffsetVal);
20939
20940       // Load the scalar.
20941       Vals[i] = DAG.getLoad(ElementType, dl, Ch,
20942                             ScalarAddr, MachinePointerInfo(),
20943                             false, false, false, 0);
20944
20945     }
20946   }
20947
20948   // Replace the extracts
20949   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
20950     UE = Uses.end(); UI != UE; ++UI) {
20951     SDNode *Extract = *UI;
20952
20953     SDValue Idx = Extract->getOperand(1);
20954     uint64_t IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
20955     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), Vals[IdxVal]);
20956   }
20957
20958   // The replacement was made in place; don't return anything.
20959   return SDValue();
20960 }
20961
20962 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
20963 static std::pair<unsigned, bool>
20964 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
20965                    SelectionDAG &DAG, const X86Subtarget *Subtarget) {
20966   if (!VT.isVector())
20967     return std::make_pair(0, false);
20968
20969   bool NeedSplit = false;
20970   switch (VT.getSimpleVT().SimpleTy) {
20971   default: return std::make_pair(0, false);
20972   case MVT::v4i64:
20973   case MVT::v2i64:
20974     if (!Subtarget->hasVLX())
20975       return std::make_pair(0, false);
20976     break;
20977   case MVT::v64i8:
20978   case MVT::v32i16:
20979     if (!Subtarget->hasBWI())
20980       return std::make_pair(0, false);
20981     break;
20982   case MVT::v16i32:
20983   case MVT::v8i64:
20984     if (!Subtarget->hasAVX512())
20985       return std::make_pair(0, false);
20986     break;
20987   case MVT::v32i8:
20988   case MVT::v16i16:
20989   case MVT::v8i32:
20990     if (!Subtarget->hasAVX2())
20991       NeedSplit = true;
20992     if (!Subtarget->hasAVX())
20993       return std::make_pair(0, false);
20994     break;
20995   case MVT::v16i8:
20996   case MVT::v8i16:
20997   case MVT::v4i32:
20998     if (!Subtarget->hasSSE2())
20999       return std::make_pair(0, false);
21000   }
21001
21002   // SSE2 has only a small subset of the operations.
21003   bool hasUnsigned = Subtarget->hasSSE41() ||
21004                      (Subtarget->hasSSE2() && VT == MVT::v16i8);
21005   bool hasSigned = Subtarget->hasSSE41() ||
21006                    (Subtarget->hasSSE2() && VT == MVT::v8i16);
21007
21008   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
21009
21010   unsigned Opc = 0;
21011   // Check for x CC y ? x : y.
21012   if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
21013       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
21014     switch (CC) {
21015     default: break;
21016     case ISD::SETULT:
21017     case ISD::SETULE:
21018       Opc = hasUnsigned ? X86ISD::UMIN : 0u; break;
21019     case ISD::SETUGT:
21020     case ISD::SETUGE:
21021       Opc = hasUnsigned ? X86ISD::UMAX : 0u; break;
21022     case ISD::SETLT:
21023     case ISD::SETLE:
21024       Opc = hasSigned ? X86ISD::SMIN : 0u; break;
21025     case ISD::SETGT:
21026     case ISD::SETGE:
21027       Opc = hasSigned ? X86ISD::SMAX : 0u; break;
21028     }
21029   // Check for x CC y ? y : x -- a min/max with reversed arms.
21030   } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
21031              DAG.isEqualTo(RHS, Cond.getOperand(0))) {
21032     switch (CC) {
21033     default: break;
21034     case ISD::SETULT:
21035     case ISD::SETULE:
21036       Opc = hasUnsigned ? X86ISD::UMAX : 0u; break;
21037     case ISD::SETUGT:
21038     case ISD::SETUGE:
21039       Opc = hasUnsigned ? X86ISD::UMIN : 0u; break;
21040     case ISD::SETLT:
21041     case ISD::SETLE:
21042       Opc = hasSigned ? X86ISD::SMAX : 0u; break;
21043     case ISD::SETGT:
21044     case ISD::SETGE:
21045       Opc = hasSigned ? X86ISD::SMIN : 0u; break;
21046     }
21047   }
21048
21049   return std::make_pair(Opc, NeedSplit);
21050 }
21051
21052 static SDValue
21053 transformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
21054                                       const X86Subtarget *Subtarget) {
21055   SDLoc dl(N);
21056   SDValue Cond = N->getOperand(0);
21057   SDValue LHS = N->getOperand(1);
21058   SDValue RHS = N->getOperand(2);
21059
21060   if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
21061     SDValue CondSrc = Cond->getOperand(0);
21062     if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
21063       Cond = CondSrc->getOperand(0);
21064   }
21065
21066   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
21067     return SDValue();
21068
21069   // A vselect where all conditions and data are constants can be optimized into
21070   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
21071   if (ISD::isBuildVectorOfConstantSDNodes(LHS.getNode()) &&
21072       ISD::isBuildVectorOfConstantSDNodes(RHS.getNode()))
21073     return SDValue();
21074
21075   unsigned MaskValue = 0;
21076   if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
21077     return SDValue();
21078
21079   MVT VT = N->getSimpleValueType(0);
21080   unsigned NumElems = VT.getVectorNumElements();
21081   SmallVector<int, 8> ShuffleMask(NumElems, -1);
21082   for (unsigned i = 0; i < NumElems; ++i) {
21083     // Be sure we emit undef where we can.
21084     if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
21085       ShuffleMask[i] = -1;
21086     else
21087       ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
21088   }
21089
21090   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21091   if (!TLI.isShuffleMaskLegal(ShuffleMask, VT))
21092     return SDValue();
21093   return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
21094 }
21095
21096 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
21097 /// nodes.
21098 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
21099                                     TargetLowering::DAGCombinerInfo &DCI,
21100                                     const X86Subtarget *Subtarget) {
21101   SDLoc DL(N);
21102   SDValue Cond = N->getOperand(0);
21103   // Get the LHS/RHS of the select.
21104   SDValue LHS = N->getOperand(1);
21105   SDValue RHS = N->getOperand(2);
21106   EVT VT = LHS.getValueType();
21107   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21108
21109   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
21110   // instructions match the semantics of the common C idiom x<y?x:y but not
21111   // x<=y?x:y, because of how they handle negative zero (which can be
21112   // ignored in unsafe-math mode).
21113   // We also try to create v2f32 min/max nodes, which we later widen to v4f32.
21114   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
21115       VT != MVT::f80 && (TLI.isTypeLegal(VT) || VT == MVT::v2f32) &&
21116       (Subtarget->hasSSE2() ||
21117        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
21118     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
21119
21120     unsigned Opcode = 0;
21121     // Check for x CC y ? x : y.
21122     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
21123         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
21124       switch (CC) {
21125       default: break;
21126       case ISD::SETULT:
21127         // Converting this to a min would handle NaNs incorrectly, and swapping
21128         // the operands would cause it to handle comparisons between positive
21129         // and negative zero incorrectly.
21130         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
21131           if (!DAG.getTarget().Options.UnsafeFPMath &&
21132               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
21133             break;
21134           std::swap(LHS, RHS);
21135         }
21136         Opcode = X86ISD::FMIN;
21137         break;
21138       case ISD::SETOLE:
21139         // Converting this to a min would handle comparisons between positive
21140         // and negative zero incorrectly.
21141         if (!DAG.getTarget().Options.UnsafeFPMath &&
21142             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
21143           break;
21144         Opcode = X86ISD::FMIN;
21145         break;
21146       case ISD::SETULE:
21147         // Converting this to a min would handle both negative zeros and NaNs
21148         // incorrectly, but we can swap the operands to fix both.
21149         std::swap(LHS, RHS);
21150       case ISD::SETOLT:
21151       case ISD::SETLT:
21152       case ISD::SETLE:
21153         Opcode = X86ISD::FMIN;
21154         break;
21155
21156       case ISD::SETOGE:
21157         // Converting this to a max would handle comparisons between positive
21158         // and negative zero incorrectly.
21159         if (!DAG.getTarget().Options.UnsafeFPMath &&
21160             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
21161           break;
21162         Opcode = X86ISD::FMAX;
21163         break;
21164       case ISD::SETUGT:
21165         // Converting this to a max would handle NaNs incorrectly, and swapping
21166         // the operands would cause it to handle comparisons between positive
21167         // and negative zero incorrectly.
21168         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
21169           if (!DAG.getTarget().Options.UnsafeFPMath &&
21170               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
21171             break;
21172           std::swap(LHS, RHS);
21173         }
21174         Opcode = X86ISD::FMAX;
21175         break;
21176       case ISD::SETUGE:
21177         // Converting this to a max would handle both negative zeros and NaNs
21178         // incorrectly, but we can swap the operands to fix both.
21179         std::swap(LHS, RHS);
21180       case ISD::SETOGT:
21181       case ISD::SETGT:
21182       case ISD::SETGE:
21183         Opcode = X86ISD::FMAX;
21184         break;
21185       }
21186     // Check for x CC y ? y : x -- a min/max with reversed arms.
21187     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
21188                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
21189       switch (CC) {
21190       default: break;
21191       case ISD::SETOGE:
21192         // Converting this to a min would handle comparisons between positive
21193         // and negative zero incorrectly, and swapping the operands would
21194         // cause it to handle NaNs incorrectly.
21195         if (!DAG.getTarget().Options.UnsafeFPMath &&
21196             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
21197           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
21198             break;
21199           std::swap(LHS, RHS);
21200         }
21201         Opcode = X86ISD::FMIN;
21202         break;
21203       case ISD::SETUGT:
21204         // Converting this to a min would handle NaNs incorrectly.
21205         if (!DAG.getTarget().Options.UnsafeFPMath &&
21206             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
21207           break;
21208         Opcode = X86ISD::FMIN;
21209         break;
21210       case ISD::SETUGE:
21211         // Converting this to a min would handle both negative zeros and NaNs
21212         // incorrectly, but we can swap the operands to fix both.
21213         std::swap(LHS, RHS);
21214       case ISD::SETOGT:
21215       case ISD::SETGT:
21216       case ISD::SETGE:
21217         Opcode = X86ISD::FMIN;
21218         break;
21219
21220       case ISD::SETULT:
21221         // Converting this to a max would handle NaNs incorrectly.
21222         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
21223           break;
21224         Opcode = X86ISD::FMAX;
21225         break;
21226       case ISD::SETOLE:
21227         // Converting this to a max would handle comparisons between positive
21228         // and negative zero incorrectly, and swapping the operands would
21229         // cause it to handle NaNs incorrectly.
21230         if (!DAG.getTarget().Options.UnsafeFPMath &&
21231             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
21232           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
21233             break;
21234           std::swap(LHS, RHS);
21235         }
21236         Opcode = X86ISD::FMAX;
21237         break;
21238       case ISD::SETULE:
21239         // Converting this to a max would handle both negative zeros and NaNs
21240         // incorrectly, but we can swap the operands to fix both.
21241         std::swap(LHS, RHS);
21242       case ISD::SETOLT:
21243       case ISD::SETLT:
21244       case ISD::SETLE:
21245         Opcode = X86ISD::FMAX;
21246         break;
21247       }
21248     }
21249
21250     if (Opcode)
21251       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
21252   }
21253
21254   EVT CondVT = Cond.getValueType();
21255   if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
21256       CondVT.getVectorElementType() == MVT::i1) {
21257     // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
21258     // lowering on KNL. In this case we convert it to
21259     // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
21260     // The same situation for all 128 and 256-bit vectors of i8 and i16.
21261     // Since SKX these selects have a proper lowering.
21262     EVT OpVT = LHS.getValueType();
21263     if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
21264         (OpVT.getVectorElementType() == MVT::i8 ||
21265          OpVT.getVectorElementType() == MVT::i16) &&
21266         !(Subtarget->hasBWI() && Subtarget->hasVLX())) {
21267       Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
21268       DCI.AddToWorklist(Cond.getNode());
21269       return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
21270     }
21271   }
21272   // If this is a select between two integer constants, try to do some
21273   // optimizations.
21274   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
21275     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
21276       // Don't do this for crazy integer types.
21277       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
21278         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
21279         // so that TrueC (the true value) is larger than FalseC.
21280         bool NeedsCondInvert = false;
21281
21282         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
21283             // Efficiently invertible.
21284             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
21285              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
21286               isa<ConstantSDNode>(Cond.getOperand(1))))) {
21287           NeedsCondInvert = true;
21288           std::swap(TrueC, FalseC);
21289         }
21290
21291         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
21292         if (FalseC->getAPIntValue() == 0 &&
21293             TrueC->getAPIntValue().isPowerOf2()) {
21294           if (NeedsCondInvert) // Invert the condition if needed.
21295             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
21296                                DAG.getConstant(1, DL, Cond.getValueType()));
21297
21298           // Zero extend the condition if needed.
21299           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
21300
21301           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
21302           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
21303                              DAG.getConstant(ShAmt, DL, MVT::i8));
21304         }
21305
21306         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
21307         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
21308           if (NeedsCondInvert) // Invert the condition if needed.
21309             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
21310                                DAG.getConstant(1, DL, Cond.getValueType()));
21311
21312           // Zero extend the condition if needed.
21313           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
21314                              FalseC->getValueType(0), Cond);
21315           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
21316                              SDValue(FalseC, 0));
21317         }
21318
21319         // Optimize cases that will turn into an LEA instruction.  This requires
21320         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
21321         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
21322           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
21323           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
21324
21325           bool isFastMultiplier = false;
21326           if (Diff < 10) {
21327             switch ((unsigned char)Diff) {
21328               default: break;
21329               case 1:  // result = add base, cond
21330               case 2:  // result = lea base(    , cond*2)
21331               case 3:  // result = lea base(cond, cond*2)
21332               case 4:  // result = lea base(    , cond*4)
21333               case 5:  // result = lea base(cond, cond*4)
21334               case 8:  // result = lea base(    , cond*8)
21335               case 9:  // result = lea base(cond, cond*8)
21336                 isFastMultiplier = true;
21337                 break;
21338             }
21339           }
21340
21341           if (isFastMultiplier) {
21342             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
21343             if (NeedsCondInvert) // Invert the condition if needed.
21344               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
21345                                  DAG.getConstant(1, DL, Cond.getValueType()));
21346
21347             // Zero extend the condition if needed.
21348             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
21349                                Cond);
21350             // Scale the condition by the difference.
21351             if (Diff != 1)
21352               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
21353                                  DAG.getConstant(Diff, DL,
21354                                                  Cond.getValueType()));
21355
21356             // Add the base if non-zero.
21357             if (FalseC->getAPIntValue() != 0)
21358               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
21359                                  SDValue(FalseC, 0));
21360             return Cond;
21361           }
21362         }
21363       }
21364   }
21365
21366   // Canonicalize max and min:
21367   // (x > y) ? x : y -> (x >= y) ? x : y
21368   // (x < y) ? x : y -> (x <= y) ? x : y
21369   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
21370   // the need for an extra compare
21371   // against zero. e.g.
21372   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
21373   // subl   %esi, %edi
21374   // testl  %edi, %edi
21375   // movl   $0, %eax
21376   // cmovgl %edi, %eax
21377   // =>
21378   // xorl   %eax, %eax
21379   // subl   %esi, $edi
21380   // cmovsl %eax, %edi
21381   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
21382       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
21383       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
21384     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
21385     switch (CC) {
21386     default: break;
21387     case ISD::SETLT:
21388     case ISD::SETGT: {
21389       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
21390       Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
21391                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
21392       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
21393     }
21394     }
21395   }
21396
21397   // Early exit check
21398   if (!TLI.isTypeLegal(VT))
21399     return SDValue();
21400
21401   // Match VSELECTs into subs with unsigned saturation.
21402   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
21403       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
21404       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
21405        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
21406     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
21407
21408     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
21409     // left side invert the predicate to simplify logic below.
21410     SDValue Other;
21411     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
21412       Other = RHS;
21413       CC = ISD::getSetCCInverse(CC, true);
21414     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
21415       Other = LHS;
21416     }
21417
21418     if (Other.getNode() && Other->getNumOperands() == 2 &&
21419         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
21420       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
21421       SDValue CondRHS = Cond->getOperand(1);
21422
21423       // Look for a general sub with unsigned saturation first.
21424       // x >= y ? x-y : 0 --> subus x, y
21425       // x >  y ? x-y : 0 --> subus x, y
21426       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
21427           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
21428         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
21429
21430       if (auto *OpRHSBV = dyn_cast<BuildVectorSDNode>(OpRHS))
21431         if (auto *OpRHSConst = OpRHSBV->getConstantSplatNode()) {
21432           if (auto *CondRHSBV = dyn_cast<BuildVectorSDNode>(CondRHS))
21433             if (auto *CondRHSConst = CondRHSBV->getConstantSplatNode())
21434               // If the RHS is a constant we have to reverse the const
21435               // canonicalization.
21436               // x > C-1 ? x+-C : 0 --> subus x, C
21437               if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
21438                   CondRHSConst->getAPIntValue() ==
21439                       (-OpRHSConst->getAPIntValue() - 1))
21440                 return DAG.getNode(
21441                     X86ISD::SUBUS, DL, VT, OpLHS,
21442                     DAG.getConstant(-OpRHSConst->getAPIntValue(), DL, VT));
21443
21444           // Another special case: If C was a sign bit, the sub has been
21445           // canonicalized into a xor.
21446           // FIXME: Would it be better to use computeKnownBits to determine
21447           //        whether it's safe to decanonicalize the xor?
21448           // x s< 0 ? x^C : 0 --> subus x, C
21449           if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
21450               ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
21451               OpRHSConst->getAPIntValue().isSignBit())
21452             // Note that we have to rebuild the RHS constant here to ensure we
21453             // don't rely on particular values of undef lanes.
21454             return DAG.getNode(
21455                 X86ISD::SUBUS, DL, VT, OpLHS,
21456                 DAG.getConstant(OpRHSConst->getAPIntValue(), DL, VT));
21457         }
21458     }
21459   }
21460
21461   // Try to match a min/max vector operation.
21462   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
21463     std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
21464     unsigned Opc = ret.first;
21465     bool NeedSplit = ret.second;
21466
21467     if (Opc && NeedSplit) {
21468       unsigned NumElems = VT.getVectorNumElements();
21469       // Extract the LHS vectors
21470       SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
21471       SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
21472
21473       // Extract the RHS vectors
21474       SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
21475       SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
21476
21477       // Create min/max for each subvector
21478       LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
21479       RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
21480
21481       // Merge the result
21482       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
21483     } else if (Opc)
21484       return DAG.getNode(Opc, DL, VT, LHS, RHS);
21485   }
21486
21487   // Simplify vector selection if condition value type matches vselect
21488   // operand type
21489   if (N->getOpcode() == ISD::VSELECT && CondVT == VT) {
21490     assert(Cond.getValueType().isVector() &&
21491            "vector select expects a vector selector!");
21492
21493     bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
21494     bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
21495
21496     // Try invert the condition if true value is not all 1s and false value
21497     // is not all 0s.
21498     if (!TValIsAllOnes && !FValIsAllZeros &&
21499         // Check if the selector will be produced by CMPP*/PCMP*
21500         Cond.getOpcode() == ISD::SETCC &&
21501         // Check if SETCC has already been promoted
21502         TLI.getSetCCResultType(*DAG.getContext(), VT) == CondVT) {
21503       bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
21504       bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
21505
21506       if (TValIsAllZeros || FValIsAllOnes) {
21507         SDValue CC = Cond.getOperand(2);
21508         ISD::CondCode NewCC =
21509           ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
21510                                Cond.getOperand(0).getValueType().isInteger());
21511         Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
21512         std::swap(LHS, RHS);
21513         TValIsAllOnes = FValIsAllOnes;
21514         FValIsAllZeros = TValIsAllZeros;
21515       }
21516     }
21517
21518     if (TValIsAllOnes || FValIsAllZeros) {
21519       SDValue Ret;
21520
21521       if (TValIsAllOnes && FValIsAllZeros)
21522         Ret = Cond;
21523       else if (TValIsAllOnes)
21524         Ret = DAG.getNode(ISD::OR, DL, CondVT, Cond,
21525                           DAG.getNode(ISD::BITCAST, DL, CondVT, RHS));
21526       else if (FValIsAllZeros)
21527         Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
21528                           DAG.getNode(ISD::BITCAST, DL, CondVT, LHS));
21529
21530       return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
21531     }
21532   }
21533
21534   // We should generate an X86ISD::BLENDI from a vselect if its argument
21535   // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
21536   // constants. This specific pattern gets generated when we split a
21537   // selector for a 512 bit vector in a machine without AVX512 (but with
21538   // 256-bit vectors), during legalization:
21539   //
21540   // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
21541   //
21542   // Iff we find this pattern and the build_vectors are built from
21543   // constants, we translate the vselect into a shuffle_vector that we
21544   // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
21545   if ((N->getOpcode() == ISD::VSELECT ||
21546        N->getOpcode() == X86ISD::SHRUNKBLEND) &&
21547       !DCI.isBeforeLegalize()) {
21548     SDValue Shuffle = transformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
21549     if (Shuffle.getNode())
21550       return Shuffle;
21551   }
21552
21553   // If this is a *dynamic* select (non-constant condition) and we can match
21554   // this node with one of the variable blend instructions, restructure the
21555   // condition so that the blends can use the high bit of each element and use
21556   // SimplifyDemandedBits to simplify the condition operand.
21557   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
21558       !DCI.isBeforeLegalize() &&
21559       !ISD::isBuildVectorOfConstantSDNodes(Cond.getNode())) {
21560     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
21561
21562     // Don't optimize vector selects that map to mask-registers.
21563     if (BitWidth == 1)
21564       return SDValue();
21565
21566     // We can only handle the cases where VSELECT is directly legal on the
21567     // subtarget. We custom lower VSELECT nodes with constant conditions and
21568     // this makes it hard to see whether a dynamic VSELECT will correctly
21569     // lower, so we both check the operation's status and explicitly handle the
21570     // cases where a *dynamic* blend will fail even though a constant-condition
21571     // blend could be custom lowered.
21572     // FIXME: We should find a better way to handle this class of problems.
21573     // Potentially, we should combine constant-condition vselect nodes
21574     // pre-legalization into shuffles and not mark as many types as custom
21575     // lowered.
21576     if (!TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
21577       return SDValue();
21578     // FIXME: We don't support i16-element blends currently. We could and
21579     // should support them by making *all* the bits in the condition be set
21580     // rather than just the high bit and using an i8-element blend.
21581     if (VT.getScalarType() == MVT::i16)
21582       return SDValue();
21583     // Dynamic blending was only available from SSE4.1 onward.
21584     if (VT.getSizeInBits() == 128 && !Subtarget->hasSSE41())
21585       return SDValue();
21586     // Byte blends are only available in AVX2
21587     if (VT.getSizeInBits() == 256 && VT.getScalarType() == MVT::i8 &&
21588         !Subtarget->hasAVX2())
21589       return SDValue();
21590
21591     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
21592     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
21593
21594     APInt KnownZero, KnownOne;
21595     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
21596                                           DCI.isBeforeLegalizeOps());
21597     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
21598         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne,
21599                                  TLO)) {
21600       // If we changed the computation somewhere in the DAG, this change
21601       // will affect all users of Cond.
21602       // Make sure it is fine and update all the nodes so that we do not
21603       // use the generic VSELECT anymore. Otherwise, we may perform
21604       // wrong optimizations as we messed up with the actual expectation
21605       // for the vector boolean values.
21606       if (Cond != TLO.Old) {
21607         // Check all uses of that condition operand to check whether it will be
21608         // consumed by non-BLEND instructions, which may depend on all bits are
21609         // set properly.
21610         for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
21611              I != E; ++I)
21612           if (I->getOpcode() != ISD::VSELECT)
21613             // TODO: Add other opcodes eventually lowered into BLEND.
21614             return SDValue();
21615
21616         // Update all the users of the condition, before committing the change,
21617         // so that the VSELECT optimizations that expect the correct vector
21618         // boolean value will not be triggered.
21619         for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
21620              I != E; ++I)
21621           DAG.ReplaceAllUsesOfValueWith(
21622               SDValue(*I, 0),
21623               DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(*I), I->getValueType(0),
21624                           Cond, I->getOperand(1), I->getOperand(2)));
21625         DCI.CommitTargetLoweringOpt(TLO);
21626         return SDValue();
21627       }
21628       // At this point, only Cond is changed. Change the condition
21629       // just for N to keep the opportunity to optimize all other
21630       // users their own way.
21631       DAG.ReplaceAllUsesOfValueWith(
21632           SDValue(N, 0),
21633           DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(N), N->getValueType(0),
21634                       TLO.New, N->getOperand(1), N->getOperand(2)));
21635       return SDValue();
21636     }
21637   }
21638
21639   return SDValue();
21640 }
21641
21642 // Check whether a boolean test is testing a boolean value generated by
21643 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
21644 // code.
21645 //
21646 // Simplify the following patterns:
21647 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
21648 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
21649 // to (Op EFLAGS Cond)
21650 //
21651 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
21652 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
21653 // to (Op EFLAGS !Cond)
21654 //
21655 // where Op could be BRCOND or CMOV.
21656 //
21657 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
21658   // Quit if not CMP and SUB with its value result used.
21659   if (Cmp.getOpcode() != X86ISD::CMP &&
21660       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
21661       return SDValue();
21662
21663   // Quit if not used as a boolean value.
21664   if (CC != X86::COND_E && CC != X86::COND_NE)
21665     return SDValue();
21666
21667   // Check CMP operands. One of them should be 0 or 1 and the other should be
21668   // an SetCC or extended from it.
21669   SDValue Op1 = Cmp.getOperand(0);
21670   SDValue Op2 = Cmp.getOperand(1);
21671
21672   SDValue SetCC;
21673   const ConstantSDNode* C = nullptr;
21674   bool needOppositeCond = (CC == X86::COND_E);
21675   bool checkAgainstTrue = false; // Is it a comparison against 1?
21676
21677   if ((C = dyn_cast<ConstantSDNode>(Op1)))
21678     SetCC = Op2;
21679   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
21680     SetCC = Op1;
21681   else // Quit if all operands are not constants.
21682     return SDValue();
21683
21684   if (C->getZExtValue() == 1) {
21685     needOppositeCond = !needOppositeCond;
21686     checkAgainstTrue = true;
21687   } else if (C->getZExtValue() != 0)
21688     // Quit if the constant is neither 0 or 1.
21689     return SDValue();
21690
21691   bool truncatedToBoolWithAnd = false;
21692   // Skip (zext $x), (trunc $x), or (and $x, 1) node.
21693   while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
21694          SetCC.getOpcode() == ISD::TRUNCATE ||
21695          SetCC.getOpcode() == ISD::AND) {
21696     if (SetCC.getOpcode() == ISD::AND) {
21697       int OpIdx = -1;
21698       ConstantSDNode *CS;
21699       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
21700           CS->getZExtValue() == 1)
21701         OpIdx = 1;
21702       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
21703           CS->getZExtValue() == 1)
21704         OpIdx = 0;
21705       if (OpIdx == -1)
21706         break;
21707       SetCC = SetCC.getOperand(OpIdx);
21708       truncatedToBoolWithAnd = true;
21709     } else
21710       SetCC = SetCC.getOperand(0);
21711   }
21712
21713   switch (SetCC.getOpcode()) {
21714   case X86ISD::SETCC_CARRY:
21715     // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
21716     // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
21717     // i.e. it's a comparison against true but the result of SETCC_CARRY is not
21718     // truncated to i1 using 'and'.
21719     if (checkAgainstTrue && !truncatedToBoolWithAnd)
21720       break;
21721     assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
21722            "Invalid use of SETCC_CARRY!");
21723     // FALL THROUGH
21724   case X86ISD::SETCC:
21725     // Set the condition code or opposite one if necessary.
21726     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
21727     if (needOppositeCond)
21728       CC = X86::GetOppositeBranchCondition(CC);
21729     return SetCC.getOperand(1);
21730   case X86ISD::CMOV: {
21731     // Check whether false/true value has canonical one, i.e. 0 or 1.
21732     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
21733     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
21734     // Quit if true value is not a constant.
21735     if (!TVal)
21736       return SDValue();
21737     // Quit if false value is not a constant.
21738     if (!FVal) {
21739       SDValue Op = SetCC.getOperand(0);
21740       // Skip 'zext' or 'trunc' node.
21741       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
21742           Op.getOpcode() == ISD::TRUNCATE)
21743         Op = Op.getOperand(0);
21744       // A special case for rdrand/rdseed, where 0 is set if false cond is
21745       // found.
21746       if ((Op.getOpcode() != X86ISD::RDRAND &&
21747            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
21748         return SDValue();
21749     }
21750     // Quit if false value is not the constant 0 or 1.
21751     bool FValIsFalse = true;
21752     if (FVal && FVal->getZExtValue() != 0) {
21753       if (FVal->getZExtValue() != 1)
21754         return SDValue();
21755       // If FVal is 1, opposite cond is needed.
21756       needOppositeCond = !needOppositeCond;
21757       FValIsFalse = false;
21758     }
21759     // Quit if TVal is not the constant opposite of FVal.
21760     if (FValIsFalse && TVal->getZExtValue() != 1)
21761       return SDValue();
21762     if (!FValIsFalse && TVal->getZExtValue() != 0)
21763       return SDValue();
21764     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
21765     if (needOppositeCond)
21766       CC = X86::GetOppositeBranchCondition(CC);
21767     return SetCC.getOperand(3);
21768   }
21769   }
21770
21771   return SDValue();
21772 }
21773
21774 /// Check whether Cond is an AND/OR of SETCCs off of the same EFLAGS.
21775 /// Match:
21776 ///   (X86or (X86setcc) (X86setcc))
21777 ///   (X86cmp (and (X86setcc) (X86setcc)), 0)
21778 static bool checkBoolTestAndOrSetCCCombine(SDValue Cond, X86::CondCode &CC0,
21779                                            X86::CondCode &CC1, SDValue &Flags,
21780                                            bool &isAnd) {
21781   if (Cond->getOpcode() == X86ISD::CMP) {
21782     ConstantSDNode *CondOp1C = dyn_cast<ConstantSDNode>(Cond->getOperand(1));
21783     if (!CondOp1C || !CondOp1C->isNullValue())
21784       return false;
21785
21786     Cond = Cond->getOperand(0);
21787   }
21788
21789   isAnd = false;
21790
21791   SDValue SetCC0, SetCC1;
21792   switch (Cond->getOpcode()) {
21793   default: return false;
21794   case ISD::AND:
21795   case X86ISD::AND:
21796     isAnd = true;
21797     // fallthru
21798   case ISD::OR:
21799   case X86ISD::OR:
21800     SetCC0 = Cond->getOperand(0);
21801     SetCC1 = Cond->getOperand(1);
21802     break;
21803   };
21804
21805   // Make sure we have SETCC nodes, using the same flags value.
21806   if (SetCC0.getOpcode() != X86ISD::SETCC ||
21807       SetCC1.getOpcode() != X86ISD::SETCC ||
21808       SetCC0->getOperand(1) != SetCC1->getOperand(1))
21809     return false;
21810
21811   CC0 = (X86::CondCode)SetCC0->getConstantOperandVal(0);
21812   CC1 = (X86::CondCode)SetCC1->getConstantOperandVal(0);
21813   Flags = SetCC0->getOperand(1);
21814   return true;
21815 }
21816
21817 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
21818 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
21819                                   TargetLowering::DAGCombinerInfo &DCI,
21820                                   const X86Subtarget *Subtarget) {
21821   SDLoc DL(N);
21822
21823   // If the flag operand isn't dead, don't touch this CMOV.
21824   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
21825     return SDValue();
21826
21827   SDValue FalseOp = N->getOperand(0);
21828   SDValue TrueOp = N->getOperand(1);
21829   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
21830   SDValue Cond = N->getOperand(3);
21831
21832   if (CC == X86::COND_E || CC == X86::COND_NE) {
21833     switch (Cond.getOpcode()) {
21834     default: break;
21835     case X86ISD::BSR:
21836     case X86ISD::BSF:
21837       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
21838       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
21839         return (CC == X86::COND_E) ? FalseOp : TrueOp;
21840     }
21841   }
21842
21843   SDValue Flags;
21844
21845   Flags = checkBoolTestSetCCCombine(Cond, CC);
21846   if (Flags.getNode() &&
21847       // Extra check as FCMOV only supports a subset of X86 cond.
21848       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
21849     SDValue Ops[] = { FalseOp, TrueOp,
21850                       DAG.getConstant(CC, DL, MVT::i8), Flags };
21851     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
21852   }
21853
21854   // If this is a select between two integer constants, try to do some
21855   // optimizations.  Note that the operands are ordered the opposite of SELECT
21856   // operands.
21857   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
21858     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
21859       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
21860       // larger than FalseC (the false value).
21861       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
21862         CC = X86::GetOppositeBranchCondition(CC);
21863         std::swap(TrueC, FalseC);
21864         std::swap(TrueOp, FalseOp);
21865       }
21866
21867       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
21868       // This is efficient for any integer data type (including i8/i16) and
21869       // shift amount.
21870       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
21871         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
21872                            DAG.getConstant(CC, DL, MVT::i8), Cond);
21873
21874         // Zero extend the condition if needed.
21875         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
21876
21877         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
21878         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
21879                            DAG.getConstant(ShAmt, DL, MVT::i8));
21880         if (N->getNumValues() == 2)  // Dead flag value?
21881           return DCI.CombineTo(N, Cond, SDValue());
21882         return Cond;
21883       }
21884
21885       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
21886       // for any integer data type, including i8/i16.
21887       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
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,
21893                            FalseC->getValueType(0), Cond);
21894         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
21895                            SDValue(FalseC, 0));
21896
21897         if (N->getNumValues() == 2)  // Dead flag value?
21898           return DCI.CombineTo(N, Cond, SDValue());
21899         return Cond;
21900       }
21901
21902       // Optimize cases that will turn into an LEA instruction.  This requires
21903       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
21904       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
21905         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
21906         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
21907
21908         bool isFastMultiplier = false;
21909         if (Diff < 10) {
21910           switch ((unsigned char)Diff) {
21911           default: break;
21912           case 1:  // result = add base, cond
21913           case 2:  // result = lea base(    , cond*2)
21914           case 3:  // result = lea base(cond, cond*2)
21915           case 4:  // result = lea base(    , cond*4)
21916           case 5:  // result = lea base(cond, cond*4)
21917           case 8:  // result = lea base(    , cond*8)
21918           case 9:  // result = lea base(cond, cond*8)
21919             isFastMultiplier = true;
21920             break;
21921           }
21922         }
21923
21924         if (isFastMultiplier) {
21925           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
21926           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
21927                              DAG.getConstant(CC, DL, MVT::i8), Cond);
21928           // Zero extend the condition if needed.
21929           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
21930                              Cond);
21931           // Scale the condition by the difference.
21932           if (Diff != 1)
21933             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
21934                                DAG.getConstant(Diff, DL, Cond.getValueType()));
21935
21936           // Add the base if non-zero.
21937           if (FalseC->getAPIntValue() != 0)
21938             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
21939                                SDValue(FalseC, 0));
21940           if (N->getNumValues() == 2)  // Dead flag value?
21941             return DCI.CombineTo(N, Cond, SDValue());
21942           return Cond;
21943         }
21944       }
21945     }
21946   }
21947
21948   // Handle these cases:
21949   //   (select (x != c), e, c) -> select (x != c), e, x),
21950   //   (select (x == c), c, e) -> select (x == c), x, e)
21951   // where the c is an integer constant, and the "select" is the combination
21952   // of CMOV and CMP.
21953   //
21954   // The rationale for this change is that the conditional-move from a constant
21955   // needs two instructions, however, conditional-move from a register needs
21956   // only one instruction.
21957   //
21958   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
21959   //  some instruction-combining opportunities. This opt needs to be
21960   //  postponed as late as possible.
21961   //
21962   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
21963     // the DCI.xxxx conditions are provided to postpone the optimization as
21964     // late as possible.
21965
21966     ConstantSDNode *CmpAgainst = nullptr;
21967     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
21968         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
21969         !isa<ConstantSDNode>(Cond.getOperand(0))) {
21970
21971       if (CC == X86::COND_NE &&
21972           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
21973         CC = X86::GetOppositeBranchCondition(CC);
21974         std::swap(TrueOp, FalseOp);
21975       }
21976
21977       if (CC == X86::COND_E &&
21978           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
21979         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
21980                           DAG.getConstant(CC, DL, MVT::i8), Cond };
21981         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
21982       }
21983     }
21984   }
21985
21986   // Fold and/or of setcc's to double CMOV:
21987   //   (CMOV F, T, ((cc1 | cc2) != 0)) -> (CMOV (CMOV F, T, cc1), T, cc2)
21988   //   (CMOV F, T, ((cc1 & cc2) != 0)) -> (CMOV (CMOV T, F, !cc1), F, !cc2)
21989   //
21990   // This combine lets us generate:
21991   //   cmovcc1 (jcc1 if we don't have CMOV)
21992   //   cmovcc2 (same)
21993   // instead of:
21994   //   setcc1
21995   //   setcc2
21996   //   and/or
21997   //   cmovne (jne if we don't have CMOV)
21998   // When we can't use the CMOV instruction, it might increase branch
21999   // mispredicts.
22000   // When we can use CMOV, or when there is no mispredict, this improves
22001   // throughput and reduces register pressure.
22002   //
22003   if (CC == X86::COND_NE) {
22004     SDValue Flags;
22005     X86::CondCode CC0, CC1;
22006     bool isAndSetCC;
22007     if (checkBoolTestAndOrSetCCCombine(Cond, CC0, CC1, Flags, isAndSetCC)) {
22008       if (isAndSetCC) {
22009         std::swap(FalseOp, TrueOp);
22010         CC0 = X86::GetOppositeBranchCondition(CC0);
22011         CC1 = X86::GetOppositeBranchCondition(CC1);
22012       }
22013
22014       SDValue LOps[] = {FalseOp, TrueOp, DAG.getConstant(CC0, DL, MVT::i8),
22015         Flags};
22016       SDValue LCMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), LOps);
22017       SDValue Ops[] = {LCMOV, TrueOp, DAG.getConstant(CC1, DL, MVT::i8), Flags};
22018       SDValue CMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
22019       DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SDValue(CMOV.getNode(), 1));
22020       return CMOV;
22021     }
22022   }
22023
22024   return SDValue();
22025 }
22026
22027 static SDValue PerformINTRINSIC_WO_CHAINCombine(SDNode *N, SelectionDAG &DAG,
22028                                                 const X86Subtarget *Subtarget) {
22029   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
22030   switch (IntNo) {
22031   default: return SDValue();
22032   // SSE/AVX/AVX2 blend intrinsics.
22033   case Intrinsic::x86_avx2_pblendvb:
22034     // Don't try to simplify this intrinsic if we don't have AVX2.
22035     if (!Subtarget->hasAVX2())
22036       return SDValue();
22037     // FALL-THROUGH
22038   case Intrinsic::x86_avx_blendv_pd_256:
22039   case Intrinsic::x86_avx_blendv_ps_256:
22040     // Don't try to simplify this intrinsic if we don't have AVX.
22041     if (!Subtarget->hasAVX())
22042       return SDValue();
22043     // FALL-THROUGH
22044   case Intrinsic::x86_sse41_blendvps:
22045   case Intrinsic::x86_sse41_blendvpd:
22046   case Intrinsic::x86_sse41_pblendvb: {
22047     SDValue Op0 = N->getOperand(1);
22048     SDValue Op1 = N->getOperand(2);
22049     SDValue Mask = N->getOperand(3);
22050
22051     // Don't try to simplify this intrinsic if we don't have SSE4.1.
22052     if (!Subtarget->hasSSE41())
22053       return SDValue();
22054
22055     // fold (blend A, A, Mask) -> A
22056     if (Op0 == Op1)
22057       return Op0;
22058     // fold (blend A, B, allZeros) -> A
22059     if (ISD::isBuildVectorAllZeros(Mask.getNode()))
22060       return Op0;
22061     // fold (blend A, B, allOnes) -> B
22062     if (ISD::isBuildVectorAllOnes(Mask.getNode()))
22063       return Op1;
22064
22065     // Simplify the case where the mask is a constant i32 value.
22066     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Mask)) {
22067       if (C->isNullValue())
22068         return Op0;
22069       if (C->isAllOnesValue())
22070         return Op1;
22071     }
22072
22073     return SDValue();
22074   }
22075
22076   // Packed SSE2/AVX2 arithmetic shift immediate intrinsics.
22077   case Intrinsic::x86_sse2_psrai_w:
22078   case Intrinsic::x86_sse2_psrai_d:
22079   case Intrinsic::x86_avx2_psrai_w:
22080   case Intrinsic::x86_avx2_psrai_d:
22081   case Intrinsic::x86_sse2_psra_w:
22082   case Intrinsic::x86_sse2_psra_d:
22083   case Intrinsic::x86_avx2_psra_w:
22084   case Intrinsic::x86_avx2_psra_d: {
22085     SDValue Op0 = N->getOperand(1);
22086     SDValue Op1 = N->getOperand(2);
22087     EVT VT = Op0.getValueType();
22088     assert(VT.isVector() && "Expected a vector type!");
22089
22090     if (isa<BuildVectorSDNode>(Op1))
22091       Op1 = Op1.getOperand(0);
22092
22093     if (!isa<ConstantSDNode>(Op1))
22094       return SDValue();
22095
22096     EVT SVT = VT.getVectorElementType();
22097     unsigned SVTBits = SVT.getSizeInBits();
22098
22099     ConstantSDNode *CND = cast<ConstantSDNode>(Op1);
22100     const APInt &C = APInt(SVTBits, CND->getAPIntValue().getZExtValue());
22101     uint64_t ShAmt = C.getZExtValue();
22102
22103     // Don't try to convert this shift into a ISD::SRA if the shift
22104     // count is bigger than or equal to the element size.
22105     if (ShAmt >= SVTBits)
22106       return SDValue();
22107
22108     // Trivial case: if the shift count is zero, then fold this
22109     // into the first operand.
22110     if (ShAmt == 0)
22111       return Op0;
22112
22113     // Replace this packed shift intrinsic with a target independent
22114     // shift dag node.
22115     SDLoc DL(N);
22116     SDValue Splat = DAG.getConstant(C, DL, VT);
22117     return DAG.getNode(ISD::SRA, DL, VT, Op0, Splat);
22118   }
22119   }
22120 }
22121
22122 /// PerformMulCombine - Optimize a single multiply with constant into two
22123 /// in order to implement it with two cheaper instructions, e.g.
22124 /// LEA + SHL, LEA + LEA.
22125 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
22126                                  TargetLowering::DAGCombinerInfo &DCI) {
22127   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
22128     return SDValue();
22129
22130   EVT VT = N->getValueType(0);
22131   if (VT != MVT::i64 && VT != MVT::i32)
22132     return SDValue();
22133
22134   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
22135   if (!C)
22136     return SDValue();
22137   uint64_t MulAmt = C->getZExtValue();
22138   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
22139     return SDValue();
22140
22141   uint64_t MulAmt1 = 0;
22142   uint64_t MulAmt2 = 0;
22143   if ((MulAmt % 9) == 0) {
22144     MulAmt1 = 9;
22145     MulAmt2 = MulAmt / 9;
22146   } else if ((MulAmt % 5) == 0) {
22147     MulAmt1 = 5;
22148     MulAmt2 = MulAmt / 5;
22149   } else if ((MulAmt % 3) == 0) {
22150     MulAmt1 = 3;
22151     MulAmt2 = MulAmt / 3;
22152   }
22153   if (MulAmt2 &&
22154       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
22155     SDLoc DL(N);
22156
22157     if (isPowerOf2_64(MulAmt2) &&
22158         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
22159       // If second multiplifer is pow2, issue it first. We want the multiply by
22160       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
22161       // is an add.
22162       std::swap(MulAmt1, MulAmt2);
22163
22164     SDValue NewMul;
22165     if (isPowerOf2_64(MulAmt1))
22166       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
22167                            DAG.getConstant(Log2_64(MulAmt1), DL, MVT::i8));
22168     else
22169       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
22170                            DAG.getConstant(MulAmt1, DL, VT));
22171
22172     if (isPowerOf2_64(MulAmt2))
22173       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
22174                            DAG.getConstant(Log2_64(MulAmt2), DL, MVT::i8));
22175     else
22176       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
22177                            DAG.getConstant(MulAmt2, DL, VT));
22178
22179     // Do not add new nodes to DAG combiner worklist.
22180     DCI.CombineTo(N, NewMul, false);
22181   }
22182   return SDValue();
22183 }
22184
22185 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
22186   SDValue N0 = N->getOperand(0);
22187   SDValue N1 = N->getOperand(1);
22188   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
22189   EVT VT = N0.getValueType();
22190
22191   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
22192   // since the result of setcc_c is all zero's or all ones.
22193   if (VT.isInteger() && !VT.isVector() &&
22194       N1C && N0.getOpcode() == ISD::AND &&
22195       N0.getOperand(1).getOpcode() == ISD::Constant) {
22196     SDValue N00 = N0.getOperand(0);
22197     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
22198         ((N00.getOpcode() == ISD::ANY_EXTEND ||
22199           N00.getOpcode() == ISD::ZERO_EXTEND) &&
22200          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
22201       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
22202       APInt ShAmt = N1C->getAPIntValue();
22203       Mask = Mask.shl(ShAmt);
22204       if (Mask != 0) {
22205         SDLoc DL(N);
22206         return DAG.getNode(ISD::AND, DL, VT,
22207                            N00, DAG.getConstant(Mask, DL, VT));
22208       }
22209     }
22210   }
22211
22212   // Hardware support for vector shifts is sparse which makes us scalarize the
22213   // vector operations in many cases. Also, on sandybridge ADD is faster than
22214   // shl.
22215   // (shl V, 1) -> add V,V
22216   if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
22217     if (auto *N1SplatC = N1BV->getConstantSplatNode()) {
22218       assert(N0.getValueType().isVector() && "Invalid vector shift type");
22219       // We shift all of the values by one. In many cases we do not have
22220       // hardware support for this operation. This is better expressed as an ADD
22221       // of two values.
22222       if (N1SplatC->getZExtValue() == 1)
22223         return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
22224     }
22225
22226   return SDValue();
22227 }
22228
22229 /// \brief Returns a vector of 0s if the node in input is a vector logical
22230 /// shift by a constant amount which is known to be bigger than or equal
22231 /// to the vector element size in bits.
22232 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
22233                                       const X86Subtarget *Subtarget) {
22234   EVT VT = N->getValueType(0);
22235
22236   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
22237       (!Subtarget->hasInt256() ||
22238        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
22239     return SDValue();
22240
22241   SDValue Amt = N->getOperand(1);
22242   SDLoc DL(N);
22243   if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Amt))
22244     if (auto *AmtSplat = AmtBV->getConstantSplatNode()) {
22245       APInt ShiftAmt = AmtSplat->getAPIntValue();
22246       unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
22247
22248       // SSE2/AVX2 logical shifts always return a vector of 0s
22249       // if the shift amount is bigger than or equal to
22250       // the element size. The constant shift amount will be
22251       // encoded as a 8-bit immediate.
22252       if (ShiftAmt.trunc(8).uge(MaxAmount))
22253         return getZeroVector(VT, Subtarget, DAG, DL);
22254     }
22255
22256   return SDValue();
22257 }
22258
22259 /// PerformShiftCombine - Combine shifts.
22260 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
22261                                    TargetLowering::DAGCombinerInfo &DCI,
22262                                    const X86Subtarget *Subtarget) {
22263   if (N->getOpcode() == ISD::SHL) {
22264     SDValue V = PerformSHLCombine(N, DAG);
22265     if (V.getNode()) return V;
22266   }
22267
22268   if (N->getOpcode() != ISD::SRA) {
22269     // Try to fold this logical shift into a zero vector.
22270     SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
22271     if (V.getNode()) return V;
22272   }
22273
22274   return SDValue();
22275 }
22276
22277 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
22278 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
22279 // and friends.  Likewise for OR -> CMPNEQSS.
22280 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
22281                             TargetLowering::DAGCombinerInfo &DCI,
22282                             const X86Subtarget *Subtarget) {
22283   unsigned opcode;
22284
22285   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
22286   // we're requiring SSE2 for both.
22287   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
22288     SDValue N0 = N->getOperand(0);
22289     SDValue N1 = N->getOperand(1);
22290     SDValue CMP0 = N0->getOperand(1);
22291     SDValue CMP1 = N1->getOperand(1);
22292     SDLoc DL(N);
22293
22294     // The SETCCs should both refer to the same CMP.
22295     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
22296       return SDValue();
22297
22298     SDValue CMP00 = CMP0->getOperand(0);
22299     SDValue CMP01 = CMP0->getOperand(1);
22300     EVT     VT    = CMP00.getValueType();
22301
22302     if (VT == MVT::f32 || VT == MVT::f64) {
22303       bool ExpectingFlags = false;
22304       // Check for any users that want flags:
22305       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
22306            !ExpectingFlags && UI != UE; ++UI)
22307         switch (UI->getOpcode()) {
22308         default:
22309         case ISD::BR_CC:
22310         case ISD::BRCOND:
22311         case ISD::SELECT:
22312           ExpectingFlags = true;
22313           break;
22314         case ISD::CopyToReg:
22315         case ISD::SIGN_EXTEND:
22316         case ISD::ZERO_EXTEND:
22317         case ISD::ANY_EXTEND:
22318           break;
22319         }
22320
22321       if (!ExpectingFlags) {
22322         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
22323         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
22324
22325         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
22326           X86::CondCode tmp = cc0;
22327           cc0 = cc1;
22328           cc1 = tmp;
22329         }
22330
22331         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
22332             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
22333           // FIXME: need symbolic constants for these magic numbers.
22334           // See X86ATTInstPrinter.cpp:printSSECC().
22335           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
22336           if (Subtarget->hasAVX512()) {
22337             SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
22338                                          CMP01,
22339                                          DAG.getConstant(x86cc, DL, MVT::i8));
22340             if (N->getValueType(0) != MVT::i1)
22341               return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
22342                                  FSetCC);
22343             return FSetCC;
22344           }
22345           SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
22346                                               CMP00.getValueType(), CMP00, CMP01,
22347                                               DAG.getConstant(x86cc, DL,
22348                                                               MVT::i8));
22349
22350           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
22351           MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
22352
22353           if (is64BitFP && !Subtarget->is64Bit()) {
22354             // On a 32-bit target, we cannot bitcast the 64-bit float to a
22355             // 64-bit integer, since that's not a legal type. Since
22356             // OnesOrZeroesF is all ones of all zeroes, we don't need all the
22357             // bits, but can do this little dance to extract the lowest 32 bits
22358             // and work with those going forward.
22359             SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
22360                                            OnesOrZeroesF);
22361             SDValue Vector32 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f32,
22362                                            Vector64);
22363             OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
22364                                         Vector32, DAG.getIntPtrConstant(0, DL));
22365             IntVT = MVT::i32;
22366           }
22367
22368           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, IntVT,
22369                                               OnesOrZeroesF);
22370           SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
22371                                       DAG.getConstant(1, DL, IntVT));
22372           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8,
22373                                               ANDed);
22374           return OneBitOfTruth;
22375         }
22376       }
22377     }
22378   }
22379   return SDValue();
22380 }
22381
22382 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
22383 /// so it can be folded inside ANDNP.
22384 static bool CanFoldXORWithAllOnes(const SDNode *N) {
22385   EVT VT = N->getValueType(0);
22386
22387   // Match direct AllOnes for 128 and 256-bit vectors
22388   if (ISD::isBuildVectorAllOnes(N))
22389     return true;
22390
22391   // Look through a bit convert.
22392   if (N->getOpcode() == ISD::BITCAST)
22393     N = N->getOperand(0).getNode();
22394
22395   // Sometimes the operand may come from a insert_subvector building a 256-bit
22396   // allones vector
22397   if (VT.is256BitVector() &&
22398       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
22399     SDValue V1 = N->getOperand(0);
22400     SDValue V2 = N->getOperand(1);
22401
22402     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
22403         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
22404         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
22405         ISD::isBuildVectorAllOnes(V2.getNode()))
22406       return true;
22407   }
22408
22409   return false;
22410 }
22411
22412 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
22413 // register. In most cases we actually compare or select YMM-sized registers
22414 // and mixing the two types creates horrible code. This method optimizes
22415 // some of the transition sequences.
22416 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
22417                                  TargetLowering::DAGCombinerInfo &DCI,
22418                                  const X86Subtarget *Subtarget) {
22419   EVT VT = N->getValueType(0);
22420   if (!VT.is256BitVector())
22421     return SDValue();
22422
22423   assert((N->getOpcode() == ISD::ANY_EXTEND ||
22424           N->getOpcode() == ISD::ZERO_EXTEND ||
22425           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
22426
22427   SDValue Narrow = N->getOperand(0);
22428   EVT NarrowVT = Narrow->getValueType(0);
22429   if (!NarrowVT.is128BitVector())
22430     return SDValue();
22431
22432   if (Narrow->getOpcode() != ISD::XOR &&
22433       Narrow->getOpcode() != ISD::AND &&
22434       Narrow->getOpcode() != ISD::OR)
22435     return SDValue();
22436
22437   SDValue N0  = Narrow->getOperand(0);
22438   SDValue N1  = Narrow->getOperand(1);
22439   SDLoc DL(Narrow);
22440
22441   // The Left side has to be a trunc.
22442   if (N0.getOpcode() != ISD::TRUNCATE)
22443     return SDValue();
22444
22445   // The type of the truncated inputs.
22446   EVT WideVT = N0->getOperand(0)->getValueType(0);
22447   if (WideVT != VT)
22448     return SDValue();
22449
22450   // The right side has to be a 'trunc' or a constant vector.
22451   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
22452   ConstantSDNode *RHSConstSplat = nullptr;
22453   if (auto *RHSBV = dyn_cast<BuildVectorSDNode>(N1))
22454     RHSConstSplat = RHSBV->getConstantSplatNode();
22455   if (!RHSTrunc && !RHSConstSplat)
22456     return SDValue();
22457
22458   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22459
22460   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
22461     return SDValue();
22462
22463   // Set N0 and N1 to hold the inputs to the new wide operation.
22464   N0 = N0->getOperand(0);
22465   if (RHSConstSplat) {
22466     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
22467                      SDValue(RHSConstSplat, 0));
22468     SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
22469     N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
22470   } else if (RHSTrunc) {
22471     N1 = N1->getOperand(0);
22472   }
22473
22474   // Generate the wide operation.
22475   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
22476   unsigned Opcode = N->getOpcode();
22477   switch (Opcode) {
22478   case ISD::ANY_EXTEND:
22479     return Op;
22480   case ISD::ZERO_EXTEND: {
22481     unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
22482     APInt Mask = APInt::getAllOnesValue(InBits);
22483     Mask = Mask.zext(VT.getScalarType().getSizeInBits());
22484     return DAG.getNode(ISD::AND, DL, VT,
22485                        Op, DAG.getConstant(Mask, DL, VT));
22486   }
22487   case ISD::SIGN_EXTEND:
22488     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
22489                        Op, DAG.getValueType(NarrowVT));
22490   default:
22491     llvm_unreachable("Unexpected opcode");
22492   }
22493 }
22494
22495 static SDValue VectorZextCombine(SDNode *N, SelectionDAG &DAG,
22496                                  TargetLowering::DAGCombinerInfo &DCI,
22497                                  const X86Subtarget *Subtarget) {
22498   SDValue N0 = N->getOperand(0);
22499   SDValue N1 = N->getOperand(1);
22500   SDLoc DL(N);
22501
22502   // A vector zext_in_reg may be represented as a shuffle,
22503   // feeding into a bitcast (this represents anyext) feeding into
22504   // an and with a mask.
22505   // We'd like to try to combine that into a shuffle with zero
22506   // plus a bitcast, removing the and.
22507   if (N0.getOpcode() != ISD::BITCAST ||
22508       N0.getOperand(0).getOpcode() != ISD::VECTOR_SHUFFLE)
22509     return SDValue();
22510
22511   // The other side of the AND should be a splat of 2^C, where C
22512   // is the number of bits in the source type.
22513   if (N1.getOpcode() == ISD::BITCAST)
22514     N1 = N1.getOperand(0);
22515   if (N1.getOpcode() != ISD::BUILD_VECTOR)
22516     return SDValue();
22517   BuildVectorSDNode *Vector = cast<BuildVectorSDNode>(N1);
22518
22519   ShuffleVectorSDNode *Shuffle = cast<ShuffleVectorSDNode>(N0.getOperand(0));
22520   EVT SrcType = Shuffle->getValueType(0);
22521
22522   // We expect a single-source shuffle
22523   if (Shuffle->getOperand(1)->getOpcode() != ISD::UNDEF)
22524     return SDValue();
22525
22526   unsigned SrcSize = SrcType.getScalarSizeInBits();
22527
22528   APInt SplatValue, SplatUndef;
22529   unsigned SplatBitSize;
22530   bool HasAnyUndefs;
22531   if (!Vector->isConstantSplat(SplatValue, SplatUndef,
22532                                 SplatBitSize, HasAnyUndefs))
22533     return SDValue();
22534
22535   unsigned ResSize = N1.getValueType().getScalarSizeInBits();
22536   // Make sure the splat matches the mask we expect
22537   if (SplatBitSize > ResSize ||
22538       (SplatValue + 1).exactLogBase2() != (int)SrcSize)
22539     return SDValue();
22540
22541   // Make sure the input and output size make sense
22542   if (SrcSize >= ResSize || ResSize % SrcSize)
22543     return SDValue();
22544
22545   // We expect a shuffle of the form <0, u, u, u, 1, u, u, u...>
22546   // The number of u's between each two values depends on the ratio between
22547   // the source and dest type.
22548   unsigned ZextRatio = ResSize / SrcSize;
22549   bool IsZext = true;
22550   for (unsigned i = 0; i < SrcType.getVectorNumElements(); ++i) {
22551     if (i % ZextRatio) {
22552       if (Shuffle->getMaskElt(i) > 0) {
22553         // Expected undef
22554         IsZext = false;
22555         break;
22556       }
22557     } else {
22558       if (Shuffle->getMaskElt(i) != (int)(i / ZextRatio)) {
22559         // Expected element number
22560         IsZext = false;
22561         break;
22562       }
22563     }
22564   }
22565
22566   if (!IsZext)
22567     return SDValue();
22568
22569   // Ok, perform the transformation - replace the shuffle with
22570   // a shuffle of the form <0, k, k, k, 1, k, k, k> with zero
22571   // (instead of undef) where the k elements come from the zero vector.
22572   SmallVector<int, 8> Mask;
22573   unsigned NumElems = SrcType.getVectorNumElements();
22574   for (unsigned i = 0; i < NumElems; ++i)
22575     if (i % ZextRatio)
22576       Mask.push_back(NumElems);
22577     else
22578       Mask.push_back(i / ZextRatio);
22579
22580   SDValue NewShuffle = DAG.getVectorShuffle(Shuffle->getValueType(0), DL,
22581     Shuffle->getOperand(0), DAG.getConstant(0, DL, SrcType), Mask);
22582   return DAG.getNode(ISD::BITCAST, DL, N0.getValueType(), NewShuffle);
22583 }
22584
22585 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
22586                                  TargetLowering::DAGCombinerInfo &DCI,
22587                                  const X86Subtarget *Subtarget) {
22588   if (DCI.isBeforeLegalizeOps())
22589     return SDValue();
22590
22591   if (SDValue Zext = VectorZextCombine(N, DAG, DCI, Subtarget))
22592     return Zext;
22593
22594   if (SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget))
22595     return R;
22596
22597   EVT VT = N->getValueType(0);
22598   SDValue N0 = N->getOperand(0);
22599   SDValue N1 = N->getOperand(1);
22600   SDLoc DL(N);
22601
22602   // Create BEXTR instructions
22603   // BEXTR is ((X >> imm) & (2**size-1))
22604   if (VT == MVT::i32 || VT == MVT::i64) {
22605     // Check for BEXTR.
22606     if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
22607         (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
22608       ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
22609       ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
22610       if (MaskNode && ShiftNode) {
22611         uint64_t Mask = MaskNode->getZExtValue();
22612         uint64_t Shift = ShiftNode->getZExtValue();
22613         if (isMask_64(Mask)) {
22614           uint64_t MaskSize = countPopulation(Mask);
22615           if (Shift + MaskSize <= VT.getSizeInBits())
22616             return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
22617                                DAG.getConstant(Shift | (MaskSize << 8), DL,
22618                                                VT));
22619         }
22620       }
22621     } // BEXTR
22622
22623     return SDValue();
22624   }
22625
22626   // Want to form ANDNP nodes:
22627   // 1) In the hopes of then easily combining them with OR and AND nodes
22628   //    to form PBLEND/PSIGN.
22629   // 2) To match ANDN packed intrinsics
22630   if (VT != MVT::v2i64 && VT != MVT::v4i64)
22631     return SDValue();
22632
22633   // Check LHS for vnot
22634   if (N0.getOpcode() == ISD::XOR &&
22635       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
22636       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
22637     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
22638
22639   // Check RHS for vnot
22640   if (N1.getOpcode() == ISD::XOR &&
22641       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
22642       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
22643     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
22644
22645   return SDValue();
22646 }
22647
22648 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
22649                                 TargetLowering::DAGCombinerInfo &DCI,
22650                                 const X86Subtarget *Subtarget) {
22651   if (DCI.isBeforeLegalizeOps())
22652     return SDValue();
22653
22654   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
22655   if (R.getNode())
22656     return R;
22657
22658   SDValue N0 = N->getOperand(0);
22659   SDValue N1 = N->getOperand(1);
22660   EVT VT = N->getValueType(0);
22661
22662   // look for psign/blend
22663   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
22664     if (!Subtarget->hasSSSE3() ||
22665         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
22666       return SDValue();
22667
22668     // Canonicalize pandn to RHS
22669     if (N0.getOpcode() == X86ISD::ANDNP)
22670       std::swap(N0, N1);
22671     // or (and (m, y), (pandn m, x))
22672     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
22673       SDValue Mask = N1.getOperand(0);
22674       SDValue X    = N1.getOperand(1);
22675       SDValue Y;
22676       if (N0.getOperand(0) == Mask)
22677         Y = N0.getOperand(1);
22678       if (N0.getOperand(1) == Mask)
22679         Y = N0.getOperand(0);
22680
22681       // Check to see if the mask appeared in both the AND and ANDNP and
22682       if (!Y.getNode())
22683         return SDValue();
22684
22685       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
22686       // Look through mask bitcast.
22687       if (Mask.getOpcode() == ISD::BITCAST)
22688         Mask = Mask.getOperand(0);
22689       if (X.getOpcode() == ISD::BITCAST)
22690         X = X.getOperand(0);
22691       if (Y.getOpcode() == ISD::BITCAST)
22692         Y = Y.getOperand(0);
22693
22694       EVT MaskVT = Mask.getValueType();
22695
22696       // Validate that the Mask operand is a vector sra node.
22697       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
22698       // there is no psrai.b
22699       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
22700       unsigned SraAmt = ~0;
22701       if (Mask.getOpcode() == ISD::SRA) {
22702         if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Mask.getOperand(1)))
22703           if (auto *AmtConst = AmtBV->getConstantSplatNode())
22704             SraAmt = AmtConst->getZExtValue();
22705       } else if (Mask.getOpcode() == X86ISD::VSRAI) {
22706         SDValue SraC = Mask.getOperand(1);
22707         SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
22708       }
22709       if ((SraAmt + 1) != EltBits)
22710         return SDValue();
22711
22712       SDLoc DL(N);
22713
22714       // Now we know we at least have a plendvb with the mask val.  See if
22715       // we can form a psignb/w/d.
22716       // psign = x.type == y.type == mask.type && y = sub(0, x);
22717       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
22718           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
22719           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
22720         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
22721                "Unsupported VT for PSIGN");
22722         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
22723         return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
22724       }
22725       // PBLENDVB only available on SSE 4.1
22726       if (!Subtarget->hasSSE41())
22727         return SDValue();
22728
22729       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
22730
22731       X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
22732       Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
22733       Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
22734       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
22735       return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
22736     }
22737   }
22738
22739   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
22740     return SDValue();
22741
22742   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
22743   MachineFunction &MF = DAG.getMachineFunction();
22744   bool OptForSize =
22745       MF.getFunction()->hasFnAttribute(Attribute::OptimizeForSize);
22746
22747   // SHLD/SHRD instructions have lower register pressure, but on some
22748   // platforms they have higher latency than the equivalent
22749   // series of shifts/or that would otherwise be generated.
22750   // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
22751   // have higher latencies and we are not optimizing for size.
22752   if (!OptForSize && Subtarget->isSHLDSlow())
22753     return SDValue();
22754
22755   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
22756     std::swap(N0, N1);
22757   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
22758     return SDValue();
22759   if (!N0.hasOneUse() || !N1.hasOneUse())
22760     return SDValue();
22761
22762   SDValue ShAmt0 = N0.getOperand(1);
22763   if (ShAmt0.getValueType() != MVT::i8)
22764     return SDValue();
22765   SDValue ShAmt1 = N1.getOperand(1);
22766   if (ShAmt1.getValueType() != MVT::i8)
22767     return SDValue();
22768   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
22769     ShAmt0 = ShAmt0.getOperand(0);
22770   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
22771     ShAmt1 = ShAmt1.getOperand(0);
22772
22773   SDLoc DL(N);
22774   unsigned Opc = X86ISD::SHLD;
22775   SDValue Op0 = N0.getOperand(0);
22776   SDValue Op1 = N1.getOperand(0);
22777   if (ShAmt0.getOpcode() == ISD::SUB) {
22778     Opc = X86ISD::SHRD;
22779     std::swap(Op0, Op1);
22780     std::swap(ShAmt0, ShAmt1);
22781   }
22782
22783   unsigned Bits = VT.getSizeInBits();
22784   if (ShAmt1.getOpcode() == ISD::SUB) {
22785     SDValue Sum = ShAmt1.getOperand(0);
22786     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
22787       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
22788       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
22789         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
22790       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
22791         return DAG.getNode(Opc, DL, VT,
22792                            Op0, Op1,
22793                            DAG.getNode(ISD::TRUNCATE, DL,
22794                                        MVT::i8, ShAmt0));
22795     }
22796   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
22797     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
22798     if (ShAmt0C &&
22799         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
22800       return DAG.getNode(Opc, DL, VT,
22801                          N0.getOperand(0), N1.getOperand(0),
22802                          DAG.getNode(ISD::TRUNCATE, DL,
22803                                        MVT::i8, ShAmt0));
22804   }
22805
22806   return SDValue();
22807 }
22808
22809 // Generate NEG and CMOV for integer abs.
22810 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
22811   EVT VT = N->getValueType(0);
22812
22813   // Since X86 does not have CMOV for 8-bit integer, we don't convert
22814   // 8-bit integer abs to NEG and CMOV.
22815   if (VT.isInteger() && VT.getSizeInBits() == 8)
22816     return SDValue();
22817
22818   SDValue N0 = N->getOperand(0);
22819   SDValue N1 = N->getOperand(1);
22820   SDLoc DL(N);
22821
22822   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
22823   // and change it to SUB and CMOV.
22824   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
22825       N0.getOpcode() == ISD::ADD &&
22826       N0.getOperand(1) == N1 &&
22827       N1.getOpcode() == ISD::SRA &&
22828       N1.getOperand(0) == N0.getOperand(0))
22829     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
22830       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
22831         // Generate SUB & CMOV.
22832         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
22833                                   DAG.getConstant(0, DL, VT), N0.getOperand(0));
22834
22835         SDValue Ops[] = { N0.getOperand(0), Neg,
22836                           DAG.getConstant(X86::COND_GE, DL, MVT::i8),
22837                           SDValue(Neg.getNode(), 1) };
22838         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
22839       }
22840   return SDValue();
22841 }
22842
22843 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
22844 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
22845                                  TargetLowering::DAGCombinerInfo &DCI,
22846                                  const X86Subtarget *Subtarget) {
22847   if (DCI.isBeforeLegalizeOps())
22848     return SDValue();
22849
22850   if (Subtarget->hasCMov()) {
22851     SDValue RV = performIntegerAbsCombine(N, DAG);
22852     if (RV.getNode())
22853       return RV;
22854   }
22855
22856   return SDValue();
22857 }
22858
22859 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
22860 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
22861                                   TargetLowering::DAGCombinerInfo &DCI,
22862                                   const X86Subtarget *Subtarget) {
22863   LoadSDNode *Ld = cast<LoadSDNode>(N);
22864   EVT RegVT = Ld->getValueType(0);
22865   EVT MemVT = Ld->getMemoryVT();
22866   SDLoc dl(Ld);
22867   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22868
22869   // For chips with slow 32-byte unaligned loads, break the 32-byte operation
22870   // into two 16-byte operations.
22871   ISD::LoadExtType Ext = Ld->getExtensionType();
22872   unsigned Alignment = Ld->getAlignment();
22873   bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
22874   if (RegVT.is256BitVector() && Subtarget->isUnalignedMem32Slow() &&
22875       !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
22876     unsigned NumElems = RegVT.getVectorNumElements();
22877     if (NumElems < 2)
22878       return SDValue();
22879
22880     SDValue Ptr = Ld->getBasePtr();
22881     SDValue Increment = DAG.getConstant(16, dl, TLI.getPointerTy());
22882
22883     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
22884                                   NumElems/2);
22885     SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
22886                                 Ld->getPointerInfo(), Ld->isVolatile(),
22887                                 Ld->isNonTemporal(), Ld->isInvariant(),
22888                                 Alignment);
22889     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
22890     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
22891                                 Ld->getPointerInfo(), Ld->isVolatile(),
22892                                 Ld->isNonTemporal(), Ld->isInvariant(),
22893                                 std::min(16U, Alignment));
22894     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
22895                              Load1.getValue(1),
22896                              Load2.getValue(1));
22897
22898     SDValue NewVec = DAG.getUNDEF(RegVT);
22899     NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
22900     NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
22901     return DCI.CombineTo(N, NewVec, TF, true);
22902   }
22903
22904   return SDValue();
22905 }
22906
22907 /// PerformMLOADCombine - Resolve extending loads
22908 static SDValue PerformMLOADCombine(SDNode *N, SelectionDAG &DAG,
22909                                    TargetLowering::DAGCombinerInfo &DCI,
22910                                    const X86Subtarget *Subtarget) {
22911   MaskedLoadSDNode *Mld = cast<MaskedLoadSDNode>(N);
22912   if (Mld->getExtensionType() != ISD::SEXTLOAD)
22913     return SDValue();
22914
22915   EVT VT = Mld->getValueType(0);
22916   unsigned NumElems = VT.getVectorNumElements();
22917   EVT LdVT = Mld->getMemoryVT();
22918   SDLoc dl(Mld);
22919
22920   assert(LdVT != VT && "Cannot extend to the same type");
22921   unsigned ToSz = VT.getVectorElementType().getSizeInBits();
22922   unsigned FromSz = LdVT.getVectorElementType().getSizeInBits();
22923   // From, To sizes and ElemCount must be pow of two
22924   assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
22925     "Unexpected size for extending masked load");
22926
22927   unsigned SizeRatio  = ToSz / FromSz;
22928   assert(SizeRatio * NumElems * FromSz == VT.getSizeInBits());
22929
22930   // Create a type on which we perform the shuffle
22931   EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
22932           LdVT.getScalarType(), NumElems*SizeRatio);
22933   assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
22934
22935   // Convert Src0 value
22936   SDValue WideSrc0 = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Mld->getSrc0());
22937   if (Mld->getSrc0().getOpcode() != ISD::UNDEF) {
22938     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
22939     for (unsigned i = 0; i != NumElems; ++i)
22940       ShuffleVec[i] = i * SizeRatio;
22941
22942     // Can't shuffle using an illegal type.
22943     assert (DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT)
22944             && "WideVecVT should be legal");
22945     WideSrc0 = DAG.getVectorShuffle(WideVecVT, dl, WideSrc0,
22946                                     DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
22947   }
22948   // Prepare the new mask
22949   SDValue NewMask;
22950   SDValue Mask = Mld->getMask();
22951   if (Mask.getValueType() == VT) {
22952     // Mask and original value have the same type
22953     NewMask = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Mask);
22954     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
22955     for (unsigned i = 0; i != NumElems; ++i)
22956       ShuffleVec[i] = i * SizeRatio;
22957     for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
22958       ShuffleVec[i] = NumElems*SizeRatio;
22959     NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
22960                                    DAG.getConstant(0, dl, WideVecVT),
22961                                    &ShuffleVec[0]);
22962   }
22963   else {
22964     assert(Mask.getValueType().getVectorElementType() == MVT::i1);
22965     unsigned WidenNumElts = NumElems*SizeRatio;
22966     unsigned MaskNumElts = VT.getVectorNumElements();
22967     EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(),  MVT::i1,
22968                                      WidenNumElts);
22969
22970     unsigned NumConcat = WidenNumElts / MaskNumElts;
22971     SmallVector<SDValue, 16> Ops(NumConcat);
22972     SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
22973     Ops[0] = Mask;
22974     for (unsigned i = 1; i != NumConcat; ++i)
22975       Ops[i] = ZeroVal;
22976
22977     NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
22978   }
22979
22980   SDValue WideLd = DAG.getMaskedLoad(WideVecVT, dl, Mld->getChain(),
22981                                      Mld->getBasePtr(), NewMask, WideSrc0,
22982                                      Mld->getMemoryVT(), Mld->getMemOperand(),
22983                                      ISD::NON_EXTLOAD);
22984   SDValue NewVec = DAG.getNode(X86ISD::VSEXT, dl, VT, WideLd);
22985   return DCI.CombineTo(N, NewVec, WideLd.getValue(1), true);
22986
22987 }
22988 /// PerformMSTORECombine - Resolve truncating stores
22989 static SDValue PerformMSTORECombine(SDNode *N, SelectionDAG &DAG,
22990                                     const X86Subtarget *Subtarget) {
22991   MaskedStoreSDNode *Mst = cast<MaskedStoreSDNode>(N);
22992   if (!Mst->isTruncatingStore())
22993     return SDValue();
22994
22995   EVT VT = Mst->getValue().getValueType();
22996   unsigned NumElems = VT.getVectorNumElements();
22997   EVT StVT = Mst->getMemoryVT();
22998   SDLoc dl(Mst);
22999
23000   assert(StVT != VT && "Cannot truncate to the same type");
23001   unsigned FromSz = VT.getVectorElementType().getSizeInBits();
23002   unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
23003
23004   // From, To sizes and ElemCount must be pow of two
23005   assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
23006     "Unexpected size for truncating masked store");
23007   // We are going to use the original vector elt for storing.
23008   // Accumulated smaller vector elements must be a multiple of the store size.
23009   assert (((NumElems * FromSz) % ToSz) == 0 &&
23010           "Unexpected ratio for truncating masked store");
23011
23012   unsigned SizeRatio  = FromSz / ToSz;
23013   assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
23014
23015   // Create a type on which we perform the shuffle
23016   EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
23017           StVT.getScalarType(), NumElems*SizeRatio);
23018
23019   assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
23020
23021   SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Mst->getValue());
23022   SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
23023   for (unsigned i = 0; i != NumElems; ++i)
23024     ShuffleVec[i] = i * SizeRatio;
23025
23026   // Can't shuffle using an illegal type.
23027   assert (DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT)
23028           && "WideVecVT should be legal");
23029
23030   SDValue TruncatedVal = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
23031                                         DAG.getUNDEF(WideVecVT),
23032                                         &ShuffleVec[0]);
23033
23034   SDValue NewMask;
23035   SDValue Mask = Mst->getMask();
23036   if (Mask.getValueType() == VT) {
23037     // Mask and original value have the same type
23038     NewMask = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Mask);
23039     for (unsigned i = 0; i != NumElems; ++i)
23040       ShuffleVec[i] = i * SizeRatio;
23041     for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
23042       ShuffleVec[i] = NumElems*SizeRatio;
23043     NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
23044                                    DAG.getConstant(0, dl, WideVecVT),
23045                                    &ShuffleVec[0]);
23046   }
23047   else {
23048     assert(Mask.getValueType().getVectorElementType() == MVT::i1);
23049     unsigned WidenNumElts = NumElems*SizeRatio;
23050     unsigned MaskNumElts = VT.getVectorNumElements();
23051     EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(),  MVT::i1,
23052                                      WidenNumElts);
23053
23054     unsigned NumConcat = WidenNumElts / MaskNumElts;
23055     SmallVector<SDValue, 16> Ops(NumConcat);
23056     SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
23057     Ops[0] = Mask;
23058     for (unsigned i = 1; i != NumConcat; ++i)
23059       Ops[i] = ZeroVal;
23060
23061     NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
23062   }
23063
23064   return DAG.getMaskedStore(Mst->getChain(), dl, TruncatedVal, Mst->getBasePtr(),
23065                             NewMask, StVT, Mst->getMemOperand(), false);
23066 }
23067 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
23068 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
23069                                    const X86Subtarget *Subtarget) {
23070   StoreSDNode *St = cast<StoreSDNode>(N);
23071   EVT VT = St->getValue().getValueType();
23072   EVT StVT = St->getMemoryVT();
23073   SDLoc dl(St);
23074   SDValue StoredVal = St->getOperand(1);
23075   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23076
23077   // If we are saving a concatenation of two XMM registers and 32-byte stores
23078   // are slow, such as on Sandy Bridge, perform two 16-byte stores.
23079   unsigned Alignment = St->getAlignment();
23080   bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
23081   if (VT.is256BitVector() && Subtarget->isUnalignedMem32Slow() &&
23082       StVT == VT && !IsAligned) {
23083     unsigned NumElems = VT.getVectorNumElements();
23084     if (NumElems < 2)
23085       return SDValue();
23086
23087     SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
23088     SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
23089
23090     SDValue Stride = DAG.getConstant(16, dl, TLI.getPointerTy());
23091     SDValue Ptr0 = St->getBasePtr();
23092     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
23093
23094     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
23095                                 St->getPointerInfo(), St->isVolatile(),
23096                                 St->isNonTemporal(), Alignment);
23097     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
23098                                 St->getPointerInfo(), St->isVolatile(),
23099                                 St->isNonTemporal(),
23100                                 std::min(16U, Alignment));
23101     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
23102   }
23103
23104   // Optimize trunc store (of multiple scalars) to shuffle and store.
23105   // First, pack all of the elements in one place. Next, store to memory
23106   // in fewer chunks.
23107   if (St->isTruncatingStore() && VT.isVector()) {
23108     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23109     unsigned NumElems = VT.getVectorNumElements();
23110     assert(StVT != VT && "Cannot truncate to the same type");
23111     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
23112     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
23113
23114     // From, To sizes and ElemCount must be pow of two
23115     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
23116     // We are going to use the original vector elt for storing.
23117     // Accumulated smaller vector elements must be a multiple of the store size.
23118     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
23119
23120     unsigned SizeRatio  = FromSz / ToSz;
23121
23122     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
23123
23124     // Create a type on which we perform the shuffle
23125     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
23126             StVT.getScalarType(), NumElems*SizeRatio);
23127
23128     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
23129
23130     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
23131     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
23132     for (unsigned i = 0; i != NumElems; ++i)
23133       ShuffleVec[i] = i * SizeRatio;
23134
23135     // Can't shuffle using an illegal type.
23136     if (!TLI.isTypeLegal(WideVecVT))
23137       return SDValue();
23138
23139     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
23140                                          DAG.getUNDEF(WideVecVT),
23141                                          &ShuffleVec[0]);
23142     // At this point all of the data is stored at the bottom of the
23143     // register. We now need to save it to mem.
23144
23145     // Find the largest store unit
23146     MVT StoreType = MVT::i8;
23147     for (MVT Tp : MVT::integer_valuetypes()) {
23148       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
23149         StoreType = Tp;
23150     }
23151
23152     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
23153     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
23154         (64 <= NumElems * ToSz))
23155       StoreType = MVT::f64;
23156
23157     // Bitcast the original vector into a vector of store-size units
23158     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
23159             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
23160     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
23161     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
23162     SmallVector<SDValue, 8> Chains;
23163     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8, dl,
23164                                         TLI.getPointerTy());
23165     SDValue Ptr = St->getBasePtr();
23166
23167     // Perform one or more big stores into memory.
23168     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
23169       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
23170                                    StoreType, ShuffWide,
23171                                    DAG.getIntPtrConstant(i, dl));
23172       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
23173                                 St->getPointerInfo(), St->isVolatile(),
23174                                 St->isNonTemporal(), St->getAlignment());
23175       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
23176       Chains.push_back(Ch);
23177     }
23178
23179     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
23180   }
23181
23182   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
23183   // the FP state in cases where an emms may be missing.
23184   // A preferable solution to the general problem is to figure out the right
23185   // places to insert EMMS.  This qualifies as a quick hack.
23186
23187   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
23188   if (VT.getSizeInBits() != 64)
23189     return SDValue();
23190
23191   const Function *F = DAG.getMachineFunction().getFunction();
23192   bool NoImplicitFloatOps = F->hasFnAttribute(Attribute::NoImplicitFloat);
23193   bool F64IsLegal =
23194       !Subtarget->useSoftFloat() && !NoImplicitFloatOps && Subtarget->hasSSE2();
23195   if ((VT.isVector() ||
23196        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
23197       isa<LoadSDNode>(St->getValue()) &&
23198       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
23199       St->getChain().hasOneUse() && !St->isVolatile()) {
23200     SDNode* LdVal = St->getValue().getNode();
23201     LoadSDNode *Ld = nullptr;
23202     int TokenFactorIndex = -1;
23203     SmallVector<SDValue, 8> Ops;
23204     SDNode* ChainVal = St->getChain().getNode();
23205     // Must be a store of a load.  We currently handle two cases:  the load
23206     // is a direct child, and it's under an intervening TokenFactor.  It is
23207     // possible to dig deeper under nested TokenFactors.
23208     if (ChainVal == LdVal)
23209       Ld = cast<LoadSDNode>(St->getChain());
23210     else if (St->getValue().hasOneUse() &&
23211              ChainVal->getOpcode() == ISD::TokenFactor) {
23212       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
23213         if (ChainVal->getOperand(i).getNode() == LdVal) {
23214           TokenFactorIndex = i;
23215           Ld = cast<LoadSDNode>(St->getValue());
23216         } else
23217           Ops.push_back(ChainVal->getOperand(i));
23218       }
23219     }
23220
23221     if (!Ld || !ISD::isNormalLoad(Ld))
23222       return SDValue();
23223
23224     // If this is not the MMX case, i.e. we are just turning i64 load/store
23225     // into f64 load/store, avoid the transformation if there are multiple
23226     // uses of the loaded value.
23227     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
23228       return SDValue();
23229
23230     SDLoc LdDL(Ld);
23231     SDLoc StDL(N);
23232     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
23233     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
23234     // pair instead.
23235     if (Subtarget->is64Bit() || F64IsLegal) {
23236       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
23237       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
23238                                   Ld->getPointerInfo(), Ld->isVolatile(),
23239                                   Ld->isNonTemporal(), Ld->isInvariant(),
23240                                   Ld->getAlignment());
23241       SDValue NewChain = NewLd.getValue(1);
23242       if (TokenFactorIndex != -1) {
23243         Ops.push_back(NewChain);
23244         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
23245       }
23246       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
23247                           St->getPointerInfo(),
23248                           St->isVolatile(), St->isNonTemporal(),
23249                           St->getAlignment());
23250     }
23251
23252     // Otherwise, lower to two pairs of 32-bit loads / stores.
23253     SDValue LoAddr = Ld->getBasePtr();
23254     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
23255                                  DAG.getConstant(4, LdDL, MVT::i32));
23256
23257     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
23258                                Ld->getPointerInfo(),
23259                                Ld->isVolatile(), Ld->isNonTemporal(),
23260                                Ld->isInvariant(), Ld->getAlignment());
23261     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
23262                                Ld->getPointerInfo().getWithOffset(4),
23263                                Ld->isVolatile(), Ld->isNonTemporal(),
23264                                Ld->isInvariant(),
23265                                MinAlign(Ld->getAlignment(), 4));
23266
23267     SDValue NewChain = LoLd.getValue(1);
23268     if (TokenFactorIndex != -1) {
23269       Ops.push_back(LoLd);
23270       Ops.push_back(HiLd);
23271       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
23272     }
23273
23274     LoAddr = St->getBasePtr();
23275     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
23276                          DAG.getConstant(4, StDL, MVT::i32));
23277
23278     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
23279                                 St->getPointerInfo(),
23280                                 St->isVolatile(), St->isNonTemporal(),
23281                                 St->getAlignment());
23282     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
23283                                 St->getPointerInfo().getWithOffset(4),
23284                                 St->isVolatile(),
23285                                 St->isNonTemporal(),
23286                                 MinAlign(St->getAlignment(), 4));
23287     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
23288   }
23289
23290   // This is similar to the above case, but here we handle a scalar 64-bit
23291   // integer store that is extracted from a vector on a 32-bit target.
23292   // If we have SSE2, then we can treat it like a floating-point double
23293   // to get past legalization. The execution dependencies fixup pass will
23294   // choose the optimal machine instruction for the store if this really is
23295   // an integer or v2f32 rather than an f64.
23296   if (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit() &&
23297       St->getOperand(1).getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
23298     SDValue OldExtract = St->getOperand(1);
23299     SDValue ExtOp0 = OldExtract.getOperand(0);
23300     unsigned VecSize = ExtOp0.getValueSizeInBits();
23301     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, VecSize / 64);
23302     SDValue BitCast = DAG.getNode(ISD::BITCAST, dl, VecVT, ExtOp0);
23303     SDValue NewExtract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
23304                                      BitCast, OldExtract.getOperand(1));
23305     return DAG.getStore(St->getChain(), dl, NewExtract, St->getBasePtr(),
23306                         St->getPointerInfo(), St->isVolatile(),
23307                         St->isNonTemporal(), St->getAlignment());
23308   }
23309
23310   return SDValue();
23311 }
23312
23313 /// Return 'true' if this vector operation is "horizontal"
23314 /// and return the operands for the horizontal operation in LHS and RHS.  A
23315 /// horizontal operation performs the binary operation on successive elements
23316 /// of its first operand, then on successive elements of its second operand,
23317 /// returning the resulting values in a vector.  For example, if
23318 ///   A = < float a0, float a1, float a2, float a3 >
23319 /// and
23320 ///   B = < float b0, float b1, float b2, float b3 >
23321 /// then the result of doing a horizontal operation on A and B is
23322 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
23323 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
23324 /// A horizontal-op B, for some already available A and B, and if so then LHS is
23325 /// set to A, RHS to B, and the routine returns 'true'.
23326 /// Note that the binary operation should have the property that if one of the
23327 /// operands is UNDEF then the result is UNDEF.
23328 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
23329   // Look for the following pattern: if
23330   //   A = < float a0, float a1, float a2, float a3 >
23331   //   B = < float b0, float b1, float b2, float b3 >
23332   // and
23333   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
23334   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
23335   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
23336   // which is A horizontal-op B.
23337
23338   // At least one of the operands should be a vector shuffle.
23339   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
23340       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
23341     return false;
23342
23343   MVT VT = LHS.getSimpleValueType();
23344
23345   assert((VT.is128BitVector() || VT.is256BitVector()) &&
23346          "Unsupported vector type for horizontal add/sub");
23347
23348   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
23349   // operate independently on 128-bit lanes.
23350   unsigned NumElts = VT.getVectorNumElements();
23351   unsigned NumLanes = VT.getSizeInBits()/128;
23352   unsigned NumLaneElts = NumElts / NumLanes;
23353   assert((NumLaneElts % 2 == 0) &&
23354          "Vector type should have an even number of elements in each lane");
23355   unsigned HalfLaneElts = NumLaneElts/2;
23356
23357   // View LHS in the form
23358   //   LHS = VECTOR_SHUFFLE A, B, LMask
23359   // If LHS is not a shuffle then pretend it is the shuffle
23360   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
23361   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
23362   // type VT.
23363   SDValue A, B;
23364   SmallVector<int, 16> LMask(NumElts);
23365   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
23366     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
23367       A = LHS.getOperand(0);
23368     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
23369       B = LHS.getOperand(1);
23370     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
23371     std::copy(Mask.begin(), Mask.end(), LMask.begin());
23372   } else {
23373     if (LHS.getOpcode() != ISD::UNDEF)
23374       A = LHS;
23375     for (unsigned i = 0; i != NumElts; ++i)
23376       LMask[i] = i;
23377   }
23378
23379   // Likewise, view RHS in the form
23380   //   RHS = VECTOR_SHUFFLE C, D, RMask
23381   SDValue C, D;
23382   SmallVector<int, 16> RMask(NumElts);
23383   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
23384     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
23385       C = RHS.getOperand(0);
23386     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
23387       D = RHS.getOperand(1);
23388     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
23389     std::copy(Mask.begin(), Mask.end(), RMask.begin());
23390   } else {
23391     if (RHS.getOpcode() != ISD::UNDEF)
23392       C = RHS;
23393     for (unsigned i = 0; i != NumElts; ++i)
23394       RMask[i] = i;
23395   }
23396
23397   // Check that the shuffles are both shuffling the same vectors.
23398   if (!(A == C && B == D) && !(A == D && B == C))
23399     return false;
23400
23401   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
23402   if (!A.getNode() && !B.getNode())
23403     return false;
23404
23405   // If A and B occur in reverse order in RHS, then "swap" them (which means
23406   // rewriting the mask).
23407   if (A != C)
23408     ShuffleVectorSDNode::commuteMask(RMask);
23409
23410   // At this point LHS and RHS are equivalent to
23411   //   LHS = VECTOR_SHUFFLE A, B, LMask
23412   //   RHS = VECTOR_SHUFFLE A, B, RMask
23413   // Check that the masks correspond to performing a horizontal operation.
23414   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
23415     for (unsigned i = 0; i != NumLaneElts; ++i) {
23416       int LIdx = LMask[i+l], RIdx = RMask[i+l];
23417
23418       // Ignore any UNDEF components.
23419       if (LIdx < 0 || RIdx < 0 ||
23420           (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
23421           (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
23422         continue;
23423
23424       // Check that successive elements are being operated on.  If not, this is
23425       // not a horizontal operation.
23426       unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
23427       int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
23428       if (!(LIdx == Index && RIdx == Index + 1) &&
23429           !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
23430         return false;
23431     }
23432   }
23433
23434   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
23435   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
23436   return true;
23437 }
23438
23439 /// Do target-specific dag combines on floating point adds.
23440 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
23441                                   const X86Subtarget *Subtarget) {
23442   EVT VT = N->getValueType(0);
23443   SDValue LHS = N->getOperand(0);
23444   SDValue RHS = N->getOperand(1);
23445
23446   // Try to synthesize horizontal adds from adds of shuffles.
23447   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
23448        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
23449       isHorizontalBinOp(LHS, RHS, true))
23450     return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
23451   return SDValue();
23452 }
23453
23454 /// Do target-specific dag combines on floating point subs.
23455 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
23456                                   const X86Subtarget *Subtarget) {
23457   EVT VT = N->getValueType(0);
23458   SDValue LHS = N->getOperand(0);
23459   SDValue RHS = N->getOperand(1);
23460
23461   // Try to synthesize horizontal subs from subs of shuffles.
23462   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
23463        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
23464       isHorizontalBinOp(LHS, RHS, false))
23465     return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
23466   return SDValue();
23467 }
23468
23469 /// Do target-specific dag combines on X86ISD::FOR and X86ISD::FXOR nodes.
23470 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
23471   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
23472
23473   // F[X]OR(0.0, x) -> x
23474   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
23475     if (C->getValueAPF().isPosZero())
23476       return N->getOperand(1);
23477
23478   // F[X]OR(x, 0.0) -> x
23479   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
23480     if (C->getValueAPF().isPosZero())
23481       return N->getOperand(0);
23482   return SDValue();
23483 }
23484
23485 /// Do target-specific dag combines on X86ISD::FMIN and X86ISD::FMAX nodes.
23486 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
23487   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
23488
23489   // Only perform optimizations if UnsafeMath is used.
23490   if (!DAG.getTarget().Options.UnsafeFPMath)
23491     return SDValue();
23492
23493   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
23494   // into FMINC and FMAXC, which are Commutative operations.
23495   unsigned NewOp = 0;
23496   switch (N->getOpcode()) {
23497     default: llvm_unreachable("unknown opcode");
23498     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
23499     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
23500   }
23501
23502   return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
23503                      N->getOperand(0), N->getOperand(1));
23504 }
23505
23506 /// Do target-specific dag combines on X86ISD::FAND nodes.
23507 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
23508   // FAND(0.0, x) -> 0.0
23509   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
23510     if (C->getValueAPF().isPosZero())
23511       return N->getOperand(0);
23512
23513   // FAND(x, 0.0) -> 0.0
23514   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
23515     if (C->getValueAPF().isPosZero())
23516       return N->getOperand(1);
23517
23518   return SDValue();
23519 }
23520
23521 /// Do target-specific dag combines on X86ISD::FANDN nodes
23522 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
23523   // FANDN(0.0, x) -> x
23524   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
23525     if (C->getValueAPF().isPosZero())
23526       return N->getOperand(1);
23527
23528   // FANDN(x, 0.0) -> 0.0
23529   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
23530     if (C->getValueAPF().isPosZero())
23531       return N->getOperand(1);
23532
23533   return SDValue();
23534 }
23535
23536 static SDValue PerformBTCombine(SDNode *N,
23537                                 SelectionDAG &DAG,
23538                                 TargetLowering::DAGCombinerInfo &DCI) {
23539   // BT ignores high bits in the bit index operand.
23540   SDValue Op1 = N->getOperand(1);
23541   if (Op1.hasOneUse()) {
23542     unsigned BitWidth = Op1.getValueSizeInBits();
23543     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
23544     APInt KnownZero, KnownOne;
23545     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
23546                                           !DCI.isBeforeLegalizeOps());
23547     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23548     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
23549         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
23550       DCI.CommitTargetLoweringOpt(TLO);
23551   }
23552   return SDValue();
23553 }
23554
23555 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
23556   SDValue Op = N->getOperand(0);
23557   if (Op.getOpcode() == ISD::BITCAST)
23558     Op = Op.getOperand(0);
23559   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
23560   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
23561       VT.getVectorElementType().getSizeInBits() ==
23562       OpVT.getVectorElementType().getSizeInBits()) {
23563     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
23564   }
23565   return SDValue();
23566 }
23567
23568 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
23569                                                const X86Subtarget *Subtarget) {
23570   EVT VT = N->getValueType(0);
23571   if (!VT.isVector())
23572     return SDValue();
23573
23574   SDValue N0 = N->getOperand(0);
23575   SDValue N1 = N->getOperand(1);
23576   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
23577   SDLoc dl(N);
23578
23579   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
23580   // both SSE and AVX2 since there is no sign-extended shift right
23581   // operation on a vector with 64-bit elements.
23582   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
23583   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
23584   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
23585       N0.getOpcode() == ISD::SIGN_EXTEND)) {
23586     SDValue N00 = N0.getOperand(0);
23587
23588     // EXTLOAD has a better solution on AVX2,
23589     // it may be replaced with X86ISD::VSEXT node.
23590     if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
23591       if (!ISD::isNormalLoad(N00.getNode()))
23592         return SDValue();
23593
23594     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
23595         SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
23596                                   N00, N1);
23597       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
23598     }
23599   }
23600   return SDValue();
23601 }
23602
23603 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
23604                                   TargetLowering::DAGCombinerInfo &DCI,
23605                                   const X86Subtarget *Subtarget) {
23606   SDValue N0 = N->getOperand(0);
23607   EVT VT = N->getValueType(0);
23608
23609   // (i8,i32 sext (sdivrem (i8 x, i8 y)) ->
23610   // (i8,i32 (sdivrem_sext_hreg (i8 x, i8 y)
23611   // This exposes the sext to the sdivrem lowering, so that it directly extends
23612   // from AH (which we otherwise need to do contortions to access).
23613   if (N0.getOpcode() == ISD::SDIVREM && N0.getResNo() == 1 &&
23614       N0.getValueType() == MVT::i8 && VT == MVT::i32) {
23615     SDLoc dl(N);
23616     SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
23617     SDValue R = DAG.getNode(X86ISD::SDIVREM8_SEXT_HREG, dl, NodeTys,
23618                             N0.getOperand(0), N0.getOperand(1));
23619     DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
23620     return R.getValue(1);
23621   }
23622
23623   if (!DCI.isBeforeLegalizeOps())
23624     return SDValue();
23625
23626   if (!Subtarget->hasFp256())
23627     return SDValue();
23628
23629   if (VT.isVector() && VT.getSizeInBits() == 256) {
23630     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
23631     if (R.getNode())
23632       return R;
23633   }
23634
23635   return SDValue();
23636 }
23637
23638 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
23639                                  const X86Subtarget* Subtarget) {
23640   SDLoc dl(N);
23641   EVT VT = N->getValueType(0);
23642
23643   // Let legalize expand this if it isn't a legal type yet.
23644   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
23645     return SDValue();
23646
23647   EVT ScalarVT = VT.getScalarType();
23648   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
23649       (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
23650     return SDValue();
23651
23652   SDValue A = N->getOperand(0);
23653   SDValue B = N->getOperand(1);
23654   SDValue C = N->getOperand(2);
23655
23656   bool NegA = (A.getOpcode() == ISD::FNEG);
23657   bool NegB = (B.getOpcode() == ISD::FNEG);
23658   bool NegC = (C.getOpcode() == ISD::FNEG);
23659
23660   // Negative multiplication when NegA xor NegB
23661   bool NegMul = (NegA != NegB);
23662   if (NegA)
23663     A = A.getOperand(0);
23664   if (NegB)
23665     B = B.getOperand(0);
23666   if (NegC)
23667     C = C.getOperand(0);
23668
23669   unsigned Opcode;
23670   if (!NegMul)
23671     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
23672   else
23673     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
23674
23675   return DAG.getNode(Opcode, dl, VT, A, B, C);
23676 }
23677
23678 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
23679                                   TargetLowering::DAGCombinerInfo &DCI,
23680                                   const X86Subtarget *Subtarget) {
23681   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
23682   //           (and (i32 x86isd::setcc_carry), 1)
23683   // This eliminates the zext. This transformation is necessary because
23684   // ISD::SETCC is always legalized to i8.
23685   SDLoc dl(N);
23686   SDValue N0 = N->getOperand(0);
23687   EVT VT = N->getValueType(0);
23688
23689   if (N0.getOpcode() == ISD::AND &&
23690       N0.hasOneUse() &&
23691       N0.getOperand(0).hasOneUse()) {
23692     SDValue N00 = N0.getOperand(0);
23693     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
23694       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
23695       if (!C || C->getZExtValue() != 1)
23696         return SDValue();
23697       return DAG.getNode(ISD::AND, dl, VT,
23698                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
23699                                      N00.getOperand(0), N00.getOperand(1)),
23700                          DAG.getConstant(1, dl, VT));
23701     }
23702   }
23703
23704   if (N0.getOpcode() == ISD::TRUNCATE &&
23705       N0.hasOneUse() &&
23706       N0.getOperand(0).hasOneUse()) {
23707     SDValue N00 = N0.getOperand(0);
23708     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
23709       return DAG.getNode(ISD::AND, dl, VT,
23710                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
23711                                      N00.getOperand(0), N00.getOperand(1)),
23712                          DAG.getConstant(1, dl, VT));
23713     }
23714   }
23715   if (VT.is256BitVector()) {
23716     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
23717     if (R.getNode())
23718       return R;
23719   }
23720
23721   // (i8,i32 zext (udivrem (i8 x, i8 y)) ->
23722   // (i8,i32 (udivrem_zext_hreg (i8 x, i8 y)
23723   // This exposes the zext to the udivrem lowering, so that it directly extends
23724   // from AH (which we otherwise need to do contortions to access).
23725   if (N0.getOpcode() == ISD::UDIVREM &&
23726       N0.getResNo() == 1 && N0.getValueType() == MVT::i8 &&
23727       (VT == MVT::i32 || VT == MVT::i64)) {
23728     SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
23729     SDValue R = DAG.getNode(X86ISD::UDIVREM8_ZEXT_HREG, dl, NodeTys,
23730                             N0.getOperand(0), N0.getOperand(1));
23731     DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
23732     return R.getValue(1);
23733   }
23734
23735   return SDValue();
23736 }
23737
23738 // Optimize x == -y --> x+y == 0
23739 //          x != -y --> x+y != 0
23740 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
23741                                       const X86Subtarget* Subtarget) {
23742   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
23743   SDValue LHS = N->getOperand(0);
23744   SDValue RHS = N->getOperand(1);
23745   EVT VT = N->getValueType(0);
23746   SDLoc DL(N);
23747
23748   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
23749     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
23750       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
23751         SDValue addV = DAG.getNode(ISD::ADD, DL, LHS.getValueType(), RHS,
23752                                    LHS.getOperand(1));
23753         return DAG.getSetCC(DL, N->getValueType(0), addV,
23754                             DAG.getConstant(0, DL, addV.getValueType()), CC);
23755       }
23756   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
23757     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
23758       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
23759         SDValue addV = DAG.getNode(ISD::ADD, DL, RHS.getValueType(), LHS,
23760                                    RHS.getOperand(1));
23761         return DAG.getSetCC(DL, N->getValueType(0), addV,
23762                             DAG.getConstant(0, DL, addV.getValueType()), CC);
23763       }
23764
23765   if (VT.getScalarType() == MVT::i1 &&
23766       (CC == ISD::SETNE || CC == ISD::SETEQ || ISD::isSignedIntSetCC(CC))) {
23767     bool IsSEXT0 =
23768         (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
23769         (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
23770     bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
23771
23772     if (!IsSEXT0 || !IsVZero1) {
23773       // Swap the operands and update the condition code.
23774       std::swap(LHS, RHS);
23775       CC = ISD::getSetCCSwappedOperands(CC);
23776
23777       IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
23778                 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
23779       IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
23780     }
23781
23782     if (IsSEXT0 && IsVZero1) {
23783       assert(VT == LHS.getOperand(0).getValueType() &&
23784              "Uexpected operand type");
23785       if (CC == ISD::SETGT)
23786         return DAG.getConstant(0, DL, VT);
23787       if (CC == ISD::SETLE)
23788         return DAG.getConstant(1, DL, VT);
23789       if (CC == ISD::SETEQ || CC == ISD::SETGE)
23790         return DAG.getNOT(DL, LHS.getOperand(0), VT);
23791
23792       assert((CC == ISD::SETNE || CC == ISD::SETLT) &&
23793              "Unexpected condition code!");
23794       return LHS.getOperand(0);
23795     }
23796   }
23797
23798   return SDValue();
23799 }
23800
23801 static SDValue NarrowVectorLoadToElement(LoadSDNode *Load, unsigned Index,
23802                                          SelectionDAG &DAG) {
23803   SDLoc dl(Load);
23804   MVT VT = Load->getSimpleValueType(0);
23805   MVT EVT = VT.getVectorElementType();
23806   SDValue Addr = Load->getOperand(1);
23807   SDValue NewAddr = DAG.getNode(
23808       ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
23809       DAG.getConstant(Index * EVT.getStoreSize(), dl,
23810                       Addr.getSimpleValueType()));
23811
23812   SDValue NewLoad =
23813       DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
23814                   DAG.getMachineFunction().getMachineMemOperand(
23815                       Load->getMemOperand(), 0, EVT.getStoreSize()));
23816   return NewLoad;
23817 }
23818
23819 static SDValue PerformINSERTPSCombine(SDNode *N, SelectionDAG &DAG,
23820                                       const X86Subtarget *Subtarget) {
23821   SDLoc dl(N);
23822   MVT VT = N->getOperand(1)->getSimpleValueType(0);
23823   assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
23824          "X86insertps is only defined for v4x32");
23825
23826   SDValue Ld = N->getOperand(1);
23827   if (MayFoldLoad(Ld)) {
23828     // Extract the countS bits from the immediate so we can get the proper
23829     // address when narrowing the vector load to a specific element.
23830     // When the second source op is a memory address, insertps doesn't use
23831     // countS and just gets an f32 from that address.
23832     unsigned DestIndex =
23833         cast<ConstantSDNode>(N->getOperand(2))->getZExtValue() >> 6;
23834
23835     Ld = NarrowVectorLoadToElement(cast<LoadSDNode>(Ld), DestIndex, DAG);
23836
23837     // Create this as a scalar to vector to match the instruction pattern.
23838     SDValue LoadScalarToVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Ld);
23839     // countS bits are ignored when loading from memory on insertps, which
23840     // means we don't need to explicitly set them to 0.
23841     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N->getOperand(0),
23842                        LoadScalarToVector, N->getOperand(2));
23843   }
23844   return SDValue();
23845 }
23846
23847 static SDValue PerformBLENDICombine(SDNode *N, SelectionDAG &DAG) {
23848   SDValue V0 = N->getOperand(0);
23849   SDValue V1 = N->getOperand(1);
23850   SDLoc DL(N);
23851   EVT VT = N->getValueType(0);
23852
23853   // Canonicalize a v2f64 blend with a mask of 2 by swapping the vector
23854   // operands and changing the mask to 1. This saves us a bunch of
23855   // pattern-matching possibilities related to scalar math ops in SSE/AVX.
23856   // x86InstrInfo knows how to commute this back after instruction selection
23857   // if it would help register allocation.
23858
23859   // TODO: If optimizing for size or a processor that doesn't suffer from
23860   // partial register update stalls, this should be transformed into a MOVSD
23861   // instruction because a MOVSD is 1-2 bytes smaller than a BLENDPD.
23862
23863   if (VT == MVT::v2f64)
23864     if (auto *Mask = dyn_cast<ConstantSDNode>(N->getOperand(2)))
23865       if (Mask->getZExtValue() == 2 && !isShuffleFoldableLoad(V0)) {
23866         SDValue NewMask = DAG.getConstant(1, DL, MVT::i8);
23867         return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V0, NewMask);
23868       }
23869
23870   return SDValue();
23871 }
23872
23873 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
23874 // as "sbb reg,reg", since it can be extended without zext and produces
23875 // an all-ones bit which is more useful than 0/1 in some cases.
23876 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
23877                                MVT VT) {
23878   if (VT == MVT::i8)
23879     return DAG.getNode(ISD::AND, DL, VT,
23880                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
23881                                    DAG.getConstant(X86::COND_B, DL, MVT::i8),
23882                                    EFLAGS),
23883                        DAG.getConstant(1, DL, VT));
23884   assert (VT == MVT::i1 && "Unexpected type for SECCC node");
23885   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
23886                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
23887                                  DAG.getConstant(X86::COND_B, DL, MVT::i8),
23888                                  EFLAGS));
23889 }
23890
23891 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
23892 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
23893                                    TargetLowering::DAGCombinerInfo &DCI,
23894                                    const X86Subtarget *Subtarget) {
23895   SDLoc DL(N);
23896   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
23897   SDValue EFLAGS = N->getOperand(1);
23898
23899   if (CC == X86::COND_A) {
23900     // Try to convert COND_A into COND_B in an attempt to facilitate
23901     // materializing "setb reg".
23902     //
23903     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
23904     // cannot take an immediate as its first operand.
23905     //
23906     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
23907         EFLAGS.getValueType().isInteger() &&
23908         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
23909       SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
23910                                    EFLAGS.getNode()->getVTList(),
23911                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
23912       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
23913       return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
23914     }
23915   }
23916
23917   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
23918   // a zext and produces an all-ones bit which is more useful than 0/1 in some
23919   // cases.
23920   if (CC == X86::COND_B)
23921     return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
23922
23923   SDValue Flags;
23924
23925   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
23926   if (Flags.getNode()) {
23927     SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
23928     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
23929   }
23930
23931   return SDValue();
23932 }
23933
23934 // Optimize branch condition evaluation.
23935 //
23936 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
23937                                     TargetLowering::DAGCombinerInfo &DCI,
23938                                     const X86Subtarget *Subtarget) {
23939   SDLoc DL(N);
23940   SDValue Chain = N->getOperand(0);
23941   SDValue Dest = N->getOperand(1);
23942   SDValue EFLAGS = N->getOperand(3);
23943   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
23944
23945   SDValue Flags;
23946
23947   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
23948   if (Flags.getNode()) {
23949     SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
23950     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
23951                        Flags);
23952   }
23953
23954   return SDValue();
23955 }
23956
23957 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
23958                                                          SelectionDAG &DAG) {
23959   // Take advantage of vector comparisons producing 0 or -1 in each lane to
23960   // optimize away operation when it's from a constant.
23961   //
23962   // The general transformation is:
23963   //    UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
23964   //       AND(VECTOR_CMP(x,y), constant2)
23965   //    constant2 = UNARYOP(constant)
23966
23967   // Early exit if this isn't a vector operation, the operand of the
23968   // unary operation isn't a bitwise AND, or if the sizes of the operations
23969   // aren't the same.
23970   EVT VT = N->getValueType(0);
23971   if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
23972       N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
23973       VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
23974     return SDValue();
23975
23976   // Now check that the other operand of the AND is a constant. We could
23977   // make the transformation for non-constant splats as well, but it's unclear
23978   // that would be a benefit as it would not eliminate any operations, just
23979   // perform one more step in scalar code before moving to the vector unit.
23980   if (BuildVectorSDNode *BV =
23981           dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
23982     // Bail out if the vector isn't a constant.
23983     if (!BV->isConstant())
23984       return SDValue();
23985
23986     // Everything checks out. Build up the new and improved node.
23987     SDLoc DL(N);
23988     EVT IntVT = BV->getValueType(0);
23989     // Create a new constant of the appropriate type for the transformed
23990     // DAG.
23991     SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
23992     // The AND node needs bitcasts to/from an integer vector type around it.
23993     SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
23994     SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
23995                                  N->getOperand(0)->getOperand(0), MaskConst);
23996     SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
23997     return Res;
23998   }
23999
24000   return SDValue();
24001 }
24002
24003 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
24004                                         const X86Subtarget *Subtarget) {
24005   // First try to optimize away the conversion entirely when it's
24006   // conditionally from a constant. Vectors only.
24007   SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG);
24008   if (Res != SDValue())
24009     return Res;
24010
24011   // Now move on to more general possibilities.
24012   SDValue Op0 = N->getOperand(0);
24013   EVT InVT = Op0->getValueType(0);
24014
24015   // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
24016   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
24017     SDLoc dl(N);
24018     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
24019     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
24020     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
24021   }
24022
24023   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
24024   // a 32-bit target where SSE doesn't support i64->FP operations.
24025   if (Op0.getOpcode() == ISD::LOAD) {
24026     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
24027     EVT VT = Ld->getValueType(0);
24028
24029     // This transformation is not supported if the result type is f16
24030     if (N->getValueType(0) == MVT::f16)
24031       return SDValue();
24032
24033     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
24034         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
24035         !Subtarget->is64Bit() && VT == MVT::i64) {
24036       SDValue FILDChain = Subtarget->getTargetLowering()->BuildFILD(
24037           SDValue(N, 0), Ld->getValueType(0), Ld->getChain(), Op0, DAG);
24038       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
24039       return FILDChain;
24040     }
24041   }
24042   return SDValue();
24043 }
24044
24045 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
24046 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
24047                                  X86TargetLowering::DAGCombinerInfo &DCI) {
24048   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
24049   // the result is either zero or one (depending on the input carry bit).
24050   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
24051   if (X86::isZeroNode(N->getOperand(0)) &&
24052       X86::isZeroNode(N->getOperand(1)) &&
24053       // We don't have a good way to replace an EFLAGS use, so only do this when
24054       // dead right now.
24055       SDValue(N, 1).use_empty()) {
24056     SDLoc DL(N);
24057     EVT VT = N->getValueType(0);
24058     SDValue CarryOut = DAG.getConstant(0, DL, N->getValueType(1));
24059     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
24060                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
24061                                            DAG.getConstant(X86::COND_B, DL,
24062                                                            MVT::i8),
24063                                            N->getOperand(2)),
24064                                DAG.getConstant(1, DL, VT));
24065     return DCI.CombineTo(N, Res1, CarryOut);
24066   }
24067
24068   return SDValue();
24069 }
24070
24071 // fold (add Y, (sete  X, 0)) -> adc  0, Y
24072 //      (add Y, (setne X, 0)) -> sbb -1, Y
24073 //      (sub (sete  X, 0), Y) -> sbb  0, Y
24074 //      (sub (setne X, 0), Y) -> adc -1, Y
24075 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
24076   SDLoc DL(N);
24077
24078   // Look through ZExts.
24079   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
24080   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
24081     return SDValue();
24082
24083   SDValue SetCC = Ext.getOperand(0);
24084   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
24085     return SDValue();
24086
24087   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
24088   if (CC != X86::COND_E && CC != X86::COND_NE)
24089     return SDValue();
24090
24091   SDValue Cmp = SetCC.getOperand(1);
24092   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
24093       !X86::isZeroNode(Cmp.getOperand(1)) ||
24094       !Cmp.getOperand(0).getValueType().isInteger())
24095     return SDValue();
24096
24097   SDValue CmpOp0 = Cmp.getOperand(0);
24098   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
24099                                DAG.getConstant(1, DL, CmpOp0.getValueType()));
24100
24101   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
24102   if (CC == X86::COND_NE)
24103     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
24104                        DL, OtherVal.getValueType(), OtherVal,
24105                        DAG.getConstant(-1ULL, DL, OtherVal.getValueType()),
24106                        NewCmp);
24107   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
24108                      DL, OtherVal.getValueType(), OtherVal,
24109                      DAG.getConstant(0, DL, OtherVal.getValueType()), NewCmp);
24110 }
24111
24112 /// PerformADDCombine - Do target-specific dag combines on integer adds.
24113 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
24114                                  const X86Subtarget *Subtarget) {
24115   EVT VT = N->getValueType(0);
24116   SDValue Op0 = N->getOperand(0);
24117   SDValue Op1 = N->getOperand(1);
24118
24119   // Try to synthesize horizontal adds from adds of shuffles.
24120   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
24121        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
24122       isHorizontalBinOp(Op0, Op1, true))
24123     return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
24124
24125   return OptimizeConditionalInDecrement(N, DAG);
24126 }
24127
24128 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
24129                                  const X86Subtarget *Subtarget) {
24130   SDValue Op0 = N->getOperand(0);
24131   SDValue Op1 = N->getOperand(1);
24132
24133   // X86 can't encode an immediate LHS of a sub. See if we can push the
24134   // negation into a preceding instruction.
24135   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
24136     // If the RHS of the sub is a XOR with one use and a constant, invert the
24137     // immediate. Then add one to the LHS of the sub so we can turn
24138     // X-Y -> X+~Y+1, saving one register.
24139     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
24140         isa<ConstantSDNode>(Op1.getOperand(1))) {
24141       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
24142       EVT VT = Op0.getValueType();
24143       SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
24144                                    Op1.getOperand(0),
24145                                    DAG.getConstant(~XorC, SDLoc(Op1), VT));
24146       return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
24147                          DAG.getConstant(C->getAPIntValue() + 1, SDLoc(N), VT));
24148     }
24149   }
24150
24151   // Try to synthesize horizontal adds from adds of shuffles.
24152   EVT VT = N->getValueType(0);
24153   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
24154        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
24155       isHorizontalBinOp(Op0, Op1, true))
24156     return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
24157
24158   return OptimizeConditionalInDecrement(N, DAG);
24159 }
24160
24161 /// performVZEXTCombine - Performs build vector combines
24162 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
24163                                    TargetLowering::DAGCombinerInfo &DCI,
24164                                    const X86Subtarget *Subtarget) {
24165   SDLoc DL(N);
24166   MVT VT = N->getSimpleValueType(0);
24167   SDValue Op = N->getOperand(0);
24168   MVT OpVT = Op.getSimpleValueType();
24169   MVT OpEltVT = OpVT.getVectorElementType();
24170   unsigned InputBits = OpEltVT.getSizeInBits() * VT.getVectorNumElements();
24171
24172   // (vzext (bitcast (vzext (x)) -> (vzext x)
24173   SDValue V = Op;
24174   while (V.getOpcode() == ISD::BITCAST)
24175     V = V.getOperand(0);
24176
24177   if (V != Op && V.getOpcode() == X86ISD::VZEXT) {
24178     MVT InnerVT = V.getSimpleValueType();
24179     MVT InnerEltVT = InnerVT.getVectorElementType();
24180
24181     // If the element sizes match exactly, we can just do one larger vzext. This
24182     // is always an exact type match as vzext operates on integer types.
24183     if (OpEltVT == InnerEltVT) {
24184       assert(OpVT == InnerVT && "Types must match for vzext!");
24185       return DAG.getNode(X86ISD::VZEXT, DL, VT, V.getOperand(0));
24186     }
24187
24188     // The only other way we can combine them is if only a single element of the
24189     // inner vzext is used in the input to the outer vzext.
24190     if (InnerEltVT.getSizeInBits() < InputBits)
24191       return SDValue();
24192
24193     // In this case, the inner vzext is completely dead because we're going to
24194     // only look at bits inside of the low element. Just do the outer vzext on
24195     // a bitcast of the input to the inner.
24196     return DAG.getNode(X86ISD::VZEXT, DL, VT,
24197                        DAG.getNode(ISD::BITCAST, DL, OpVT, V));
24198   }
24199
24200   // Check if we can bypass extracting and re-inserting an element of an input
24201   // vector. Essentialy:
24202   // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
24203   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR &&
24204       V.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
24205       V.getOperand(0).getSimpleValueType().getSizeInBits() == InputBits) {
24206     SDValue ExtractedV = V.getOperand(0);
24207     SDValue OrigV = ExtractedV.getOperand(0);
24208     if (auto *ExtractIdx = dyn_cast<ConstantSDNode>(ExtractedV.getOperand(1)))
24209       if (ExtractIdx->getZExtValue() == 0) {
24210         MVT OrigVT = OrigV.getSimpleValueType();
24211         // Extract a subvector if necessary...
24212         if (OrigVT.getSizeInBits() > OpVT.getSizeInBits()) {
24213           int Ratio = OrigVT.getSizeInBits() / OpVT.getSizeInBits();
24214           OrigVT = MVT::getVectorVT(OrigVT.getVectorElementType(),
24215                                     OrigVT.getVectorNumElements() / Ratio);
24216           OrigV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigVT, OrigV,
24217                               DAG.getIntPtrConstant(0, DL));
24218         }
24219         Op = DAG.getNode(ISD::BITCAST, DL, OpVT, OrigV);
24220         return DAG.getNode(X86ISD::VZEXT, DL, VT, Op);
24221       }
24222   }
24223
24224   return SDValue();
24225 }
24226
24227 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
24228                                              DAGCombinerInfo &DCI) const {
24229   SelectionDAG &DAG = DCI.DAG;
24230   switch (N->getOpcode()) {
24231   default: break;
24232   case ISD::EXTRACT_VECTOR_ELT:
24233     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
24234   case ISD::VSELECT:
24235   case ISD::SELECT:
24236   case X86ISD::SHRUNKBLEND:
24237     return PerformSELECTCombine(N, DAG, DCI, Subtarget);
24238   case ISD::BITCAST:        return PerformBITCASTCombine(N, DAG);
24239   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
24240   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
24241   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
24242   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
24243   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
24244   case ISD::SHL:
24245   case ISD::SRA:
24246   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
24247   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
24248   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
24249   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
24250   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
24251   case ISD::MLOAD:          return PerformMLOADCombine(N, DAG, DCI, Subtarget);
24252   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
24253   case ISD::MSTORE:         return PerformMSTORECombine(N, DAG, Subtarget);
24254   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, Subtarget);
24255   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
24256   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
24257   case X86ISD::FXOR:
24258   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
24259   case X86ISD::FMIN:
24260   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
24261   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
24262   case X86ISD::FANDN:       return PerformFANDNCombine(N, DAG);
24263   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
24264   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
24265   case ISD::ANY_EXTEND:
24266   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
24267   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
24268   case ISD::SIGN_EXTEND_INREG:
24269     return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
24270   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG, Subtarget);
24271   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
24272   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
24273   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
24274   case X86ISD::SHUFP:       // Handle all target specific shuffles
24275   case X86ISD::PALIGNR:
24276   case X86ISD::UNPCKH:
24277   case X86ISD::UNPCKL:
24278   case X86ISD::MOVHLPS:
24279   case X86ISD::MOVLHPS:
24280   case X86ISD::PSHUFB:
24281   case X86ISD::PSHUFD:
24282   case X86ISD::PSHUFHW:
24283   case X86ISD::PSHUFLW:
24284   case X86ISD::MOVSS:
24285   case X86ISD::MOVSD:
24286   case X86ISD::VPERMILPI:
24287   case X86ISD::VPERM2X128:
24288   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
24289   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
24290   case ISD::INTRINSIC_WO_CHAIN:
24291     return PerformINTRINSIC_WO_CHAINCombine(N, DAG, Subtarget);
24292   case X86ISD::INSERTPS: {
24293     if (getTargetMachine().getOptLevel() > CodeGenOpt::None)
24294       return PerformINSERTPSCombine(N, DAG, Subtarget);
24295     break;
24296   }
24297   case X86ISD::BLENDI:    return PerformBLENDICombine(N, DAG);
24298   }
24299
24300   return SDValue();
24301 }
24302
24303 /// isTypeDesirableForOp - Return true if the target has native support for
24304 /// the specified value type and it is 'desirable' to use the type for the
24305 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
24306 /// instruction encodings are longer and some i16 instructions are slow.
24307 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
24308   if (!isTypeLegal(VT))
24309     return false;
24310   if (VT != MVT::i16)
24311     return true;
24312
24313   switch (Opc) {
24314   default:
24315     return true;
24316   case ISD::LOAD:
24317   case ISD::SIGN_EXTEND:
24318   case ISD::ZERO_EXTEND:
24319   case ISD::ANY_EXTEND:
24320   case ISD::SHL:
24321   case ISD::SRL:
24322   case ISD::SUB:
24323   case ISD::ADD:
24324   case ISD::MUL:
24325   case ISD::AND:
24326   case ISD::OR:
24327   case ISD::XOR:
24328     return false;
24329   }
24330 }
24331
24332 /// IsDesirableToPromoteOp - This method query the target whether it is
24333 /// beneficial for dag combiner to promote the specified node. If true, it
24334 /// should return the desired promotion type by reference.
24335 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
24336   EVT VT = Op.getValueType();
24337   if (VT != MVT::i16)
24338     return false;
24339
24340   bool Promote = false;
24341   bool Commute = false;
24342   switch (Op.getOpcode()) {
24343   default: break;
24344   case ISD::LOAD: {
24345     LoadSDNode *LD = cast<LoadSDNode>(Op);
24346     // If the non-extending load has a single use and it's not live out, then it
24347     // might be folded.
24348     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
24349                                                      Op.hasOneUse()*/) {
24350       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
24351              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
24352         // The only case where we'd want to promote LOAD (rather then it being
24353         // promoted as an operand is when it's only use is liveout.
24354         if (UI->getOpcode() != ISD::CopyToReg)
24355           return false;
24356       }
24357     }
24358     Promote = true;
24359     break;
24360   }
24361   case ISD::SIGN_EXTEND:
24362   case ISD::ZERO_EXTEND:
24363   case ISD::ANY_EXTEND:
24364     Promote = true;
24365     break;
24366   case ISD::SHL:
24367   case ISD::SRL: {
24368     SDValue N0 = Op.getOperand(0);
24369     // Look out for (store (shl (load), x)).
24370     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
24371       return false;
24372     Promote = true;
24373     break;
24374   }
24375   case ISD::ADD:
24376   case ISD::MUL:
24377   case ISD::AND:
24378   case ISD::OR:
24379   case ISD::XOR:
24380     Commute = true;
24381     // fallthrough
24382   case ISD::SUB: {
24383     SDValue N0 = Op.getOperand(0);
24384     SDValue N1 = Op.getOperand(1);
24385     if (!Commute && MayFoldLoad(N1))
24386       return false;
24387     // Avoid disabling potential load folding opportunities.
24388     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
24389       return false;
24390     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
24391       return false;
24392     Promote = true;
24393   }
24394   }
24395
24396   PVT = MVT::i32;
24397   return Promote;
24398 }
24399
24400 //===----------------------------------------------------------------------===//
24401 //                           X86 Inline Assembly Support
24402 //===----------------------------------------------------------------------===//
24403
24404 // Helper to match a string separated by whitespace.
24405 static bool matchAsm(StringRef S, ArrayRef<const char *> Pieces) {
24406   S = S.substr(S.find_first_not_of(" \t")); // Skip leading whitespace.
24407
24408   for (StringRef Piece : Pieces) {
24409     if (!S.startswith(Piece)) // Check if the piece matches.
24410       return false;
24411
24412     S = S.substr(Piece.size());
24413     StringRef::size_type Pos = S.find_first_not_of(" \t");
24414     if (Pos == 0) // We matched a prefix.
24415       return false;
24416
24417     S = S.substr(Pos);
24418   }
24419
24420   return S.empty();
24421 }
24422
24423 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
24424
24425   if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
24426     if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
24427         std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
24428         std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
24429
24430       if (AsmPieces.size() == 3)
24431         return true;
24432       else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
24433         return true;
24434     }
24435   }
24436   return false;
24437 }
24438
24439 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
24440   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
24441
24442   std::string AsmStr = IA->getAsmString();
24443
24444   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
24445   if (!Ty || Ty->getBitWidth() % 16 != 0)
24446     return false;
24447
24448   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
24449   SmallVector<StringRef, 4> AsmPieces;
24450   SplitString(AsmStr, AsmPieces, ";\n");
24451
24452   switch (AsmPieces.size()) {
24453   default: return false;
24454   case 1:
24455     // FIXME: this should verify that we are targeting a 486 or better.  If not,
24456     // we will turn this bswap into something that will be lowered to logical
24457     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
24458     // lower so don't worry about this.
24459     // bswap $0
24460     if (matchAsm(AsmPieces[0], {"bswap", "$0"}) ||
24461         matchAsm(AsmPieces[0], {"bswapl", "$0"}) ||
24462         matchAsm(AsmPieces[0], {"bswapq", "$0"}) ||
24463         matchAsm(AsmPieces[0], {"bswap", "${0:q}"}) ||
24464         matchAsm(AsmPieces[0], {"bswapl", "${0:q}"}) ||
24465         matchAsm(AsmPieces[0], {"bswapq", "${0:q}"})) {
24466       // No need to check constraints, nothing other than the equivalent of
24467       // "=r,0" would be valid here.
24468       return IntrinsicLowering::LowerToByteSwap(CI);
24469     }
24470
24471     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
24472     if (CI->getType()->isIntegerTy(16) &&
24473         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
24474         (matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) ||
24475          matchAsm(AsmPieces[0], {"rolw", "$$8,", "${0:w}"}))) {
24476       AsmPieces.clear();
24477       const std::string &ConstraintsStr = IA->getConstraintString();
24478       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
24479       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
24480       if (clobbersFlagRegisters(AsmPieces))
24481         return IntrinsicLowering::LowerToByteSwap(CI);
24482     }
24483     break;
24484   case 3:
24485     if (CI->getType()->isIntegerTy(32) &&
24486         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
24487         matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) &&
24488         matchAsm(AsmPieces[1], {"rorl", "$$16,", "$0"}) &&
24489         matchAsm(AsmPieces[2], {"rorw", "$$8,", "${0:w}"})) {
24490       AsmPieces.clear();
24491       const std::string &ConstraintsStr = IA->getConstraintString();
24492       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
24493       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
24494       if (clobbersFlagRegisters(AsmPieces))
24495         return IntrinsicLowering::LowerToByteSwap(CI);
24496     }
24497
24498     if (CI->getType()->isIntegerTy(64)) {
24499       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
24500       if (Constraints.size() >= 2 &&
24501           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
24502           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
24503         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
24504         if (matchAsm(AsmPieces[0], {"bswap", "%eax"}) &&
24505             matchAsm(AsmPieces[1], {"bswap", "%edx"}) &&
24506             matchAsm(AsmPieces[2], {"xchgl", "%eax,", "%edx"}))
24507           return IntrinsicLowering::LowerToByteSwap(CI);
24508       }
24509     }
24510     break;
24511   }
24512   return false;
24513 }
24514
24515 /// getConstraintType - Given a constraint letter, return the type of
24516 /// constraint it is for this target.
24517 X86TargetLowering::ConstraintType
24518 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
24519   if (Constraint.size() == 1) {
24520     switch (Constraint[0]) {
24521     case 'R':
24522     case 'q':
24523     case 'Q':
24524     case 'f':
24525     case 't':
24526     case 'u':
24527     case 'y':
24528     case 'x':
24529     case 'Y':
24530     case 'l':
24531       return C_RegisterClass;
24532     case 'a':
24533     case 'b':
24534     case 'c':
24535     case 'd':
24536     case 'S':
24537     case 'D':
24538     case 'A':
24539       return C_Register;
24540     case 'I':
24541     case 'J':
24542     case 'K':
24543     case 'L':
24544     case 'M':
24545     case 'N':
24546     case 'G':
24547     case 'C':
24548     case 'e':
24549     case 'Z':
24550       return C_Other;
24551     default:
24552       break;
24553     }
24554   }
24555   return TargetLowering::getConstraintType(Constraint);
24556 }
24557
24558 /// Examine constraint type and operand type and determine a weight value.
24559 /// This object must already have been set up with the operand type
24560 /// and the current alternative constraint selected.
24561 TargetLowering::ConstraintWeight
24562   X86TargetLowering::getSingleConstraintMatchWeight(
24563     AsmOperandInfo &info, const char *constraint) const {
24564   ConstraintWeight weight = CW_Invalid;
24565   Value *CallOperandVal = info.CallOperandVal;
24566     // If we don't have a value, we can't do a match,
24567     // but allow it at the lowest weight.
24568   if (!CallOperandVal)
24569     return CW_Default;
24570   Type *type = CallOperandVal->getType();
24571   // Look at the constraint type.
24572   switch (*constraint) {
24573   default:
24574     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
24575   case 'R':
24576   case 'q':
24577   case 'Q':
24578   case 'a':
24579   case 'b':
24580   case 'c':
24581   case 'd':
24582   case 'S':
24583   case 'D':
24584   case 'A':
24585     if (CallOperandVal->getType()->isIntegerTy())
24586       weight = CW_SpecificReg;
24587     break;
24588   case 'f':
24589   case 't':
24590   case 'u':
24591     if (type->isFloatingPointTy())
24592       weight = CW_SpecificReg;
24593     break;
24594   case 'y':
24595     if (type->isX86_MMXTy() && Subtarget->hasMMX())
24596       weight = CW_SpecificReg;
24597     break;
24598   case 'x':
24599   case 'Y':
24600     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
24601         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
24602       weight = CW_Register;
24603     break;
24604   case 'I':
24605     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
24606       if (C->getZExtValue() <= 31)
24607         weight = CW_Constant;
24608     }
24609     break;
24610   case 'J':
24611     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24612       if (C->getZExtValue() <= 63)
24613         weight = CW_Constant;
24614     }
24615     break;
24616   case 'K':
24617     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24618       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
24619         weight = CW_Constant;
24620     }
24621     break;
24622   case 'L':
24623     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24624       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
24625         weight = CW_Constant;
24626     }
24627     break;
24628   case 'M':
24629     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24630       if (C->getZExtValue() <= 3)
24631         weight = CW_Constant;
24632     }
24633     break;
24634   case 'N':
24635     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24636       if (C->getZExtValue() <= 0xff)
24637         weight = CW_Constant;
24638     }
24639     break;
24640   case 'G':
24641   case 'C':
24642     if (isa<ConstantFP>(CallOperandVal)) {
24643       weight = CW_Constant;
24644     }
24645     break;
24646   case 'e':
24647     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24648       if ((C->getSExtValue() >= -0x80000000LL) &&
24649           (C->getSExtValue() <= 0x7fffffffLL))
24650         weight = CW_Constant;
24651     }
24652     break;
24653   case 'Z':
24654     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24655       if (C->getZExtValue() <= 0xffffffff)
24656         weight = CW_Constant;
24657     }
24658     break;
24659   }
24660   return weight;
24661 }
24662
24663 /// LowerXConstraint - try to replace an X constraint, which matches anything,
24664 /// with another that has more specific requirements based on the type of the
24665 /// corresponding operand.
24666 const char *X86TargetLowering::
24667 LowerXConstraint(EVT ConstraintVT) const {
24668   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
24669   // 'f' like normal targets.
24670   if (ConstraintVT.isFloatingPoint()) {
24671     if (Subtarget->hasSSE2())
24672       return "Y";
24673     if (Subtarget->hasSSE1())
24674       return "x";
24675   }
24676
24677   return TargetLowering::LowerXConstraint(ConstraintVT);
24678 }
24679
24680 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
24681 /// vector.  If it is invalid, don't add anything to Ops.
24682 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
24683                                                      std::string &Constraint,
24684                                                      std::vector<SDValue>&Ops,
24685                                                      SelectionDAG &DAG) const {
24686   SDValue Result;
24687
24688   // Only support length 1 constraints for now.
24689   if (Constraint.length() > 1) return;
24690
24691   char ConstraintLetter = Constraint[0];
24692   switch (ConstraintLetter) {
24693   default: break;
24694   case 'I':
24695     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24696       if (C->getZExtValue() <= 31) {
24697         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
24698                                        Op.getValueType());
24699         break;
24700       }
24701     }
24702     return;
24703   case 'J':
24704     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24705       if (C->getZExtValue() <= 63) {
24706         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
24707                                        Op.getValueType());
24708         break;
24709       }
24710     }
24711     return;
24712   case 'K':
24713     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24714       if (isInt<8>(C->getSExtValue())) {
24715         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
24716                                        Op.getValueType());
24717         break;
24718       }
24719     }
24720     return;
24721   case 'L':
24722     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24723       if (C->getZExtValue() == 0xff || C->getZExtValue() == 0xffff ||
24724           (Subtarget->is64Bit() && C->getZExtValue() == 0xffffffff)) {
24725         Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op),
24726                                        Op.getValueType());
24727         break;
24728       }
24729     }
24730     return;
24731   case 'M':
24732     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24733       if (C->getZExtValue() <= 3) {
24734         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
24735                                        Op.getValueType());
24736         break;
24737       }
24738     }
24739     return;
24740   case 'N':
24741     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24742       if (C->getZExtValue() <= 255) {
24743         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
24744                                        Op.getValueType());
24745         break;
24746       }
24747     }
24748     return;
24749   case 'O':
24750     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24751       if (C->getZExtValue() <= 127) {
24752         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
24753                                        Op.getValueType());
24754         break;
24755       }
24756     }
24757     return;
24758   case 'e': {
24759     // 32-bit signed value
24760     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24761       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
24762                                            C->getSExtValue())) {
24763         // Widen to 64 bits here to get it sign extended.
24764         Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op), MVT::i64);
24765         break;
24766       }
24767     // FIXME gcc accepts some relocatable values here too, but only in certain
24768     // memory models; it's complicated.
24769     }
24770     return;
24771   }
24772   case 'Z': {
24773     // 32-bit unsigned value
24774     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24775       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
24776                                            C->getZExtValue())) {
24777         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
24778                                        Op.getValueType());
24779         break;
24780       }
24781     }
24782     // FIXME gcc accepts some relocatable values here too, but only in certain
24783     // memory models; it's complicated.
24784     return;
24785   }
24786   case 'i': {
24787     // Literal immediates are always ok.
24788     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
24789       // Widen to 64 bits here to get it sign extended.
24790       Result = DAG.getTargetConstant(CST->getSExtValue(), SDLoc(Op), MVT::i64);
24791       break;
24792     }
24793
24794     // In any sort of PIC mode addresses need to be computed at runtime by
24795     // adding in a register or some sort of table lookup.  These can't
24796     // be used as immediates.
24797     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
24798       return;
24799
24800     // If we are in non-pic codegen mode, we allow the address of a global (with
24801     // an optional displacement) to be used with 'i'.
24802     GlobalAddressSDNode *GA = nullptr;
24803     int64_t Offset = 0;
24804
24805     // Match either (GA), (GA+C), (GA+C1+C2), etc.
24806     while (1) {
24807       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
24808         Offset += GA->getOffset();
24809         break;
24810       } else if (Op.getOpcode() == ISD::ADD) {
24811         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
24812           Offset += C->getZExtValue();
24813           Op = Op.getOperand(0);
24814           continue;
24815         }
24816       } else if (Op.getOpcode() == ISD::SUB) {
24817         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
24818           Offset += -C->getZExtValue();
24819           Op = Op.getOperand(0);
24820           continue;
24821         }
24822       }
24823
24824       // Otherwise, this isn't something we can handle, reject it.
24825       return;
24826     }
24827
24828     const GlobalValue *GV = GA->getGlobal();
24829     // If we require an extra load to get this address, as in PIC mode, we
24830     // can't accept it.
24831     if (isGlobalStubReference(
24832             Subtarget->ClassifyGlobalReference(GV, DAG.getTarget())))
24833       return;
24834
24835     Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
24836                                         GA->getValueType(0), Offset);
24837     break;
24838   }
24839   }
24840
24841   if (Result.getNode()) {
24842     Ops.push_back(Result);
24843     return;
24844   }
24845   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
24846 }
24847
24848 std::pair<unsigned, const TargetRegisterClass *>
24849 X86TargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
24850                                                 const std::string &Constraint,
24851                                                 MVT VT) const {
24852   // First, see if this is a constraint that directly corresponds to an LLVM
24853   // register class.
24854   if (Constraint.size() == 1) {
24855     // GCC Constraint Letters
24856     switch (Constraint[0]) {
24857     default: break;
24858       // TODO: Slight differences here in allocation order and leaving
24859       // RIP in the class. Do they matter any more here than they do
24860       // in the normal allocation?
24861     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
24862       if (Subtarget->is64Bit()) {
24863         if (VT == MVT::i32 || VT == MVT::f32)
24864           return std::make_pair(0U, &X86::GR32RegClass);
24865         if (VT == MVT::i16)
24866           return std::make_pair(0U, &X86::GR16RegClass);
24867         if (VT == MVT::i8 || VT == MVT::i1)
24868           return std::make_pair(0U, &X86::GR8RegClass);
24869         if (VT == MVT::i64 || VT == MVT::f64)
24870           return std::make_pair(0U, &X86::GR64RegClass);
24871         break;
24872       }
24873       // 32-bit fallthrough
24874     case 'Q':   // Q_REGS
24875       if (VT == MVT::i32 || VT == MVT::f32)
24876         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
24877       if (VT == MVT::i16)
24878         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
24879       if (VT == MVT::i8 || VT == MVT::i1)
24880         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
24881       if (VT == MVT::i64)
24882         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
24883       break;
24884     case 'r':   // GENERAL_REGS
24885     case 'l':   // INDEX_REGS
24886       if (VT == MVT::i8 || VT == MVT::i1)
24887         return std::make_pair(0U, &X86::GR8RegClass);
24888       if (VT == MVT::i16)
24889         return std::make_pair(0U, &X86::GR16RegClass);
24890       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
24891         return std::make_pair(0U, &X86::GR32RegClass);
24892       return std::make_pair(0U, &X86::GR64RegClass);
24893     case 'R':   // LEGACY_REGS
24894       if (VT == MVT::i8 || VT == MVT::i1)
24895         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
24896       if (VT == MVT::i16)
24897         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
24898       if (VT == MVT::i32 || !Subtarget->is64Bit())
24899         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
24900       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
24901     case 'f':  // FP Stack registers.
24902       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
24903       // value to the correct fpstack register class.
24904       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
24905         return std::make_pair(0U, &X86::RFP32RegClass);
24906       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
24907         return std::make_pair(0U, &X86::RFP64RegClass);
24908       return std::make_pair(0U, &X86::RFP80RegClass);
24909     case 'y':   // MMX_REGS if MMX allowed.
24910       if (!Subtarget->hasMMX()) break;
24911       return std::make_pair(0U, &X86::VR64RegClass);
24912     case 'Y':   // SSE_REGS if SSE2 allowed
24913       if (!Subtarget->hasSSE2()) break;
24914       // FALL THROUGH.
24915     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
24916       if (!Subtarget->hasSSE1()) break;
24917
24918       switch (VT.SimpleTy) {
24919       default: break;
24920       // Scalar SSE types.
24921       case MVT::f32:
24922       case MVT::i32:
24923         return std::make_pair(0U, &X86::FR32RegClass);
24924       case MVT::f64:
24925       case MVT::i64:
24926         return std::make_pair(0U, &X86::FR64RegClass);
24927       // Vector types.
24928       case MVT::v16i8:
24929       case MVT::v8i16:
24930       case MVT::v4i32:
24931       case MVT::v2i64:
24932       case MVT::v4f32:
24933       case MVT::v2f64:
24934         return std::make_pair(0U, &X86::VR128RegClass);
24935       // AVX types.
24936       case MVT::v32i8:
24937       case MVT::v16i16:
24938       case MVT::v8i32:
24939       case MVT::v4i64:
24940       case MVT::v8f32:
24941       case MVT::v4f64:
24942         return std::make_pair(0U, &X86::VR256RegClass);
24943       case MVT::v8f64:
24944       case MVT::v16f32:
24945       case MVT::v16i32:
24946       case MVT::v8i64:
24947         return std::make_pair(0U, &X86::VR512RegClass);
24948       }
24949       break;
24950     }
24951   }
24952
24953   // Use the default implementation in TargetLowering to convert the register
24954   // constraint into a member of a register class.
24955   std::pair<unsigned, const TargetRegisterClass*> Res;
24956   Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
24957
24958   // Not found as a standard register?
24959   if (!Res.second) {
24960     // Map st(0) -> st(7) -> ST0
24961     if (Constraint.size() == 7 && Constraint[0] == '{' &&
24962         tolower(Constraint[1]) == 's' &&
24963         tolower(Constraint[2]) == 't' &&
24964         Constraint[3] == '(' &&
24965         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
24966         Constraint[5] == ')' &&
24967         Constraint[6] == '}') {
24968
24969       Res.first = X86::FP0+Constraint[4]-'0';
24970       Res.second = &X86::RFP80RegClass;
24971       return Res;
24972     }
24973
24974     // GCC allows "st(0)" to be called just plain "st".
24975     if (StringRef("{st}").equals_lower(Constraint)) {
24976       Res.first = X86::FP0;
24977       Res.second = &X86::RFP80RegClass;
24978       return Res;
24979     }
24980
24981     // flags -> EFLAGS
24982     if (StringRef("{flags}").equals_lower(Constraint)) {
24983       Res.first = X86::EFLAGS;
24984       Res.second = &X86::CCRRegClass;
24985       return Res;
24986     }
24987
24988     // 'A' means EAX + EDX.
24989     if (Constraint == "A") {
24990       Res.first = X86::EAX;
24991       Res.second = &X86::GR32_ADRegClass;
24992       return Res;
24993     }
24994     return Res;
24995   }
24996
24997   // Otherwise, check to see if this is a register class of the wrong value
24998   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
24999   // turn into {ax},{dx}.
25000   if (Res.second->hasType(VT))
25001     return Res;   // Correct type already, nothing to do.
25002
25003   // All of the single-register GCC register classes map their values onto
25004   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
25005   // really want an 8-bit or 32-bit register, map to the appropriate register
25006   // class and return the appropriate register.
25007   if (Res.second == &X86::GR16RegClass) {
25008     if (VT == MVT::i8 || VT == MVT::i1) {
25009       unsigned DestReg = 0;
25010       switch (Res.first) {
25011       default: break;
25012       case X86::AX: DestReg = X86::AL; break;
25013       case X86::DX: DestReg = X86::DL; break;
25014       case X86::CX: DestReg = X86::CL; break;
25015       case X86::BX: DestReg = X86::BL; break;
25016       }
25017       if (DestReg) {
25018         Res.first = DestReg;
25019         Res.second = &X86::GR8RegClass;
25020       }
25021     } else if (VT == MVT::i32 || VT == MVT::f32) {
25022       unsigned DestReg = 0;
25023       switch (Res.first) {
25024       default: break;
25025       case X86::AX: DestReg = X86::EAX; break;
25026       case X86::DX: DestReg = X86::EDX; break;
25027       case X86::CX: DestReg = X86::ECX; break;
25028       case X86::BX: DestReg = X86::EBX; break;
25029       case X86::SI: DestReg = X86::ESI; break;
25030       case X86::DI: DestReg = X86::EDI; break;
25031       case X86::BP: DestReg = X86::EBP; break;
25032       case X86::SP: DestReg = X86::ESP; break;
25033       }
25034       if (DestReg) {
25035         Res.first = DestReg;
25036         Res.second = &X86::GR32RegClass;
25037       }
25038     } else if (VT == MVT::i64 || VT == MVT::f64) {
25039       unsigned DestReg = 0;
25040       switch (Res.first) {
25041       default: break;
25042       case X86::AX: DestReg = X86::RAX; break;
25043       case X86::DX: DestReg = X86::RDX; break;
25044       case X86::CX: DestReg = X86::RCX; break;
25045       case X86::BX: DestReg = X86::RBX; break;
25046       case X86::SI: DestReg = X86::RSI; break;
25047       case X86::DI: DestReg = X86::RDI; break;
25048       case X86::BP: DestReg = X86::RBP; break;
25049       case X86::SP: DestReg = X86::RSP; break;
25050       }
25051       if (DestReg) {
25052         Res.first = DestReg;
25053         Res.second = &X86::GR64RegClass;
25054       }
25055     }
25056   } else if (Res.second == &X86::FR32RegClass ||
25057              Res.second == &X86::FR64RegClass ||
25058              Res.second == &X86::VR128RegClass ||
25059              Res.second == &X86::VR256RegClass ||
25060              Res.second == &X86::FR32XRegClass ||
25061              Res.second == &X86::FR64XRegClass ||
25062              Res.second == &X86::VR128XRegClass ||
25063              Res.second == &X86::VR256XRegClass ||
25064              Res.second == &X86::VR512RegClass) {
25065     // Handle references to XMM physical registers that got mapped into the
25066     // wrong class.  This can happen with constraints like {xmm0} where the
25067     // target independent register mapper will just pick the first match it can
25068     // find, ignoring the required type.
25069
25070     if (VT == MVT::f32 || VT == MVT::i32)
25071       Res.second = &X86::FR32RegClass;
25072     else if (VT == MVT::f64 || VT == MVT::i64)
25073       Res.second = &X86::FR64RegClass;
25074     else if (X86::VR128RegClass.hasType(VT))
25075       Res.second = &X86::VR128RegClass;
25076     else if (X86::VR256RegClass.hasType(VT))
25077       Res.second = &X86::VR256RegClass;
25078     else if (X86::VR512RegClass.hasType(VT))
25079       Res.second = &X86::VR512RegClass;
25080   }
25081
25082   return Res;
25083 }
25084
25085 int X86TargetLowering::getScalingFactorCost(const AddrMode &AM,
25086                                             Type *Ty) const {
25087   // Scaling factors are not free at all.
25088   // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
25089   // will take 2 allocations in the out of order engine instead of 1
25090   // for plain addressing mode, i.e. inst (reg1).
25091   // E.g.,
25092   // vaddps (%rsi,%drx), %ymm0, %ymm1
25093   // Requires two allocations (one for the load, one for the computation)
25094   // whereas:
25095   // vaddps (%rsi), %ymm0, %ymm1
25096   // Requires just 1 allocation, i.e., freeing allocations for other operations
25097   // and having less micro operations to execute.
25098   //
25099   // For some X86 architectures, this is even worse because for instance for
25100   // stores, the complex addressing mode forces the instruction to use the
25101   // "load" ports instead of the dedicated "store" port.
25102   // E.g., on Haswell:
25103   // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
25104   // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.
25105   if (isLegalAddressingMode(AM, Ty))
25106     // Scale represents reg2 * scale, thus account for 1
25107     // as soon as we use a second register.
25108     return AM.Scale != 0;
25109   return -1;
25110 }
25111
25112 bool X86TargetLowering::isTargetFTOL() const {
25113   return Subtarget->isTargetKnownWindowsMSVC() && !Subtarget->is64Bit();
25114 }