X86: Do not select X86 custom vector nodes if operand types don't match
[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 (!TM.Options.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 (!TM.Options.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 (!TM.Options.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 (TM.Options.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   if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
517     // f32 and f64 use SSE.
518     // Set up the FP register classes.
519     addRegisterClass(MVT::f32, &X86::FR32RegClass);
520     addRegisterClass(MVT::f64, &X86::FR64RegClass);
521
522     // Use ANDPD to simulate FABS.
523     setOperationAction(ISD::FABS , MVT::f64, Custom);
524     setOperationAction(ISD::FABS , MVT::f32, Custom);
525
526     // Use XORP to simulate FNEG.
527     setOperationAction(ISD::FNEG , MVT::f64, Custom);
528     setOperationAction(ISD::FNEG , MVT::f32, Custom);
529
530     // Use ANDPD and ORPD to simulate FCOPYSIGN.
531     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
532     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
533
534     // Lower this to FGETSIGNx86 plus an AND.
535     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
536     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
537
538     // We don't support sin/cos/fmod
539     setOperationAction(ISD::FSIN   , MVT::f64, Expand);
540     setOperationAction(ISD::FCOS   , MVT::f64, Expand);
541     setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
542     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
543     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
544     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
545
546     // Expand FP immediates into loads from the stack, except for the special
547     // cases we handle.
548     addLegalFPImmediate(APFloat(+0.0)); // xorpd
549     addLegalFPImmediate(APFloat(+0.0f)); // xorps
550   } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
551     // Use SSE for f32, x87 for f64.
552     // Set up the FP register classes.
553     addRegisterClass(MVT::f32, &X86::FR32RegClass);
554     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
555
556     // Use ANDPS to simulate FABS.
557     setOperationAction(ISD::FABS , MVT::f32, Custom);
558
559     // Use XORP to simulate FNEG.
560     setOperationAction(ISD::FNEG , MVT::f32, Custom);
561
562     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
563
564     // Use ANDPS and ORPS to simulate FCOPYSIGN.
565     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
566     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
567
568     // We don't support sin/cos/fmod
569     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
570     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
571     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
572
573     // Special cases we handle for FP constants.
574     addLegalFPImmediate(APFloat(+0.0f)); // xorps
575     addLegalFPImmediate(APFloat(+0.0)); // FLD0
576     addLegalFPImmediate(APFloat(+1.0)); // FLD1
577     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
578     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
579
580     if (!TM.Options.UnsafeFPMath) {
581       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
582       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
583       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
584     }
585   } else if (!TM.Options.UseSoftFloat) {
586     // f32 and f64 in x87.
587     // Set up the FP register classes.
588     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
589     addRegisterClass(MVT::f32, &X86::RFP32RegClass);
590
591     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
592     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
593     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
594     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
595
596     if (!TM.Options.UnsafeFPMath) {
597       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
598       setOperationAction(ISD::FSIN   , MVT::f32, Expand);
599       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
600       setOperationAction(ISD::FCOS   , MVT::f32, Expand);
601       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
602       setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
603     }
604     addLegalFPImmediate(APFloat(+0.0)); // FLD0
605     addLegalFPImmediate(APFloat(+1.0)); // FLD1
606     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
607     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
608     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
609     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
610     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
611     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
612   }
613
614   // We don't support FMA.
615   setOperationAction(ISD::FMA, MVT::f64, Expand);
616   setOperationAction(ISD::FMA, MVT::f32, Expand);
617
618   // Long double always uses X87.
619   if (!TM.Options.UseSoftFloat) {
620     addRegisterClass(MVT::f80, &X86::RFP80RegClass);
621     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
622     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
623     {
624       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
625       addLegalFPImmediate(TmpFlt);  // FLD0
626       TmpFlt.changeSign();
627       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
628
629       bool ignored;
630       APFloat TmpFlt2(+1.0);
631       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
632                       &ignored);
633       addLegalFPImmediate(TmpFlt2);  // FLD1
634       TmpFlt2.changeSign();
635       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
636     }
637
638     if (!TM.Options.UnsafeFPMath) {
639       setOperationAction(ISD::FSIN   , MVT::f80, Expand);
640       setOperationAction(ISD::FCOS   , MVT::f80, Expand);
641       setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
642     }
643
644     setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
645     setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
646     setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
647     setOperationAction(ISD::FRINT,  MVT::f80, Expand);
648     setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
649     setOperationAction(ISD::FMA, MVT::f80, Expand);
650   }
651
652   // Always use a library call for pow.
653   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
654   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
655   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
656
657   setOperationAction(ISD::FLOG, MVT::f80, Expand);
658   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
659   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
660   setOperationAction(ISD::FEXP, MVT::f80, Expand);
661   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
662   setOperationAction(ISD::FMINNUM, MVT::f80, Expand);
663   setOperationAction(ISD::FMAXNUM, MVT::f80, Expand);
664
665   // First set operation action for all vector types to either promote
666   // (for widening) or expand (for scalarization). Then we will selectively
667   // turn on ones that can be effectively codegen'd.
668   for (MVT VT : MVT::vector_valuetypes()) {
669     setOperationAction(ISD::ADD , VT, Expand);
670     setOperationAction(ISD::SUB , VT, Expand);
671     setOperationAction(ISD::FADD, VT, Expand);
672     setOperationAction(ISD::FNEG, VT, Expand);
673     setOperationAction(ISD::FSUB, VT, Expand);
674     setOperationAction(ISD::MUL , VT, Expand);
675     setOperationAction(ISD::FMUL, VT, Expand);
676     setOperationAction(ISD::SDIV, VT, Expand);
677     setOperationAction(ISD::UDIV, VT, Expand);
678     setOperationAction(ISD::FDIV, VT, Expand);
679     setOperationAction(ISD::SREM, VT, Expand);
680     setOperationAction(ISD::UREM, VT, Expand);
681     setOperationAction(ISD::LOAD, VT, Expand);
682     setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
683     setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
684     setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
685     setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
686     setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
687     setOperationAction(ISD::FABS, VT, Expand);
688     setOperationAction(ISD::FSIN, VT, Expand);
689     setOperationAction(ISD::FSINCOS, VT, Expand);
690     setOperationAction(ISD::FCOS, VT, Expand);
691     setOperationAction(ISD::FSINCOS, VT, Expand);
692     setOperationAction(ISD::FREM, VT, Expand);
693     setOperationAction(ISD::FMA,  VT, Expand);
694     setOperationAction(ISD::FPOWI, VT, Expand);
695     setOperationAction(ISD::FSQRT, VT, Expand);
696     setOperationAction(ISD::FCOPYSIGN, VT, Expand);
697     setOperationAction(ISD::FFLOOR, VT, Expand);
698     setOperationAction(ISD::FCEIL, VT, Expand);
699     setOperationAction(ISD::FTRUNC, VT, Expand);
700     setOperationAction(ISD::FRINT, VT, Expand);
701     setOperationAction(ISD::FNEARBYINT, VT, Expand);
702     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
703     setOperationAction(ISD::MULHS, VT, Expand);
704     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
705     setOperationAction(ISD::MULHU, VT, Expand);
706     setOperationAction(ISD::SDIVREM, VT, Expand);
707     setOperationAction(ISD::UDIVREM, VT, Expand);
708     setOperationAction(ISD::FPOW, VT, Expand);
709     setOperationAction(ISD::CTPOP, VT, Expand);
710     setOperationAction(ISD::CTTZ, VT, Expand);
711     setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
712     setOperationAction(ISD::CTLZ, VT, Expand);
713     setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
714     setOperationAction(ISD::SHL, VT, Expand);
715     setOperationAction(ISD::SRA, VT, Expand);
716     setOperationAction(ISD::SRL, VT, Expand);
717     setOperationAction(ISD::ROTL, VT, Expand);
718     setOperationAction(ISD::ROTR, VT, Expand);
719     setOperationAction(ISD::BSWAP, VT, Expand);
720     setOperationAction(ISD::SETCC, VT, Expand);
721     setOperationAction(ISD::FLOG, VT, Expand);
722     setOperationAction(ISD::FLOG2, VT, Expand);
723     setOperationAction(ISD::FLOG10, VT, Expand);
724     setOperationAction(ISD::FEXP, VT, Expand);
725     setOperationAction(ISD::FEXP2, VT, Expand);
726     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
727     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
728     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
729     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
730     setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
731     setOperationAction(ISD::TRUNCATE, VT, Expand);
732     setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
733     setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
734     setOperationAction(ISD::ANY_EXTEND, VT, Expand);
735     setOperationAction(ISD::VSELECT, VT, Expand);
736     setOperationAction(ISD::SELECT_CC, VT, Expand);
737     for (MVT InnerVT : MVT::vector_valuetypes()) {
738       setTruncStoreAction(InnerVT, VT, Expand);
739
740       setLoadExtAction(ISD::SEXTLOAD, InnerVT, VT, Expand);
741       setLoadExtAction(ISD::ZEXTLOAD, InnerVT, VT, Expand);
742
743       // N.b. ISD::EXTLOAD legality is basically ignored except for i1-like
744       // types, we have to deal with them whether we ask for Expansion or not.
745       // Setting Expand causes its own optimisation problems though, so leave
746       // them legal.
747       if (VT.getVectorElementType() == MVT::i1)
748         setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
749     }
750   }
751
752   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
753   // with -msoft-float, disable use of MMX as well.
754   if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
755     addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
756     // No operations on x86mmx supported, everything uses intrinsics.
757   }
758
759   // MMX-sized vectors (other than x86mmx) are expected to be expanded
760   // into smaller operations.
761   for (MVT MMXTy : {MVT::v8i8, MVT::v4i16, MVT::v2i32, MVT::v1i64}) {
762     setOperationAction(ISD::MULHS,              MMXTy,      Expand);
763     setOperationAction(ISD::AND,                MMXTy,      Expand);
764     setOperationAction(ISD::OR,                 MMXTy,      Expand);
765     setOperationAction(ISD::XOR,                MMXTy,      Expand);
766     setOperationAction(ISD::SCALAR_TO_VECTOR,   MMXTy,      Expand);
767     setOperationAction(ISD::SELECT,             MMXTy,      Expand);
768     setOperationAction(ISD::BITCAST,            MMXTy,      Expand);
769   }
770   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
771
772   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
773     addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
774
775     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
776     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
777     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
778     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
779     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
780     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
781     setOperationAction(ISD::FABS,               MVT::v4f32, Custom);
782     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
783     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
784     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
785     setOperationAction(ISD::VSELECT,            MVT::v4f32, Custom);
786     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
787     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
788     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Custom);
789   }
790
791   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
792     addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
793
794     // FIXME: Unfortunately, -soft-float and -no-implicit-float mean XMM
795     // registers cannot be used even for integer operations.
796     addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
797     addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
798     addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
799     addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
800
801     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
802     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
803     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
804     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
805     setOperationAction(ISD::MUL,                MVT::v4i32, Custom);
806     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
807     setOperationAction(ISD::UMUL_LOHI,          MVT::v4i32, Custom);
808     setOperationAction(ISD::SMUL_LOHI,          MVT::v4i32, Custom);
809     setOperationAction(ISD::MULHU,              MVT::v8i16, Legal);
810     setOperationAction(ISD::MULHS,              MVT::v8i16, Legal);
811     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
812     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
813     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
814     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
815     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
816     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
817     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
818     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
819     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
820     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
821     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
822     setOperationAction(ISD::FABS,               MVT::v2f64, Custom);
823
824     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
825     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
826     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
827     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
828
829     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
830     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
831     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
832     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
833     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
834
835     // Only provide customized ctpop vector bit twiddling for vector types we
836     // know to perform better than using the popcnt instructions on each vector
837     // element. If popcnt isn't supported, always provide the custom version.
838     if (!Subtarget->hasPOPCNT()) {
839       setOperationAction(ISD::CTPOP,            MVT::v4i32, Custom);
840       setOperationAction(ISD::CTPOP,            MVT::v2i64, Custom);
841     }
842
843     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
844     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
845       MVT VT = (MVT::SimpleValueType)i;
846       // Do not attempt to custom lower non-power-of-2 vectors
847       if (!isPowerOf2_32(VT.getVectorNumElements()))
848         continue;
849       // Do not attempt to custom lower non-128-bit vectors
850       if (!VT.is128BitVector())
851         continue;
852       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
853       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
854       setOperationAction(ISD::VSELECT,            VT, Custom);
855       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
856     }
857
858     // We support custom legalizing of sext and anyext loads for specific
859     // memory vector types which we can load as a scalar (or sequence of
860     // scalars) and extend in-register to a legal 128-bit vector type. For sext
861     // loads these must work with a single scalar load.
862     for (MVT VT : MVT::integer_vector_valuetypes()) {
863       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i8, Custom);
864       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i16, Custom);
865       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v8i8, Custom);
866       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i8, Custom);
867       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i16, Custom);
868       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i32, Custom);
869       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i8, Custom);
870       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i16, Custom);
871       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8i8, Custom);
872     }
873
874     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
875     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
876     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
877     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
878     setOperationAction(ISD::VSELECT,            MVT::v2f64, Custom);
879     setOperationAction(ISD::VSELECT,            MVT::v2i64, Custom);
880     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
881     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
882
883     if (Subtarget->is64Bit()) {
884       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
885       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
886     }
887
888     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
889     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
890       MVT VT = (MVT::SimpleValueType)i;
891
892       // Do not attempt to promote non-128-bit vectors
893       if (!VT.is128BitVector())
894         continue;
895
896       setOperationAction(ISD::AND,    VT, Promote);
897       AddPromotedToType (ISD::AND,    VT, MVT::v2i64);
898       setOperationAction(ISD::OR,     VT, Promote);
899       AddPromotedToType (ISD::OR,     VT, MVT::v2i64);
900       setOperationAction(ISD::XOR,    VT, Promote);
901       AddPromotedToType (ISD::XOR,    VT, MVT::v2i64);
902       setOperationAction(ISD::LOAD,   VT, Promote);
903       AddPromotedToType (ISD::LOAD,   VT, MVT::v2i64);
904       setOperationAction(ISD::SELECT, VT, Promote);
905       AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
906     }
907
908     // Custom lower v2i64 and v2f64 selects.
909     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
910     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
911     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
912     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
913
914     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
915     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
916
917     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i8,  Custom);
918     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i16, Custom);
919     // As there is no 64-bit GPR available, we need build a special custom
920     // sequence to convert from v2i32 to v2f32.
921     if (!Subtarget->is64Bit())
922       setOperationAction(ISD::UINT_TO_FP,       MVT::v2f32, Custom);
923
924     setOperationAction(ISD::FP_EXTEND,          MVT::v2f32, Custom);
925     setOperationAction(ISD::FP_ROUND,           MVT::v2f32, Custom);
926
927     for (MVT VT : MVT::fp_vector_valuetypes())
928       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2f32, Legal);
929
930     setOperationAction(ISD::BITCAST,            MVT::v2i32, Custom);
931     setOperationAction(ISD::BITCAST,            MVT::v4i16, Custom);
932     setOperationAction(ISD::BITCAST,            MVT::v8i8,  Custom);
933   }
934
935   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE41()) {
936     for (MVT RoundedTy : {MVT::f32, MVT::f64, MVT::v4f32, MVT::v2f64}) {
937       setOperationAction(ISD::FFLOOR,           RoundedTy,  Legal);
938       setOperationAction(ISD::FCEIL,            RoundedTy,  Legal);
939       setOperationAction(ISD::FTRUNC,           RoundedTy,  Legal);
940       setOperationAction(ISD::FRINT,            RoundedTy,  Legal);
941       setOperationAction(ISD::FNEARBYINT,       RoundedTy,  Legal);
942     }
943
944     // FIXME: Do we need to handle scalar-to-vector here?
945     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
946
947     // We directly match byte blends in the backend as they match the VSELECT
948     // condition form.
949     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
950
951     // SSE41 brings specific instructions for doing vector sign extend even in
952     // cases where we don't have SRA.
953     for (MVT VT : MVT::integer_vector_valuetypes()) {
954       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i8, Custom);
955       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i16, Custom);
956       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i32, Custom);
957     }
958
959     // SSE41 also has vector sign/zero extending loads, PMOV[SZ]X
960     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i16, MVT::v8i8,  Legal);
961     setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i8,  Legal);
962     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i8,  Legal);
963     setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
964     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
965     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
966
967     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i16, MVT::v8i8,  Legal);
968     setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i8,  Legal);
969     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i8,  Legal);
970     setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
971     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
972     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
973
974     // i8 and i16 vectors are custom because the source register and source
975     // source memory operand types are not the same width.  f32 vectors are
976     // custom since the immediate controlling the insert encodes additional
977     // information.
978     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
979     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
980     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
981     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
982
983     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
984     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
985     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
986     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
987
988     // FIXME: these should be Legal, but that's only for the case where
989     // the index is constant.  For now custom expand to deal with that.
990     if (Subtarget->is64Bit()) {
991       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
992       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
993     }
994   }
995
996   if (Subtarget->hasSSE2()) {
997     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
998     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
999
1000     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
1001     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
1002
1003     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
1004     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
1005
1006     // In the customized shift lowering, the legal cases in AVX2 will be
1007     // recognized.
1008     setOperationAction(ISD::SRL,               MVT::v2i64, Custom);
1009     setOperationAction(ISD::SRL,               MVT::v4i32, Custom);
1010
1011     setOperationAction(ISD::SHL,               MVT::v2i64, Custom);
1012     setOperationAction(ISD::SHL,               MVT::v4i32, Custom);
1013
1014     setOperationAction(ISD::SRA,               MVT::v4i32, Custom);
1015   }
1016
1017   if (!TM.Options.UseSoftFloat && Subtarget->hasFp256()) {
1018     addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1019     addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1020     addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1021     addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1022     addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1023     addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1024
1025     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1026     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1027     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1028
1029     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1030     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1031     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1032     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1033     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1034     setOperationAction(ISD::FFLOOR,             MVT::v8f32, Legal);
1035     setOperationAction(ISD::FCEIL,              MVT::v8f32, Legal);
1036     setOperationAction(ISD::FTRUNC,             MVT::v8f32, Legal);
1037     setOperationAction(ISD::FRINT,              MVT::v8f32, Legal);
1038     setOperationAction(ISD::FNEARBYINT,         MVT::v8f32, Legal);
1039     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1040     setOperationAction(ISD::FABS,               MVT::v8f32, Custom);
1041
1042     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1043     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1044     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1045     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1046     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1047     setOperationAction(ISD::FFLOOR,             MVT::v4f64, Legal);
1048     setOperationAction(ISD::FCEIL,              MVT::v4f64, Legal);
1049     setOperationAction(ISD::FTRUNC,             MVT::v4f64, Legal);
1050     setOperationAction(ISD::FRINT,              MVT::v4f64, Legal);
1051     setOperationAction(ISD::FNEARBYINT,         MVT::v4f64, Legal);
1052     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1053     setOperationAction(ISD::FABS,               MVT::v4f64, Custom);
1054
1055     // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1056     // even though v8i16 is a legal type.
1057     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i16, Promote);
1058     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i16, Promote);
1059     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1060
1061     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i16, Promote);
1062     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1063     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1064
1065     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i8,  Custom);
1066     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i16, Custom);
1067
1068     for (MVT VT : MVT::fp_vector_valuetypes())
1069       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4f32, Legal);
1070
1071     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1072     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1073
1074     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1075     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1076
1077     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1078     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1079
1080     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1081     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1082     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1083     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1084
1085     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1086     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1087     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1088
1089     setOperationAction(ISD::SIGN_EXTEND,       MVT::v4i64, Custom);
1090     setOperationAction(ISD::SIGN_EXTEND,       MVT::v8i32, Custom);
1091     setOperationAction(ISD::SIGN_EXTEND,       MVT::v16i16, Custom);
1092     setOperationAction(ISD::ZERO_EXTEND,       MVT::v4i64, Custom);
1093     setOperationAction(ISD::ZERO_EXTEND,       MVT::v8i32, Custom);
1094     setOperationAction(ISD::ZERO_EXTEND,       MVT::v16i16, Custom);
1095     setOperationAction(ISD::ANY_EXTEND,        MVT::v4i64, Custom);
1096     setOperationAction(ISD::ANY_EXTEND,        MVT::v8i32, Custom);
1097     setOperationAction(ISD::ANY_EXTEND,        MVT::v16i16, Custom);
1098     setOperationAction(ISD::TRUNCATE,          MVT::v16i8, Custom);
1099     setOperationAction(ISD::TRUNCATE,          MVT::v8i16, Custom);
1100     setOperationAction(ISD::TRUNCATE,          MVT::v4i32, Custom);
1101
1102     if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1103       setOperationAction(ISD::FMA,             MVT::v8f32, Legal);
1104       setOperationAction(ISD::FMA,             MVT::v4f64, Legal);
1105       setOperationAction(ISD::FMA,             MVT::v4f32, Legal);
1106       setOperationAction(ISD::FMA,             MVT::v2f64, Legal);
1107       setOperationAction(ISD::FMA,             MVT::f32, Legal);
1108       setOperationAction(ISD::FMA,             MVT::f64, Legal);
1109     }
1110
1111     if (Subtarget->hasInt256()) {
1112       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1113       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1114       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1115       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1116
1117       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1118       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1119       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1120       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1121
1122       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1123       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1124       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1125       // Don't lower v32i8 because there is no 128-bit byte mul
1126
1127       setOperationAction(ISD::UMUL_LOHI,       MVT::v8i32, Custom);
1128       setOperationAction(ISD::SMUL_LOHI,       MVT::v8i32, Custom);
1129       setOperationAction(ISD::MULHU,           MVT::v16i16, Legal);
1130       setOperationAction(ISD::MULHS,           MVT::v16i16, Legal);
1131
1132       // The custom lowering for UINT_TO_FP for v8i32 becomes interesting
1133       // when we have a 256bit-wide blend with immediate.
1134       setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Custom);
1135
1136       // Only provide customized ctpop vector bit twiddling for vector types we
1137       // know to perform better than using the popcnt instructions on each
1138       // vector element. If popcnt isn't supported, always provide the custom
1139       // version.
1140       if (!Subtarget->hasPOPCNT())
1141         setOperationAction(ISD::CTPOP,           MVT::v4i64, Custom);
1142
1143       // Custom CTPOP always performs better on natively supported v8i32
1144       setOperationAction(ISD::CTPOP,             MVT::v8i32, Custom);
1145
1146       // AVX2 also has wider vector sign/zero extending loads, VPMOV[SZ]X
1147       setLoadExtAction(ISD::SEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1148       setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32,  MVT::v8i8,  Legal);
1149       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i8,  Legal);
1150       setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32,  MVT::v8i16, Legal);
1151       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i16, Legal);
1152       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i32, Legal);
1153
1154       setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1155       setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32,  MVT::v8i8,  Legal);
1156       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i8,  Legal);
1157       setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32,  MVT::v8i16, Legal);
1158       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i16, Legal);
1159       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i32, Legal);
1160     } else {
1161       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1162       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1163       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1164       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1165
1166       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1167       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1168       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1169       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1170
1171       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1172       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1173       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1174       // Don't lower v32i8 because there is no 128-bit byte mul
1175     }
1176
1177     // In the customized shift lowering, the legal cases in AVX2 will be
1178     // recognized.
1179     setOperationAction(ISD::SRL,               MVT::v4i64, Custom);
1180     setOperationAction(ISD::SRL,               MVT::v8i32, Custom);
1181
1182     setOperationAction(ISD::SHL,               MVT::v4i64, Custom);
1183     setOperationAction(ISD::SHL,               MVT::v8i32, Custom);
1184
1185     setOperationAction(ISD::SRA,               MVT::v8i32, Custom);
1186
1187     // Custom lower several nodes for 256-bit types.
1188     for (MVT VT : MVT::vector_valuetypes()) {
1189       if (VT.getScalarSizeInBits() >= 32) {
1190         setOperationAction(ISD::MLOAD,  VT, Legal);
1191         setOperationAction(ISD::MSTORE, VT, Legal);
1192       }
1193       // Extract subvector is special because the value type
1194       // (result) is 128-bit but the source is 256-bit wide.
1195       if (VT.is128BitVector()) {
1196         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1197       }
1198       // Do not attempt to custom lower other non-256-bit vectors
1199       if (!VT.is256BitVector())
1200         continue;
1201
1202       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1203       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1204       setOperationAction(ISD::VSELECT,            VT, Custom);
1205       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1206       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1207       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1208       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1209       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1210     }
1211
1212     if (Subtarget->hasInt256())
1213       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1214
1215
1216     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1217     for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1218       MVT VT = (MVT::SimpleValueType)i;
1219
1220       // Do not attempt to promote non-256-bit vectors
1221       if (!VT.is256BitVector())
1222         continue;
1223
1224       setOperationAction(ISD::AND,    VT, Promote);
1225       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1226       setOperationAction(ISD::OR,     VT, Promote);
1227       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1228       setOperationAction(ISD::XOR,    VT, Promote);
1229       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1230       setOperationAction(ISD::LOAD,   VT, Promote);
1231       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1232       setOperationAction(ISD::SELECT, VT, Promote);
1233       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1234     }
1235   }
1236
1237   if (!TM.Options.UseSoftFloat && Subtarget->hasAVX512()) {
1238     addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1239     addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1240     addRegisterClass(MVT::v8i64,  &X86::VR512RegClass);
1241     addRegisterClass(MVT::v8f64,  &X86::VR512RegClass);
1242
1243     addRegisterClass(MVT::i1,     &X86::VK1RegClass);
1244     addRegisterClass(MVT::v8i1,   &X86::VK8RegClass);
1245     addRegisterClass(MVT::v16i1,  &X86::VK16RegClass);
1246
1247     for (MVT VT : MVT::fp_vector_valuetypes())
1248       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8f32, Legal);
1249
1250     setOperationAction(ISD::BR_CC,              MVT::i1,    Expand);
1251     setOperationAction(ISD::SETCC,              MVT::i1,    Custom);
1252     setOperationAction(ISD::XOR,                MVT::i1,    Legal);
1253     setOperationAction(ISD::OR,                 MVT::i1,    Legal);
1254     setOperationAction(ISD::AND,                MVT::i1,    Legal);
1255     setOperationAction(ISD::LOAD,               MVT::v16f32, Legal);
1256     setOperationAction(ISD::LOAD,               MVT::v8f64, Legal);
1257     setOperationAction(ISD::LOAD,               MVT::v8i64, Legal);
1258     setOperationAction(ISD::LOAD,               MVT::v16i32, Legal);
1259     setOperationAction(ISD::LOAD,               MVT::v16i1, Legal);
1260
1261     setOperationAction(ISD::FADD,               MVT::v16f32, Legal);
1262     setOperationAction(ISD::FSUB,               MVT::v16f32, Legal);
1263     setOperationAction(ISD::FMUL,               MVT::v16f32, Legal);
1264     setOperationAction(ISD::FDIV,               MVT::v16f32, Legal);
1265     setOperationAction(ISD::FSQRT,              MVT::v16f32, Legal);
1266     setOperationAction(ISD::FNEG,               MVT::v16f32, Custom);
1267
1268     setOperationAction(ISD::FADD,               MVT::v8f64, Legal);
1269     setOperationAction(ISD::FSUB,               MVT::v8f64, Legal);
1270     setOperationAction(ISD::FMUL,               MVT::v8f64, Legal);
1271     setOperationAction(ISD::FDIV,               MVT::v8f64, Legal);
1272     setOperationAction(ISD::FSQRT,              MVT::v8f64, Legal);
1273     setOperationAction(ISD::FNEG,               MVT::v8f64, Custom);
1274     setOperationAction(ISD::FMA,                MVT::v8f64, Legal);
1275     setOperationAction(ISD::FMA,                MVT::v16f32, Legal);
1276
1277     setOperationAction(ISD::FP_TO_SINT,         MVT::i32, Legal);
1278     setOperationAction(ISD::FP_TO_UINT,         MVT::i32, Legal);
1279     setOperationAction(ISD::SINT_TO_FP,         MVT::i32, Legal);
1280     setOperationAction(ISD::UINT_TO_FP,         MVT::i32, Legal);
1281     if (Subtarget->is64Bit()) {
1282       setOperationAction(ISD::FP_TO_UINT,       MVT::i64, Legal);
1283       setOperationAction(ISD::FP_TO_SINT,       MVT::i64, Legal);
1284       setOperationAction(ISD::SINT_TO_FP,       MVT::i64, Legal);
1285       setOperationAction(ISD::UINT_TO_FP,       MVT::i64, Legal);
1286     }
1287     setOperationAction(ISD::FP_TO_SINT,         MVT::v16i32, Legal);
1288     setOperationAction(ISD::FP_TO_UINT,         MVT::v16i32, Legal);
1289     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i32, Legal);
1290     setOperationAction(ISD::FP_TO_UINT,         MVT::v4i32, Legal);
1291     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i32, Legal);
1292     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i1,   Custom);
1293     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i1,  Custom);
1294     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i8,  Promote);
1295     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i16, Promote);
1296     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i32, Legal);
1297     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i32, Legal);
1298     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Legal);
1299     setOperationAction(ISD::FP_ROUND,           MVT::v8f32, Legal);
1300     setOperationAction(ISD::FP_EXTEND,          MVT::v8f32, Legal);
1301
1302     setOperationAction(ISD::TRUNCATE,           MVT::i1, Custom);
1303     setOperationAction(ISD::TRUNCATE,           MVT::v16i8, Custom);
1304     setOperationAction(ISD::TRUNCATE,           MVT::v8i32, Custom);
1305     setOperationAction(ISD::TRUNCATE,           MVT::v8i1, Custom);
1306     setOperationAction(ISD::TRUNCATE,           MVT::v16i1, Custom);
1307     setOperationAction(ISD::TRUNCATE,           MVT::v16i16, Custom);
1308     setOperationAction(ISD::ZERO_EXTEND,        MVT::v16i32, Custom);
1309     setOperationAction(ISD::ZERO_EXTEND,        MVT::v8i64, Custom);
1310     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i32, Custom);
1311     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i64, Custom);
1312     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i8, Custom);
1313     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i16, Custom);
1314     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i16, Custom);
1315
1316     setOperationAction(ISD::FFLOOR,             MVT::v16f32, Legal);
1317     setOperationAction(ISD::FFLOOR,             MVT::v8f64, Legal);
1318     setOperationAction(ISD::FCEIL,              MVT::v16f32, Legal);
1319     setOperationAction(ISD::FCEIL,              MVT::v8f64, Legal);
1320     setOperationAction(ISD::FTRUNC,             MVT::v16f32, Legal);
1321     setOperationAction(ISD::FTRUNC,             MVT::v8f64, Legal);
1322     setOperationAction(ISD::FRINT,              MVT::v16f32, Legal);
1323     setOperationAction(ISD::FRINT,              MVT::v8f64, Legal);
1324     setOperationAction(ISD::FNEARBYINT,         MVT::v16f32, Legal);
1325     setOperationAction(ISD::FNEARBYINT,         MVT::v8f64, Legal);
1326
1327     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8f64,  Custom);
1328     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i64,  Custom);
1329     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16f32,  Custom);
1330     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i32,  Custom);
1331     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i1, Legal);
1332
1333     setOperationAction(ISD::SETCC,              MVT::v16i1, Custom);
1334     setOperationAction(ISD::SETCC,              MVT::v8i1, Custom);
1335
1336     setOperationAction(ISD::MUL,              MVT::v8i64, Custom);
1337
1338     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1,  Custom);
1339     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1340     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i1, Custom);
1341     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i1, Custom);
1342     setOperationAction(ISD::BUILD_VECTOR,       MVT::v8i1, Custom);
1343     setOperationAction(ISD::BUILD_VECTOR,       MVT::v16i1, Custom);
1344     setOperationAction(ISD::SELECT,             MVT::v8f64, Custom);
1345     setOperationAction(ISD::SELECT,             MVT::v8i64, Custom);
1346     setOperationAction(ISD::SELECT,             MVT::v16f32, Custom);
1347
1348     setOperationAction(ISD::ADD,                MVT::v8i64, Legal);
1349     setOperationAction(ISD::ADD,                MVT::v16i32, Legal);
1350
1351     setOperationAction(ISD::SUB,                MVT::v8i64, Legal);
1352     setOperationAction(ISD::SUB,                MVT::v16i32, Legal);
1353
1354     setOperationAction(ISD::MUL,                MVT::v16i32, Legal);
1355
1356     setOperationAction(ISD::SRL,                MVT::v8i64, Custom);
1357     setOperationAction(ISD::SRL,                MVT::v16i32, Custom);
1358
1359     setOperationAction(ISD::SHL,                MVT::v8i64, Custom);
1360     setOperationAction(ISD::SHL,                MVT::v16i32, Custom);
1361
1362     setOperationAction(ISD::SRA,                MVT::v8i64, Custom);
1363     setOperationAction(ISD::SRA,                MVT::v16i32, Custom);
1364
1365     setOperationAction(ISD::AND,                MVT::v8i64, Legal);
1366     setOperationAction(ISD::OR,                 MVT::v8i64, Legal);
1367     setOperationAction(ISD::XOR,                MVT::v8i64, Legal);
1368     setOperationAction(ISD::AND,                MVT::v16i32, Legal);
1369     setOperationAction(ISD::OR,                 MVT::v16i32, Legal);
1370     setOperationAction(ISD::XOR,                MVT::v16i32, Legal);
1371
1372     if (Subtarget->hasCDI()) {
1373       setOperationAction(ISD::CTLZ,             MVT::v8i64, Legal);
1374       setOperationAction(ISD::CTLZ,             MVT::v16i32, Legal);
1375     }
1376
1377     // Custom lower several nodes.
1378     for (MVT VT : MVT::vector_valuetypes()) {
1379       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1380       // Extract subvector is special because the value type
1381       // (result) is 256/128-bit but the source is 512-bit wide.
1382       if (VT.is128BitVector() || VT.is256BitVector()) {
1383         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1384       }
1385       if (VT.getVectorElementType() == MVT::i1)
1386         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1387
1388       // Do not attempt to custom lower other non-512-bit vectors
1389       if (!VT.is512BitVector())
1390         continue;
1391
1392       if ( EltSize >= 32) {
1393         setOperationAction(ISD::VECTOR_SHUFFLE,      VT, Custom);
1394         setOperationAction(ISD::INSERT_VECTOR_ELT,   VT, Custom);
1395         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1396         setOperationAction(ISD::VSELECT,             VT, Legal);
1397         setOperationAction(ISD::EXTRACT_VECTOR_ELT,  VT, Custom);
1398         setOperationAction(ISD::SCALAR_TO_VECTOR,    VT, Custom);
1399         setOperationAction(ISD::INSERT_SUBVECTOR,    VT, Custom);
1400         setOperationAction(ISD::MLOAD,               VT, Legal);
1401         setOperationAction(ISD::MSTORE,              VT, Legal);
1402       }
1403     }
1404     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1405       MVT VT = (MVT::SimpleValueType)i;
1406
1407       // Do not attempt to promote non-512-bit vectors.
1408       if (!VT.is512BitVector())
1409         continue;
1410
1411       setOperationAction(ISD::SELECT, VT, Promote);
1412       AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1413     }
1414   }// has  AVX-512
1415
1416   if (!TM.Options.UseSoftFloat && Subtarget->hasBWI()) {
1417     addRegisterClass(MVT::v32i16, &X86::VR512RegClass);
1418     addRegisterClass(MVT::v64i8,  &X86::VR512RegClass);
1419
1420     addRegisterClass(MVT::v32i1,  &X86::VK32RegClass);
1421     addRegisterClass(MVT::v64i1,  &X86::VK64RegClass);
1422
1423     setOperationAction(ISD::LOAD,               MVT::v32i16, Legal);
1424     setOperationAction(ISD::LOAD,               MVT::v64i8, Legal);
1425     setOperationAction(ISD::SETCC,              MVT::v32i1, Custom);
1426     setOperationAction(ISD::SETCC,              MVT::v64i1, Custom);
1427     setOperationAction(ISD::ADD,                MVT::v32i16, Legal);
1428     setOperationAction(ISD::ADD,                MVT::v64i8, Legal);
1429     setOperationAction(ISD::SUB,                MVT::v32i16, Legal);
1430     setOperationAction(ISD::SUB,                MVT::v64i8, Legal);
1431     setOperationAction(ISD::MUL,                MVT::v32i16, Legal);
1432     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v32i1, Custom);
1433     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v64i1, Custom);
1434     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v32i1, Custom);
1435     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v64i1, Custom);
1436
1437     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1438       const MVT VT = (MVT::SimpleValueType)i;
1439
1440       const unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1441
1442       // Do not attempt to promote non-512-bit vectors.
1443       if (!VT.is512BitVector())
1444         continue;
1445
1446       if (EltSize < 32) {
1447         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1448         setOperationAction(ISD::VSELECT,             VT, Legal);
1449       }
1450     }
1451   }
1452
1453   if (!TM.Options.UseSoftFloat && Subtarget->hasVLX()) {
1454     addRegisterClass(MVT::v4i1,   &X86::VK4RegClass);
1455     addRegisterClass(MVT::v2i1,   &X86::VK2RegClass);
1456
1457     setOperationAction(ISD::SETCC,              MVT::v4i1, Custom);
1458     setOperationAction(ISD::SETCC,              MVT::v2i1, Custom);
1459     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4i1, Custom);
1460     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i1, Custom);
1461     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v8i1, Custom);
1462     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v4i1, Custom);
1463
1464     setOperationAction(ISD::AND,                MVT::v8i32, Legal);
1465     setOperationAction(ISD::OR,                 MVT::v8i32, Legal);
1466     setOperationAction(ISD::XOR,                MVT::v8i32, Legal);
1467     setOperationAction(ISD::AND,                MVT::v4i32, Legal);
1468     setOperationAction(ISD::OR,                 MVT::v4i32, Legal);
1469     setOperationAction(ISD::XOR,                MVT::v4i32, Legal);
1470   }
1471
1472   // We want to custom lower some of our intrinsics.
1473   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1474   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1475   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1476   if (!Subtarget->is64Bit())
1477     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1478
1479   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1480   // handle type legalization for these operations here.
1481   //
1482   // FIXME: We really should do custom legalization for addition and
1483   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1484   // than generic legalization for 64-bit multiplication-with-overflow, though.
1485   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1486     // Add/Sub/Mul with overflow operations are custom lowered.
1487     MVT VT = IntVTs[i];
1488     setOperationAction(ISD::SADDO, VT, Custom);
1489     setOperationAction(ISD::UADDO, VT, Custom);
1490     setOperationAction(ISD::SSUBO, VT, Custom);
1491     setOperationAction(ISD::USUBO, VT, Custom);
1492     setOperationAction(ISD::SMULO, VT, Custom);
1493     setOperationAction(ISD::UMULO, VT, Custom);
1494   }
1495
1496
1497   if (!Subtarget->is64Bit()) {
1498     // These libcalls are not available in 32-bit.
1499     setLibcallName(RTLIB::SHL_I128, nullptr);
1500     setLibcallName(RTLIB::SRL_I128, nullptr);
1501     setLibcallName(RTLIB::SRA_I128, nullptr);
1502   }
1503
1504   // Combine sin / cos into one node or libcall if possible.
1505   if (Subtarget->hasSinCos()) {
1506     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1507     setLibcallName(RTLIB::SINCOS_F64, "sincos");
1508     if (Subtarget->isTargetDarwin()) {
1509       // For MacOSX, we don't want the normal expansion of a libcall to sincos.
1510       // We want to issue a libcall to __sincos_stret to avoid memory traffic.
1511       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1512       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1513     }
1514   }
1515
1516   if (Subtarget->isTargetWin64()) {
1517     setOperationAction(ISD::SDIV, MVT::i128, Custom);
1518     setOperationAction(ISD::UDIV, MVT::i128, Custom);
1519     setOperationAction(ISD::SREM, MVT::i128, Custom);
1520     setOperationAction(ISD::UREM, MVT::i128, Custom);
1521     setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1522     setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1523   }
1524
1525   // We have target-specific dag combine patterns for the following nodes:
1526   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1527   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1528   setTargetDAGCombine(ISD::BITCAST);
1529   setTargetDAGCombine(ISD::VSELECT);
1530   setTargetDAGCombine(ISD::SELECT);
1531   setTargetDAGCombine(ISD::SHL);
1532   setTargetDAGCombine(ISD::SRA);
1533   setTargetDAGCombine(ISD::SRL);
1534   setTargetDAGCombine(ISD::OR);
1535   setTargetDAGCombine(ISD::AND);
1536   setTargetDAGCombine(ISD::ADD);
1537   setTargetDAGCombine(ISD::FADD);
1538   setTargetDAGCombine(ISD::FSUB);
1539   setTargetDAGCombine(ISD::FMA);
1540   setTargetDAGCombine(ISD::SUB);
1541   setTargetDAGCombine(ISD::LOAD);
1542   setTargetDAGCombine(ISD::MLOAD);
1543   setTargetDAGCombine(ISD::STORE);
1544   setTargetDAGCombine(ISD::MSTORE);
1545   setTargetDAGCombine(ISD::ZERO_EXTEND);
1546   setTargetDAGCombine(ISD::ANY_EXTEND);
1547   setTargetDAGCombine(ISD::SIGN_EXTEND);
1548   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1549   setTargetDAGCombine(ISD::TRUNCATE);
1550   setTargetDAGCombine(ISD::SINT_TO_FP);
1551   setTargetDAGCombine(ISD::SETCC);
1552   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1553   setTargetDAGCombine(ISD::BUILD_VECTOR);
1554   setTargetDAGCombine(ISD::MUL);
1555   setTargetDAGCombine(ISD::XOR);
1556
1557   computeRegisterProperties(Subtarget->getRegisterInfo());
1558
1559   // On Darwin, -Os means optimize for size without hurting performance,
1560   // do not reduce the limit.
1561   MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1562   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1563   MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1564   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1565   MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1566   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1567   setPrefLoopAlignment(4); // 2^4 bytes.
1568
1569   // Predictable cmov don't hurt on atom because it's in-order.
1570   PredictableSelectIsExpensive = !Subtarget->isAtom();
1571   EnableExtLdPromotion = true;
1572   setPrefFunctionAlignment(4); // 2^4 bytes.
1573
1574   verifyIntrinsicTables();
1575 }
1576
1577 // This has so far only been implemented for 64-bit MachO.
1578 bool X86TargetLowering::useLoadStackGuardNode() const {
1579   return Subtarget->isTargetMachO() && Subtarget->is64Bit();
1580 }
1581
1582 TargetLoweringBase::LegalizeTypeAction
1583 X86TargetLowering::getPreferredVectorAction(EVT VT) const {
1584   if (ExperimentalVectorWideningLegalization &&
1585       VT.getVectorNumElements() != 1 &&
1586       VT.getVectorElementType().getSimpleVT() != MVT::i1)
1587     return TypeWidenVector;
1588
1589   return TargetLoweringBase::getPreferredVectorAction(VT);
1590 }
1591
1592 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1593   if (!VT.isVector())
1594     return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1595
1596   const unsigned NumElts = VT.getVectorNumElements();
1597   const EVT EltVT = VT.getVectorElementType();
1598   if (VT.is512BitVector()) {
1599     if (Subtarget->hasAVX512())
1600       if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1601           EltVT == MVT::f32 || EltVT == MVT::f64)
1602         switch(NumElts) {
1603         case  8: return MVT::v8i1;
1604         case 16: return MVT::v16i1;
1605       }
1606     if (Subtarget->hasBWI())
1607       if (EltVT == MVT::i8 || EltVT == MVT::i16)
1608         switch(NumElts) {
1609         case 32: return MVT::v32i1;
1610         case 64: return MVT::v64i1;
1611       }
1612   }
1613
1614   if (VT.is256BitVector() || VT.is128BitVector()) {
1615     if (Subtarget->hasVLX())
1616       if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1617           EltVT == MVT::f32 || EltVT == MVT::f64)
1618         switch(NumElts) {
1619         case 2: return MVT::v2i1;
1620         case 4: return MVT::v4i1;
1621         case 8: return MVT::v8i1;
1622       }
1623     if (Subtarget->hasBWI() && Subtarget->hasVLX())
1624       if (EltVT == MVT::i8 || EltVT == MVT::i16)
1625         switch(NumElts) {
1626         case  8: return MVT::v8i1;
1627         case 16: return MVT::v16i1;
1628         case 32: return MVT::v32i1;
1629       }
1630   }
1631
1632   return VT.changeVectorElementTypeToInteger();
1633 }
1634
1635 /// Helper for getByValTypeAlignment to determine
1636 /// the desired ByVal argument alignment.
1637 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1638   if (MaxAlign == 16)
1639     return;
1640   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1641     if (VTy->getBitWidth() == 128)
1642       MaxAlign = 16;
1643   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1644     unsigned EltAlign = 0;
1645     getMaxByValAlign(ATy->getElementType(), EltAlign);
1646     if (EltAlign > MaxAlign)
1647       MaxAlign = EltAlign;
1648   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1649     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1650       unsigned EltAlign = 0;
1651       getMaxByValAlign(STy->getElementType(i), EltAlign);
1652       if (EltAlign > MaxAlign)
1653         MaxAlign = EltAlign;
1654       if (MaxAlign == 16)
1655         break;
1656     }
1657   }
1658 }
1659
1660 /// Return the desired alignment for ByVal aggregate
1661 /// function arguments in the caller parameter area. For X86, aggregates
1662 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1663 /// are at 4-byte boundaries.
1664 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1665   if (Subtarget->is64Bit()) {
1666     // Max of 8 and alignment of type.
1667     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1668     if (TyAlign > 8)
1669       return TyAlign;
1670     return 8;
1671   }
1672
1673   unsigned Align = 4;
1674   if (Subtarget->hasSSE1())
1675     getMaxByValAlign(Ty, Align);
1676   return Align;
1677 }
1678
1679 /// Returns the target specific optimal type for load
1680 /// and store operations as a result of memset, memcpy, and memmove
1681 /// lowering. If DstAlign is zero that means it's safe to destination
1682 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1683 /// means there isn't a need to check it against alignment requirement,
1684 /// probably because the source does not need to be loaded. If 'IsMemset' is
1685 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1686 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1687 /// source is constant so it does not need to be loaded.
1688 /// It returns EVT::Other if the type should be determined using generic
1689 /// target-independent logic.
1690 EVT
1691 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1692                                        unsigned DstAlign, unsigned SrcAlign,
1693                                        bool IsMemset, bool ZeroMemset,
1694                                        bool MemcpyStrSrc,
1695                                        MachineFunction &MF) const {
1696   const Function *F = MF.getFunction();
1697   if ((!IsMemset || ZeroMemset) &&
1698       !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
1699     if (Size >= 16 &&
1700         (Subtarget->isUnalignedMemAccessFast() ||
1701          ((DstAlign == 0 || DstAlign >= 16) &&
1702           (SrcAlign == 0 || SrcAlign >= 16)))) {
1703       if (Size >= 32) {
1704         if (Subtarget->hasInt256())
1705           return MVT::v8i32;
1706         if (Subtarget->hasFp256())
1707           return MVT::v8f32;
1708       }
1709       if (Subtarget->hasSSE2())
1710         return MVT::v4i32;
1711       if (Subtarget->hasSSE1())
1712         return MVT::v4f32;
1713     } else if (!MemcpyStrSrc && Size >= 8 &&
1714                !Subtarget->is64Bit() &&
1715                Subtarget->hasSSE2()) {
1716       // Do not use f64 to lower memcpy if source is string constant. It's
1717       // better to use i32 to avoid the loads.
1718       return MVT::f64;
1719     }
1720   }
1721   if (Subtarget->is64Bit() && Size >= 8)
1722     return MVT::i64;
1723   return MVT::i32;
1724 }
1725
1726 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1727   if (VT == MVT::f32)
1728     return X86ScalarSSEf32;
1729   else if (VT == MVT::f64)
1730     return X86ScalarSSEf64;
1731   return true;
1732 }
1733
1734 bool
1735 X86TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
1736                                                   unsigned,
1737                                                   unsigned,
1738                                                   bool *Fast) const {
1739   if (Fast)
1740     *Fast = Subtarget->isUnalignedMemAccessFast();
1741   return true;
1742 }
1743
1744 /// Return the entry encoding for a jump table in the
1745 /// current function.  The returned value is a member of the
1746 /// MachineJumpTableInfo::JTEntryKind enum.
1747 unsigned X86TargetLowering::getJumpTableEncoding() const {
1748   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1749   // symbol.
1750   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1751       Subtarget->isPICStyleGOT())
1752     return MachineJumpTableInfo::EK_Custom32;
1753
1754   // Otherwise, use the normal jump table encoding heuristics.
1755   return TargetLowering::getJumpTableEncoding();
1756 }
1757
1758 const MCExpr *
1759 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1760                                              const MachineBasicBlock *MBB,
1761                                              unsigned uid,MCContext &Ctx) const{
1762   assert(MBB->getParent()->getTarget().getRelocationModel() == Reloc::PIC_ &&
1763          Subtarget->isPICStyleGOT());
1764   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1765   // entries.
1766   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1767                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1768 }
1769
1770 /// Returns relocation base for the given PIC jumptable.
1771 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1772                                                     SelectionDAG &DAG) const {
1773   if (!Subtarget->is64Bit())
1774     // This doesn't have SDLoc associated with it, but is not really the
1775     // same as a Register.
1776     return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy());
1777   return Table;
1778 }
1779
1780 /// This returns the relocation base for the given PIC jumptable,
1781 /// the same as getPICJumpTableRelocBase, but as an MCExpr.
1782 const MCExpr *X86TargetLowering::
1783 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1784                              MCContext &Ctx) const {
1785   // X86-64 uses RIP relative addressing based on the jump table label.
1786   if (Subtarget->isPICStyleRIPRel())
1787     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1788
1789   // Otherwise, the reference is relative to the PIC base.
1790   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1791 }
1792
1793 std::pair<const TargetRegisterClass *, uint8_t>
1794 X86TargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
1795                                            MVT VT) const {
1796   const TargetRegisterClass *RRC = nullptr;
1797   uint8_t Cost = 1;
1798   switch (VT.SimpleTy) {
1799   default:
1800     return TargetLowering::findRepresentativeClass(TRI, VT);
1801   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1802     RRC = Subtarget->is64Bit() ? &X86::GR64RegClass : &X86::GR32RegClass;
1803     break;
1804   case MVT::x86mmx:
1805     RRC = &X86::VR64RegClass;
1806     break;
1807   case MVT::f32: case MVT::f64:
1808   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1809   case MVT::v4f32: case MVT::v2f64:
1810   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1811   case MVT::v4f64:
1812     RRC = &X86::VR128RegClass;
1813     break;
1814   }
1815   return std::make_pair(RRC, Cost);
1816 }
1817
1818 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1819                                                unsigned &Offset) const {
1820   if (!Subtarget->isTargetLinux())
1821     return false;
1822
1823   if (Subtarget->is64Bit()) {
1824     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1825     Offset = 0x28;
1826     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1827       AddressSpace = 256;
1828     else
1829       AddressSpace = 257;
1830   } else {
1831     // %gs:0x14 on i386
1832     Offset = 0x14;
1833     AddressSpace = 256;
1834   }
1835   return true;
1836 }
1837
1838 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1839                                             unsigned DestAS) const {
1840   assert(SrcAS != DestAS && "Expected different address spaces!");
1841
1842   return SrcAS < 256 && DestAS < 256;
1843 }
1844
1845 //===----------------------------------------------------------------------===//
1846 //               Return Value Calling Convention Implementation
1847 //===----------------------------------------------------------------------===//
1848
1849 #include "X86GenCallingConv.inc"
1850
1851 bool
1852 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1853                                   MachineFunction &MF, bool isVarArg,
1854                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1855                         LLVMContext &Context) const {
1856   SmallVector<CCValAssign, 16> RVLocs;
1857   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
1858   return CCInfo.CheckReturn(Outs, RetCC_X86);
1859 }
1860
1861 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
1862   static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
1863   return ScratchRegs;
1864 }
1865
1866 SDValue
1867 X86TargetLowering::LowerReturn(SDValue Chain,
1868                                CallingConv::ID CallConv, bool isVarArg,
1869                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1870                                const SmallVectorImpl<SDValue> &OutVals,
1871                                SDLoc dl, SelectionDAG &DAG) const {
1872   MachineFunction &MF = DAG.getMachineFunction();
1873   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1874
1875   SmallVector<CCValAssign, 16> RVLocs;
1876   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, *DAG.getContext());
1877   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1878
1879   SDValue Flag;
1880   SmallVector<SDValue, 6> RetOps;
1881   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1882   // Operand #1 = Bytes To Pop
1883   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1884                    MVT::i16));
1885
1886   // Copy the result values into the output registers.
1887   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1888     CCValAssign &VA = RVLocs[i];
1889     assert(VA.isRegLoc() && "Can only return in registers!");
1890     SDValue ValToCopy = OutVals[i];
1891     EVT ValVT = ValToCopy.getValueType();
1892
1893     // Promote values to the appropriate types.
1894     if (VA.getLocInfo() == CCValAssign::SExt)
1895       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1896     else if (VA.getLocInfo() == CCValAssign::ZExt)
1897       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1898     else if (VA.getLocInfo() == CCValAssign::AExt)
1899       ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1900     else if (VA.getLocInfo() == CCValAssign::BCvt)
1901       ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1902
1903     assert(VA.getLocInfo() != CCValAssign::FPExt &&
1904            "Unexpected FP-extend for return value.");
1905
1906     // If this is x86-64, and we disabled SSE, we can't return FP values,
1907     // or SSE or MMX vectors.
1908     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1909          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1910           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1911       report_fatal_error("SSE register return with SSE disabled");
1912     }
1913     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1914     // llvm-gcc has never done it right and no one has noticed, so this
1915     // should be OK for now.
1916     if (ValVT == MVT::f64 &&
1917         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1918       report_fatal_error("SSE2 register return with SSE2 disabled");
1919
1920     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1921     // the RET instruction and handled by the FP Stackifier.
1922     if (VA.getLocReg() == X86::FP0 ||
1923         VA.getLocReg() == X86::FP1) {
1924       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1925       // change the value to the FP stack register class.
1926       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1927         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1928       RetOps.push_back(ValToCopy);
1929       // Don't emit a copytoreg.
1930       continue;
1931     }
1932
1933     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1934     // which is returned in RAX / RDX.
1935     if (Subtarget->is64Bit()) {
1936       if (ValVT == MVT::x86mmx) {
1937         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1938           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1939           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1940                                   ValToCopy);
1941           // If we don't have SSE2 available, convert to v4f32 so the generated
1942           // register is legal.
1943           if (!Subtarget->hasSSE2())
1944             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1945         }
1946       }
1947     }
1948
1949     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1950     Flag = Chain.getValue(1);
1951     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1952   }
1953
1954   // The x86-64 ABIs require that for returning structs by value we copy
1955   // the sret argument into %rax/%eax (depending on ABI) for the return.
1956   // Win32 requires us to put the sret argument to %eax as well.
1957   // We saved the argument into a virtual register in the entry block,
1958   // so now we copy the value out and into %rax/%eax.
1959   //
1960   // Checking Function.hasStructRetAttr() here is insufficient because the IR
1961   // may not have an explicit sret argument. If FuncInfo.CanLowerReturn is
1962   // false, then an sret argument may be implicitly inserted in the SelDAG. In
1963   // either case FuncInfo->setSRetReturnReg() will have been called.
1964   if (unsigned SRetReg = FuncInfo->getSRetReturnReg()) {
1965     assert((Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC()) &&
1966            "No need for an sret register");
1967     SDValue Val = DAG.getCopyFromReg(Chain, dl, SRetReg, getPointerTy());
1968
1969     unsigned RetValReg
1970         = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
1971           X86::RAX : X86::EAX;
1972     Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
1973     Flag = Chain.getValue(1);
1974
1975     // RAX/EAX now acts like a return value.
1976     RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
1977   }
1978
1979   RetOps[0] = Chain;  // Update chain.
1980
1981   // Add the flag if we have it.
1982   if (Flag.getNode())
1983     RetOps.push_back(Flag);
1984
1985   return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
1986 }
1987
1988 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1989   if (N->getNumValues() != 1)
1990     return false;
1991   if (!N->hasNUsesOfValue(1, 0))
1992     return false;
1993
1994   SDValue TCChain = Chain;
1995   SDNode *Copy = *N->use_begin();
1996   if (Copy->getOpcode() == ISD::CopyToReg) {
1997     // If the copy has a glue operand, we conservatively assume it isn't safe to
1998     // perform a tail call.
1999     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2000       return false;
2001     TCChain = Copy->getOperand(0);
2002   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
2003     return false;
2004
2005   bool HasRet = false;
2006   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2007        UI != UE; ++UI) {
2008     if (UI->getOpcode() != X86ISD::RET_FLAG)
2009       return false;
2010     // If we are returning more than one value, we can definitely
2011     // not make a tail call see PR19530
2012     if (UI->getNumOperands() > 4)
2013       return false;
2014     if (UI->getNumOperands() == 4 &&
2015         UI->getOperand(UI->getNumOperands()-1).getValueType() != MVT::Glue)
2016       return false;
2017     HasRet = true;
2018   }
2019
2020   if (!HasRet)
2021     return false;
2022
2023   Chain = TCChain;
2024   return true;
2025 }
2026
2027 EVT
2028 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
2029                                             ISD::NodeType ExtendKind) const {
2030   MVT ReturnMVT;
2031   // TODO: Is this also valid on 32-bit?
2032   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
2033     ReturnMVT = MVT::i8;
2034   else
2035     ReturnMVT = MVT::i32;
2036
2037   EVT MinVT = getRegisterType(Context, ReturnMVT);
2038   return VT.bitsLT(MinVT) ? MinVT : VT;
2039 }
2040
2041 /// Lower the result values of a call into the
2042 /// appropriate copies out of appropriate physical registers.
2043 ///
2044 SDValue
2045 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2046                                    CallingConv::ID CallConv, bool isVarArg,
2047                                    const SmallVectorImpl<ISD::InputArg> &Ins,
2048                                    SDLoc dl, SelectionDAG &DAG,
2049                                    SmallVectorImpl<SDValue> &InVals) const {
2050
2051   // Assign locations to each value returned by this call.
2052   SmallVector<CCValAssign, 16> RVLocs;
2053   bool Is64Bit = Subtarget->is64Bit();
2054   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2055                  *DAG.getContext());
2056   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2057
2058   // Copy all of the result registers out of their specified physreg.
2059   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2060     CCValAssign &VA = RVLocs[i];
2061     EVT CopyVT = VA.getValVT();
2062
2063     // If this is x86-64, and we disabled SSE, we can't return FP values
2064     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2065         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2066       report_fatal_error("SSE register return with SSE disabled");
2067     }
2068
2069     // If we prefer to use the value in xmm registers, copy it out as f80 and
2070     // use a truncate to move it from fp stack reg to xmm reg.
2071     if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
2072         isScalarFPTypeInSSEReg(VA.getValVT()))
2073       CopyVT = MVT::f80;
2074
2075     Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2076                                CopyVT, InFlag).getValue(1);
2077     SDValue Val = Chain.getValue(0);
2078
2079     if (CopyVT != VA.getValVT())
2080       Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2081                         // This truncation won't change the value.
2082                         DAG.getIntPtrConstant(1));
2083
2084     InFlag = Chain.getValue(2);
2085     InVals.push_back(Val);
2086   }
2087
2088   return Chain;
2089 }
2090
2091 //===----------------------------------------------------------------------===//
2092 //                C & StdCall & Fast Calling Convention implementation
2093 //===----------------------------------------------------------------------===//
2094 //  StdCall calling convention seems to be standard for many Windows' API
2095 //  routines and around. It differs from C calling convention just a little:
2096 //  callee should clean up the stack, not caller. Symbols should be also
2097 //  decorated in some fancy way :) It doesn't support any vector arguments.
2098 //  For info on fast calling convention see Fast Calling Convention (tail call)
2099 //  implementation LowerX86_32FastCCCallTo.
2100
2101 /// CallIsStructReturn - Determines whether a call uses struct return
2102 /// semantics.
2103 enum StructReturnType {
2104   NotStructReturn,
2105   RegStructReturn,
2106   StackStructReturn
2107 };
2108 static StructReturnType
2109 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2110   if (Outs.empty())
2111     return NotStructReturn;
2112
2113   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2114   if (!Flags.isSRet())
2115     return NotStructReturn;
2116   if (Flags.isInReg())
2117     return RegStructReturn;
2118   return StackStructReturn;
2119 }
2120
2121 /// Determines whether a function uses struct return semantics.
2122 static StructReturnType
2123 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2124   if (Ins.empty())
2125     return NotStructReturn;
2126
2127   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2128   if (!Flags.isSRet())
2129     return NotStructReturn;
2130   if (Flags.isInReg())
2131     return RegStructReturn;
2132   return StackStructReturn;
2133 }
2134
2135 /// Make a copy of an aggregate at address specified by "Src" to address
2136 /// "Dst" with size and alignment information specified by the specific
2137 /// parameter attribute. The copy will be passed as a byval function parameter.
2138 static SDValue
2139 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2140                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2141                           SDLoc dl) {
2142   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
2143
2144   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2145                        /*isVolatile*/false, /*AlwaysInline=*/true,
2146                        /*isTailCall*/false,
2147                        MachinePointerInfo(), MachinePointerInfo());
2148 }
2149
2150 /// Return true if the calling convention is one that
2151 /// supports tail call optimization.
2152 static bool IsTailCallConvention(CallingConv::ID CC) {
2153   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2154           CC == CallingConv::HiPE);
2155 }
2156
2157 /// \brief Return true if the calling convention is a C calling convention.
2158 static bool IsCCallConvention(CallingConv::ID CC) {
2159   return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2160           CC == CallingConv::X86_64_SysV);
2161 }
2162
2163 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2164   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2165     return false;
2166
2167   CallSite CS(CI);
2168   CallingConv::ID CalleeCC = CS.getCallingConv();
2169   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2170     return false;
2171
2172   return true;
2173 }
2174
2175 /// Return true if the function is being made into
2176 /// a tailcall target by changing its ABI.
2177 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2178                                    bool GuaranteedTailCallOpt) {
2179   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2180 }
2181
2182 SDValue
2183 X86TargetLowering::LowerMemArgument(SDValue Chain,
2184                                     CallingConv::ID CallConv,
2185                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2186                                     SDLoc dl, SelectionDAG &DAG,
2187                                     const CCValAssign &VA,
2188                                     MachineFrameInfo *MFI,
2189                                     unsigned i) const {
2190   // Create the nodes corresponding to a load from this parameter slot.
2191   ISD::ArgFlagsTy Flags = Ins[i].Flags;
2192   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(
2193       CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2194   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2195   EVT ValVT;
2196
2197   // If value is passed by pointer we have address passed instead of the value
2198   // itself.
2199   if (VA.getLocInfo() == CCValAssign::Indirect)
2200     ValVT = VA.getLocVT();
2201   else
2202     ValVT = VA.getValVT();
2203
2204   // FIXME: For now, all byval parameter objects are marked mutable. This can be
2205   // changed with more analysis.
2206   // In case of tail call optimization mark all arguments mutable. Since they
2207   // could be overwritten by lowering of arguments in case of a tail call.
2208   if (Flags.isByVal()) {
2209     unsigned Bytes = Flags.getByValSize();
2210     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2211     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2212     return DAG.getFrameIndex(FI, getPointerTy());
2213   } else {
2214     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2215                                     VA.getLocMemOffset(), isImmutable);
2216     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2217     return DAG.getLoad(ValVT, dl, Chain, FIN,
2218                        MachinePointerInfo::getFixedStack(FI),
2219                        false, false, false, 0);
2220   }
2221 }
2222
2223 // FIXME: Get this from tablegen.
2224 static ArrayRef<MCPhysReg> get64BitArgumentGPRs(CallingConv::ID CallConv,
2225                                                 const X86Subtarget *Subtarget) {
2226   assert(Subtarget->is64Bit());
2227
2228   if (Subtarget->isCallingConvWin64(CallConv)) {
2229     static const MCPhysReg GPR64ArgRegsWin64[] = {
2230       X86::RCX, X86::RDX, X86::R8,  X86::R9
2231     };
2232     return makeArrayRef(std::begin(GPR64ArgRegsWin64), std::end(GPR64ArgRegsWin64));
2233   }
2234
2235   static const MCPhysReg GPR64ArgRegs64Bit[] = {
2236     X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2237   };
2238   return makeArrayRef(std::begin(GPR64ArgRegs64Bit), std::end(GPR64ArgRegs64Bit));
2239 }
2240
2241 // FIXME: Get this from tablegen.
2242 static ArrayRef<MCPhysReg> get64BitArgumentXMMs(MachineFunction &MF,
2243                                                 CallingConv::ID CallConv,
2244                                                 const X86Subtarget *Subtarget) {
2245   assert(Subtarget->is64Bit());
2246   if (Subtarget->isCallingConvWin64(CallConv)) {
2247     // The XMM registers which might contain var arg parameters are shadowed
2248     // in their paired GPR.  So we only need to save the GPR to their home
2249     // slots.
2250     // TODO: __vectorcall will change this.
2251     return None;
2252   }
2253
2254   const Function *Fn = MF.getFunction();
2255   bool NoImplicitFloatOps = Fn->hasFnAttribute(Attribute::NoImplicitFloat);
2256   assert(!(MF.getTarget().Options.UseSoftFloat && NoImplicitFloatOps) &&
2257          "SSE register cannot be used when SSE is disabled!");
2258   if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2259       !Subtarget->hasSSE1())
2260     // Kernel mode asks for SSE to be disabled, so there are no XMM argument
2261     // registers.
2262     return None;
2263
2264   static const MCPhysReg XMMArgRegs64Bit[] = {
2265     X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2266     X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2267   };
2268   return makeArrayRef(std::begin(XMMArgRegs64Bit), std::end(XMMArgRegs64Bit));
2269 }
2270
2271 SDValue
2272 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2273                                         CallingConv::ID CallConv,
2274                                         bool isVarArg,
2275                                       const SmallVectorImpl<ISD::InputArg> &Ins,
2276                                         SDLoc dl,
2277                                         SelectionDAG &DAG,
2278                                         SmallVectorImpl<SDValue> &InVals)
2279                                           const {
2280   MachineFunction &MF = DAG.getMachineFunction();
2281   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2282   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
2283
2284   const Function* Fn = MF.getFunction();
2285   if (Fn->hasExternalLinkage() &&
2286       Subtarget->isTargetCygMing() &&
2287       Fn->getName() == "main")
2288     FuncInfo->setForceFramePointer(true);
2289
2290   MachineFrameInfo *MFI = MF.getFrameInfo();
2291   bool Is64Bit = Subtarget->is64Bit();
2292   bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2293
2294   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2295          "Var args not supported with calling convention fastcc, ghc or hipe");
2296
2297   // Assign locations to all of the incoming arguments.
2298   SmallVector<CCValAssign, 16> ArgLocs;
2299   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2300
2301   // Allocate shadow area for Win64
2302   if (IsWin64)
2303     CCInfo.AllocateStack(32, 8);
2304
2305   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2306
2307   unsigned LastVal = ~0U;
2308   SDValue ArgValue;
2309   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2310     CCValAssign &VA = ArgLocs[i];
2311     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2312     // places.
2313     assert(VA.getValNo() != LastVal &&
2314            "Don't support value assigned to multiple locs yet");
2315     (void)LastVal;
2316     LastVal = VA.getValNo();
2317
2318     if (VA.isRegLoc()) {
2319       EVT RegVT = VA.getLocVT();
2320       const TargetRegisterClass *RC;
2321       if (RegVT == MVT::i32)
2322         RC = &X86::GR32RegClass;
2323       else if (Is64Bit && RegVT == MVT::i64)
2324         RC = &X86::GR64RegClass;
2325       else if (RegVT == MVT::f32)
2326         RC = &X86::FR32RegClass;
2327       else if (RegVT == MVT::f64)
2328         RC = &X86::FR64RegClass;
2329       else if (RegVT.is512BitVector())
2330         RC = &X86::VR512RegClass;
2331       else if (RegVT.is256BitVector())
2332         RC = &X86::VR256RegClass;
2333       else if (RegVT.is128BitVector())
2334         RC = &X86::VR128RegClass;
2335       else if (RegVT == MVT::x86mmx)
2336         RC = &X86::VR64RegClass;
2337       else if (RegVT == MVT::i1)
2338         RC = &X86::VK1RegClass;
2339       else if (RegVT == MVT::v8i1)
2340         RC = &X86::VK8RegClass;
2341       else if (RegVT == MVT::v16i1)
2342         RC = &X86::VK16RegClass;
2343       else if (RegVT == MVT::v32i1)
2344         RC = &X86::VK32RegClass;
2345       else if (RegVT == MVT::v64i1)
2346         RC = &X86::VK64RegClass;
2347       else
2348         llvm_unreachable("Unknown argument type!");
2349
2350       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2351       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2352
2353       // If this is an 8 or 16-bit value, it is really passed promoted to 32
2354       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
2355       // right size.
2356       if (VA.getLocInfo() == CCValAssign::SExt)
2357         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2358                                DAG.getValueType(VA.getValVT()));
2359       else if (VA.getLocInfo() == CCValAssign::ZExt)
2360         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2361                                DAG.getValueType(VA.getValVT()));
2362       else if (VA.getLocInfo() == CCValAssign::BCvt)
2363         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2364
2365       if (VA.isExtInLoc()) {
2366         // Handle MMX values passed in XMM regs.
2367         if (RegVT.isVector())
2368           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2369         else
2370           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2371       }
2372     } else {
2373       assert(VA.isMemLoc());
2374       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2375     }
2376
2377     // If value is passed via pointer - do a load.
2378     if (VA.getLocInfo() == CCValAssign::Indirect)
2379       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2380                              MachinePointerInfo(), false, false, false, 0);
2381
2382     InVals.push_back(ArgValue);
2383   }
2384
2385   if (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC()) {
2386     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2387       // The x86-64 ABIs require that for returning structs by value we copy
2388       // the sret argument into %rax/%eax (depending on ABI) for the return.
2389       // Win32 requires us to put the sret argument to %eax as well.
2390       // Save the argument into a virtual register so that we can access it
2391       // from the return points.
2392       if (Ins[i].Flags.isSRet()) {
2393         unsigned Reg = FuncInfo->getSRetReturnReg();
2394         if (!Reg) {
2395           MVT PtrTy = getPointerTy();
2396           Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2397           FuncInfo->setSRetReturnReg(Reg);
2398         }
2399         SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2400         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2401         break;
2402       }
2403     }
2404   }
2405
2406   unsigned StackSize = CCInfo.getNextStackOffset();
2407   // Align stack specially for tail calls.
2408   if (FuncIsMadeTailCallSafe(CallConv,
2409                              MF.getTarget().Options.GuaranteedTailCallOpt))
2410     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2411
2412   // If the function takes variable number of arguments, make a frame index for
2413   // the start of the first vararg value... for expansion of llvm.va_start. We
2414   // can skip this if there are no va_start calls.
2415   if (MFI->hasVAStart() &&
2416       (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2417                    CallConv != CallingConv::X86_ThisCall))) {
2418     FuncInfo->setVarArgsFrameIndex(
2419         MFI->CreateFixedObject(1, StackSize, true));
2420   }
2421
2422   MachineModuleInfo &MMI = MF.getMMI();
2423   const Function *WinEHParent = nullptr;
2424   if (IsWin64 && MMI.hasWinEHFuncInfo(Fn))
2425     WinEHParent = MMI.getWinEHParent(Fn);
2426   bool IsWinEHOutlined = WinEHParent && WinEHParent != Fn;
2427   bool IsWinEHParent = WinEHParent && WinEHParent == Fn;
2428
2429   // Figure out if XMM registers are in use.
2430   assert(!(MF.getTarget().Options.UseSoftFloat &&
2431            Fn->hasFnAttribute(Attribute::NoImplicitFloat)) &&
2432          "SSE register cannot be used when SSE is disabled!");
2433
2434   // 64-bit calling conventions support varargs and register parameters, so we
2435   // have to do extra work to spill them in the prologue.
2436   if (Is64Bit && isVarArg && MFI->hasVAStart()) {
2437     // Find the first unallocated argument registers.
2438     ArrayRef<MCPhysReg> ArgGPRs = get64BitArgumentGPRs(CallConv, Subtarget);
2439     ArrayRef<MCPhysReg> ArgXMMs = get64BitArgumentXMMs(MF, CallConv, Subtarget);
2440     unsigned NumIntRegs = CCInfo.getFirstUnallocated(ArgGPRs);
2441     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(ArgXMMs);
2442     assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2443            "SSE register cannot be used when SSE is disabled!");
2444
2445     // Gather all the live in physical registers.
2446     SmallVector<SDValue, 6> LiveGPRs;
2447     SmallVector<SDValue, 8> LiveXMMRegs;
2448     SDValue ALVal;
2449     for (MCPhysReg Reg : ArgGPRs.slice(NumIntRegs)) {
2450       unsigned GPR = MF.addLiveIn(Reg, &X86::GR64RegClass);
2451       LiveGPRs.push_back(
2452           DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64));
2453     }
2454     if (!ArgXMMs.empty()) {
2455       unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2456       ALVal = DAG.getCopyFromReg(Chain, dl, AL, MVT::i8);
2457       for (MCPhysReg Reg : ArgXMMs.slice(NumXMMRegs)) {
2458         unsigned XMMReg = MF.addLiveIn(Reg, &X86::VR128RegClass);
2459         LiveXMMRegs.push_back(
2460             DAG.getCopyFromReg(Chain, dl, XMMReg, MVT::v4f32));
2461       }
2462     }
2463
2464     if (IsWin64) {
2465       // Get to the caller-allocated home save location.  Add 8 to account
2466       // for the return address.
2467       int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2468       FuncInfo->setRegSaveFrameIndex(
2469           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2470       // Fixup to set vararg frame on shadow area (4 x i64).
2471       if (NumIntRegs < 4)
2472         FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2473     } else {
2474       // For X86-64, if there are vararg parameters that are passed via
2475       // registers, then we must store them to their spots on the stack so
2476       // they may be loaded by deferencing the result of va_next.
2477       FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2478       FuncInfo->setVarArgsFPOffset(ArgGPRs.size() * 8 + NumXMMRegs * 16);
2479       FuncInfo->setRegSaveFrameIndex(MFI->CreateStackObject(
2480           ArgGPRs.size() * 8 + ArgXMMs.size() * 16, 16, false));
2481     }
2482
2483     // Store the integer parameter registers.
2484     SmallVector<SDValue, 8> MemOps;
2485     SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2486                                       getPointerTy());
2487     unsigned Offset = FuncInfo->getVarArgsGPOffset();
2488     for (SDValue Val : LiveGPRs) {
2489       SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2490                                 DAG.getIntPtrConstant(Offset));
2491       SDValue Store =
2492         DAG.getStore(Val.getValue(1), dl, Val, FIN,
2493                      MachinePointerInfo::getFixedStack(
2494                        FuncInfo->getRegSaveFrameIndex(), Offset),
2495                      false, false, 0);
2496       MemOps.push_back(Store);
2497       Offset += 8;
2498     }
2499
2500     if (!ArgXMMs.empty() && NumXMMRegs != ArgXMMs.size()) {
2501       // Now store the XMM (fp + vector) parameter registers.
2502       SmallVector<SDValue, 12> SaveXMMOps;
2503       SaveXMMOps.push_back(Chain);
2504       SaveXMMOps.push_back(ALVal);
2505       SaveXMMOps.push_back(DAG.getIntPtrConstant(
2506                              FuncInfo->getRegSaveFrameIndex()));
2507       SaveXMMOps.push_back(DAG.getIntPtrConstant(
2508                              FuncInfo->getVarArgsFPOffset()));
2509       SaveXMMOps.insert(SaveXMMOps.end(), LiveXMMRegs.begin(),
2510                         LiveXMMRegs.end());
2511       MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2512                                    MVT::Other, SaveXMMOps));
2513     }
2514
2515     if (!MemOps.empty())
2516       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2517   } else if (IsWinEHOutlined) {
2518     // Get to the caller-allocated home save location.  Add 8 to account
2519     // for the return address.
2520     int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2521     FuncInfo->setRegSaveFrameIndex(MFI->CreateFixedObject(
2522         /*Size=*/1, /*SPOffset=*/HomeOffset + 8, /*Immutable=*/false));
2523
2524     MMI.getWinEHFuncInfo(Fn)
2525         .CatchHandlerParentFrameObjIdx[const_cast<Function *>(Fn)] =
2526         FuncInfo->getRegSaveFrameIndex();
2527
2528     // Store the second integer parameter (rdx) into rsp+16 relative to the
2529     // stack pointer at the entry of the function.
2530     SDValue RSFIN =
2531         DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(), getPointerTy());
2532     unsigned GPR = MF.addLiveIn(X86::RDX, &X86::GR64RegClass);
2533     SDValue Val = DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64);
2534     Chain = DAG.getStore(
2535         Val.getValue(1), dl, Val, RSFIN,
2536         MachinePointerInfo::getFixedStack(FuncInfo->getRegSaveFrameIndex()),
2537         /*isVolatile=*/true, /*isNonTemporal=*/false, /*Alignment=*/0);
2538   }
2539
2540   if (isVarArg && MFI->hasMustTailInVarArgFunc()) {
2541     // Find the largest legal vector type.
2542     MVT VecVT = MVT::Other;
2543     // FIXME: Only some x86_32 calling conventions support AVX512.
2544     if (Subtarget->hasAVX512() &&
2545         (Is64Bit || (CallConv == CallingConv::X86_VectorCall ||
2546                      CallConv == CallingConv::Intel_OCL_BI)))
2547       VecVT = MVT::v16f32;
2548     else if (Subtarget->hasAVX())
2549       VecVT = MVT::v8f32;
2550     else if (Subtarget->hasSSE2())
2551       VecVT = MVT::v4f32;
2552
2553     // We forward some GPRs and some vector types.
2554     SmallVector<MVT, 2> RegParmTypes;
2555     MVT IntVT = Is64Bit ? MVT::i64 : MVT::i32;
2556     RegParmTypes.push_back(IntVT);
2557     if (VecVT != MVT::Other)
2558       RegParmTypes.push_back(VecVT);
2559
2560     // Compute the set of forwarded registers. The rest are scratch.
2561     SmallVectorImpl<ForwardedRegister> &Forwards =
2562         FuncInfo->getForwardedMustTailRegParms();
2563     CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes, CC_X86);
2564
2565     // Conservatively forward AL on x86_64, since it might be used for varargs.
2566     if (Is64Bit && !CCInfo.isAllocated(X86::AL)) {
2567       unsigned ALVReg = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2568       Forwards.push_back(ForwardedRegister(ALVReg, X86::AL, MVT::i8));
2569     }
2570
2571     // Copy all forwards from physical to virtual registers.
2572     for (ForwardedRegister &F : Forwards) {
2573       // FIXME: Can we use a less constrained schedule?
2574       SDValue RegVal = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
2575       F.VReg = MF.getRegInfo().createVirtualRegister(getRegClassFor(F.VT));
2576       Chain = DAG.getCopyToReg(Chain, dl, F.VReg, RegVal);
2577     }
2578   }
2579
2580   // Some CCs need callee pop.
2581   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2582                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2583     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2584   } else {
2585     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2586     // If this is an sret function, the return should pop the hidden pointer.
2587     if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2588         !Subtarget->getTargetTriple().isOSMSVCRT() &&
2589         argsAreStructReturn(Ins) == StackStructReturn)
2590       FuncInfo->setBytesToPopOnReturn(4);
2591   }
2592
2593   if (!Is64Bit) {
2594     // RegSaveFrameIndex is X86-64 only.
2595     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2596     if (CallConv == CallingConv::X86_FastCall ||
2597         CallConv == CallingConv::X86_ThisCall)
2598       // fastcc functions can't have varargs.
2599       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2600   }
2601
2602   FuncInfo->setArgumentStackSize(StackSize);
2603
2604   if (IsWinEHParent) {
2605     int UnwindHelpFI = MFI->CreateStackObject(8, 8, /*isSS=*/false);
2606     SDValue StackSlot = DAG.getFrameIndex(UnwindHelpFI, MVT::i64);
2607     MMI.getWinEHFuncInfo(MF.getFunction()).UnwindHelpFrameIdx = UnwindHelpFI;
2608     SDValue Neg2 = DAG.getConstant(-2, MVT::i64);
2609     Chain = DAG.getStore(Chain, dl, Neg2, StackSlot,
2610                          MachinePointerInfo::getFixedStack(UnwindHelpFI),
2611                          /*isVolatile=*/true,
2612                          /*isNonTemporal=*/false, /*Alignment=*/0);
2613   }
2614
2615   return Chain;
2616 }
2617
2618 SDValue
2619 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2620                                     SDValue StackPtr, SDValue Arg,
2621                                     SDLoc dl, SelectionDAG &DAG,
2622                                     const CCValAssign &VA,
2623                                     ISD::ArgFlagsTy Flags) const {
2624   unsigned LocMemOffset = VA.getLocMemOffset();
2625   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2626   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2627   if (Flags.isByVal())
2628     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2629
2630   return DAG.getStore(Chain, dl, Arg, PtrOff,
2631                       MachinePointerInfo::getStack(LocMemOffset),
2632                       false, false, 0);
2633 }
2634
2635 /// Emit a load of return address if tail call
2636 /// optimization is performed and it is required.
2637 SDValue
2638 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2639                                            SDValue &OutRetAddr, SDValue Chain,
2640                                            bool IsTailCall, bool Is64Bit,
2641                                            int FPDiff, SDLoc dl) const {
2642   // Adjust the Return address stack slot.
2643   EVT VT = getPointerTy();
2644   OutRetAddr = getReturnAddressFrameIndex(DAG);
2645
2646   // Load the "old" Return address.
2647   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2648                            false, false, false, 0);
2649   return SDValue(OutRetAddr.getNode(), 1);
2650 }
2651
2652 /// Emit a store of the return address if tail call
2653 /// optimization is performed and it is required (FPDiff!=0).
2654 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2655                                         SDValue Chain, SDValue RetAddrFrIdx,
2656                                         EVT PtrVT, unsigned SlotSize,
2657                                         int FPDiff, SDLoc dl) {
2658   // Store the return address to the appropriate stack slot.
2659   if (!FPDiff) return Chain;
2660   // Calculate the new stack slot for the return address.
2661   int NewReturnAddrFI =
2662     MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2663                                          false);
2664   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2665   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2666                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2667                        false, false, 0);
2668   return Chain;
2669 }
2670
2671 SDValue
2672 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2673                              SmallVectorImpl<SDValue> &InVals) const {
2674   SelectionDAG &DAG                     = CLI.DAG;
2675   SDLoc &dl                             = CLI.DL;
2676   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2677   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
2678   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
2679   SDValue Chain                         = CLI.Chain;
2680   SDValue Callee                        = CLI.Callee;
2681   CallingConv::ID CallConv              = CLI.CallConv;
2682   bool &isTailCall                      = CLI.IsTailCall;
2683   bool isVarArg                         = CLI.IsVarArg;
2684
2685   MachineFunction &MF = DAG.getMachineFunction();
2686   bool Is64Bit        = Subtarget->is64Bit();
2687   bool IsWin64        = Subtarget->isCallingConvWin64(CallConv);
2688   StructReturnType SR = callIsStructReturn(Outs);
2689   bool IsSibcall      = false;
2690   X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2691
2692   if (MF.getTarget().Options.DisableTailCalls)
2693     isTailCall = false;
2694
2695   bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
2696   if (IsMustTail) {
2697     // Force this to be a tail call.  The verifier rules are enough to ensure
2698     // that we can lower this successfully without moving the return address
2699     // around.
2700     isTailCall = true;
2701   } else if (isTailCall) {
2702     // Check if it's really possible to do a tail call.
2703     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2704                     isVarArg, SR != NotStructReturn,
2705                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2706                     Outs, OutVals, Ins, DAG);
2707
2708     // Sibcalls are automatically detected tailcalls which do not require
2709     // ABI changes.
2710     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2711       IsSibcall = true;
2712
2713     if (isTailCall)
2714       ++NumTailCalls;
2715   }
2716
2717   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2718          "Var args not supported with calling convention fastcc, ghc or hipe");
2719
2720   // Analyze operands of the call, assigning locations to each operand.
2721   SmallVector<CCValAssign, 16> ArgLocs;
2722   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2723
2724   // Allocate shadow area for Win64
2725   if (IsWin64)
2726     CCInfo.AllocateStack(32, 8);
2727
2728   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2729
2730   // Get a count of how many bytes are to be pushed on the stack.
2731   unsigned NumBytes = CCInfo.getNextStackOffset();
2732   if (IsSibcall)
2733     // This is a sibcall. The memory operands are available in caller's
2734     // own caller's stack.
2735     NumBytes = 0;
2736   else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
2737            IsTailCallConvention(CallConv))
2738     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2739
2740   int FPDiff = 0;
2741   if (isTailCall && !IsSibcall && !IsMustTail) {
2742     // Lower arguments at fp - stackoffset + fpdiff.
2743     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2744
2745     FPDiff = NumBytesCallerPushed - NumBytes;
2746
2747     // Set the delta of movement of the returnaddr stackslot.
2748     // But only set if delta is greater than previous delta.
2749     if (FPDiff < X86Info->getTCReturnAddrDelta())
2750       X86Info->setTCReturnAddrDelta(FPDiff);
2751   }
2752
2753   unsigned NumBytesToPush = NumBytes;
2754   unsigned NumBytesToPop = NumBytes;
2755
2756   // If we have an inalloca argument, all stack space has already been allocated
2757   // for us and be right at the top of the stack.  We don't support multiple
2758   // arguments passed in memory when using inalloca.
2759   if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
2760     NumBytesToPush = 0;
2761     if (!ArgLocs.back().isMemLoc())
2762       report_fatal_error("cannot use inalloca attribute on a register "
2763                          "parameter");
2764     if (ArgLocs.back().getLocMemOffset() != 0)
2765       report_fatal_error("any parameter with the inalloca attribute must be "
2766                          "the only memory argument");
2767   }
2768
2769   if (!IsSibcall)
2770     Chain = DAG.getCALLSEQ_START(
2771         Chain, DAG.getIntPtrConstant(NumBytesToPush, true), dl);
2772
2773   SDValue RetAddrFrIdx;
2774   // Load return address for tail calls.
2775   if (isTailCall && FPDiff)
2776     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2777                                     Is64Bit, FPDiff, dl);
2778
2779   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2780   SmallVector<SDValue, 8> MemOpChains;
2781   SDValue StackPtr;
2782
2783   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2784   // of tail call optimization arguments are handle later.
2785   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
2786   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2787     // Skip inalloca arguments, they have already been written.
2788     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2789     if (Flags.isInAlloca())
2790       continue;
2791
2792     CCValAssign &VA = ArgLocs[i];
2793     EVT RegVT = VA.getLocVT();
2794     SDValue Arg = OutVals[i];
2795     bool isByVal = Flags.isByVal();
2796
2797     // Promote the value if needed.
2798     switch (VA.getLocInfo()) {
2799     default: llvm_unreachable("Unknown loc info!");
2800     case CCValAssign::Full: break;
2801     case CCValAssign::SExt:
2802       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2803       break;
2804     case CCValAssign::ZExt:
2805       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2806       break;
2807     case CCValAssign::AExt:
2808       if (RegVT.is128BitVector()) {
2809         // Special case: passing MMX values in XMM registers.
2810         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2811         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2812         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2813       } else
2814         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2815       break;
2816     case CCValAssign::BCvt:
2817       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2818       break;
2819     case CCValAssign::Indirect: {
2820       // Store the argument.
2821       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2822       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2823       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2824                            MachinePointerInfo::getFixedStack(FI),
2825                            false, false, 0);
2826       Arg = SpillSlot;
2827       break;
2828     }
2829     }
2830
2831     if (VA.isRegLoc()) {
2832       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2833       if (isVarArg && IsWin64) {
2834         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2835         // shadow reg if callee is a varargs function.
2836         unsigned ShadowReg = 0;
2837         switch (VA.getLocReg()) {
2838         case X86::XMM0: ShadowReg = X86::RCX; break;
2839         case X86::XMM1: ShadowReg = X86::RDX; break;
2840         case X86::XMM2: ShadowReg = X86::R8; break;
2841         case X86::XMM3: ShadowReg = X86::R9; break;
2842         }
2843         if (ShadowReg)
2844           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2845       }
2846     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2847       assert(VA.isMemLoc());
2848       if (!StackPtr.getNode())
2849         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2850                                       getPointerTy());
2851       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2852                                              dl, DAG, VA, Flags));
2853     }
2854   }
2855
2856   if (!MemOpChains.empty())
2857     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
2858
2859   if (Subtarget->isPICStyleGOT()) {
2860     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2861     // GOT pointer.
2862     if (!isTailCall) {
2863       RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2864                DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
2865     } else {
2866       // If we are tail calling and generating PIC/GOT style code load the
2867       // address of the callee into ECX. The value in ecx is used as target of
2868       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2869       // for tail calls on PIC/GOT architectures. Normally we would just put the
2870       // address of GOT into ebx and then call target@PLT. But for tail calls
2871       // ebx would be restored (since ebx is callee saved) before jumping to the
2872       // target@PLT.
2873
2874       // Note: The actual moving to ECX is done further down.
2875       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2876       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2877           !G->getGlobal()->hasProtectedVisibility())
2878         Callee = LowerGlobalAddress(Callee, DAG);
2879       else if (isa<ExternalSymbolSDNode>(Callee))
2880         Callee = LowerExternalSymbol(Callee, DAG);
2881     }
2882   }
2883
2884   if (Is64Bit && isVarArg && !IsWin64 && !IsMustTail) {
2885     // From AMD64 ABI document:
2886     // For calls that may call functions that use varargs or stdargs
2887     // (prototype-less calls or calls to functions containing ellipsis (...) in
2888     // the declaration) %al is used as hidden argument to specify the number
2889     // of SSE registers used. The contents of %al do not need to match exactly
2890     // the number of registers, but must be an ubound on the number of SSE
2891     // registers used and is in the range 0 - 8 inclusive.
2892
2893     // Count the number of XMM registers allocated.
2894     static const MCPhysReg XMMArgRegs[] = {
2895       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2896       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2897     };
2898     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs);
2899     assert((Subtarget->hasSSE1() || !NumXMMRegs)
2900            && "SSE registers cannot be used when SSE is disabled");
2901
2902     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2903                                         DAG.getConstant(NumXMMRegs, MVT::i8)));
2904   }
2905
2906   if (isVarArg && IsMustTail) {
2907     const auto &Forwards = X86Info->getForwardedMustTailRegParms();
2908     for (const auto &F : Forwards) {
2909       SDValue Val = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
2910       RegsToPass.push_back(std::make_pair(unsigned(F.PReg), Val));
2911     }
2912   }
2913
2914   // For tail calls lower the arguments to the 'real' stack slots.  Sibcalls
2915   // don't need this because the eligibility check rejects calls that require
2916   // shuffling arguments passed in memory.
2917   if (!IsSibcall && isTailCall) {
2918     // Force all the incoming stack arguments to be loaded from the stack
2919     // before any new outgoing arguments are stored to the stack, because the
2920     // outgoing stack slots may alias the incoming argument stack slots, and
2921     // the alias isn't otherwise explicit. This is slightly more conservative
2922     // than necessary, because it means that each store effectively depends
2923     // on every argument instead of just those arguments it would clobber.
2924     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2925
2926     SmallVector<SDValue, 8> MemOpChains2;
2927     SDValue FIN;
2928     int FI = 0;
2929     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2930       CCValAssign &VA = ArgLocs[i];
2931       if (VA.isRegLoc())
2932         continue;
2933       assert(VA.isMemLoc());
2934       SDValue Arg = OutVals[i];
2935       ISD::ArgFlagsTy Flags = Outs[i].Flags;
2936       // Skip inalloca arguments.  They don't require any work.
2937       if (Flags.isInAlloca())
2938         continue;
2939       // Create frame index.
2940       int32_t Offset = VA.getLocMemOffset()+FPDiff;
2941       uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2942       FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2943       FIN = DAG.getFrameIndex(FI, getPointerTy());
2944
2945       if (Flags.isByVal()) {
2946         // Copy relative to framepointer.
2947         SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2948         if (!StackPtr.getNode())
2949           StackPtr = DAG.getCopyFromReg(Chain, dl,
2950                                         RegInfo->getStackRegister(),
2951                                         getPointerTy());
2952         Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2953
2954         MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2955                                                          ArgChain,
2956                                                          Flags, DAG, dl));
2957       } else {
2958         // Store relative to framepointer.
2959         MemOpChains2.push_back(
2960           DAG.getStore(ArgChain, dl, Arg, FIN,
2961                        MachinePointerInfo::getFixedStack(FI),
2962                        false, false, 0));
2963       }
2964     }
2965
2966     if (!MemOpChains2.empty())
2967       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
2968
2969     // Store the return address to the appropriate stack slot.
2970     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
2971                                      getPointerTy(), RegInfo->getSlotSize(),
2972                                      FPDiff, dl);
2973   }
2974
2975   // Build a sequence of copy-to-reg nodes chained together with token chain
2976   // and flag operands which copy the outgoing args into registers.
2977   SDValue InFlag;
2978   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2979     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2980                              RegsToPass[i].second, InFlag);
2981     InFlag = Chain.getValue(1);
2982   }
2983
2984   if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
2985     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2986     // In the 64-bit large code model, we have to make all calls
2987     // through a register, since the call instruction's 32-bit
2988     // pc-relative offset may not be large enough to hold the whole
2989     // address.
2990   } else if (Callee->getOpcode() == ISD::GlobalAddress) {
2991     // If the callee is a GlobalAddress node (quite common, every direct call
2992     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2993     // it.
2994     GlobalAddressSDNode* G = cast<GlobalAddressSDNode>(Callee);
2995
2996     // We should use extra load for direct calls to dllimported functions in
2997     // non-JIT mode.
2998     const GlobalValue *GV = G->getGlobal();
2999     if (!GV->hasDLLImportStorageClass()) {
3000       unsigned char OpFlags = 0;
3001       bool ExtraLoad = false;
3002       unsigned WrapperKind = ISD::DELETED_NODE;
3003
3004       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
3005       // external symbols most go through the PLT in PIC mode.  If the symbol
3006       // has hidden or protected visibility, or if it is static or local, then
3007       // we don't need to use the PLT - we can directly call it.
3008       if (Subtarget->isTargetELF() &&
3009           DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
3010           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
3011         OpFlags = X86II::MO_PLT;
3012       } else if (Subtarget->isPICStyleStubAny() &&
3013                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
3014                  (!Subtarget->getTargetTriple().isMacOSX() ||
3015                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3016         // PC-relative references to external symbols should go through $stub,
3017         // unless we're building with the leopard linker or later, which
3018         // automatically synthesizes these stubs.
3019         OpFlags = X86II::MO_DARWIN_STUB;
3020       } else if (Subtarget->isPICStyleRIPRel() && isa<Function>(GV) &&
3021                  cast<Function>(GV)->hasFnAttribute(Attribute::NonLazyBind)) {
3022         // If the function is marked as non-lazy, generate an indirect call
3023         // which loads from the GOT directly. This avoids runtime overhead
3024         // at the cost of eager binding (and one extra byte of encoding).
3025         OpFlags = X86II::MO_GOTPCREL;
3026         WrapperKind = X86ISD::WrapperRIP;
3027         ExtraLoad = true;
3028       }
3029
3030       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
3031                                           G->getOffset(), OpFlags);
3032
3033       // Add a wrapper if needed.
3034       if (WrapperKind != ISD::DELETED_NODE)
3035         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
3036       // Add extra indirection if needed.
3037       if (ExtraLoad)
3038         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
3039                              MachinePointerInfo::getGOT(),
3040                              false, false, false, 0);
3041     }
3042   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3043     unsigned char OpFlags = 0;
3044
3045     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
3046     // external symbols should go through the PLT.
3047     if (Subtarget->isTargetELF() &&
3048         DAG.getTarget().getRelocationModel() == Reloc::PIC_) {
3049       OpFlags = X86II::MO_PLT;
3050     } else if (Subtarget->isPICStyleStubAny() &&
3051                (!Subtarget->getTargetTriple().isMacOSX() ||
3052                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3053       // PC-relative references to external symbols should go through $stub,
3054       // unless we're building with the leopard linker or later, which
3055       // automatically synthesizes these stubs.
3056       OpFlags = X86II::MO_DARWIN_STUB;
3057     }
3058
3059     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
3060                                          OpFlags);
3061   } else if (Subtarget->isTarget64BitILP32() &&
3062              Callee->getValueType(0) == MVT::i32) {
3063     // Zero-extend the 32-bit Callee address into a 64-bit according to x32 ABI
3064     Callee = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, Callee);
3065   }
3066
3067   // Returns a chain & a flag for retval copy to use.
3068   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3069   SmallVector<SDValue, 8> Ops;
3070
3071   if (!IsSibcall && isTailCall) {
3072     Chain = DAG.getCALLSEQ_END(Chain,
3073                                DAG.getIntPtrConstant(NumBytesToPop, true),
3074                                DAG.getIntPtrConstant(0, true), InFlag, dl);
3075     InFlag = Chain.getValue(1);
3076   }
3077
3078   Ops.push_back(Chain);
3079   Ops.push_back(Callee);
3080
3081   if (isTailCall)
3082     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
3083
3084   // Add argument registers to the end of the list so that they are known live
3085   // into the call.
3086   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3087     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3088                                   RegsToPass[i].second.getValueType()));
3089
3090   // Add a register mask operand representing the call-preserved registers.
3091   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
3092   const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
3093   assert(Mask && "Missing call preserved mask for calling convention");
3094   Ops.push_back(DAG.getRegisterMask(Mask));
3095
3096   if (InFlag.getNode())
3097     Ops.push_back(InFlag);
3098
3099   if (isTailCall) {
3100     // We used to do:
3101     //// If this is the first return lowered for this function, add the regs
3102     //// to the liveout set for the function.
3103     // This isn't right, although it's probably harmless on x86; liveouts
3104     // should be computed from returns not tail calls.  Consider a void
3105     // function making a tail call to a function returning int.
3106     return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
3107   }
3108
3109   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
3110   InFlag = Chain.getValue(1);
3111
3112   // Create the CALLSEQ_END node.
3113   unsigned NumBytesForCalleeToPop;
3114   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
3115                        DAG.getTarget().Options.GuaranteedTailCallOpt))
3116     NumBytesForCalleeToPop = NumBytes;    // Callee pops everything
3117   else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
3118            !Subtarget->getTargetTriple().isOSMSVCRT() &&
3119            SR == StackStructReturn)
3120     // If this is a call to a struct-return function, the callee
3121     // pops the hidden struct pointer, so we have to push it back.
3122     // This is common for Darwin/X86, Linux & Mingw32 targets.
3123     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
3124     NumBytesForCalleeToPop = 4;
3125   else
3126     NumBytesForCalleeToPop = 0;  // Callee pops nothing.
3127
3128   // Returns a flag for retval copy to use.
3129   if (!IsSibcall) {
3130     Chain = DAG.getCALLSEQ_END(Chain,
3131                                DAG.getIntPtrConstant(NumBytesToPop, true),
3132                                DAG.getIntPtrConstant(NumBytesForCalleeToPop,
3133                                                      true),
3134                                InFlag, dl);
3135     InFlag = Chain.getValue(1);
3136   }
3137
3138   // Handle result values, copying them out of physregs into vregs that we
3139   // return.
3140   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3141                          Ins, dl, DAG, InVals);
3142 }
3143
3144 //===----------------------------------------------------------------------===//
3145 //                Fast Calling Convention (tail call) implementation
3146 //===----------------------------------------------------------------------===//
3147
3148 //  Like std call, callee cleans arguments, convention except that ECX is
3149 //  reserved for storing the tail called function address. Only 2 registers are
3150 //  free for argument passing (inreg). Tail call optimization is performed
3151 //  provided:
3152 //                * tailcallopt is enabled
3153 //                * caller/callee are fastcc
3154 //  On X86_64 architecture with GOT-style position independent code only local
3155 //  (within module) calls are supported at the moment.
3156 //  To keep the stack aligned according to platform abi the function
3157 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
3158 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3159 //  If a tail called function callee has more arguments than the caller the
3160 //  caller needs to make sure that there is room to move the RETADDR to. This is
3161 //  achieved by reserving an area the size of the argument delta right after the
3162 //  original RETADDR, but before the saved framepointer or the spilled registers
3163 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3164 //  stack layout:
3165 //    arg1
3166 //    arg2
3167 //    RETADDR
3168 //    [ new RETADDR
3169 //      move area ]
3170 //    (possible EBP)
3171 //    ESI
3172 //    EDI
3173 //    local1 ..
3174
3175 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
3176 /// for a 16 byte align requirement.
3177 unsigned
3178 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3179                                                SelectionDAG& DAG) const {
3180   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3181   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
3182   unsigned StackAlignment = TFI.getStackAlignment();
3183   uint64_t AlignMask = StackAlignment - 1;
3184   int64_t Offset = StackSize;
3185   unsigned SlotSize = RegInfo->getSlotSize();
3186   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3187     // Number smaller than 12 so just add the difference.
3188     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3189   } else {
3190     // Mask out lower bits, add stackalignment once plus the 12 bytes.
3191     Offset = ((~AlignMask) & Offset) + StackAlignment +
3192       (StackAlignment-SlotSize);
3193   }
3194   return Offset;
3195 }
3196
3197 /// MatchingStackOffset - Return true if the given stack call argument is
3198 /// already available in the same position (relatively) of the caller's
3199 /// incoming argument stack.
3200 static
3201 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3202                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3203                          const X86InstrInfo *TII) {
3204   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3205   int FI = INT_MAX;
3206   if (Arg.getOpcode() == ISD::CopyFromReg) {
3207     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3208     if (!TargetRegisterInfo::isVirtualRegister(VR))
3209       return false;
3210     MachineInstr *Def = MRI->getVRegDef(VR);
3211     if (!Def)
3212       return false;
3213     if (!Flags.isByVal()) {
3214       if (!TII->isLoadFromStackSlot(Def, FI))
3215         return false;
3216     } else {
3217       unsigned Opcode = Def->getOpcode();
3218       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r ||
3219            Opcode == X86::LEA64_32r) &&
3220           Def->getOperand(1).isFI()) {
3221         FI = Def->getOperand(1).getIndex();
3222         Bytes = Flags.getByValSize();
3223       } else
3224         return false;
3225     }
3226   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3227     if (Flags.isByVal())
3228       // ByVal argument is passed in as a pointer but it's now being
3229       // dereferenced. e.g.
3230       // define @foo(%struct.X* %A) {
3231       //   tail call @bar(%struct.X* byval %A)
3232       // }
3233       return false;
3234     SDValue Ptr = Ld->getBasePtr();
3235     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3236     if (!FINode)
3237       return false;
3238     FI = FINode->getIndex();
3239   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3240     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3241     FI = FINode->getIndex();
3242     Bytes = Flags.getByValSize();
3243   } else
3244     return false;
3245
3246   assert(FI != INT_MAX);
3247   if (!MFI->isFixedObjectIndex(FI))
3248     return false;
3249   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3250 }
3251
3252 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3253 /// for tail call optimization. Targets which want to do tail call
3254 /// optimization should implement this function.
3255 bool
3256 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3257                                                      CallingConv::ID CalleeCC,
3258                                                      bool isVarArg,
3259                                                      bool isCalleeStructRet,
3260                                                      bool isCallerStructRet,
3261                                                      Type *RetTy,
3262                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
3263                                     const SmallVectorImpl<SDValue> &OutVals,
3264                                     const SmallVectorImpl<ISD::InputArg> &Ins,
3265                                                      SelectionDAG &DAG) const {
3266   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3267     return false;
3268
3269   // If -tailcallopt is specified, make fastcc functions tail-callable.
3270   const MachineFunction &MF = DAG.getMachineFunction();
3271   const Function *CallerF = MF.getFunction();
3272
3273   // If the function return type is x86_fp80 and the callee return type is not,
3274   // then the FP_EXTEND of the call result is not a nop. It's not safe to
3275   // perform a tailcall optimization here.
3276   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3277     return false;
3278
3279   CallingConv::ID CallerCC = CallerF->getCallingConv();
3280   bool CCMatch = CallerCC == CalleeCC;
3281   bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3282   bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3283
3284   // Win64 functions have extra shadow space for argument homing. Don't do the
3285   // sibcall if the caller and callee have mismatched expectations for this
3286   // space.
3287   if (IsCalleeWin64 != IsCallerWin64)
3288     return false;
3289
3290   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3291     if (IsTailCallConvention(CalleeCC) && CCMatch)
3292       return true;
3293     return false;
3294   }
3295
3296   // Look for obvious safe cases to perform tail call optimization that do not
3297   // require ABI changes. This is what gcc calls sibcall.
3298
3299   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3300   // emit a special epilogue.
3301   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3302   if (RegInfo->needsStackRealignment(MF))
3303     return false;
3304
3305   // Also avoid sibcall optimization if either caller or callee uses struct
3306   // return semantics.
3307   if (isCalleeStructRet || isCallerStructRet)
3308     return false;
3309
3310   // An stdcall/thiscall caller is expected to clean up its arguments; the
3311   // callee isn't going to do that.
3312   // FIXME: this is more restrictive than needed. We could produce a tailcall
3313   // when the stack adjustment matches. For example, with a thiscall that takes
3314   // only one argument.
3315   if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3316                    CallerCC == CallingConv::X86_ThisCall))
3317     return false;
3318
3319   // Do not sibcall optimize vararg calls unless all arguments are passed via
3320   // registers.
3321   if (isVarArg && !Outs.empty()) {
3322
3323     // Optimizing for varargs on Win64 is unlikely to be safe without
3324     // additional testing.
3325     if (IsCalleeWin64 || IsCallerWin64)
3326       return false;
3327
3328     SmallVector<CCValAssign, 16> ArgLocs;
3329     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3330                    *DAG.getContext());
3331
3332     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3333     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3334       if (!ArgLocs[i].isRegLoc())
3335         return false;
3336   }
3337
3338   // If the call result is in ST0 / ST1, it needs to be popped off the x87
3339   // stack.  Therefore, if it's not used by the call it is not safe to optimize
3340   // this into a sibcall.
3341   bool Unused = false;
3342   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3343     if (!Ins[i].Used) {
3344       Unused = true;
3345       break;
3346     }
3347   }
3348   if (Unused) {
3349     SmallVector<CCValAssign, 16> RVLocs;
3350     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(), RVLocs,
3351                    *DAG.getContext());
3352     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3353     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3354       CCValAssign &VA = RVLocs[i];
3355       if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
3356         return false;
3357     }
3358   }
3359
3360   // If the calling conventions do not match, then we'd better make sure the
3361   // results are returned in the same way as what the caller expects.
3362   if (!CCMatch) {
3363     SmallVector<CCValAssign, 16> RVLocs1;
3364     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
3365                     *DAG.getContext());
3366     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3367
3368     SmallVector<CCValAssign, 16> RVLocs2;
3369     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
3370                     *DAG.getContext());
3371     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3372
3373     if (RVLocs1.size() != RVLocs2.size())
3374       return false;
3375     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3376       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3377         return false;
3378       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3379         return false;
3380       if (RVLocs1[i].isRegLoc()) {
3381         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3382           return false;
3383       } else {
3384         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3385           return false;
3386       }
3387     }
3388   }
3389
3390   // If the callee takes no arguments then go on to check the results of the
3391   // call.
3392   if (!Outs.empty()) {
3393     // Check if stack adjustment is needed. For now, do not do this if any
3394     // argument is passed on the stack.
3395     SmallVector<CCValAssign, 16> ArgLocs;
3396     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3397                    *DAG.getContext());
3398
3399     // Allocate shadow area for Win64
3400     if (IsCalleeWin64)
3401       CCInfo.AllocateStack(32, 8);
3402
3403     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3404     if (CCInfo.getNextStackOffset()) {
3405       MachineFunction &MF = DAG.getMachineFunction();
3406       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3407         return false;
3408
3409       // Check if the arguments are already laid out in the right way as
3410       // the caller's fixed stack objects.
3411       MachineFrameInfo *MFI = MF.getFrameInfo();
3412       const MachineRegisterInfo *MRI = &MF.getRegInfo();
3413       const X86InstrInfo *TII = Subtarget->getInstrInfo();
3414       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3415         CCValAssign &VA = ArgLocs[i];
3416         SDValue Arg = OutVals[i];
3417         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3418         if (VA.getLocInfo() == CCValAssign::Indirect)
3419           return false;
3420         if (!VA.isRegLoc()) {
3421           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3422                                    MFI, MRI, TII))
3423             return false;
3424         }
3425       }
3426     }
3427
3428     // If the tailcall address may be in a register, then make sure it's
3429     // possible to register allocate for it. In 32-bit, the call address can
3430     // only target EAX, EDX, or ECX since the tail call must be scheduled after
3431     // callee-saved registers are restored. These happen to be the same
3432     // registers used to pass 'inreg' arguments so watch out for those.
3433     if (!Subtarget->is64Bit() &&
3434         ((!isa<GlobalAddressSDNode>(Callee) &&
3435           !isa<ExternalSymbolSDNode>(Callee)) ||
3436          DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3437       unsigned NumInRegs = 0;
3438       // In PIC we need an extra register to formulate the address computation
3439       // for the callee.
3440       unsigned MaxInRegs =
3441         (DAG.getTarget().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3442
3443       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3444         CCValAssign &VA = ArgLocs[i];
3445         if (!VA.isRegLoc())
3446           continue;
3447         unsigned Reg = VA.getLocReg();
3448         switch (Reg) {
3449         default: break;
3450         case X86::EAX: case X86::EDX: case X86::ECX:
3451           if (++NumInRegs == MaxInRegs)
3452             return false;
3453           break;
3454         }
3455       }
3456     }
3457   }
3458
3459   return true;
3460 }
3461
3462 FastISel *
3463 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3464                                   const TargetLibraryInfo *libInfo) const {
3465   return X86::createFastISel(funcInfo, libInfo);
3466 }
3467
3468 //===----------------------------------------------------------------------===//
3469 //                           Other Lowering Hooks
3470 //===----------------------------------------------------------------------===//
3471
3472 static bool MayFoldLoad(SDValue Op) {
3473   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3474 }
3475
3476 static bool MayFoldIntoStore(SDValue Op) {
3477   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3478 }
3479
3480 static bool isTargetShuffle(unsigned Opcode) {
3481   switch(Opcode) {
3482   default: return false;
3483   case X86ISD::BLENDI:
3484   case X86ISD::PSHUFB:
3485   case X86ISD::PSHUFD:
3486   case X86ISD::PSHUFHW:
3487   case X86ISD::PSHUFLW:
3488   case X86ISD::SHUFP:
3489   case X86ISD::PALIGNR:
3490   case X86ISD::MOVLHPS:
3491   case X86ISD::MOVLHPD:
3492   case X86ISD::MOVHLPS:
3493   case X86ISD::MOVLPS:
3494   case X86ISD::MOVLPD:
3495   case X86ISD::MOVSHDUP:
3496   case X86ISD::MOVSLDUP:
3497   case X86ISD::MOVDDUP:
3498   case X86ISD::MOVSS:
3499   case X86ISD::MOVSD:
3500   case X86ISD::UNPCKL:
3501   case X86ISD::UNPCKH:
3502   case X86ISD::VPERMILPI:
3503   case X86ISD::VPERM2X128:
3504   case X86ISD::VPERMI:
3505     return true;
3506   }
3507 }
3508
3509 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3510                                     SDValue V1, unsigned TargetMask,
3511                                     SelectionDAG &DAG) {
3512   switch(Opc) {
3513   default: llvm_unreachable("Unknown x86 shuffle node");
3514   case X86ISD::PSHUFD:
3515   case X86ISD::PSHUFHW:
3516   case X86ISD::PSHUFLW:
3517   case X86ISD::VPERMILPI:
3518   case X86ISD::VPERMI:
3519     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3520   }
3521 }
3522
3523 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3524                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
3525   switch(Opc) {
3526   default: llvm_unreachable("Unknown x86 shuffle node");
3527   case X86ISD::MOVLHPS:
3528   case X86ISD::MOVLHPD:
3529   case X86ISD::MOVHLPS:
3530   case X86ISD::MOVLPS:
3531   case X86ISD::MOVLPD:
3532   case X86ISD::MOVSS:
3533   case X86ISD::MOVSD:
3534   case X86ISD::UNPCKL:
3535   case X86ISD::UNPCKH:
3536     return DAG.getNode(Opc, dl, VT, V1, V2);
3537   }
3538 }
3539
3540 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3541   MachineFunction &MF = DAG.getMachineFunction();
3542   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3543   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3544   int ReturnAddrIndex = FuncInfo->getRAIndex();
3545
3546   if (ReturnAddrIndex == 0) {
3547     // Set up a frame object for the return address.
3548     unsigned SlotSize = RegInfo->getSlotSize();
3549     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3550                                                            -(int64_t)SlotSize,
3551                                                            false);
3552     FuncInfo->setRAIndex(ReturnAddrIndex);
3553   }
3554
3555   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3556 }
3557
3558 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3559                                        bool hasSymbolicDisplacement) {
3560   // Offset should fit into 32 bit immediate field.
3561   if (!isInt<32>(Offset))
3562     return false;
3563
3564   // If we don't have a symbolic displacement - we don't have any extra
3565   // restrictions.
3566   if (!hasSymbolicDisplacement)
3567     return true;
3568
3569   // FIXME: Some tweaks might be needed for medium code model.
3570   if (M != CodeModel::Small && M != CodeModel::Kernel)
3571     return false;
3572
3573   // For small code model we assume that latest object is 16MB before end of 31
3574   // bits boundary. We may also accept pretty large negative constants knowing
3575   // that all objects are in the positive half of address space.
3576   if (M == CodeModel::Small && Offset < 16*1024*1024)
3577     return true;
3578
3579   // For kernel code model we know that all object resist in the negative half
3580   // of 32bits address space. We may not accept negative offsets, since they may
3581   // be just off and we may accept pretty large positive ones.
3582   if (M == CodeModel::Kernel && Offset >= 0)
3583     return true;
3584
3585   return false;
3586 }
3587
3588 /// isCalleePop - Determines whether the callee is required to pop its
3589 /// own arguments. Callee pop is necessary to support tail calls.
3590 bool X86::isCalleePop(CallingConv::ID CallingConv,
3591                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3592   switch (CallingConv) {
3593   default:
3594     return false;
3595   case CallingConv::X86_StdCall:
3596   case CallingConv::X86_FastCall:
3597   case CallingConv::X86_ThisCall:
3598     return !is64Bit;
3599   case CallingConv::Fast:
3600   case CallingConv::GHC:
3601   case CallingConv::HiPE:
3602     if (IsVarArg)
3603       return false;
3604     return TailCallOpt;
3605   }
3606 }
3607
3608 /// \brief Return true if the condition is an unsigned comparison operation.
3609 static bool isX86CCUnsigned(unsigned X86CC) {
3610   switch (X86CC) {
3611   default: llvm_unreachable("Invalid integer condition!");
3612   case X86::COND_E:     return true;
3613   case X86::COND_G:     return false;
3614   case X86::COND_GE:    return false;
3615   case X86::COND_L:     return false;
3616   case X86::COND_LE:    return false;
3617   case X86::COND_NE:    return true;
3618   case X86::COND_B:     return true;
3619   case X86::COND_A:     return true;
3620   case X86::COND_BE:    return true;
3621   case X86::COND_AE:    return true;
3622   }
3623   llvm_unreachable("covered switch fell through?!");
3624 }
3625
3626 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3627 /// specific condition code, returning the condition code and the LHS/RHS of the
3628 /// comparison to make.
3629 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3630                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3631   if (!isFP) {
3632     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3633       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3634         // X > -1   -> X == 0, jump !sign.
3635         RHS = DAG.getConstant(0, RHS.getValueType());
3636         return X86::COND_NS;
3637       }
3638       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3639         // X < 0   -> X == 0, jump on sign.
3640         return X86::COND_S;
3641       }
3642       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3643         // X < 1   -> X <= 0
3644         RHS = DAG.getConstant(0, RHS.getValueType());
3645         return X86::COND_LE;
3646       }
3647     }
3648
3649     switch (SetCCOpcode) {
3650     default: llvm_unreachable("Invalid integer condition!");
3651     case ISD::SETEQ:  return X86::COND_E;
3652     case ISD::SETGT:  return X86::COND_G;
3653     case ISD::SETGE:  return X86::COND_GE;
3654     case ISD::SETLT:  return X86::COND_L;
3655     case ISD::SETLE:  return X86::COND_LE;
3656     case ISD::SETNE:  return X86::COND_NE;
3657     case ISD::SETULT: return X86::COND_B;
3658     case ISD::SETUGT: return X86::COND_A;
3659     case ISD::SETULE: return X86::COND_BE;
3660     case ISD::SETUGE: return X86::COND_AE;
3661     }
3662   }
3663
3664   // First determine if it is required or is profitable to flip the operands.
3665
3666   // If LHS is a foldable load, but RHS is not, flip the condition.
3667   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3668       !ISD::isNON_EXTLoad(RHS.getNode())) {
3669     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3670     std::swap(LHS, RHS);
3671   }
3672
3673   switch (SetCCOpcode) {
3674   default: break;
3675   case ISD::SETOLT:
3676   case ISD::SETOLE:
3677   case ISD::SETUGT:
3678   case ISD::SETUGE:
3679     std::swap(LHS, RHS);
3680     break;
3681   }
3682
3683   // On a floating point condition, the flags are set as follows:
3684   // ZF  PF  CF   op
3685   //  0 | 0 | 0 | X > Y
3686   //  0 | 0 | 1 | X < Y
3687   //  1 | 0 | 0 | X == Y
3688   //  1 | 1 | 1 | unordered
3689   switch (SetCCOpcode) {
3690   default: llvm_unreachable("Condcode should be pre-legalized away");
3691   case ISD::SETUEQ:
3692   case ISD::SETEQ:   return X86::COND_E;
3693   case ISD::SETOLT:              // flipped
3694   case ISD::SETOGT:
3695   case ISD::SETGT:   return X86::COND_A;
3696   case ISD::SETOLE:              // flipped
3697   case ISD::SETOGE:
3698   case ISD::SETGE:   return X86::COND_AE;
3699   case ISD::SETUGT:              // flipped
3700   case ISD::SETULT:
3701   case ISD::SETLT:   return X86::COND_B;
3702   case ISD::SETUGE:              // flipped
3703   case ISD::SETULE:
3704   case ISD::SETLE:   return X86::COND_BE;
3705   case ISD::SETONE:
3706   case ISD::SETNE:   return X86::COND_NE;
3707   case ISD::SETUO:   return X86::COND_P;
3708   case ISD::SETO:    return X86::COND_NP;
3709   case ISD::SETOEQ:
3710   case ISD::SETUNE:  return X86::COND_INVALID;
3711   }
3712 }
3713
3714 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3715 /// code. Current x86 isa includes the following FP cmov instructions:
3716 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3717 static bool hasFPCMov(unsigned X86CC) {
3718   switch (X86CC) {
3719   default:
3720     return false;
3721   case X86::COND_B:
3722   case X86::COND_BE:
3723   case X86::COND_E:
3724   case X86::COND_P:
3725   case X86::COND_A:
3726   case X86::COND_AE:
3727   case X86::COND_NE:
3728   case X86::COND_NP:
3729     return true;
3730   }
3731 }
3732
3733 /// isFPImmLegal - Returns true if the target can instruction select the
3734 /// specified FP immediate natively. If false, the legalizer will
3735 /// materialize the FP immediate as a load from a constant pool.
3736 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3737   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3738     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3739       return true;
3740   }
3741   return false;
3742 }
3743
3744 bool X86TargetLowering::shouldReduceLoadWidth(SDNode *Load,
3745                                               ISD::LoadExtType ExtTy,
3746                                               EVT NewVT) const {
3747   // "ELF Handling for Thread-Local Storage" specifies that R_X86_64_GOTTPOFF
3748   // relocation target a movq or addq instruction: don't let the load shrink.
3749   SDValue BasePtr = cast<LoadSDNode>(Load)->getBasePtr();
3750   if (BasePtr.getOpcode() == X86ISD::WrapperRIP)
3751     if (const auto *GA = dyn_cast<GlobalAddressSDNode>(BasePtr.getOperand(0)))
3752       return GA->getTargetFlags() != X86II::MO_GOTTPOFF;
3753   return true;
3754 }
3755
3756 /// \brief Returns true if it is beneficial to convert a load of a constant
3757 /// to just the constant itself.
3758 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
3759                                                           Type *Ty) const {
3760   assert(Ty->isIntegerTy());
3761
3762   unsigned BitSize = Ty->getPrimitiveSizeInBits();
3763   if (BitSize == 0 || BitSize > 64)
3764     return false;
3765   return true;
3766 }
3767
3768 bool X86TargetLowering::isExtractSubvectorCheap(EVT ResVT,
3769                                                 unsigned Index) const {
3770   if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
3771     return false;
3772
3773   return (Index == 0 || Index == ResVT.getVectorNumElements());
3774 }
3775
3776 bool X86TargetLowering::isCheapToSpeculateCttz() const {
3777   // Speculate cttz only if we can directly use TZCNT.
3778   return Subtarget->hasBMI();
3779 }
3780
3781 bool X86TargetLowering::isCheapToSpeculateCtlz() const {
3782   // Speculate ctlz only if we can directly use LZCNT.
3783   return Subtarget->hasLZCNT();
3784 }
3785
3786 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3787 /// the specified range (L, H].
3788 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3789   return (Val < 0) || (Val >= Low && Val < Hi);
3790 }
3791
3792 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3793 /// specified value.
3794 static bool isUndefOrEqual(int Val, int CmpVal) {
3795   return (Val < 0 || Val == CmpVal);
3796 }
3797
3798 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3799 /// from position Pos and ending in Pos+Size, falls within the specified
3800 /// sequential range (Low, Low+Size]. or is undef.
3801 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3802                                        unsigned Pos, unsigned Size, int Low) {
3803   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3804     if (!isUndefOrEqual(Mask[i], Low))
3805       return false;
3806   return true;
3807 }
3808
3809 /// isVEXTRACTIndex - Return true if the specified
3810 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
3811 /// suitable for instruction that extract 128 or 256 bit vectors
3812 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
3813   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
3814   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3815     return false;
3816
3817   // The index should be aligned on a vecWidth-bit boundary.
3818   uint64_t Index =
3819     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3820
3821   MVT VT = N->getSimpleValueType(0);
3822   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
3823   bool Result = (Index * ElSize) % vecWidth == 0;
3824
3825   return Result;
3826 }
3827
3828 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
3829 /// operand specifies a subvector insert that is suitable for input to
3830 /// insertion of 128 or 256-bit subvectors
3831 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
3832   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
3833   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3834     return false;
3835   // The index should be aligned on a vecWidth-bit boundary.
3836   uint64_t Index =
3837     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3838
3839   MVT VT = N->getSimpleValueType(0);
3840   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
3841   bool Result = (Index * ElSize) % vecWidth == 0;
3842
3843   return Result;
3844 }
3845
3846 bool X86::isVINSERT128Index(SDNode *N) {
3847   return isVINSERTIndex(N, 128);
3848 }
3849
3850 bool X86::isVINSERT256Index(SDNode *N) {
3851   return isVINSERTIndex(N, 256);
3852 }
3853
3854 bool X86::isVEXTRACT128Index(SDNode *N) {
3855   return isVEXTRACTIndex(N, 128);
3856 }
3857
3858 bool X86::isVEXTRACT256Index(SDNode *N) {
3859   return isVEXTRACTIndex(N, 256);
3860 }
3861
3862 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
3863   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
3864   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3865     llvm_unreachable("Illegal extract subvector for VEXTRACT");
3866
3867   uint64_t Index =
3868     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3869
3870   MVT VecVT = N->getOperand(0).getSimpleValueType();
3871   MVT ElVT = VecVT.getVectorElementType();
3872
3873   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
3874   return Index / NumElemsPerChunk;
3875 }
3876
3877 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
3878   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
3879   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3880     llvm_unreachable("Illegal insert subvector for VINSERT");
3881
3882   uint64_t Index =
3883     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3884
3885   MVT VecVT = N->getSimpleValueType(0);
3886   MVT ElVT = VecVT.getVectorElementType();
3887
3888   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
3889   return Index / NumElemsPerChunk;
3890 }
3891
3892 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
3893 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
3894 /// and VINSERTI128 instructions.
3895 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
3896   return getExtractVEXTRACTImmediate(N, 128);
3897 }
3898
3899 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
3900 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
3901 /// and VINSERTI64x4 instructions.
3902 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
3903   return getExtractVEXTRACTImmediate(N, 256);
3904 }
3905
3906 /// getInsertVINSERT128Immediate - Return the appropriate immediate
3907 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
3908 /// and VINSERTI128 instructions.
3909 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
3910   return getInsertVINSERTImmediate(N, 128);
3911 }
3912
3913 /// getInsertVINSERT256Immediate - Return the appropriate immediate
3914 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
3915 /// and VINSERTI64x4 instructions.
3916 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
3917   return getInsertVINSERTImmediate(N, 256);
3918 }
3919
3920 /// isZero - Returns true if Elt is a constant integer zero
3921 static bool isZero(SDValue V) {
3922   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
3923   return C && C->isNullValue();
3924 }
3925
3926 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
3927 /// constant +0.0.
3928 bool X86::isZeroNode(SDValue Elt) {
3929   if (isZero(Elt))
3930     return true;
3931   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
3932     return CFP->getValueAPF().isPosZero();
3933   return false;
3934 }
3935
3936 /// getZeroVector - Returns a vector of specified type with all zero elements.
3937 ///
3938 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
3939                              SelectionDAG &DAG, SDLoc dl) {
3940   assert(VT.isVector() && "Expected a vector type");
3941
3942   // Always build SSE zero vectors as <4 x i32> bitcasted
3943   // to their dest type. This ensures they get CSE'd.
3944   SDValue Vec;
3945   if (VT.is128BitVector()) {  // SSE
3946     if (Subtarget->hasSSE2()) {  // SSE2
3947       SDValue Cst = DAG.getConstant(0, MVT::i32);
3948       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3949     } else { // SSE1
3950       SDValue Cst = DAG.getConstantFP(+0.0, MVT::f32);
3951       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
3952     }
3953   } else if (VT.is256BitVector()) { // AVX
3954     if (Subtarget->hasInt256()) { // AVX2
3955       SDValue Cst = DAG.getConstant(0, MVT::i32);
3956       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
3957       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
3958     } else {
3959       // 256-bit logic and arithmetic instructions in AVX are all
3960       // floating-point, no support for integer ops. Emit fp zeroed vectors.
3961       SDValue Cst = DAG.getConstantFP(+0.0, MVT::f32);
3962       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
3963       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
3964     }
3965   } else if (VT.is512BitVector()) { // AVX-512
3966       SDValue Cst = DAG.getConstant(0, MVT::i32);
3967       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
3968                         Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
3969       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
3970   } else if (VT.getScalarType() == MVT::i1) {
3971
3972     assert((Subtarget->hasBWI() || VT.getVectorNumElements() <= 16)
3973             && "Unexpected vector type");
3974     assert((Subtarget->hasVLX() || VT.getVectorNumElements() >= 8)
3975             && "Unexpected vector type");
3976     SDValue Cst = DAG.getConstant(0, MVT::i1);
3977     SmallVector<SDValue, 64> Ops(VT.getVectorNumElements(), Cst);
3978     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
3979   } else
3980     llvm_unreachable("Unexpected vector type");
3981
3982   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
3983 }
3984
3985 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
3986                                 SelectionDAG &DAG, SDLoc dl,
3987                                 unsigned vectorWidth) {
3988   assert((vectorWidth == 128 || vectorWidth == 256) &&
3989          "Unsupported vector width");
3990   EVT VT = Vec.getValueType();
3991   EVT ElVT = VT.getVectorElementType();
3992   unsigned Factor = VT.getSizeInBits()/vectorWidth;
3993   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
3994                                   VT.getVectorNumElements()/Factor);
3995
3996   // Extract from UNDEF is UNDEF.
3997   if (Vec.getOpcode() == ISD::UNDEF)
3998     return DAG.getUNDEF(ResultVT);
3999
4000   // Extract the relevant vectorWidth bits.  Generate an EXTRACT_SUBVECTOR
4001   unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
4002
4003   // This is the index of the first element of the vectorWidth-bit chunk
4004   // we want.
4005   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / vectorWidth)
4006                                * ElemsPerChunk);
4007
4008   // If the input is a buildvector just emit a smaller one.
4009   if (Vec.getOpcode() == ISD::BUILD_VECTOR)
4010     return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
4011                        makeArrayRef(Vec->op_begin() + NormalizedIdxVal,
4012                                     ElemsPerChunk));
4013
4014   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
4015   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec, VecIdx);
4016 }
4017
4018 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
4019 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
4020 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
4021 /// instructions or a simple subregister reference. Idx is an index in the
4022 /// 128 bits we want.  It need not be aligned to a 128-bit boundary.  That makes
4023 /// lowering EXTRACT_VECTOR_ELT operations easier.
4024 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
4025                                    SelectionDAG &DAG, SDLoc dl) {
4026   assert((Vec.getValueType().is256BitVector() ||
4027           Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
4028   return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
4029 }
4030
4031 /// Generate a DAG to grab 256-bits from a 512-bit vector.
4032 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
4033                                    SelectionDAG &DAG, SDLoc dl) {
4034   assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
4035   return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
4036 }
4037
4038 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
4039                                unsigned IdxVal, SelectionDAG &DAG,
4040                                SDLoc dl, unsigned vectorWidth) {
4041   assert((vectorWidth == 128 || vectorWidth == 256) &&
4042          "Unsupported vector width");
4043   // Inserting UNDEF is Result
4044   if (Vec.getOpcode() == ISD::UNDEF)
4045     return Result;
4046   EVT VT = Vec.getValueType();
4047   EVT ElVT = VT.getVectorElementType();
4048   EVT ResultVT = Result.getValueType();
4049
4050   // Insert the relevant vectorWidth bits.
4051   unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
4052
4053   // This is the index of the first element of the vectorWidth-bit chunk
4054   // we want.
4055   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/vectorWidth)
4056                                * ElemsPerChunk);
4057
4058   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
4059   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec, VecIdx);
4060 }
4061
4062 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
4063 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
4064 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
4065 /// simple superregister reference.  Idx is an index in the 128 bits
4066 /// we want.  It need not be aligned to a 128-bit boundary.  That makes
4067 /// lowering INSERT_VECTOR_ELT operations easier.
4068 static SDValue Insert128BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4069                                   SelectionDAG &DAG, SDLoc dl) {
4070   assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
4071
4072   // For insertion into the zero index (low half) of a 256-bit vector, it is
4073   // more efficient to generate a blend with immediate instead of an insert*128.
4074   // We are still creating an INSERT_SUBVECTOR below with an undef node to
4075   // extend the subvector to the size of the result vector. Make sure that
4076   // we are not recursing on that node by checking for undef here.
4077   if (IdxVal == 0 && Result.getValueType().is256BitVector() &&
4078       Result.getOpcode() != ISD::UNDEF) {
4079     EVT ResultVT = Result.getValueType();
4080     SDValue ZeroIndex = DAG.getIntPtrConstant(0);
4081     SDValue Undef = DAG.getUNDEF(ResultVT);
4082     SDValue Vec256 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Undef,
4083                                  Vec, ZeroIndex);
4084
4085     // The blend instruction, and therefore its mask, depend on the data type.
4086     MVT ScalarType = ResultVT.getScalarType().getSimpleVT();
4087     if (ScalarType.isFloatingPoint()) {
4088       // Choose either vblendps (float) or vblendpd (double).
4089       unsigned ScalarSize = ScalarType.getSizeInBits();
4090       assert((ScalarSize == 64 || ScalarSize == 32) && "Unknown float type");
4091       unsigned MaskVal = (ScalarSize == 64) ? 0x03 : 0x0f;
4092       SDValue Mask = DAG.getConstant(MaskVal, MVT::i8);
4093       return DAG.getNode(X86ISD::BLENDI, dl, ResultVT, Result, Vec256, Mask);
4094     }
4095
4096     const X86Subtarget &Subtarget =
4097     static_cast<const X86Subtarget &>(DAG.getSubtarget());
4098
4099     // AVX2 is needed for 256-bit integer blend support.
4100     // Integers must be cast to 32-bit because there is only vpblendd;
4101     // vpblendw can't be used for this because it has a handicapped mask.
4102
4103     // If we don't have AVX2, then cast to float. Using a wrong domain blend
4104     // is still more efficient than using the wrong domain vinsertf128 that
4105     // will be created by InsertSubVector().
4106     MVT CastVT = Subtarget.hasAVX2() ? MVT::v8i32 : MVT::v8f32;
4107
4108     SDValue Mask = DAG.getConstant(0x0f, MVT::i8);
4109     Vec256 = DAG.getNode(ISD::BITCAST, dl, CastVT, Vec256);
4110     Vec256 = DAG.getNode(X86ISD::BLENDI, dl, CastVT, Result, Vec256, Mask);
4111     return DAG.getNode(ISD::BITCAST, dl, ResultVT, Vec256);
4112   }
4113
4114   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
4115 }
4116
4117 static SDValue Insert256BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4118                                   SelectionDAG &DAG, SDLoc dl) {
4119   assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
4120   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
4121 }
4122
4123 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
4124 /// instructions. This is used because creating CONCAT_VECTOR nodes of
4125 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
4126 /// large BUILD_VECTORS.
4127 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
4128                                    unsigned NumElems, SelectionDAG &DAG,
4129                                    SDLoc dl) {
4130   SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4131   return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
4132 }
4133
4134 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
4135                                    unsigned NumElems, SelectionDAG &DAG,
4136                                    SDLoc dl) {
4137   SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4138   return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
4139 }
4140
4141 /// getOnesVector - Returns a vector of specified type with all bits set.
4142 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4143 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4144 /// Then bitcast to their original type, ensuring they get CSE'd.
4145 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4146                              SDLoc dl) {
4147   assert(VT.isVector() && "Expected a vector type");
4148
4149   SDValue Cst = DAG.getConstant(~0U, MVT::i32);
4150   SDValue Vec;
4151   if (VT.is256BitVector()) {
4152     if (HasInt256) { // AVX2
4153       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4154       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4155     } else { // AVX
4156       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4157       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4158     }
4159   } else if (VT.is128BitVector()) {
4160     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4161   } else
4162     llvm_unreachable("Unexpected vector type");
4163
4164   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4165 }
4166
4167 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4168 /// operation of specified width.
4169 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4170                        SDValue V2) {
4171   unsigned NumElems = VT.getVectorNumElements();
4172   SmallVector<int, 8> Mask;
4173   Mask.push_back(NumElems);
4174   for (unsigned i = 1; i != NumElems; ++i)
4175     Mask.push_back(i);
4176   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4177 }
4178
4179 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4180 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4181                           SDValue V2) {
4182   unsigned NumElems = VT.getVectorNumElements();
4183   SmallVector<int, 8> Mask;
4184   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4185     Mask.push_back(i);
4186     Mask.push_back(i + NumElems);
4187   }
4188   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4189 }
4190
4191 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4192 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4193                           SDValue V2) {
4194   unsigned NumElems = VT.getVectorNumElements();
4195   SmallVector<int, 8> Mask;
4196   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4197     Mask.push_back(i + Half);
4198     Mask.push_back(i + NumElems + Half);
4199   }
4200   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4201 }
4202
4203 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4204 /// vector of zero or undef vector.  This produces a shuffle where the low
4205 /// element of V2 is swizzled into the zero/undef vector, landing at element
4206 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
4207 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4208                                            bool IsZero,
4209                                            const X86Subtarget *Subtarget,
4210                                            SelectionDAG &DAG) {
4211   MVT VT = V2.getSimpleValueType();
4212   SDValue V1 = IsZero
4213     ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
4214   unsigned NumElems = VT.getVectorNumElements();
4215   SmallVector<int, 16> MaskVec;
4216   for (unsigned i = 0; i != NumElems; ++i)
4217     // If this is the insertion idx, put the low elt of V2 here.
4218     MaskVec.push_back(i == Idx ? NumElems : i);
4219   return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
4220 }
4221
4222 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
4223 /// target specific opcode. Returns true if the Mask could be calculated. Sets
4224 /// IsUnary to true if only uses one source. Note that this will set IsUnary for
4225 /// shuffles which use a single input multiple times, and in those cases it will
4226 /// adjust the mask to only have indices within that single input.
4227 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4228                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
4229   unsigned NumElems = VT.getVectorNumElements();
4230   SDValue ImmN;
4231
4232   IsUnary = false;
4233   bool IsFakeUnary = false;
4234   switch(N->getOpcode()) {
4235   case X86ISD::BLENDI:
4236     ImmN = N->getOperand(N->getNumOperands()-1);
4237     DecodeBLENDMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4238     break;
4239   case X86ISD::SHUFP:
4240     ImmN = N->getOperand(N->getNumOperands()-1);
4241     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4242     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4243     break;
4244   case X86ISD::UNPCKH:
4245     DecodeUNPCKHMask(VT, Mask);
4246     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4247     break;
4248   case X86ISD::UNPCKL:
4249     DecodeUNPCKLMask(VT, Mask);
4250     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4251     break;
4252   case X86ISD::MOVHLPS:
4253     DecodeMOVHLPSMask(NumElems, Mask);
4254     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4255     break;
4256   case X86ISD::MOVLHPS:
4257     DecodeMOVLHPSMask(NumElems, Mask);
4258     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4259     break;
4260   case X86ISD::PALIGNR:
4261     ImmN = N->getOperand(N->getNumOperands()-1);
4262     DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4263     break;
4264   case X86ISD::PSHUFD:
4265   case X86ISD::VPERMILPI:
4266     ImmN = N->getOperand(N->getNumOperands()-1);
4267     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4268     IsUnary = true;
4269     break;
4270   case X86ISD::PSHUFHW:
4271     ImmN = N->getOperand(N->getNumOperands()-1);
4272     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4273     IsUnary = true;
4274     break;
4275   case X86ISD::PSHUFLW:
4276     ImmN = N->getOperand(N->getNumOperands()-1);
4277     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4278     IsUnary = true;
4279     break;
4280   case X86ISD::PSHUFB: {
4281     IsUnary = true;
4282     SDValue MaskNode = N->getOperand(1);
4283     while (MaskNode->getOpcode() == ISD::BITCAST)
4284       MaskNode = MaskNode->getOperand(0);
4285
4286     if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
4287       // If we have a build-vector, then things are easy.
4288       EVT VT = MaskNode.getValueType();
4289       assert(VT.isVector() &&
4290              "Can't produce a non-vector with a build_vector!");
4291       if (!VT.isInteger())
4292         return false;
4293
4294       int NumBytesPerElement = VT.getVectorElementType().getSizeInBits() / 8;
4295
4296       SmallVector<uint64_t, 32> RawMask;
4297       for (int i = 0, e = MaskNode->getNumOperands(); i < e; ++i) {
4298         SDValue Op = MaskNode->getOperand(i);
4299         if (Op->getOpcode() == ISD::UNDEF) {
4300           RawMask.push_back((uint64_t)SM_SentinelUndef);
4301           continue;
4302         }
4303         auto *CN = dyn_cast<ConstantSDNode>(Op.getNode());
4304         if (!CN)
4305           return false;
4306         APInt MaskElement = CN->getAPIntValue();
4307
4308         // We now have to decode the element which could be any integer size and
4309         // extract each byte of it.
4310         for (int j = 0; j < NumBytesPerElement; ++j) {
4311           // Note that this is x86 and so always little endian: the low byte is
4312           // the first byte of the mask.
4313           RawMask.push_back(MaskElement.getLoBits(8).getZExtValue());
4314           MaskElement = MaskElement.lshr(8);
4315         }
4316       }
4317       DecodePSHUFBMask(RawMask, Mask);
4318       break;
4319     }
4320
4321     auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
4322     if (!MaskLoad)
4323       return false;
4324
4325     SDValue Ptr = MaskLoad->getBasePtr();
4326     if (Ptr->getOpcode() == X86ISD::Wrapper)
4327       Ptr = Ptr->getOperand(0);
4328
4329     auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
4330     if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
4331       return false;
4332
4333     if (auto *C = dyn_cast<Constant>(MaskCP->getConstVal())) {
4334       DecodePSHUFBMask(C, Mask);
4335       if (Mask.empty())
4336         return false;
4337       break;
4338     }
4339
4340     return false;
4341   }
4342   case X86ISD::VPERMI:
4343     ImmN = N->getOperand(N->getNumOperands()-1);
4344     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4345     IsUnary = true;
4346     break;
4347   case X86ISD::MOVSS:
4348   case X86ISD::MOVSD:
4349     DecodeScalarMoveMask(VT, /* IsLoad */ false, Mask);
4350     break;
4351   case X86ISD::VPERM2X128:
4352     ImmN = N->getOperand(N->getNumOperands()-1);
4353     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4354     if (Mask.empty()) return false;
4355     break;
4356   case X86ISD::MOVSLDUP:
4357     DecodeMOVSLDUPMask(VT, Mask);
4358     IsUnary = true;
4359     break;
4360   case X86ISD::MOVSHDUP:
4361     DecodeMOVSHDUPMask(VT, Mask);
4362     IsUnary = true;
4363     break;
4364   case X86ISD::MOVDDUP:
4365     DecodeMOVDDUPMask(VT, Mask);
4366     IsUnary = true;
4367     break;
4368   case X86ISD::MOVLHPD:
4369   case X86ISD::MOVLPD:
4370   case X86ISD::MOVLPS:
4371     // Not yet implemented
4372     return false;
4373   default: llvm_unreachable("unknown target shuffle node");
4374   }
4375
4376   // If we have a fake unary shuffle, the shuffle mask is spread across two
4377   // inputs that are actually the same node. Re-map the mask to always point
4378   // into the first input.
4379   if (IsFakeUnary)
4380     for (int &M : Mask)
4381       if (M >= (int)Mask.size())
4382         M -= Mask.size();
4383
4384   return true;
4385 }
4386
4387 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4388 /// element of the result of the vector shuffle.
4389 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4390                                    unsigned Depth) {
4391   if (Depth == 6)
4392     return SDValue();  // Limit search depth.
4393
4394   SDValue V = SDValue(N, 0);
4395   EVT VT = V.getValueType();
4396   unsigned Opcode = V.getOpcode();
4397
4398   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4399   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4400     int Elt = SV->getMaskElt(Index);
4401
4402     if (Elt < 0)
4403       return DAG.getUNDEF(VT.getVectorElementType());
4404
4405     unsigned NumElems = VT.getVectorNumElements();
4406     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4407                                          : SV->getOperand(1);
4408     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4409   }
4410
4411   // Recurse into target specific vector shuffles to find scalars.
4412   if (isTargetShuffle(Opcode)) {
4413     MVT ShufVT = V.getSimpleValueType();
4414     unsigned NumElems = ShufVT.getVectorNumElements();
4415     SmallVector<int, 16> ShuffleMask;
4416     bool IsUnary;
4417
4418     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4419       return SDValue();
4420
4421     int Elt = ShuffleMask[Index];
4422     if (Elt < 0)
4423       return DAG.getUNDEF(ShufVT.getVectorElementType());
4424
4425     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4426                                          : N->getOperand(1);
4427     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4428                                Depth+1);
4429   }
4430
4431   // Actual nodes that may contain scalar elements
4432   if (Opcode == ISD::BITCAST) {
4433     V = V.getOperand(0);
4434     EVT SrcVT = V.getValueType();
4435     unsigned NumElems = VT.getVectorNumElements();
4436
4437     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4438       return SDValue();
4439   }
4440
4441   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4442     return (Index == 0) ? V.getOperand(0)
4443                         : DAG.getUNDEF(VT.getVectorElementType());
4444
4445   if (V.getOpcode() == ISD::BUILD_VECTOR)
4446     return V.getOperand(Index);
4447
4448   return SDValue();
4449 }
4450
4451 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4452 ///
4453 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4454                                        unsigned NumNonZero, unsigned NumZero,
4455                                        SelectionDAG &DAG,
4456                                        const X86Subtarget* Subtarget,
4457                                        const TargetLowering &TLI) {
4458   if (NumNonZero > 8)
4459     return SDValue();
4460
4461   SDLoc dl(Op);
4462   SDValue V;
4463   bool First = true;
4464
4465   // SSE4.1 - use PINSRB to insert each byte directly.
4466   if (Subtarget->hasSSE41()) {
4467     for (unsigned i = 0; i < 16; ++i) {
4468       bool isNonZero = (NonZeros & (1 << i)) != 0;
4469       if (isNonZero) {
4470         if (First) {
4471           if (NumZero)
4472             V = getZeroVector(MVT::v16i8, Subtarget, DAG, dl);
4473           else
4474             V = DAG.getUNDEF(MVT::v16i8);
4475           First = false;
4476         }
4477         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4478                         MVT::v16i8, V, Op.getOperand(i),
4479                         DAG.getIntPtrConstant(i));
4480       }
4481     }
4482
4483     return V;
4484   }
4485
4486   // Pre-SSE4.1 - merge byte pairs and insert with PINSRW.
4487   for (unsigned i = 0; i < 16; ++i) {
4488     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4489     if (ThisIsNonZero && First) {
4490       if (NumZero)
4491         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4492       else
4493         V = DAG.getUNDEF(MVT::v8i16);
4494       First = false;
4495     }
4496
4497     if ((i & 1) != 0) {
4498       SDValue ThisElt, LastElt;
4499       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4500       if (LastIsNonZero) {
4501         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4502                               MVT::i16, Op.getOperand(i-1));
4503       }
4504       if (ThisIsNonZero) {
4505         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4506         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4507                               ThisElt, DAG.getConstant(8, MVT::i8));
4508         if (LastIsNonZero)
4509           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4510       } else
4511         ThisElt = LastElt;
4512
4513       if (ThisElt.getNode())
4514         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4515                         DAG.getIntPtrConstant(i/2));
4516     }
4517   }
4518
4519   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4520 }
4521
4522 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4523 ///
4524 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4525                                      unsigned NumNonZero, unsigned NumZero,
4526                                      SelectionDAG &DAG,
4527                                      const X86Subtarget* Subtarget,
4528                                      const TargetLowering &TLI) {
4529   if (NumNonZero > 4)
4530     return SDValue();
4531
4532   SDLoc dl(Op);
4533   SDValue V;
4534   bool First = true;
4535   for (unsigned i = 0; i < 8; ++i) {
4536     bool isNonZero = (NonZeros & (1 << i)) != 0;
4537     if (isNonZero) {
4538       if (First) {
4539         if (NumZero)
4540           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4541         else
4542           V = DAG.getUNDEF(MVT::v8i16);
4543         First = false;
4544       }
4545       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4546                       MVT::v8i16, V, Op.getOperand(i),
4547                       DAG.getIntPtrConstant(i));
4548     }
4549   }
4550
4551   return V;
4552 }
4553
4554 /// LowerBuildVectorv4x32 - Custom lower build_vector of v4i32 or v4f32.
4555 static SDValue LowerBuildVectorv4x32(SDValue Op, SelectionDAG &DAG,
4556                                      const X86Subtarget *Subtarget,
4557                                      const TargetLowering &TLI) {
4558   // Find all zeroable elements.
4559   std::bitset<4> Zeroable;
4560   for (int i=0; i < 4; ++i) {
4561     SDValue Elt = Op->getOperand(i);
4562     Zeroable[i] = (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt));
4563   }
4564   assert(Zeroable.size() - Zeroable.count() > 1 &&
4565          "We expect at least two non-zero elements!");
4566
4567   // We only know how to deal with build_vector nodes where elements are either
4568   // zeroable or extract_vector_elt with constant index.
4569   SDValue FirstNonZero;
4570   unsigned FirstNonZeroIdx;
4571   for (unsigned i=0; i < 4; ++i) {
4572     if (Zeroable[i])
4573       continue;
4574     SDValue Elt = Op->getOperand(i);
4575     if (Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4576         !isa<ConstantSDNode>(Elt.getOperand(1)))
4577       return SDValue();
4578     // Make sure that this node is extracting from a 128-bit vector.
4579     MVT VT = Elt.getOperand(0).getSimpleValueType();
4580     if (!VT.is128BitVector())
4581       return SDValue();
4582     if (!FirstNonZero.getNode()) {
4583       FirstNonZero = Elt;
4584       FirstNonZeroIdx = i;
4585     }
4586   }
4587
4588   assert(FirstNonZero.getNode() && "Unexpected build vector of all zeros!");
4589   SDValue V1 = FirstNonZero.getOperand(0);
4590   MVT VT = V1.getSimpleValueType();
4591
4592   // See if this build_vector can be lowered as a blend with zero.
4593   SDValue Elt;
4594   unsigned EltMaskIdx, EltIdx;
4595   int Mask[4];
4596   for (EltIdx = 0; EltIdx < 4; ++EltIdx) {
4597     if (Zeroable[EltIdx]) {
4598       // The zero vector will be on the right hand side.
4599       Mask[EltIdx] = EltIdx+4;
4600       continue;
4601     }
4602
4603     Elt = Op->getOperand(EltIdx);
4604     // By construction, Elt is a EXTRACT_VECTOR_ELT with constant index.
4605     EltMaskIdx = cast<ConstantSDNode>(Elt.getOperand(1))->getZExtValue();
4606     if (Elt.getOperand(0) != V1 || EltMaskIdx != EltIdx)
4607       break;
4608     Mask[EltIdx] = EltIdx;
4609   }
4610
4611   if (EltIdx == 4) {
4612     // Let the shuffle legalizer deal with blend operations.
4613     SDValue VZero = getZeroVector(VT, Subtarget, DAG, SDLoc(Op));
4614     if (V1.getSimpleValueType() != VT)
4615       V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), VT, V1);
4616     return DAG.getVectorShuffle(VT, SDLoc(V1), V1, VZero, &Mask[0]);
4617   }
4618
4619   // See if we can lower this build_vector to a INSERTPS.
4620   if (!Subtarget->hasSSE41())
4621     return SDValue();
4622
4623   SDValue V2 = Elt.getOperand(0);
4624   if (Elt == FirstNonZero && EltIdx == FirstNonZeroIdx)
4625     V1 = SDValue();
4626
4627   bool CanFold = true;
4628   for (unsigned i = EltIdx + 1; i < 4 && CanFold; ++i) {
4629     if (Zeroable[i])
4630       continue;
4631
4632     SDValue Current = Op->getOperand(i);
4633     SDValue SrcVector = Current->getOperand(0);
4634     if (!V1.getNode())
4635       V1 = SrcVector;
4636     CanFold = SrcVector == V1 &&
4637       cast<ConstantSDNode>(Current.getOperand(1))->getZExtValue() == i;
4638   }
4639
4640   if (!CanFold)
4641     return SDValue();
4642
4643   assert(V1.getNode() && "Expected at least two non-zero elements!");
4644   if (V1.getSimpleValueType() != MVT::v4f32)
4645     V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), MVT::v4f32, V1);
4646   if (V2.getSimpleValueType() != MVT::v4f32)
4647     V2 = DAG.getNode(ISD::BITCAST, SDLoc(V2), MVT::v4f32, V2);
4648
4649   // Ok, we can emit an INSERTPS instruction.
4650   unsigned ZMask = Zeroable.to_ulong();
4651
4652   unsigned InsertPSMask = EltMaskIdx << 6 | EltIdx << 4 | ZMask;
4653   assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
4654   SDValue Result = DAG.getNode(X86ISD::INSERTPS, SDLoc(Op), MVT::v4f32, V1, V2,
4655                                DAG.getIntPtrConstant(InsertPSMask));
4656   return DAG.getNode(ISD::BITCAST, SDLoc(Op), VT, Result);
4657 }
4658
4659 /// Return a vector logical shift node.
4660 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4661                          unsigned NumBits, SelectionDAG &DAG,
4662                          const TargetLowering &TLI, SDLoc dl) {
4663   assert(VT.is128BitVector() && "Unknown type for VShift");
4664   MVT ShVT = MVT::v2i64;
4665   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
4666   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4667   MVT ScalarShiftTy = TLI.getScalarShiftAmountTy(SrcOp.getValueType());
4668   assert(NumBits % 8 == 0 && "Only support byte sized shifts");
4669   SDValue ShiftVal = DAG.getConstant(NumBits/8, ScalarShiftTy);
4670   return DAG.getNode(ISD::BITCAST, dl, VT,
4671                      DAG.getNode(Opc, dl, ShVT, SrcOp, ShiftVal));
4672 }
4673
4674 static SDValue
4675 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
4676
4677   // Check if the scalar load can be widened into a vector load. And if
4678   // the address is "base + cst" see if the cst can be "absorbed" into
4679   // the shuffle mask.
4680   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4681     SDValue Ptr = LD->getBasePtr();
4682     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4683       return SDValue();
4684     EVT PVT = LD->getValueType(0);
4685     if (PVT != MVT::i32 && PVT != MVT::f32)
4686       return SDValue();
4687
4688     int FI = -1;
4689     int64_t Offset = 0;
4690     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4691       FI = FINode->getIndex();
4692       Offset = 0;
4693     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4694                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4695       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4696       Offset = Ptr.getConstantOperandVal(1);
4697       Ptr = Ptr.getOperand(0);
4698     } else {
4699       return SDValue();
4700     }
4701
4702     // FIXME: 256-bit vector instructions don't require a strict alignment,
4703     // improve this code to support it better.
4704     unsigned RequiredAlign = VT.getSizeInBits()/8;
4705     SDValue Chain = LD->getChain();
4706     // Make sure the stack object alignment is at least 16 or 32.
4707     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4708     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
4709       if (MFI->isFixedObjectIndex(FI)) {
4710         // Can't change the alignment. FIXME: It's possible to compute
4711         // the exact stack offset and reference FI + adjust offset instead.
4712         // If someone *really* cares about this. That's the way to implement it.
4713         return SDValue();
4714       } else {
4715         MFI->setObjectAlignment(FI, RequiredAlign);
4716       }
4717     }
4718
4719     // (Offset % 16 or 32) must be multiple of 4. Then address is then
4720     // Ptr + (Offset & ~15).
4721     if (Offset < 0)
4722       return SDValue();
4723     if ((Offset % RequiredAlign) & 3)
4724       return SDValue();
4725     int64_t StartOffset = Offset & ~(RequiredAlign-1);
4726     if (StartOffset)
4727       Ptr = DAG.getNode(ISD::ADD, SDLoc(Ptr), Ptr.getValueType(),
4728                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
4729
4730     int EltNo = (Offset - StartOffset) >> 2;
4731     unsigned NumElems = VT.getVectorNumElements();
4732
4733     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
4734     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
4735                              LD->getPointerInfo().getWithOffset(StartOffset),
4736                              false, false, false, 0);
4737
4738     SmallVector<int, 8> Mask(NumElems, EltNo);
4739
4740     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
4741   }
4742
4743   return SDValue();
4744 }
4745
4746 /// Given the initializing elements 'Elts' of a vector of type 'VT', see if the
4747 /// elements can be replaced by a single large load which has the same value as
4748 /// a build_vector or insert_subvector whose loaded operands are 'Elts'.
4749 ///
4750 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4751 ///
4752 /// FIXME: we'd also like to handle the case where the last elements are zero
4753 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4754 /// There's even a handy isZeroNode for that purpose.
4755 static SDValue EltsFromConsecutiveLoads(EVT VT, ArrayRef<SDValue> Elts,
4756                                         SDLoc &DL, SelectionDAG &DAG,
4757                                         bool isAfterLegalize) {
4758   unsigned NumElems = Elts.size();
4759
4760   LoadSDNode *LDBase = nullptr;
4761   unsigned LastLoadedElt = -1U;
4762
4763   // For each element in the initializer, see if we've found a load or an undef.
4764   // If we don't find an initial load element, or later load elements are
4765   // non-consecutive, bail out.
4766   for (unsigned i = 0; i < NumElems; ++i) {
4767     SDValue Elt = Elts[i];
4768     // Look through a bitcast.
4769     if (Elt.getNode() && Elt.getOpcode() == ISD::BITCAST)
4770       Elt = Elt.getOperand(0);
4771     if (!Elt.getNode() ||
4772         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
4773       return SDValue();
4774     if (!LDBase) {
4775       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
4776         return SDValue();
4777       LDBase = cast<LoadSDNode>(Elt.getNode());
4778       LastLoadedElt = i;
4779       continue;
4780     }
4781     if (Elt.getOpcode() == ISD::UNDEF)
4782       continue;
4783
4784     LoadSDNode *LD = cast<LoadSDNode>(Elt);
4785     EVT LdVT = Elt.getValueType();
4786     // Each loaded element must be the correct fractional portion of the
4787     // requested vector load.
4788     if (LdVT.getSizeInBits() != VT.getSizeInBits() / NumElems)
4789       return SDValue();
4790     if (!DAG.isConsecutiveLoad(LD, LDBase, LdVT.getSizeInBits() / 8, i))
4791       return SDValue();
4792     LastLoadedElt = i;
4793   }
4794
4795   // If we have found an entire vector of loads and undefs, then return a large
4796   // load of the entire vector width starting at the base pointer.  If we found
4797   // consecutive loads for the low half, generate a vzext_load node.
4798   if (LastLoadedElt == NumElems - 1) {
4799     assert(LDBase && "Did not find base load for merging consecutive loads");
4800     EVT EltVT = LDBase->getValueType(0);
4801     // Ensure that the input vector size for the merged loads matches the
4802     // cumulative size of the input elements.
4803     if (VT.getSizeInBits() != EltVT.getSizeInBits() * NumElems)
4804       return SDValue();
4805
4806     if (isAfterLegalize &&
4807         !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
4808       return SDValue();
4809
4810     SDValue NewLd = SDValue();
4811
4812     NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4813                         LDBase->getPointerInfo(), LDBase->isVolatile(),
4814                         LDBase->isNonTemporal(), LDBase->isInvariant(),
4815                         LDBase->getAlignment());
4816
4817     if (LDBase->hasAnyUseOfValue(1)) {
4818       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
4819                                      SDValue(LDBase, 1),
4820                                      SDValue(NewLd.getNode(), 1));
4821       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
4822       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
4823                              SDValue(NewLd.getNode(), 1));
4824     }
4825
4826     return NewLd;
4827   }
4828
4829   //TODO: The code below fires only for for loading the low v2i32 / v2f32
4830   //of a v4i32 / v4f32. It's probably worth generalizing.
4831   EVT EltVT = VT.getVectorElementType();
4832   if (NumElems == 4 && LastLoadedElt == 1 && (EltVT.getSizeInBits() == 32) &&
4833       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
4834     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
4835     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
4836     SDValue ResNode =
4837         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
4838                                 LDBase->getPointerInfo(),
4839                                 LDBase->getAlignment(),
4840                                 false/*isVolatile*/, true/*ReadMem*/,
4841                                 false/*WriteMem*/);
4842
4843     // Make sure the newly-created LOAD is in the same position as LDBase in
4844     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
4845     // update uses of LDBase's output chain to use the TokenFactor.
4846     if (LDBase->hasAnyUseOfValue(1)) {
4847       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
4848                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
4849       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
4850       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
4851                              SDValue(ResNode.getNode(), 1));
4852     }
4853
4854     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
4855   }
4856   return SDValue();
4857 }
4858
4859 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
4860 /// to generate a splat value for the following cases:
4861 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
4862 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
4863 /// a scalar load, or a constant.
4864 /// The VBROADCAST node is returned when a pattern is found,
4865 /// or SDValue() otherwise.
4866 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
4867                                     SelectionDAG &DAG) {
4868   // VBROADCAST requires AVX.
4869   // TODO: Splats could be generated for non-AVX CPUs using SSE
4870   // instructions, but there's less potential gain for only 128-bit vectors.
4871   if (!Subtarget->hasAVX())
4872     return SDValue();
4873
4874   MVT VT = Op.getSimpleValueType();
4875   SDLoc dl(Op);
4876
4877   assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
4878          "Unsupported vector type for broadcast.");
4879
4880   SDValue Ld;
4881   bool ConstSplatVal;
4882
4883   switch (Op.getOpcode()) {
4884     default:
4885       // Unknown pattern found.
4886       return SDValue();
4887
4888     case ISD::BUILD_VECTOR: {
4889       auto *BVOp = cast<BuildVectorSDNode>(Op.getNode());
4890       BitVector UndefElements;
4891       SDValue Splat = BVOp->getSplatValue(&UndefElements);
4892
4893       // We need a splat of a single value to use broadcast, and it doesn't
4894       // make any sense if the value is only in one element of the vector.
4895       if (!Splat || (VT.getVectorNumElements() - UndefElements.count()) <= 1)
4896         return SDValue();
4897
4898       Ld = Splat;
4899       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
4900                        Ld.getOpcode() == ISD::ConstantFP);
4901
4902       // Make sure that all of the users of a non-constant load are from the
4903       // BUILD_VECTOR node.
4904       if (!ConstSplatVal && !BVOp->isOnlyUserOf(Ld.getNode()))
4905         return SDValue();
4906       break;
4907     }
4908
4909     case ISD::VECTOR_SHUFFLE: {
4910       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
4911
4912       // Shuffles must have a splat mask where the first element is
4913       // broadcasted.
4914       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
4915         return SDValue();
4916
4917       SDValue Sc = Op.getOperand(0);
4918       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
4919           Sc.getOpcode() != ISD::BUILD_VECTOR) {
4920
4921         if (!Subtarget->hasInt256())
4922           return SDValue();
4923
4924         // Use the register form of the broadcast instruction available on AVX2.
4925         if (VT.getSizeInBits() >= 256)
4926           Sc = Extract128BitVector(Sc, 0, DAG, dl);
4927         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
4928       }
4929
4930       Ld = Sc.getOperand(0);
4931       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
4932                        Ld.getOpcode() == ISD::ConstantFP);
4933
4934       // The scalar_to_vector node and the suspected
4935       // load node must have exactly one user.
4936       // Constants may have multiple users.
4937
4938       // AVX-512 has register version of the broadcast
4939       bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
4940         Ld.getValueType().getSizeInBits() >= 32;
4941       if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
4942           !hasRegVer))
4943         return SDValue();
4944       break;
4945     }
4946   }
4947
4948   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
4949   bool IsGE256 = (VT.getSizeInBits() >= 256);
4950
4951   // When optimizing for size, generate up to 5 extra bytes for a broadcast
4952   // instruction to save 8 or more bytes of constant pool data.
4953   // TODO: If multiple splats are generated to load the same constant,
4954   // it may be detrimental to overall size. There needs to be a way to detect
4955   // that condition to know if this is truly a size win.
4956   const Function *F = DAG.getMachineFunction().getFunction();
4957   bool OptForSize = F->hasFnAttribute(Attribute::OptimizeForSize);
4958
4959   // Handle broadcasting a single constant scalar from the constant pool
4960   // into a vector.
4961   // On Sandybridge (no AVX2), it is still better to load a constant vector
4962   // from the constant pool and not to broadcast it from a scalar.
4963   // But override that restriction when optimizing for size.
4964   // TODO: Check if splatting is recommended for other AVX-capable CPUs.
4965   if (ConstSplatVal && (Subtarget->hasAVX2() || OptForSize)) {
4966     EVT CVT = Ld.getValueType();
4967     assert(!CVT.isVector() && "Must not broadcast a vector type");
4968
4969     // Splat f32, i32, v4f64, v4i64 in all cases with AVX2.
4970     // For size optimization, also splat v2f64 and v2i64, and for size opt
4971     // with AVX2, also splat i8 and i16.
4972     // With pattern matching, the VBROADCAST node may become a VMOVDDUP.
4973     if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
4974         (OptForSize && (ScalarSize == 64 || Subtarget->hasAVX2()))) {
4975       const Constant *C = nullptr;
4976       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
4977         C = CI->getConstantIntValue();
4978       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
4979         C = CF->getConstantFPValue();
4980
4981       assert(C && "Invalid constant type");
4982
4983       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4984       SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
4985       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
4986       Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
4987                        MachinePointerInfo::getConstantPool(),
4988                        false, false, false, Alignment);
4989
4990       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
4991     }
4992   }
4993
4994   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
4995
4996   // Handle AVX2 in-register broadcasts.
4997   if (!IsLoad && Subtarget->hasInt256() &&
4998       (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
4999     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5000
5001   // The scalar source must be a normal load.
5002   if (!IsLoad)
5003     return SDValue();
5004
5005   if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5006       (Subtarget->hasVLX() && ScalarSize == 64))
5007     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5008
5009   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5010   // double since there is no vbroadcastsd xmm
5011   if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5012     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5013       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5014   }
5015
5016   // Unsupported broadcast.
5017   return SDValue();
5018 }
5019
5020 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
5021 /// underlying vector and index.
5022 ///
5023 /// Modifies \p ExtractedFromVec to the real vector and returns the real
5024 /// index.
5025 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
5026                                          SDValue ExtIdx) {
5027   int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5028   if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
5029     return Idx;
5030
5031   // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
5032   // lowered this:
5033   //   (extract_vector_elt (v8f32 %vreg1), Constant<6>)
5034   // to:
5035   //   (extract_vector_elt (vector_shuffle<2,u,u,u>
5036   //                           (extract_subvector (v8f32 %vreg0), Constant<4>),
5037   //                           undef)
5038   //                       Constant<0>)
5039   // In this case the vector is the extract_subvector expression and the index
5040   // is 2, as specified by the shuffle.
5041   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
5042   SDValue ShuffleVec = SVOp->getOperand(0);
5043   MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
5044   assert(ShuffleVecVT.getVectorElementType() ==
5045          ExtractedFromVec.getSimpleValueType().getVectorElementType());
5046
5047   int ShuffleIdx = SVOp->getMaskElt(Idx);
5048   if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
5049     ExtractedFromVec = ShuffleVec;
5050     return ShuffleIdx;
5051   }
5052   return Idx;
5053 }
5054
5055 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5056   MVT VT = Op.getSimpleValueType();
5057
5058   // Skip if insert_vec_elt is not supported.
5059   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5060   if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5061     return SDValue();
5062
5063   SDLoc DL(Op);
5064   unsigned NumElems = Op.getNumOperands();
5065
5066   SDValue VecIn1;
5067   SDValue VecIn2;
5068   SmallVector<unsigned, 4> InsertIndices;
5069   SmallVector<int, 8> Mask(NumElems, -1);
5070
5071   for (unsigned i = 0; i != NumElems; ++i) {
5072     unsigned Opc = Op.getOperand(i).getOpcode();
5073
5074     if (Opc == ISD::UNDEF)
5075       continue;
5076
5077     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5078       // Quit if more than 1 elements need inserting.
5079       if (InsertIndices.size() > 1)
5080         return SDValue();
5081
5082       InsertIndices.push_back(i);
5083       continue;
5084     }
5085
5086     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5087     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5088     // Quit if non-constant index.
5089     if (!isa<ConstantSDNode>(ExtIdx))
5090       return SDValue();
5091     int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5092
5093     // Quit if extracted from vector of different type.
5094     if (ExtractedFromVec.getValueType() != VT)
5095       return SDValue();
5096
5097     if (!VecIn1.getNode())
5098       VecIn1 = ExtractedFromVec;
5099     else if (VecIn1 != ExtractedFromVec) {
5100       if (!VecIn2.getNode())
5101         VecIn2 = ExtractedFromVec;
5102       else if (VecIn2 != ExtractedFromVec)
5103         // Quit if more than 2 vectors to shuffle
5104         return SDValue();
5105     }
5106
5107     if (ExtractedFromVec == VecIn1)
5108       Mask[i] = Idx;
5109     else if (ExtractedFromVec == VecIn2)
5110       Mask[i] = Idx + NumElems;
5111   }
5112
5113   if (!VecIn1.getNode())
5114     return SDValue();
5115
5116   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5117   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5118   for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5119     unsigned Idx = InsertIndices[i];
5120     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5121                      DAG.getIntPtrConstant(Idx));
5122   }
5123
5124   return NV;
5125 }
5126
5127 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5128 SDValue
5129 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5130
5131   MVT VT = Op.getSimpleValueType();
5132   assert((VT.getVectorElementType() == MVT::i1) && (VT.getSizeInBits() <= 16) &&
5133          "Unexpected type in LowerBUILD_VECTORvXi1!");
5134
5135   SDLoc dl(Op);
5136   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5137     SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
5138     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5139     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5140   }
5141
5142   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5143     SDValue Cst = DAG.getTargetConstant(1, MVT::i1);
5144     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5145     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5146   }
5147
5148   bool AllContants = true;
5149   uint64_t Immediate = 0;
5150   int NonConstIdx = -1;
5151   bool IsSplat = true;
5152   unsigned NumNonConsts = 0;
5153   unsigned NumConsts = 0;
5154   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5155     SDValue In = Op.getOperand(idx);
5156     if (In.getOpcode() == ISD::UNDEF)
5157       continue;
5158     if (!isa<ConstantSDNode>(In)) {
5159       AllContants = false;
5160       NonConstIdx = idx;
5161       NumNonConsts++;
5162     } else {
5163       NumConsts++;
5164       if (cast<ConstantSDNode>(In)->getZExtValue())
5165       Immediate |= (1ULL << idx);
5166     }
5167     if (In != Op.getOperand(0))
5168       IsSplat = false;
5169   }
5170
5171   if (AllContants) {
5172     SDValue FullMask = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1,
5173       DAG.getConstant(Immediate, MVT::i16));
5174     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, FullMask,
5175                        DAG.getIntPtrConstant(0));
5176   }
5177
5178   if (NumNonConsts == 1 && NonConstIdx != 0) {
5179     SDValue DstVec;
5180     if (NumConsts) {
5181       SDValue VecAsImm = DAG.getConstant(Immediate,
5182                                          MVT::getIntegerVT(VT.getSizeInBits()));
5183       DstVec = DAG.getNode(ISD::BITCAST, dl, VT, VecAsImm);
5184     }
5185     else
5186       DstVec = DAG.getUNDEF(VT);
5187     return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5188                        Op.getOperand(NonConstIdx),
5189                        DAG.getIntPtrConstant(NonConstIdx));
5190   }
5191   if (!IsSplat && (NonConstIdx != 0))
5192     llvm_unreachable("Unsupported BUILD_VECTOR operation");
5193   MVT SelectVT = (VT == MVT::v16i1)? MVT::i16 : MVT::i8;
5194   SDValue Select;
5195   if (IsSplat)
5196     Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
5197                           DAG.getConstant(-1, SelectVT),
5198                           DAG.getConstant(0, SelectVT));
5199   else
5200     Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
5201                          DAG.getConstant((Immediate | 1), SelectVT),
5202                          DAG.getConstant(Immediate, SelectVT));
5203   return DAG.getNode(ISD::BITCAST, dl, VT, Select);
5204 }
5205
5206 /// \brief Return true if \p N implements a horizontal binop and return the
5207 /// operands for the horizontal binop into V0 and V1.
5208 ///
5209 /// This is a helper function of PerformBUILD_VECTORCombine.
5210 /// This function checks that the build_vector \p N in input implements a
5211 /// horizontal operation. Parameter \p Opcode defines the kind of horizontal
5212 /// operation to match.
5213 /// For example, if \p Opcode is equal to ISD::ADD, then this function
5214 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
5215 /// is equal to ISD::SUB, then this function checks if this is a horizontal
5216 /// arithmetic sub.
5217 ///
5218 /// This function only analyzes elements of \p N whose indices are
5219 /// in range [BaseIdx, LastIdx).
5220 static bool isHorizontalBinOp(const BuildVectorSDNode *N, unsigned Opcode,
5221                               SelectionDAG &DAG,
5222                               unsigned BaseIdx, unsigned LastIdx,
5223                               SDValue &V0, SDValue &V1) {
5224   EVT VT = N->getValueType(0);
5225
5226   assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
5227   assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
5228          "Invalid Vector in input!");
5229
5230   bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
5231   bool CanFold = true;
5232   unsigned ExpectedVExtractIdx = BaseIdx;
5233   unsigned NumElts = LastIdx - BaseIdx;
5234   V0 = DAG.getUNDEF(VT);
5235   V1 = DAG.getUNDEF(VT);
5236
5237   // Check if N implements a horizontal binop.
5238   for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
5239     SDValue Op = N->getOperand(i + BaseIdx);
5240
5241     // Skip UNDEFs.
5242     if (Op->getOpcode() == ISD::UNDEF) {
5243       // Update the expected vector extract index.
5244       if (i * 2 == NumElts)
5245         ExpectedVExtractIdx = BaseIdx;
5246       ExpectedVExtractIdx += 2;
5247       continue;
5248     }
5249
5250     CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
5251
5252     if (!CanFold)
5253       break;
5254
5255     SDValue Op0 = Op.getOperand(0);
5256     SDValue Op1 = Op.getOperand(1);
5257
5258     // Try to match the following pattern:
5259     // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
5260     CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5261         Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5262         Op0.getOperand(0) == Op1.getOperand(0) &&
5263         isa<ConstantSDNode>(Op0.getOperand(1)) &&
5264         isa<ConstantSDNode>(Op1.getOperand(1)));
5265     if (!CanFold)
5266       break;
5267
5268     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5269     unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
5270
5271     if (i * 2 < NumElts) {
5272       if (V0.getOpcode() == ISD::UNDEF) {
5273         V0 = Op0.getOperand(0);
5274         if (V0.getValueType() != VT)
5275           return false;
5276       }
5277     } else {
5278       if (V1.getOpcode() == ISD::UNDEF) {
5279         V1 = Op0.getOperand(0);
5280         if (V1.getValueType() != VT)
5281           return false;
5282       }
5283       if (i * 2 == NumElts)
5284         ExpectedVExtractIdx = BaseIdx;
5285     }
5286
5287     SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
5288     if (I0 == ExpectedVExtractIdx)
5289       CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
5290     else if (IsCommutable && I1 == ExpectedVExtractIdx) {
5291       // Try to match the following dag sequence:
5292       // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
5293       CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
5294     } else
5295       CanFold = false;
5296
5297     ExpectedVExtractIdx += 2;
5298   }
5299
5300   return CanFold;
5301 }
5302
5303 /// \brief Emit a sequence of two 128-bit horizontal add/sub followed by
5304 /// a concat_vector.
5305 ///
5306 /// This is a helper function of PerformBUILD_VECTORCombine.
5307 /// This function expects two 256-bit vectors called V0 and V1.
5308 /// At first, each vector is split into two separate 128-bit vectors.
5309 /// Then, the resulting 128-bit vectors are used to implement two
5310 /// horizontal binary operations.
5311 ///
5312 /// The kind of horizontal binary operation is defined by \p X86Opcode.
5313 ///
5314 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
5315 /// the two new horizontal binop.
5316 /// When Mode is set, the first horizontal binop dag node would take as input
5317 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
5318 /// horizontal binop dag node would take as input the lower 128-bit of V1
5319 /// and the upper 128-bit of V1.
5320 ///   Example:
5321 ///     HADD V0_LO, V0_HI
5322 ///     HADD V1_LO, V1_HI
5323 ///
5324 /// Otherwise, the first horizontal binop dag node takes as input the lower
5325 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
5326 /// dag node takes the the upper 128-bit of V0 and the upper 128-bit of V1.
5327 ///   Example:
5328 ///     HADD V0_LO, V1_LO
5329 ///     HADD V0_HI, V1_HI
5330 ///
5331 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
5332 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
5333 /// the upper 128-bits of the result.
5334 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
5335                                      SDLoc DL, SelectionDAG &DAG,
5336                                      unsigned X86Opcode, bool Mode,
5337                                      bool isUndefLO, bool isUndefHI) {
5338   EVT VT = V0.getValueType();
5339   assert(VT.is256BitVector() && VT == V1.getValueType() &&
5340          "Invalid nodes in input!");
5341
5342   unsigned NumElts = VT.getVectorNumElements();
5343   SDValue V0_LO = Extract128BitVector(V0, 0, DAG, DL);
5344   SDValue V0_HI = Extract128BitVector(V0, NumElts/2, DAG, DL);
5345   SDValue V1_LO = Extract128BitVector(V1, 0, DAG, DL);
5346   SDValue V1_HI = Extract128BitVector(V1, NumElts/2, DAG, DL);
5347   EVT NewVT = V0_LO.getValueType();
5348
5349   SDValue LO = DAG.getUNDEF(NewVT);
5350   SDValue HI = DAG.getUNDEF(NewVT);
5351
5352   if (Mode) {
5353     // Don't emit a horizontal binop if the result is expected to be UNDEF.
5354     if (!isUndefLO && V0->getOpcode() != ISD::UNDEF)
5355       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
5356     if (!isUndefHI && V1->getOpcode() != ISD::UNDEF)
5357       HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
5358   } else {
5359     // Don't emit a horizontal binop if the result is expected to be UNDEF.
5360     if (!isUndefLO && (V0_LO->getOpcode() != ISD::UNDEF ||
5361                        V1_LO->getOpcode() != ISD::UNDEF))
5362       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
5363
5364     if (!isUndefHI && (V0_HI->getOpcode() != ISD::UNDEF ||
5365                        V1_HI->getOpcode() != ISD::UNDEF))
5366       HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
5367   }
5368
5369   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
5370 }
5371
5372 /// \brief Try to fold a build_vector that performs an 'addsub' into the
5373 /// sequence of 'vadd + vsub + blendi'.
5374 static SDValue matchAddSub(const BuildVectorSDNode *BV, SelectionDAG &DAG,
5375                            const X86Subtarget *Subtarget) {
5376   SDLoc DL(BV);
5377   EVT VT = BV->getValueType(0);
5378   unsigned NumElts = VT.getVectorNumElements();
5379   SDValue InVec0 = DAG.getUNDEF(VT);
5380   SDValue InVec1 = DAG.getUNDEF(VT);
5381
5382   assert((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v4f32 ||
5383           VT == MVT::v2f64) && "build_vector with an invalid type found!");
5384
5385   // Odd-numbered elements in the input build vector are obtained from
5386   // adding two integer/float elements.
5387   // Even-numbered elements in the input build vector are obtained from
5388   // subtracting two integer/float elements.
5389   unsigned ExpectedOpcode = ISD::FSUB;
5390   unsigned NextExpectedOpcode = ISD::FADD;
5391   bool AddFound = false;
5392   bool SubFound = false;
5393
5394   for (unsigned i = 0, e = NumElts; i != e; ++i) {
5395     SDValue Op = BV->getOperand(i);
5396
5397     // Skip 'undef' values.
5398     unsigned Opcode = Op.getOpcode();
5399     if (Opcode == ISD::UNDEF) {
5400       std::swap(ExpectedOpcode, NextExpectedOpcode);
5401       continue;
5402     }
5403
5404     // Early exit if we found an unexpected opcode.
5405     if (Opcode != ExpectedOpcode)
5406       return SDValue();
5407
5408     SDValue Op0 = Op.getOperand(0);
5409     SDValue Op1 = Op.getOperand(1);
5410
5411     // Try to match the following pattern:
5412     // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
5413     // Early exit if we cannot match that sequence.
5414     if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5415         Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5416         !isa<ConstantSDNode>(Op0.getOperand(1)) ||
5417         !isa<ConstantSDNode>(Op1.getOperand(1)) ||
5418         Op0.getOperand(1) != Op1.getOperand(1))
5419       return SDValue();
5420
5421     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5422     if (I0 != i)
5423       return SDValue();
5424
5425     // We found a valid add/sub node. Update the information accordingly.
5426     if (i & 1)
5427       AddFound = true;
5428     else
5429       SubFound = true;
5430
5431     // Update InVec0 and InVec1.
5432     if (InVec0.getOpcode() == ISD::UNDEF) {
5433       InVec0 = Op0.getOperand(0);
5434       if (InVec0.getValueType() != VT)
5435         return SDValue();
5436     }
5437     if (InVec1.getOpcode() == ISD::UNDEF) {
5438       InVec1 = Op1.getOperand(0);
5439       if (InVec1.getValueType() != VT)
5440         return SDValue();
5441     }
5442
5443     // Make sure that operands in input to each add/sub node always
5444     // come from a same pair of vectors.
5445     if (InVec0 != Op0.getOperand(0)) {
5446       if (ExpectedOpcode == ISD::FSUB)
5447         return SDValue();
5448
5449       // FADD is commutable. Try to commute the operands
5450       // and then test again.
5451       std::swap(Op0, Op1);
5452       if (InVec0 != Op0.getOperand(0))
5453         return SDValue();
5454     }
5455
5456     if (InVec1 != Op1.getOperand(0))
5457       return SDValue();
5458
5459     // Update the pair of expected opcodes.
5460     std::swap(ExpectedOpcode, NextExpectedOpcode);
5461   }
5462
5463   // Don't try to fold this build_vector into an ADDSUB if the inputs are undef.
5464   if (AddFound && SubFound && InVec0.getOpcode() != ISD::UNDEF &&
5465       InVec1.getOpcode() != ISD::UNDEF)
5466     return DAG.getNode(X86ISD::ADDSUB, DL, VT, InVec0, InVec1);
5467
5468   return SDValue();
5469 }
5470
5471 static SDValue PerformBUILD_VECTORCombine(SDNode *N, SelectionDAG &DAG,
5472                                           const X86Subtarget *Subtarget) {
5473   SDLoc DL(N);
5474   EVT VT = N->getValueType(0);
5475   unsigned NumElts = VT.getVectorNumElements();
5476   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(N);
5477   SDValue InVec0, InVec1;
5478
5479   // Try to match an ADDSUB.
5480   if ((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
5481       (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) {
5482     SDValue Value = matchAddSub(BV, DAG, Subtarget);
5483     if (Value.getNode())
5484       return Value;
5485   }
5486
5487   // Try to match horizontal ADD/SUB.
5488   unsigned NumUndefsLO = 0;
5489   unsigned NumUndefsHI = 0;
5490   unsigned Half = NumElts/2;
5491
5492   // Count the number of UNDEF operands in the build_vector in input.
5493   for (unsigned i = 0, e = Half; i != e; ++i)
5494     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
5495       NumUndefsLO++;
5496
5497   for (unsigned i = Half, e = NumElts; i != e; ++i)
5498     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
5499       NumUndefsHI++;
5500
5501   // Early exit if this is either a build_vector of all UNDEFs or all the
5502   // operands but one are UNDEF.
5503   if (NumUndefsLO + NumUndefsHI + 1 >= NumElts)
5504     return SDValue();
5505
5506   if ((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) {
5507     // Try to match an SSE3 float HADD/HSUB.
5508     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
5509       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
5510
5511     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
5512       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
5513   } else if ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) {
5514     // Try to match an SSSE3 integer HADD/HSUB.
5515     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
5516       return DAG.getNode(X86ISD::HADD, DL, VT, InVec0, InVec1);
5517
5518     if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
5519       return DAG.getNode(X86ISD::HSUB, DL, VT, InVec0, InVec1);
5520   }
5521
5522   if (!Subtarget->hasAVX())
5523     return SDValue();
5524
5525   if ((VT == MVT::v8f32 || VT == MVT::v4f64)) {
5526     // Try to match an AVX horizontal add/sub of packed single/double
5527     // precision floating point values from 256-bit vectors.
5528     SDValue InVec2, InVec3;
5529     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, Half, InVec0, InVec1) &&
5530         isHorizontalBinOp(BV, ISD::FADD, DAG, Half, NumElts, InVec2, InVec3) &&
5531         ((InVec0.getOpcode() == ISD::UNDEF ||
5532           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5533         ((InVec1.getOpcode() == ISD::UNDEF ||
5534           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5535       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
5536
5537     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, Half, InVec0, InVec1) &&
5538         isHorizontalBinOp(BV, ISD::FSUB, DAG, Half, NumElts, InVec2, InVec3) &&
5539         ((InVec0.getOpcode() == ISD::UNDEF ||
5540           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5541         ((InVec1.getOpcode() == ISD::UNDEF ||
5542           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5543       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
5544   } else if (VT == MVT::v8i32 || VT == MVT::v16i16) {
5545     // Try to match an AVX2 horizontal add/sub of signed integers.
5546     SDValue InVec2, InVec3;
5547     unsigned X86Opcode;
5548     bool CanFold = true;
5549
5550     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
5551         isHorizontalBinOp(BV, ISD::ADD, DAG, Half, NumElts, InVec2, InVec3) &&
5552         ((InVec0.getOpcode() == ISD::UNDEF ||
5553           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5554         ((InVec1.getOpcode() == ISD::UNDEF ||
5555           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5556       X86Opcode = X86ISD::HADD;
5557     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, Half, InVec0, InVec1) &&
5558         isHorizontalBinOp(BV, ISD::SUB, DAG, Half, NumElts, InVec2, InVec3) &&
5559         ((InVec0.getOpcode() == ISD::UNDEF ||
5560           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5561         ((InVec1.getOpcode() == ISD::UNDEF ||
5562           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5563       X86Opcode = X86ISD::HSUB;
5564     else
5565       CanFold = false;
5566
5567     if (CanFold) {
5568       // Fold this build_vector into a single horizontal add/sub.
5569       // Do this only if the target has AVX2.
5570       if (Subtarget->hasAVX2())
5571         return DAG.getNode(X86Opcode, DL, VT, InVec0, InVec1);
5572
5573       // Do not try to expand this build_vector into a pair of horizontal
5574       // add/sub if we can emit a pair of scalar add/sub.
5575       if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
5576         return SDValue();
5577
5578       // Convert this build_vector into a pair of horizontal binop followed by
5579       // a concat vector.
5580       bool isUndefLO = NumUndefsLO == Half;
5581       bool isUndefHI = NumUndefsHI == Half;
5582       return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, false,
5583                                    isUndefLO, isUndefHI);
5584     }
5585   }
5586
5587   if ((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
5588        VT == MVT::v16i16) && Subtarget->hasAVX()) {
5589     unsigned X86Opcode;
5590     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
5591       X86Opcode = X86ISD::HADD;
5592     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
5593       X86Opcode = X86ISD::HSUB;
5594     else if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
5595       X86Opcode = X86ISD::FHADD;
5596     else if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
5597       X86Opcode = X86ISD::FHSUB;
5598     else
5599       return SDValue();
5600
5601     // Don't try to expand this build_vector into a pair of horizontal add/sub
5602     // if we can simply emit a pair of scalar add/sub.
5603     if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
5604       return SDValue();
5605
5606     // Convert this build_vector into two horizontal add/sub followed by
5607     // a concat vector.
5608     bool isUndefLO = NumUndefsLO == Half;
5609     bool isUndefHI = NumUndefsHI == Half;
5610     return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
5611                                  isUndefLO, isUndefHI);
5612   }
5613
5614   return SDValue();
5615 }
5616
5617 SDValue
5618 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5619   SDLoc dl(Op);
5620
5621   MVT VT = Op.getSimpleValueType();
5622   MVT ExtVT = VT.getVectorElementType();
5623   unsigned NumElems = Op.getNumOperands();
5624
5625   // Generate vectors for predicate vectors.
5626   if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
5627     return LowerBUILD_VECTORvXi1(Op, DAG);
5628
5629   // Vectors containing all zeros can be matched by pxor and xorps later
5630   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5631     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5632     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5633     if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
5634       return Op;
5635
5636     return getZeroVector(VT, Subtarget, DAG, dl);
5637   }
5638
5639   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5640   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5641   // vpcmpeqd on 256-bit vectors.
5642   if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
5643     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
5644       return Op;
5645
5646     if (!VT.is512BitVector())
5647       return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
5648   }
5649
5650   if (SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG))
5651     return Broadcast;
5652
5653   unsigned EVTBits = ExtVT.getSizeInBits();
5654
5655   unsigned NumZero  = 0;
5656   unsigned NumNonZero = 0;
5657   unsigned NonZeros = 0;
5658   bool IsAllConstants = true;
5659   SmallSet<SDValue, 8> Values;
5660   for (unsigned i = 0; i < NumElems; ++i) {
5661     SDValue Elt = Op.getOperand(i);
5662     if (Elt.getOpcode() == ISD::UNDEF)
5663       continue;
5664     Values.insert(Elt);
5665     if (Elt.getOpcode() != ISD::Constant &&
5666         Elt.getOpcode() != ISD::ConstantFP)
5667       IsAllConstants = false;
5668     if (X86::isZeroNode(Elt))
5669       NumZero++;
5670     else {
5671       NonZeros |= (1 << i);
5672       NumNonZero++;
5673     }
5674   }
5675
5676   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
5677   if (NumNonZero == 0)
5678     return DAG.getUNDEF(VT);
5679
5680   // Special case for single non-zero, non-undef, element.
5681   if (NumNonZero == 1) {
5682     unsigned Idx = countTrailingZeros(NonZeros);
5683     SDValue Item = Op.getOperand(Idx);
5684
5685     // If this is an insertion of an i64 value on x86-32, and if the top bits of
5686     // the value are obviously zero, truncate the value to i32 and do the
5687     // insertion that way.  Only do this if the value is non-constant or if the
5688     // value is a constant being inserted into element 0.  It is cheaper to do
5689     // a constant pool load than it is to do a movd + shuffle.
5690     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5691         (!IsAllConstants || Idx == 0)) {
5692       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5693         // Handle SSE only.
5694         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5695         EVT VecVT = MVT::v4i32;
5696
5697         // Truncate the value (which may itself be a constant) to i32, and
5698         // convert it to a vector with movd (S2V+shuffle to zero extend).
5699         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5700         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5701         return DAG.getNode(
5702             ISD::BITCAST, dl, VT,
5703             getShuffleVectorZeroOrUndef(Item, Idx * 2, true, Subtarget, DAG));
5704       }
5705     }
5706
5707     // If we have a constant or non-constant insertion into the low element of
5708     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5709     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
5710     // depending on what the source datatype is.
5711     if (Idx == 0) {
5712       if (NumZero == 0)
5713         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5714
5715       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5716           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5717         if (VT.is512BitVector()) {
5718           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
5719           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
5720                              Item, DAG.getIntPtrConstant(0));
5721         }
5722         assert((VT.is128BitVector() || VT.is256BitVector()) &&
5723                "Expected an SSE value type!");
5724         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5725         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5726         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5727       }
5728
5729       // We can't directly insert an i8 or i16 into a vector, so zero extend
5730       // it to i32 first.
5731       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5732         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5733         if (VT.is256BitVector()) {
5734           if (Subtarget->hasAVX()) {
5735             Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v8i32, Item);
5736             Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5737           } else {
5738             // Without AVX, we need to extend to a 128-bit vector and then
5739             // insert into the 256-bit vector.
5740             Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5741             SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
5742             Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
5743           }
5744         } else {
5745           assert(VT.is128BitVector() && "Expected an SSE value type!");
5746           Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5747           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5748         }
5749         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5750       }
5751     }
5752
5753     // Is it a vector logical left shift?
5754     if (NumElems == 2 && Idx == 1 &&
5755         X86::isZeroNode(Op.getOperand(0)) &&
5756         !X86::isZeroNode(Op.getOperand(1))) {
5757       unsigned NumBits = VT.getSizeInBits();
5758       return getVShift(true, VT,
5759                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5760                                    VT, Op.getOperand(1)),
5761                        NumBits/2, DAG, *this, dl);
5762     }
5763
5764     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5765       return SDValue();
5766
5767     // Otherwise, if this is a vector with i32 or f32 elements, and the element
5768     // is a non-constant being inserted into an element other than the low one,
5769     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
5770     // movd/movss) to move this into the low element, then shuffle it into
5771     // place.
5772     if (EVTBits == 32) {
5773       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5774       return getShuffleVectorZeroOrUndef(Item, Idx, NumZero > 0, Subtarget, DAG);
5775     }
5776   }
5777
5778   // Splat is obviously ok. Let legalizer expand it to a shuffle.
5779   if (Values.size() == 1) {
5780     if (EVTBits == 32) {
5781       // Instead of a shuffle like this:
5782       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
5783       // Check if it's possible to issue this instead.
5784       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
5785       unsigned Idx = countTrailingZeros(NonZeros);
5786       SDValue Item = Op.getOperand(Idx);
5787       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
5788         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
5789     }
5790     return SDValue();
5791   }
5792
5793   // A vector full of immediates; various special cases are already
5794   // handled, so this is best done with a single constant-pool load.
5795   if (IsAllConstants)
5796     return SDValue();
5797
5798   // For AVX-length vectors, see if we can use a vector load to get all of the
5799   // elements, otherwise build the individual 128-bit pieces and use
5800   // shuffles to put them in place.
5801   if (VT.is256BitVector() || VT.is512BitVector()) {
5802     SmallVector<SDValue, 64> V(Op->op_begin(), Op->op_begin() + NumElems);
5803
5804     // Check for a build vector of consecutive loads.
5805     if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
5806       return LD;
5807
5808     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
5809
5810     // Build both the lower and upper subvector.
5811     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
5812                                 makeArrayRef(&V[0], NumElems/2));
5813     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
5814                                 makeArrayRef(&V[NumElems / 2], NumElems/2));
5815
5816     // Recreate the wider vector with the lower and upper part.
5817     if (VT.is256BitVector())
5818       return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
5819     return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
5820   }
5821
5822   // Let legalizer expand 2-wide build_vectors.
5823   if (EVTBits == 64) {
5824     if (NumNonZero == 1) {
5825       // One half is zero or undef.
5826       unsigned Idx = countTrailingZeros(NonZeros);
5827       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
5828                                  Op.getOperand(Idx));
5829       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
5830     }
5831     return SDValue();
5832   }
5833
5834   // If element VT is < 32 bits, convert it to inserts into a zero vector.
5835   if (EVTBits == 8 && NumElems == 16)
5836     if (SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
5837                                         Subtarget, *this))
5838       return V;
5839
5840   if (EVTBits == 16 && NumElems == 8)
5841     if (SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
5842                                       Subtarget, *this))
5843       return V;
5844
5845   // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
5846   if (EVTBits == 32 && NumElems == 4)
5847     if (SDValue V = LowerBuildVectorv4x32(Op, DAG, Subtarget, *this))
5848       return V;
5849
5850   // If element VT is == 32 bits, turn it into a number of shuffles.
5851   SmallVector<SDValue, 8> V(NumElems);
5852   if (NumElems == 4 && NumZero > 0) {
5853     for (unsigned i = 0; i < 4; ++i) {
5854       bool isZero = !(NonZeros & (1 << i));
5855       if (isZero)
5856         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
5857       else
5858         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5859     }
5860
5861     for (unsigned i = 0; i < 2; ++i) {
5862       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
5863         default: break;
5864         case 0:
5865           V[i] = V[i*2];  // Must be a zero vector.
5866           break;
5867         case 1:
5868           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
5869           break;
5870         case 2:
5871           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
5872           break;
5873         case 3:
5874           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
5875           break;
5876       }
5877     }
5878
5879     bool Reverse1 = (NonZeros & 0x3) == 2;
5880     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
5881     int MaskVec[] = {
5882       Reverse1 ? 1 : 0,
5883       Reverse1 ? 0 : 1,
5884       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
5885       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
5886     };
5887     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
5888   }
5889
5890   if (Values.size() > 1 && VT.is128BitVector()) {
5891     // Check for a build vector of consecutive loads.
5892     for (unsigned i = 0; i < NumElems; ++i)
5893       V[i] = Op.getOperand(i);
5894
5895     // Check for elements which are consecutive loads.
5896     if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
5897       return LD;
5898
5899     // Check for a build vector from mostly shuffle plus few inserting.
5900     if (SDValue Sh = buildFromShuffleMostly(Op, DAG))
5901       return Sh;
5902
5903     // For SSE 4.1, use insertps to put the high elements into the low element.
5904     if (Subtarget->hasSSE41()) {
5905       SDValue Result;
5906       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
5907         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
5908       else
5909         Result = DAG.getUNDEF(VT);
5910
5911       for (unsigned i = 1; i < NumElems; ++i) {
5912         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
5913         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
5914                              Op.getOperand(i), DAG.getIntPtrConstant(i));
5915       }
5916       return Result;
5917     }
5918
5919     // Otherwise, expand into a number of unpckl*, start by extending each of
5920     // our (non-undef) elements to the full vector width with the element in the
5921     // bottom slot of the vector (which generates no code for SSE).
5922     for (unsigned i = 0; i < NumElems; ++i) {
5923       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
5924         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5925       else
5926         V[i] = DAG.getUNDEF(VT);
5927     }
5928
5929     // Next, we iteratively mix elements, e.g. for v4f32:
5930     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
5931     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
5932     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
5933     unsigned EltStride = NumElems >> 1;
5934     while (EltStride != 0) {
5935       for (unsigned i = 0; i < EltStride; ++i) {
5936         // If V[i+EltStride] is undef and this is the first round of mixing,
5937         // then it is safe to just drop this shuffle: V[i] is already in the
5938         // right place, the one element (since it's the first round) being
5939         // inserted as undef can be dropped.  This isn't safe for successive
5940         // rounds because they will permute elements within both vectors.
5941         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
5942             EltStride == NumElems/2)
5943           continue;
5944
5945         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
5946       }
5947       EltStride >>= 1;
5948     }
5949     return V[0];
5950   }
5951   return SDValue();
5952 }
5953
5954 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
5955 // to create 256-bit vectors from two other 128-bit ones.
5956 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5957   SDLoc dl(Op);
5958   MVT ResVT = Op.getSimpleValueType();
5959
5960   assert((ResVT.is256BitVector() ||
5961           ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
5962
5963   SDValue V1 = Op.getOperand(0);
5964   SDValue V2 = Op.getOperand(1);
5965   unsigned NumElems = ResVT.getVectorNumElements();
5966   if (ResVT.is256BitVector())
5967     return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
5968
5969   if (Op.getNumOperands() == 4) {
5970     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
5971                                 ResVT.getVectorNumElements()/2);
5972     SDValue V3 = Op.getOperand(2);
5973     SDValue V4 = Op.getOperand(3);
5974     return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
5975       Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
5976   }
5977   return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
5978 }
5979
5980 static SDValue LowerCONCAT_VECTORSvXi1(SDValue Op,
5981                                        const X86Subtarget *Subtarget,
5982                                        SelectionDAG & DAG) {
5983   SDLoc dl(Op);
5984   MVT ResVT = Op.getSimpleValueType();
5985   unsigned NumOfOperands = Op.getNumOperands();
5986
5987   assert(isPowerOf2_32(NumOfOperands) &&
5988          "Unexpected number of operands in CONCAT_VECTORS");
5989
5990   if (NumOfOperands > 2) {
5991     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
5992                                   ResVT.getVectorNumElements()/2);
5993     SmallVector<SDValue, 2> Ops;
5994     for (unsigned i = 0; i < NumOfOperands/2; i++)
5995       Ops.push_back(Op.getOperand(i));
5996     SDValue Lo = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
5997     Ops.clear();
5998     for (unsigned i = NumOfOperands/2; i < NumOfOperands; i++)
5999       Ops.push_back(Op.getOperand(i));
6000     SDValue Hi = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6001     return DAG.getNode(ISD::CONCAT_VECTORS, dl, ResVT, Lo, Hi);
6002   }
6003
6004   SDValue V1 = Op.getOperand(0);
6005   SDValue V2 = Op.getOperand(1);
6006   bool IsZeroV1 = ISD::isBuildVectorAllZeros(V1.getNode());
6007   bool IsZeroV2 = ISD::isBuildVectorAllZeros(V2.getNode());
6008
6009   if (IsZeroV1 && IsZeroV2)
6010     return getZeroVector(ResVT, Subtarget, DAG, dl);
6011
6012   SDValue ZeroIdx = DAG.getIntPtrConstant(0);
6013   SDValue Undef = DAG.getUNDEF(ResVT);
6014   unsigned NumElems = ResVT.getVectorNumElements();
6015   SDValue ShiftBits = DAG.getConstant(NumElems/2, MVT::i8);
6016
6017   V2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V2, ZeroIdx);
6018   V2 = DAG.getNode(X86ISD::VSHLI, dl, ResVT, V2, ShiftBits);
6019   if (IsZeroV1)
6020     return V2;
6021
6022   V1 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V1, ZeroIdx);
6023   // Zero the upper bits of V1
6024   V1 = DAG.getNode(X86ISD::VSHLI, dl, ResVT, V1, ShiftBits);
6025   V1 = DAG.getNode(X86ISD::VSRLI, dl, ResVT, V1, ShiftBits);
6026   if (IsZeroV2)
6027     return V1;
6028   return DAG.getNode(ISD::OR, dl, ResVT, V1, V2);
6029 }
6030
6031 static SDValue LowerCONCAT_VECTORS(SDValue Op,
6032                                    const X86Subtarget *Subtarget,
6033                                    SelectionDAG &DAG) {
6034   MVT VT = Op.getSimpleValueType();
6035   if (VT.getVectorElementType() == MVT::i1)
6036     return LowerCONCAT_VECTORSvXi1(Op, Subtarget, DAG);
6037
6038   assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6039          (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6040           Op.getNumOperands() == 4)));
6041
6042   // AVX can use the vinsertf128 instruction to create 256-bit vectors
6043   // from two other 128-bit ones.
6044
6045   // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6046   return LowerAVXCONCAT_VECTORS(Op, DAG);
6047 }
6048
6049
6050 //===----------------------------------------------------------------------===//
6051 // Vector shuffle lowering
6052 //
6053 // This is an experimental code path for lowering vector shuffles on x86. It is
6054 // designed to handle arbitrary vector shuffles and blends, gracefully
6055 // degrading performance as necessary. It works hard to recognize idiomatic
6056 // shuffles and lower them to optimal instruction patterns without leaving
6057 // a framework that allows reasonably efficient handling of all vector shuffle
6058 // patterns.
6059 //===----------------------------------------------------------------------===//
6060
6061 /// \brief Tiny helper function to identify a no-op mask.
6062 ///
6063 /// This is a somewhat boring predicate function. It checks whether the mask
6064 /// array input, which is assumed to be a single-input shuffle mask of the kind
6065 /// used by the X86 shuffle instructions (not a fully general
6066 /// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
6067 /// in-place shuffle are 'no-op's.
6068 static bool isNoopShuffleMask(ArrayRef<int> Mask) {
6069   for (int i = 0, Size = Mask.size(); i < Size; ++i)
6070     if (Mask[i] != -1 && Mask[i] != i)
6071       return false;
6072   return true;
6073 }
6074
6075 /// \brief Helper function to classify a mask as a single-input mask.
6076 ///
6077 /// This isn't a generic single-input test because in the vector shuffle
6078 /// lowering we canonicalize single inputs to be the first input operand. This
6079 /// means we can more quickly test for a single input by only checking whether
6080 /// an input from the second operand exists. We also assume that the size of
6081 /// mask corresponds to the size of the input vectors which isn't true in the
6082 /// fully general case.
6083 static bool isSingleInputShuffleMask(ArrayRef<int> Mask) {
6084   for (int M : Mask)
6085     if (M >= (int)Mask.size())
6086       return false;
6087   return true;
6088 }
6089
6090 /// \brief Test whether there are elements crossing 128-bit lanes in this
6091 /// shuffle mask.
6092 ///
6093 /// X86 divides up its shuffles into in-lane and cross-lane shuffle operations
6094 /// and we routinely test for these.
6095 static bool is128BitLaneCrossingShuffleMask(MVT VT, ArrayRef<int> Mask) {
6096   int LaneSize = 128 / VT.getScalarSizeInBits();
6097   int Size = Mask.size();
6098   for (int i = 0; i < Size; ++i)
6099     if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
6100       return true;
6101   return false;
6102 }
6103
6104 /// \brief Test whether a shuffle mask is equivalent within each 128-bit lane.
6105 ///
6106 /// This checks a shuffle mask to see if it is performing the same
6107 /// 128-bit lane-relative shuffle in each 128-bit lane. This trivially implies
6108 /// that it is also not lane-crossing. It may however involve a blend from the
6109 /// same lane of a second vector.
6110 ///
6111 /// The specific repeated shuffle mask is populated in \p RepeatedMask, as it is
6112 /// non-trivial to compute in the face of undef lanes. The representation is
6113 /// *not* suitable for use with existing 128-bit shuffles as it will contain
6114 /// entries from both V1 and V2 inputs to the wider mask.
6115 static bool
6116 is128BitLaneRepeatedShuffleMask(MVT VT, ArrayRef<int> Mask,
6117                                 SmallVectorImpl<int> &RepeatedMask) {
6118   int LaneSize = 128 / VT.getScalarSizeInBits();
6119   RepeatedMask.resize(LaneSize, -1);
6120   int Size = Mask.size();
6121   for (int i = 0; i < Size; ++i) {
6122     if (Mask[i] < 0)
6123       continue;
6124     if ((Mask[i] % Size) / LaneSize != i / LaneSize)
6125       // This entry crosses lanes, so there is no way to model this shuffle.
6126       return false;
6127
6128     // Ok, handle the in-lane shuffles by detecting if and when they repeat.
6129     if (RepeatedMask[i % LaneSize] == -1)
6130       // This is the first non-undef entry in this slot of a 128-bit lane.
6131       RepeatedMask[i % LaneSize] =
6132           Mask[i] < Size ? Mask[i] % LaneSize : Mask[i] % LaneSize + Size;
6133     else if (RepeatedMask[i % LaneSize] + (i / LaneSize) * LaneSize != Mask[i])
6134       // Found a mismatch with the repeated mask.
6135       return false;
6136   }
6137   return true;
6138 }
6139
6140 /// \brief Checks whether a shuffle mask is equivalent to an explicit list of
6141 /// arguments.
6142 ///
6143 /// This is a fast way to test a shuffle mask against a fixed pattern:
6144 ///
6145 ///   if (isShuffleEquivalent(Mask, 3, 2, {1, 0})) { ... }
6146 ///
6147 /// It returns true if the mask is exactly as wide as the argument list, and
6148 /// each element of the mask is either -1 (signifying undef) or the value given
6149 /// in the argument.
6150 static bool isShuffleEquivalent(SDValue V1, SDValue V2, ArrayRef<int> Mask,
6151                                 ArrayRef<int> ExpectedMask) {
6152   if (Mask.size() != ExpectedMask.size())
6153     return false;
6154
6155   int Size = Mask.size();
6156
6157   // If the values are build vectors, we can look through them to find
6158   // equivalent inputs that make the shuffles equivalent.
6159   auto *BV1 = dyn_cast<BuildVectorSDNode>(V1);
6160   auto *BV2 = dyn_cast<BuildVectorSDNode>(V2);
6161
6162   for (int i = 0; i < Size; ++i)
6163     if (Mask[i] != -1 && Mask[i] != ExpectedMask[i]) {
6164       auto *MaskBV = Mask[i] < Size ? BV1 : BV2;
6165       auto *ExpectedBV = ExpectedMask[i] < Size ? BV1 : BV2;
6166       if (!MaskBV || !ExpectedBV ||
6167           MaskBV->getOperand(Mask[i] % Size) !=
6168               ExpectedBV->getOperand(ExpectedMask[i] % Size))
6169         return false;
6170     }
6171
6172   return true;
6173 }
6174
6175 /// \brief Get a 4-lane 8-bit shuffle immediate for a mask.
6176 ///
6177 /// This helper function produces an 8-bit shuffle immediate corresponding to
6178 /// the ubiquitous shuffle encoding scheme used in x86 instructions for
6179 /// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
6180 /// example.
6181 ///
6182 /// NB: We rely heavily on "undef" masks preserving the input lane.
6183 static SDValue getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask,
6184                                           SelectionDAG &DAG) {
6185   assert(Mask.size() == 4 && "Only 4-lane shuffle masks");
6186   assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!");
6187   assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!");
6188   assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!");
6189   assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!");
6190
6191   unsigned Imm = 0;
6192   Imm |= (Mask[0] == -1 ? 0 : Mask[0]) << 0;
6193   Imm |= (Mask[1] == -1 ? 1 : Mask[1]) << 2;
6194   Imm |= (Mask[2] == -1 ? 2 : Mask[2]) << 4;
6195   Imm |= (Mask[3] == -1 ? 3 : Mask[3]) << 6;
6196   return DAG.getConstant(Imm, MVT::i8);
6197 }
6198
6199 /// \brief Try to emit a blend instruction for a shuffle using bit math.
6200 ///
6201 /// This is used as a fallback approach when first class blend instructions are
6202 /// unavailable. Currently it is only suitable for integer vectors, but could
6203 /// be generalized for floating point vectors if desirable.
6204 static SDValue lowerVectorShuffleAsBitBlend(SDLoc DL, MVT VT, SDValue V1,
6205                                             SDValue V2, ArrayRef<int> Mask,
6206                                             SelectionDAG &DAG) {
6207   assert(VT.isInteger() && "Only supports integer vector types!");
6208   MVT EltVT = VT.getScalarType();
6209   int NumEltBits = EltVT.getSizeInBits();
6210   SDValue Zero = DAG.getConstant(0, EltVT);
6211   SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), EltVT);
6212   SmallVector<SDValue, 16> MaskOps;
6213   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6214     if (Mask[i] != -1 && Mask[i] != i && Mask[i] != i + Size)
6215       return SDValue(); // Shuffled input!
6216     MaskOps.push_back(Mask[i] < Size ? AllOnes : Zero);
6217   }
6218
6219   SDValue V1Mask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, MaskOps);
6220   V1 = DAG.getNode(ISD::AND, DL, VT, V1, V1Mask);
6221   // We have to cast V2 around.
6222   MVT MaskVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
6223   V2 = DAG.getNode(ISD::BITCAST, DL, VT,
6224                    DAG.getNode(X86ISD::ANDNP, DL, MaskVT,
6225                                DAG.getNode(ISD::BITCAST, DL, MaskVT, V1Mask),
6226                                DAG.getNode(ISD::BITCAST, DL, MaskVT, V2)));
6227   return DAG.getNode(ISD::OR, DL, VT, V1, V2);
6228 }
6229
6230 /// \brief Try to emit a blend instruction for a shuffle.
6231 ///
6232 /// This doesn't do any checks for the availability of instructions for blending
6233 /// these values. It relies on the availability of the X86ISD::BLENDI pattern to
6234 /// be matched in the backend with the type given. What it does check for is
6235 /// that the shuffle mask is in fact a blend.
6236 static SDValue lowerVectorShuffleAsBlend(SDLoc DL, MVT VT, SDValue V1,
6237                                          SDValue V2, ArrayRef<int> Mask,
6238                                          const X86Subtarget *Subtarget,
6239                                          SelectionDAG &DAG) {
6240   unsigned BlendMask = 0;
6241   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6242     if (Mask[i] >= Size) {
6243       if (Mask[i] != i + Size)
6244         return SDValue(); // Shuffled V2 input!
6245       BlendMask |= 1u << i;
6246       continue;
6247     }
6248     if (Mask[i] >= 0 && Mask[i] != i)
6249       return SDValue(); // Shuffled V1 input!
6250   }
6251   switch (VT.SimpleTy) {
6252   case MVT::v2f64:
6253   case MVT::v4f32:
6254   case MVT::v4f64:
6255   case MVT::v8f32:
6256     return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V2,
6257                        DAG.getConstant(BlendMask, MVT::i8));
6258
6259   case MVT::v4i64:
6260   case MVT::v8i32:
6261     assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6262     // FALLTHROUGH
6263   case MVT::v2i64:
6264   case MVT::v4i32:
6265     // If we have AVX2 it is faster to use VPBLENDD when the shuffle fits into
6266     // that instruction.
6267     if (Subtarget->hasAVX2()) {
6268       // Scale the blend by the number of 32-bit dwords per element.
6269       int Scale =  VT.getScalarSizeInBits() / 32;
6270       BlendMask = 0;
6271       for (int i = 0, Size = Mask.size(); i < Size; ++i)
6272         if (Mask[i] >= Size)
6273           for (int j = 0; j < Scale; ++j)
6274             BlendMask |= 1u << (i * Scale + j);
6275
6276       MVT BlendVT = VT.getSizeInBits() > 128 ? MVT::v8i32 : MVT::v4i32;
6277       V1 = DAG.getNode(ISD::BITCAST, DL, BlendVT, V1);
6278       V2 = DAG.getNode(ISD::BITCAST, DL, BlendVT, V2);
6279       return DAG.getNode(ISD::BITCAST, DL, VT,
6280                          DAG.getNode(X86ISD::BLENDI, DL, BlendVT, V1, V2,
6281                                      DAG.getConstant(BlendMask, MVT::i8)));
6282     }
6283     // FALLTHROUGH
6284   case MVT::v8i16: {
6285     // For integer shuffles we need to expand the mask and cast the inputs to
6286     // v8i16s prior to blending.
6287     int Scale = 8 / VT.getVectorNumElements();
6288     BlendMask = 0;
6289     for (int i = 0, Size = Mask.size(); i < Size; ++i)
6290       if (Mask[i] >= Size)
6291         for (int j = 0; j < Scale; ++j)
6292           BlendMask |= 1u << (i * Scale + j);
6293
6294     V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1);
6295     V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V2);
6296     return DAG.getNode(ISD::BITCAST, DL, VT,
6297                        DAG.getNode(X86ISD::BLENDI, DL, MVT::v8i16, V1, V2,
6298                                    DAG.getConstant(BlendMask, MVT::i8)));
6299   }
6300
6301   case MVT::v16i16: {
6302     assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6303     SmallVector<int, 8> RepeatedMask;
6304     if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
6305       // We can lower these with PBLENDW which is mirrored across 128-bit lanes.
6306       assert(RepeatedMask.size() == 8 && "Repeated mask size doesn't match!");
6307       BlendMask = 0;
6308       for (int i = 0; i < 8; ++i)
6309         if (RepeatedMask[i] >= 16)
6310           BlendMask |= 1u << i;
6311       return DAG.getNode(X86ISD::BLENDI, DL, MVT::v16i16, V1, V2,
6312                          DAG.getConstant(BlendMask, MVT::i8));
6313     }
6314   }
6315     // FALLTHROUGH
6316   case MVT::v16i8:
6317   case MVT::v32i8: {
6318     assert((VT.getSizeInBits() == 128 || Subtarget->hasAVX2()) &&
6319            "256-bit byte-blends require AVX2 support!");
6320
6321     // Scale the blend by the number of bytes per element.
6322     int Scale = VT.getScalarSizeInBits() / 8;
6323
6324     // This form of blend is always done on bytes. Compute the byte vector
6325     // type.
6326     MVT BlendVT = MVT::getVectorVT(MVT::i8, VT.getSizeInBits() / 8);
6327
6328     // Compute the VSELECT mask. Note that VSELECT is really confusing in the
6329     // mix of LLVM's code generator and the x86 backend. We tell the code
6330     // generator that boolean values in the elements of an x86 vector register
6331     // are -1 for true and 0 for false. We then use the LLVM semantics of 'true'
6332     // mapping a select to operand #1, and 'false' mapping to operand #2. The
6333     // reality in x86 is that vector masks (pre-AVX-512) use only the high bit
6334     // of the element (the remaining are ignored) and 0 in that high bit would
6335     // mean operand #1 while 1 in the high bit would mean operand #2. So while
6336     // the LLVM model for boolean values in vector elements gets the relevant
6337     // bit set, it is set backwards and over constrained relative to x86's
6338     // actual model.
6339     SmallVector<SDValue, 32> VSELECTMask;
6340     for (int i = 0, Size = Mask.size(); i < Size; ++i)
6341       for (int j = 0; j < Scale; ++j)
6342         VSELECTMask.push_back(
6343             Mask[i] < 0 ? DAG.getUNDEF(MVT::i8)
6344                         : DAG.getConstant(Mask[i] < Size ? -1 : 0, MVT::i8));
6345
6346     V1 = DAG.getNode(ISD::BITCAST, DL, BlendVT, V1);
6347     V2 = DAG.getNode(ISD::BITCAST, DL, BlendVT, V2);
6348     return DAG.getNode(
6349         ISD::BITCAST, DL, VT,
6350         DAG.getNode(ISD::VSELECT, DL, BlendVT,
6351                     DAG.getNode(ISD::BUILD_VECTOR, DL, BlendVT, VSELECTMask),
6352                     V1, V2));
6353   }
6354
6355   default:
6356     llvm_unreachable("Not a supported integer vector type!");
6357   }
6358 }
6359
6360 /// \brief Try to lower as a blend of elements from two inputs followed by
6361 /// a single-input permutation.
6362 ///
6363 /// This matches the pattern where we can blend elements from two inputs and
6364 /// then reduce the shuffle to a single-input permutation.
6365 static SDValue lowerVectorShuffleAsBlendAndPermute(SDLoc DL, MVT VT, SDValue V1,
6366                                                    SDValue V2,
6367                                                    ArrayRef<int> Mask,
6368                                                    SelectionDAG &DAG) {
6369   // We build up the blend mask while checking whether a blend is a viable way
6370   // to reduce the shuffle.
6371   SmallVector<int, 32> BlendMask(Mask.size(), -1);
6372   SmallVector<int, 32> PermuteMask(Mask.size(), -1);
6373
6374   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6375     if (Mask[i] < 0)
6376       continue;
6377
6378     assert(Mask[i] < Size * 2 && "Shuffle input is out of bounds.");
6379
6380     if (BlendMask[Mask[i] % Size] == -1)
6381       BlendMask[Mask[i] % Size] = Mask[i];
6382     else if (BlendMask[Mask[i] % Size] != Mask[i])
6383       return SDValue(); // Can't blend in the needed input!
6384
6385     PermuteMask[i] = Mask[i] % Size;
6386   }
6387
6388   SDValue V = DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
6389   return DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), PermuteMask);
6390 }
6391
6392 /// \brief Generic routine to decompose a shuffle and blend into indepndent
6393 /// blends and permutes.
6394 ///
6395 /// This matches the extremely common pattern for handling combined
6396 /// shuffle+blend operations on newer X86 ISAs where we have very fast blend
6397 /// operations. It will try to pick the best arrangement of shuffles and
6398 /// blends.
6399 static SDValue lowerVectorShuffleAsDecomposedShuffleBlend(SDLoc DL, MVT VT,
6400                                                           SDValue V1,
6401                                                           SDValue V2,
6402                                                           ArrayRef<int> Mask,
6403                                                           SelectionDAG &DAG) {
6404   // Shuffle the input elements into the desired positions in V1 and V2 and
6405   // blend them together.
6406   SmallVector<int, 32> V1Mask(Mask.size(), -1);
6407   SmallVector<int, 32> V2Mask(Mask.size(), -1);
6408   SmallVector<int, 32> BlendMask(Mask.size(), -1);
6409   for (int i = 0, Size = Mask.size(); i < Size; ++i)
6410     if (Mask[i] >= 0 && Mask[i] < Size) {
6411       V1Mask[i] = Mask[i];
6412       BlendMask[i] = i;
6413     } else if (Mask[i] >= Size) {
6414       V2Mask[i] = Mask[i] - Size;
6415       BlendMask[i] = i + Size;
6416     }
6417
6418   // Try to lower with the simpler initial blend strategy unless one of the
6419   // input shuffles would be a no-op. We prefer to shuffle inputs as the
6420   // shuffle may be able to fold with a load or other benefit. However, when
6421   // we'll have to do 2x as many shuffles in order to achieve this, blending
6422   // first is a better strategy.
6423   if (!isNoopShuffleMask(V1Mask) && !isNoopShuffleMask(V2Mask))
6424     if (SDValue BlendPerm =
6425             lowerVectorShuffleAsBlendAndPermute(DL, VT, V1, V2, Mask, DAG))
6426       return BlendPerm;
6427
6428   V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
6429   V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
6430   return DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
6431 }
6432
6433 /// \brief Try to lower a vector shuffle as a byte rotation.
6434 ///
6435 /// SSSE3 has a generic PALIGNR instruction in x86 that will do an arbitrary
6436 /// byte-rotation of the concatenation of two vectors; pre-SSSE3 can use
6437 /// a PSRLDQ/PSLLDQ/POR pattern to get a similar effect. This routine will
6438 /// try to generically lower a vector shuffle through such an pattern. It
6439 /// does not check for the profitability of lowering either as PALIGNR or
6440 /// PSRLDQ/PSLLDQ/POR, only whether the mask is valid to lower in that form.
6441 /// This matches shuffle vectors that look like:
6442 ///
6443 ///   v8i16 [11, 12, 13, 14, 15, 0, 1, 2]
6444 ///
6445 /// Essentially it concatenates V1 and V2, shifts right by some number of
6446 /// elements, and takes the low elements as the result. Note that while this is
6447 /// specified as a *right shift* because x86 is little-endian, it is a *left
6448 /// rotate* of the vector lanes.
6449 static SDValue lowerVectorShuffleAsByteRotate(SDLoc DL, MVT VT, SDValue V1,
6450                                               SDValue V2,
6451                                               ArrayRef<int> Mask,
6452                                               const X86Subtarget *Subtarget,
6453                                               SelectionDAG &DAG) {
6454   assert(!isNoopShuffleMask(Mask) && "We shouldn't lower no-op shuffles!");
6455
6456   int NumElts = Mask.size();
6457   int NumLanes = VT.getSizeInBits() / 128;
6458   int NumLaneElts = NumElts / NumLanes;
6459
6460   // We need to detect various ways of spelling a rotation:
6461   //   [11, 12, 13, 14, 15,  0,  1,  2]
6462   //   [-1, 12, 13, 14, -1, -1,  1, -1]
6463   //   [-1, -1, -1, -1, -1, -1,  1,  2]
6464   //   [ 3,  4,  5,  6,  7,  8,  9, 10]
6465   //   [-1,  4,  5,  6, -1, -1,  9, -1]
6466   //   [-1,  4,  5,  6, -1, -1, -1, -1]
6467   int Rotation = 0;
6468   SDValue Lo, Hi;
6469   for (int l = 0; l < NumElts; l += NumLaneElts) {
6470     for (int i = 0; i < NumLaneElts; ++i) {
6471       if (Mask[l + i] == -1)
6472         continue;
6473       assert(Mask[l + i] >= 0 && "Only -1 is a valid negative mask element!");
6474
6475       // Get the mod-Size index and lane correct it.
6476       int LaneIdx = (Mask[l + i] % NumElts) - l;
6477       // Make sure it was in this lane.
6478       if (LaneIdx < 0 || LaneIdx >= NumLaneElts)
6479         return SDValue();
6480
6481       // Determine where a rotated vector would have started.
6482       int StartIdx = i - LaneIdx;
6483       if (StartIdx == 0)
6484         // The identity rotation isn't interesting, stop.
6485         return SDValue();
6486
6487       // If we found the tail of a vector the rotation must be the missing
6488       // front. If we found the head of a vector, it must be how much of the
6489       // head.
6490       int CandidateRotation = StartIdx < 0 ? -StartIdx : NumLaneElts - StartIdx;
6491
6492       if (Rotation == 0)
6493         Rotation = CandidateRotation;
6494       else if (Rotation != CandidateRotation)
6495         // The rotations don't match, so we can't match this mask.
6496         return SDValue();
6497
6498       // Compute which value this mask is pointing at.
6499       SDValue MaskV = Mask[l + i] < NumElts ? V1 : V2;
6500
6501       // Compute which of the two target values this index should be assigned
6502       // to. This reflects whether the high elements are remaining or the low
6503       // elements are remaining.
6504       SDValue &TargetV = StartIdx < 0 ? Hi : Lo;
6505
6506       // Either set up this value if we've not encountered it before, or check
6507       // that it remains consistent.
6508       if (!TargetV)
6509         TargetV = MaskV;
6510       else if (TargetV != MaskV)
6511         // This may be a rotation, but it pulls from the inputs in some
6512         // unsupported interleaving.
6513         return SDValue();
6514     }
6515   }
6516
6517   // Check that we successfully analyzed the mask, and normalize the results.
6518   assert(Rotation != 0 && "Failed to locate a viable rotation!");
6519   assert((Lo || Hi) && "Failed to find a rotated input vector!");
6520   if (!Lo)
6521     Lo = Hi;
6522   else if (!Hi)
6523     Hi = Lo;
6524
6525   // The actual rotate instruction rotates bytes, so we need to scale the
6526   // rotation based on how many bytes are in the vector lane.
6527   int Scale = 16 / NumLaneElts;
6528
6529   // SSSE3 targets can use the palignr instruction.
6530   if (Subtarget->hasSSSE3()) {
6531     // Cast the inputs to i8 vector of correct length to match PALIGNR.
6532     MVT AlignVT = MVT::getVectorVT(MVT::i8, 16 * NumLanes);
6533     Lo = DAG.getNode(ISD::BITCAST, DL, AlignVT, Lo);
6534     Hi = DAG.getNode(ISD::BITCAST, DL, AlignVT, Hi);
6535
6536     return DAG.getNode(ISD::BITCAST, DL, VT,
6537                        DAG.getNode(X86ISD::PALIGNR, DL, AlignVT, Hi, Lo,
6538                                    DAG.getConstant(Rotation * Scale, MVT::i8)));
6539   }
6540
6541   assert(VT.getSizeInBits() == 128 &&
6542          "Rotate-based lowering only supports 128-bit lowering!");
6543   assert(Mask.size() <= 16 &&
6544          "Can shuffle at most 16 bytes in a 128-bit vector!");
6545
6546   // Default SSE2 implementation
6547   int LoByteShift = 16 - Rotation * Scale;
6548   int HiByteShift = Rotation * Scale;
6549
6550   // Cast the inputs to v2i64 to match PSLLDQ/PSRLDQ.
6551   Lo = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Lo);
6552   Hi = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Hi);
6553
6554   SDValue LoShift = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v2i64, Lo,
6555                                 DAG.getConstant(LoByteShift, MVT::i8));
6556   SDValue HiShift = DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v2i64, Hi,
6557                                 DAG.getConstant(HiByteShift, MVT::i8));
6558   return DAG.getNode(ISD::BITCAST, DL, VT,
6559                      DAG.getNode(ISD::OR, DL, MVT::v2i64, LoShift, HiShift));
6560 }
6561
6562 /// \brief Compute whether each element of a shuffle is zeroable.
6563 ///
6564 /// A "zeroable" vector shuffle element is one which can be lowered to zero.
6565 /// Either it is an undef element in the shuffle mask, the element of the input
6566 /// referenced is undef, or the element of the input referenced is known to be
6567 /// zero. Many x86 shuffles can zero lanes cheaply and we often want to handle
6568 /// as many lanes with this technique as possible to simplify the remaining
6569 /// shuffle.
6570 static SmallBitVector computeZeroableShuffleElements(ArrayRef<int> Mask,
6571                                                      SDValue V1, SDValue V2) {
6572   SmallBitVector Zeroable(Mask.size(), false);
6573
6574   while (V1.getOpcode() == ISD::BITCAST)
6575     V1 = V1->getOperand(0);
6576   while (V2.getOpcode() == ISD::BITCAST)
6577     V2 = V2->getOperand(0);
6578
6579   bool V1IsZero = ISD::isBuildVectorAllZeros(V1.getNode());
6580   bool V2IsZero = ISD::isBuildVectorAllZeros(V2.getNode());
6581
6582   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6583     int M = Mask[i];
6584     // Handle the easy cases.
6585     if (M < 0 || (M >= 0 && M < Size && V1IsZero) || (M >= Size && V2IsZero)) {
6586       Zeroable[i] = true;
6587       continue;
6588     }
6589
6590     // If this is an index into a build_vector node (which has the same number
6591     // of elements), dig out the input value and use it.
6592     SDValue V = M < Size ? V1 : V2;
6593     if (V.getOpcode() != ISD::BUILD_VECTOR || Size != (int)V.getNumOperands())
6594       continue;
6595
6596     SDValue Input = V.getOperand(M % Size);
6597     // The UNDEF opcode check really should be dead code here, but not quite
6598     // worth asserting on (it isn't invalid, just unexpected).
6599     if (Input.getOpcode() == ISD::UNDEF || X86::isZeroNode(Input))
6600       Zeroable[i] = true;
6601   }
6602
6603   return Zeroable;
6604 }
6605
6606 /// \brief Try to emit a bitmask instruction for a shuffle.
6607 ///
6608 /// This handles cases where we can model a blend exactly as a bitmask due to
6609 /// one of the inputs being zeroable.
6610 static SDValue lowerVectorShuffleAsBitMask(SDLoc DL, MVT VT, SDValue V1,
6611                                            SDValue V2, ArrayRef<int> Mask,
6612                                            SelectionDAG &DAG) {
6613   MVT EltVT = VT.getScalarType();
6614   int NumEltBits = EltVT.getSizeInBits();
6615   MVT IntEltVT = MVT::getIntegerVT(NumEltBits);
6616   SDValue Zero = DAG.getConstant(0, IntEltVT);
6617   SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), IntEltVT);
6618   if (EltVT.isFloatingPoint()) {
6619     Zero = DAG.getNode(ISD::BITCAST, DL, EltVT, Zero);
6620     AllOnes = DAG.getNode(ISD::BITCAST, DL, EltVT, AllOnes);
6621   }
6622   SmallVector<SDValue, 16> VMaskOps(Mask.size(), Zero);
6623   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6624   SDValue V;
6625   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6626     if (Zeroable[i])
6627       continue;
6628     if (Mask[i] % Size != i)
6629       return SDValue(); // Not a blend.
6630     if (!V)
6631       V = Mask[i] < Size ? V1 : V2;
6632     else if (V != (Mask[i] < Size ? V1 : V2))
6633       return SDValue(); // Can only let one input through the mask.
6634
6635     VMaskOps[i] = AllOnes;
6636   }
6637   if (!V)
6638     return SDValue(); // No non-zeroable elements!
6639
6640   SDValue VMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, VMaskOps);
6641   V = DAG.getNode(VT.isFloatingPoint()
6642                   ? (unsigned) X86ISD::FAND : (unsigned) ISD::AND,
6643                   DL, VT, V, VMask);
6644   return V;
6645 }
6646
6647 /// \brief Try to lower a vector shuffle as a bit shift (shifts in zeros).
6648 ///
6649 /// Attempts to match a shuffle mask against the PSLL(W/D/Q/DQ) and
6650 /// PSRL(W/D/Q/DQ) SSE2 and AVX2 logical bit-shift instructions. The function
6651 /// matches elements from one of the input vectors shuffled to the left or
6652 /// right with zeroable elements 'shifted in'. It handles both the strictly
6653 /// bit-wise element shifts and the byte shift across an entire 128-bit double
6654 /// quad word lane.
6655 ///
6656 /// PSHL : (little-endian) left bit shift.
6657 /// [ zz, 0, zz,  2 ]
6658 /// [ -1, 4, zz, -1 ]
6659 /// PSRL : (little-endian) right bit shift.
6660 /// [  1, zz,  3, zz]
6661 /// [ -1, -1,  7, zz]
6662 /// PSLLDQ : (little-endian) left byte shift
6663 /// [ zz,  0,  1,  2,  3,  4,  5,  6]
6664 /// [ zz, zz, -1, -1,  2,  3,  4, -1]
6665 /// [ zz, zz, zz, zz, zz, zz, -1,  1]
6666 /// PSRLDQ : (little-endian) right byte shift
6667 /// [  5, 6,  7, zz, zz, zz, zz, zz]
6668 /// [ -1, 5,  6,  7, zz, zz, zz, zz]
6669 /// [  1, 2, -1, -1, -1, -1, zz, zz]
6670 static SDValue lowerVectorShuffleAsShift(SDLoc DL, MVT VT, SDValue V1,
6671                                          SDValue V2, ArrayRef<int> Mask,
6672                                          SelectionDAG &DAG) {
6673   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6674
6675   int Size = Mask.size();
6676   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
6677
6678   auto CheckZeros = [&](int Shift, int Scale, bool Left) {
6679     for (int i = 0; i < Size; i += Scale)
6680       for (int j = 0; j < Shift; ++j)
6681         if (!Zeroable[i + j + (Left ? 0 : (Scale - Shift))])
6682           return false;
6683
6684     return true;
6685   };
6686
6687   auto MatchShift = [&](int Shift, int Scale, bool Left, SDValue V) {
6688     for (int i = 0; i != Size; i += Scale) {
6689       unsigned Pos = Left ? i + Shift : i;
6690       unsigned Low = Left ? i : i + Shift;
6691       unsigned Len = Scale - Shift;
6692       if (!isSequentialOrUndefInRange(Mask, Pos, Len,
6693                                       Low + (V == V1 ? 0 : Size)))
6694         return SDValue();
6695     }
6696
6697     int ShiftEltBits = VT.getScalarSizeInBits() * Scale;
6698     bool ByteShift = ShiftEltBits > 64;
6699     unsigned OpCode = Left ? (ByteShift ? X86ISD::VSHLDQ : X86ISD::VSHLI)
6700                            : (ByteShift ? X86ISD::VSRLDQ : X86ISD::VSRLI);
6701     int ShiftAmt = Shift * VT.getScalarSizeInBits() / (ByteShift ? 8 : 1);
6702
6703     // Normalize the scale for byte shifts to still produce an i64 element
6704     // type.
6705     Scale = ByteShift ? Scale / 2 : Scale;
6706
6707     // We need to round trip through the appropriate type for the shift.
6708     MVT ShiftSVT = MVT::getIntegerVT(VT.getScalarSizeInBits() * Scale);
6709     MVT ShiftVT = MVT::getVectorVT(ShiftSVT, Size / Scale);
6710     assert(DAG.getTargetLoweringInfo().isTypeLegal(ShiftVT) &&
6711            "Illegal integer vector type");
6712     V = DAG.getNode(ISD::BITCAST, DL, ShiftVT, V);
6713
6714     V = DAG.getNode(OpCode, DL, ShiftVT, V, DAG.getConstant(ShiftAmt, MVT::i8));
6715     return DAG.getNode(ISD::BITCAST, DL, VT, V);
6716   };
6717
6718   // SSE/AVX supports logical shifts up to 64-bit integers - so we can just
6719   // keep doubling the size of the integer elements up to that. We can
6720   // then shift the elements of the integer vector by whole multiples of
6721   // their width within the elements of the larger integer vector. Test each
6722   // multiple to see if we can find a match with the moved element indices
6723   // and that the shifted in elements are all zeroable.
6724   for (int Scale = 2; Scale * VT.getScalarSizeInBits() <= 128; Scale *= 2)
6725     for (int Shift = 1; Shift != Scale; ++Shift)
6726       for (bool Left : {true, false})
6727         if (CheckZeros(Shift, Scale, Left))
6728           for (SDValue V : {V1, V2})
6729             if (SDValue Match = MatchShift(Shift, Scale, Left, V))
6730               return Match;
6731
6732   // no match
6733   return SDValue();
6734 }
6735
6736 /// \brief Lower a vector shuffle as a zero or any extension.
6737 ///
6738 /// Given a specific number of elements, element bit width, and extension
6739 /// stride, produce either a zero or any extension based on the available
6740 /// features of the subtarget.
6741 static SDValue lowerVectorShuffleAsSpecificZeroOrAnyExtend(
6742     SDLoc DL, MVT VT, int Scale, bool AnyExt, SDValue InputV,
6743     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
6744   assert(Scale > 1 && "Need a scale to extend.");
6745   int NumElements = VT.getVectorNumElements();
6746   int EltBits = VT.getScalarSizeInBits();
6747   assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
6748          "Only 8, 16, and 32 bit elements can be extended.");
6749   assert(Scale * EltBits <= 64 && "Cannot zero extend past 64 bits.");
6750
6751   // Found a valid zext mask! Try various lowering strategies based on the
6752   // input type and available ISA extensions.
6753   if (Subtarget->hasSSE41()) {
6754     MVT ExtVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits * Scale),
6755                                  NumElements / Scale);
6756     return DAG.getNode(ISD::BITCAST, DL, VT,
6757                        DAG.getNode(X86ISD::VZEXT, DL, ExtVT, InputV));
6758   }
6759
6760   // For any extends we can cheat for larger element sizes and use shuffle
6761   // instructions that can fold with a load and/or copy.
6762   if (AnyExt && EltBits == 32) {
6763     int PSHUFDMask[4] = {0, -1, 1, -1};
6764     return DAG.getNode(
6765         ISD::BITCAST, DL, VT,
6766         DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
6767                     DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, InputV),
6768                     getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
6769   }
6770   if (AnyExt && EltBits == 16 && Scale > 2) {
6771     int PSHUFDMask[4] = {0, -1, 0, -1};
6772     InputV = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
6773                          DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, InputV),
6774                          getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG));
6775     int PSHUFHWMask[4] = {1, -1, -1, -1};
6776     return DAG.getNode(
6777         ISD::BITCAST, DL, VT,
6778         DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16,
6779                     DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, InputV),
6780                     getV4X86ShuffleImm8ForMask(PSHUFHWMask, DAG)));
6781   }
6782
6783   // If this would require more than 2 unpack instructions to expand, use
6784   // pshufb when available. We can only use more than 2 unpack instructions
6785   // when zero extending i8 elements which also makes it easier to use pshufb.
6786   if (Scale > 4 && EltBits == 8 && Subtarget->hasSSSE3()) {
6787     assert(NumElements == 16 && "Unexpected byte vector width!");
6788     SDValue PSHUFBMask[16];
6789     for (int i = 0; i < 16; ++i)
6790       PSHUFBMask[i] =
6791           DAG.getConstant((i % Scale == 0) ? i / Scale : 0x80, MVT::i8);
6792     InputV = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, InputV);
6793     return DAG.getNode(ISD::BITCAST, DL, VT,
6794                        DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, InputV,
6795                                    DAG.getNode(ISD::BUILD_VECTOR, DL,
6796                                                MVT::v16i8, PSHUFBMask)));
6797   }
6798
6799   // Otherwise emit a sequence of unpacks.
6800   do {
6801     MVT InputVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits), NumElements);
6802     SDValue Ext = AnyExt ? DAG.getUNDEF(InputVT)
6803                          : getZeroVector(InputVT, Subtarget, DAG, DL);
6804     InputV = DAG.getNode(ISD::BITCAST, DL, InputVT, InputV);
6805     InputV = DAG.getNode(X86ISD::UNPCKL, DL, InputVT, InputV, Ext);
6806     Scale /= 2;
6807     EltBits *= 2;
6808     NumElements /= 2;
6809   } while (Scale > 1);
6810   return DAG.getNode(ISD::BITCAST, DL, VT, InputV);
6811 }
6812
6813 /// \brief Try to lower a vector shuffle as a zero extension on any microarch.
6814 ///
6815 /// This routine will try to do everything in its power to cleverly lower
6816 /// a shuffle which happens to match the pattern of a zero extend. It doesn't
6817 /// check for the profitability of this lowering,  it tries to aggressively
6818 /// match this pattern. It will use all of the micro-architectural details it
6819 /// can to emit an efficient lowering. It handles both blends with all-zero
6820 /// inputs to explicitly zero-extend and undef-lanes (sometimes undef due to
6821 /// masking out later).
6822 ///
6823 /// The reason we have dedicated lowering for zext-style shuffles is that they
6824 /// are both incredibly common and often quite performance sensitive.
6825 static SDValue lowerVectorShuffleAsZeroOrAnyExtend(
6826     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
6827     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
6828   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6829
6830   int Bits = VT.getSizeInBits();
6831   int NumElements = VT.getVectorNumElements();
6832   assert(VT.getScalarSizeInBits() <= 32 &&
6833          "Exceeds 32-bit integer zero extension limit");
6834   assert((int)Mask.size() == NumElements && "Unexpected shuffle mask size");
6835
6836   // Define a helper function to check a particular ext-scale and lower to it if
6837   // valid.
6838   auto Lower = [&](int Scale) -> SDValue {
6839     SDValue InputV;
6840     bool AnyExt = true;
6841     for (int i = 0; i < NumElements; ++i) {
6842       if (Mask[i] == -1)
6843         continue; // Valid anywhere but doesn't tell us anything.
6844       if (i % Scale != 0) {
6845         // Each of the extended elements need to be zeroable.
6846         if (!Zeroable[i])
6847           return SDValue();
6848
6849         // We no longer are in the anyext case.
6850         AnyExt = false;
6851         continue;
6852       }
6853
6854       // Each of the base elements needs to be consecutive indices into the
6855       // same input vector.
6856       SDValue V = Mask[i] < NumElements ? V1 : V2;
6857       if (!InputV)
6858         InputV = V;
6859       else if (InputV != V)
6860         return SDValue(); // Flip-flopping inputs.
6861
6862       if (Mask[i] % NumElements != i / Scale)
6863         return SDValue(); // Non-consecutive strided elements.
6864     }
6865
6866     // If we fail to find an input, we have a zero-shuffle which should always
6867     // have already been handled.
6868     // FIXME: Maybe handle this here in case during blending we end up with one?
6869     if (!InputV)
6870       return SDValue();
6871
6872     return lowerVectorShuffleAsSpecificZeroOrAnyExtend(
6873         DL, VT, Scale, AnyExt, InputV, Subtarget, DAG);
6874   };
6875
6876   // The widest scale possible for extending is to a 64-bit integer.
6877   assert(Bits % 64 == 0 &&
6878          "The number of bits in a vector must be divisible by 64 on x86!");
6879   int NumExtElements = Bits / 64;
6880
6881   // Each iteration, try extending the elements half as much, but into twice as
6882   // many elements.
6883   for (; NumExtElements < NumElements; NumExtElements *= 2) {
6884     assert(NumElements % NumExtElements == 0 &&
6885            "The input vector size must be divisible by the extended size.");
6886     if (SDValue V = Lower(NumElements / NumExtElements))
6887       return V;
6888   }
6889
6890   // General extends failed, but 128-bit vectors may be able to use MOVQ.
6891   if (Bits != 128)
6892     return SDValue();
6893
6894   // Returns one of the source operands if the shuffle can be reduced to a
6895   // MOVQ, copying the lower 64-bits and zero-extending to the upper 64-bits.
6896   auto CanZExtLowHalf = [&]() {
6897     for (int i = NumElements / 2; i != NumElements; ++i)
6898       if (!Zeroable[i])
6899         return SDValue();
6900     if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, 0))
6901       return V1;
6902     if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, NumElements))
6903       return V2;
6904     return SDValue();
6905   };
6906
6907   if (SDValue V = CanZExtLowHalf()) {
6908     V = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, V);
6909     V = DAG.getNode(X86ISD::VZEXT_MOVL, DL, MVT::v2i64, V);
6910     return DAG.getNode(ISD::BITCAST, DL, VT, V);
6911   }
6912
6913   // No viable ext lowering found.
6914   return SDValue();
6915 }
6916
6917 /// \brief Try to get a scalar value for a specific element of a vector.
6918 ///
6919 /// Looks through BUILD_VECTOR and SCALAR_TO_VECTOR nodes to find a scalar.
6920 static SDValue getScalarValueForVectorElement(SDValue V, int Idx,
6921                                               SelectionDAG &DAG) {
6922   MVT VT = V.getSimpleValueType();
6923   MVT EltVT = VT.getVectorElementType();
6924   while (V.getOpcode() == ISD::BITCAST)
6925     V = V.getOperand(0);
6926   // If the bitcasts shift the element size, we can't extract an equivalent
6927   // element from it.
6928   MVT NewVT = V.getSimpleValueType();
6929   if (!NewVT.isVector() || NewVT.getScalarSizeInBits() != VT.getScalarSizeInBits())
6930     return SDValue();
6931
6932   if (V.getOpcode() == ISD::BUILD_VECTOR ||
6933       (Idx == 0 && V.getOpcode() == ISD::SCALAR_TO_VECTOR)) {
6934     // Ensure the scalar operand is the same size as the destination.
6935     // FIXME: Add support for scalar truncation where possible.
6936     SDValue S = V.getOperand(Idx);
6937     if (EltVT.getSizeInBits() == S.getSimpleValueType().getSizeInBits())
6938       return DAG.getNode(ISD::BITCAST, SDLoc(V), EltVT, S);
6939   }
6940
6941   return SDValue();
6942 }
6943
6944 /// \brief Helper to test for a load that can be folded with x86 shuffles.
6945 ///
6946 /// This is particularly important because the set of instructions varies
6947 /// significantly based on whether the operand is a load or not.
6948 static bool isShuffleFoldableLoad(SDValue V) {
6949   while (V.getOpcode() == ISD::BITCAST)
6950     V = V.getOperand(0);
6951
6952   return ISD::isNON_EXTLoad(V.getNode());
6953 }
6954
6955 /// \brief Try to lower insertion of a single element into a zero vector.
6956 ///
6957 /// This is a common pattern that we have especially efficient patterns to lower
6958 /// across all subtarget feature sets.
6959 static SDValue lowerVectorShuffleAsElementInsertion(
6960     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
6961     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
6962   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6963   MVT ExtVT = VT;
6964   MVT EltVT = VT.getVectorElementType();
6965
6966   int V2Index = std::find_if(Mask.begin(), Mask.end(),
6967                              [&Mask](int M) { return M >= (int)Mask.size(); }) -
6968                 Mask.begin();
6969   bool IsV1Zeroable = true;
6970   for (int i = 0, Size = Mask.size(); i < Size; ++i)
6971     if (i != V2Index && !Zeroable[i]) {
6972       IsV1Zeroable = false;
6973       break;
6974     }
6975
6976   // Check for a single input from a SCALAR_TO_VECTOR node.
6977   // FIXME: All of this should be canonicalized into INSERT_VECTOR_ELT and
6978   // all the smarts here sunk into that routine. However, the current
6979   // lowering of BUILD_VECTOR makes that nearly impossible until the old
6980   // vector shuffle lowering is dead.
6981   if (SDValue V2S = getScalarValueForVectorElement(
6982           V2, Mask[V2Index] - Mask.size(), DAG)) {
6983     // We need to zext the scalar if it is smaller than an i32.
6984     V2S = DAG.getNode(ISD::BITCAST, DL, EltVT, V2S);
6985     if (EltVT == MVT::i8 || EltVT == MVT::i16) {
6986       // Using zext to expand a narrow element won't work for non-zero
6987       // insertions.
6988       if (!IsV1Zeroable)
6989         return SDValue();
6990
6991       // Zero-extend directly to i32.
6992       ExtVT = MVT::v4i32;
6993       V2S = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, V2S);
6994     }
6995     V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, ExtVT, V2S);
6996   } else if (Mask[V2Index] != (int)Mask.size() || EltVT == MVT::i8 ||
6997              EltVT == MVT::i16) {
6998     // Either not inserting from the low element of the input or the input
6999     // element size is too small to use VZEXT_MOVL to clear the high bits.
7000     return SDValue();
7001   }
7002
7003   if (!IsV1Zeroable) {
7004     // If V1 can't be treated as a zero vector we have fewer options to lower
7005     // this. We can't support integer vectors or non-zero targets cheaply, and
7006     // the V1 elements can't be permuted in any way.
7007     assert(VT == ExtVT && "Cannot change extended type when non-zeroable!");
7008     if (!VT.isFloatingPoint() || V2Index != 0)
7009       return SDValue();
7010     SmallVector<int, 8> V1Mask(Mask.begin(), Mask.end());
7011     V1Mask[V2Index] = -1;
7012     if (!isNoopShuffleMask(V1Mask))
7013       return SDValue();
7014     // This is essentially a special case blend operation, but if we have
7015     // general purpose blend operations, they are always faster. Bail and let
7016     // the rest of the lowering handle these as blends.
7017     if (Subtarget->hasSSE41())
7018       return SDValue();
7019
7020     // Otherwise, use MOVSD or MOVSS.
7021     assert((EltVT == MVT::f32 || EltVT == MVT::f64) &&
7022            "Only two types of floating point element types to handle!");
7023     return DAG.getNode(EltVT == MVT::f32 ? X86ISD::MOVSS : X86ISD::MOVSD, DL,
7024                        ExtVT, V1, V2);
7025   }
7026
7027   // This lowering only works for the low element with floating point vectors.
7028   if (VT.isFloatingPoint() && V2Index != 0)
7029     return SDValue();
7030
7031   V2 = DAG.getNode(X86ISD::VZEXT_MOVL, DL, ExtVT, V2);
7032   if (ExtVT != VT)
7033     V2 = DAG.getNode(ISD::BITCAST, DL, VT, V2);
7034
7035   if (V2Index != 0) {
7036     // If we have 4 or fewer lanes we can cheaply shuffle the element into
7037     // the desired position. Otherwise it is more efficient to do a vector
7038     // shift left. We know that we can do a vector shift left because all
7039     // the inputs are zero.
7040     if (VT.isFloatingPoint() || VT.getVectorNumElements() <= 4) {
7041       SmallVector<int, 4> V2Shuffle(Mask.size(), 1);
7042       V2Shuffle[V2Index] = 0;
7043       V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Shuffle);
7044     } else {
7045       V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, V2);
7046       V2 = DAG.getNode(
7047           X86ISD::VSHLDQ, DL, MVT::v2i64, V2,
7048           DAG.getConstant(
7049               V2Index * EltVT.getSizeInBits()/8,
7050               DAG.getTargetLoweringInfo().getScalarShiftAmountTy(MVT::v2i64)));
7051       V2 = DAG.getNode(ISD::BITCAST, DL, VT, V2);
7052     }
7053   }
7054   return V2;
7055 }
7056
7057 /// \brief Try to lower broadcast of a single element.
7058 ///
7059 /// For convenience, this code also bundles all of the subtarget feature set
7060 /// filtering. While a little annoying to re-dispatch on type here, there isn't
7061 /// a convenient way to factor it out.
7062 static SDValue lowerVectorShuffleAsBroadcast(SDLoc DL, MVT VT, SDValue V,
7063                                              ArrayRef<int> Mask,
7064                                              const X86Subtarget *Subtarget,
7065                                              SelectionDAG &DAG) {
7066   if (!Subtarget->hasAVX())
7067     return SDValue();
7068   if (VT.isInteger() && !Subtarget->hasAVX2())
7069     return SDValue();
7070
7071   // Check that the mask is a broadcast.
7072   int BroadcastIdx = -1;
7073   for (int M : Mask)
7074     if (M >= 0 && BroadcastIdx == -1)
7075       BroadcastIdx = M;
7076     else if (M >= 0 && M != BroadcastIdx)
7077       return SDValue();
7078
7079   assert(BroadcastIdx < (int)Mask.size() && "We only expect to be called with "
7080                                             "a sorted mask where the broadcast "
7081                                             "comes from V1.");
7082
7083   // Go up the chain of (vector) values to find a scalar load that we can
7084   // combine with the broadcast.
7085   for (;;) {
7086     switch (V.getOpcode()) {
7087     case ISD::CONCAT_VECTORS: {
7088       int OperandSize = Mask.size() / V.getNumOperands();
7089       V = V.getOperand(BroadcastIdx / OperandSize);
7090       BroadcastIdx %= OperandSize;
7091       continue;
7092     }
7093
7094     case ISD::INSERT_SUBVECTOR: {
7095       SDValue VOuter = V.getOperand(0), VInner = V.getOperand(1);
7096       auto ConstantIdx = dyn_cast<ConstantSDNode>(V.getOperand(2));
7097       if (!ConstantIdx)
7098         break;
7099
7100       int BeginIdx = (int)ConstantIdx->getZExtValue();
7101       int EndIdx =
7102           BeginIdx + (int)VInner.getValueType().getVectorNumElements();
7103       if (BroadcastIdx >= BeginIdx && BroadcastIdx < EndIdx) {
7104         BroadcastIdx -= BeginIdx;
7105         V = VInner;
7106       } else {
7107         V = VOuter;
7108       }
7109       continue;
7110     }
7111     }
7112     break;
7113   }
7114
7115   // Check if this is a broadcast of a scalar. We special case lowering
7116   // for scalars so that we can more effectively fold with loads.
7117   if (V.getOpcode() == ISD::BUILD_VECTOR ||
7118       (V.getOpcode() == ISD::SCALAR_TO_VECTOR && BroadcastIdx == 0)) {
7119     V = V.getOperand(BroadcastIdx);
7120
7121     // If the scalar isn't a load, we can't broadcast from it in AVX1.
7122     // Only AVX2 has register broadcasts.
7123     if (!Subtarget->hasAVX2() && !isShuffleFoldableLoad(V))
7124       return SDValue();
7125   } else if (BroadcastIdx != 0 || !Subtarget->hasAVX2()) {
7126     // We can't broadcast from a vector register without AVX2, and we can only
7127     // broadcast from the zero-element of a vector register.
7128     return SDValue();
7129   }
7130
7131   return DAG.getNode(X86ISD::VBROADCAST, DL, VT, V);
7132 }
7133
7134 // Check for whether we can use INSERTPS to perform the shuffle. We only use
7135 // INSERTPS when the V1 elements are already in the correct locations
7136 // because otherwise we can just always use two SHUFPS instructions which
7137 // are much smaller to encode than a SHUFPS and an INSERTPS. We can also
7138 // perform INSERTPS if a single V1 element is out of place and all V2
7139 // elements are zeroable.
7140 static SDValue lowerVectorShuffleAsInsertPS(SDValue Op, SDValue V1, SDValue V2,
7141                                             ArrayRef<int> Mask,
7142                                             SelectionDAG &DAG) {
7143   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
7144   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7145   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7146   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7147
7148   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7149
7150   unsigned ZMask = 0;
7151   int V1DstIndex = -1;
7152   int V2DstIndex = -1;
7153   bool V1UsedInPlace = false;
7154
7155   for (int i = 0; i < 4; ++i) {
7156     // Synthesize a zero mask from the zeroable elements (includes undefs).
7157     if (Zeroable[i]) {
7158       ZMask |= 1 << i;
7159       continue;
7160     }
7161
7162     // Flag if we use any V1 inputs in place.
7163     if (i == Mask[i]) {
7164       V1UsedInPlace = true;
7165       continue;
7166     }
7167
7168     // We can only insert a single non-zeroable element.
7169     if (V1DstIndex != -1 || V2DstIndex != -1)
7170       return SDValue();
7171
7172     if (Mask[i] < 4) {
7173       // V1 input out of place for insertion.
7174       V1DstIndex = i;
7175     } else {
7176       // V2 input for insertion.
7177       V2DstIndex = i;
7178     }
7179   }
7180
7181   // Don't bother if we have no (non-zeroable) element for insertion.
7182   if (V1DstIndex == -1 && V2DstIndex == -1)
7183     return SDValue();
7184
7185   // Determine element insertion src/dst indices. The src index is from the
7186   // start of the inserted vector, not the start of the concatenated vector.
7187   unsigned V2SrcIndex = 0;
7188   if (V1DstIndex != -1) {
7189     // If we have a V1 input out of place, we use V1 as the V2 element insertion
7190     // and don't use the original V2 at all.
7191     V2SrcIndex = Mask[V1DstIndex];
7192     V2DstIndex = V1DstIndex;
7193     V2 = V1;
7194   } else {
7195     V2SrcIndex = Mask[V2DstIndex] - 4;
7196   }
7197
7198   // If no V1 inputs are used in place, then the result is created only from
7199   // the zero mask and the V2 insertion - so remove V1 dependency.
7200   if (!V1UsedInPlace)
7201     V1 = DAG.getUNDEF(MVT::v4f32);
7202
7203   unsigned InsertPSMask = V2SrcIndex << 6 | V2DstIndex << 4 | ZMask;
7204   assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
7205
7206   // Insert the V2 element into the desired position.
7207   SDLoc DL(Op);
7208   return DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
7209                      DAG.getConstant(InsertPSMask, MVT::i8));
7210 }
7211
7212 /// \brief Try to lower a shuffle as a permute of the inputs followed by an
7213 /// UNPCK instruction.
7214 ///
7215 /// This specifically targets cases where we end up with alternating between
7216 /// the two inputs, and so can permute them into something that feeds a single
7217 /// UNPCK instruction. Note that this routine only targets integer vectors
7218 /// because for floating point vectors we have a generalized SHUFPS lowering
7219 /// strategy that handles everything that doesn't *exactly* match an unpack,
7220 /// making this clever lowering unnecessary.
7221 static SDValue lowerVectorShuffleAsUnpack(SDLoc DL, MVT VT, SDValue V1,
7222                                           SDValue V2, ArrayRef<int> Mask,
7223                                           SelectionDAG &DAG) {
7224   assert(!VT.isFloatingPoint() &&
7225          "This routine only supports integer vectors.");
7226   assert(!isSingleInputShuffleMask(Mask) &&
7227          "This routine should only be used when blending two inputs.");
7228   assert(Mask.size() >= 2 && "Single element masks are invalid.");
7229
7230   int Size = Mask.size();
7231
7232   int NumLoInputs = std::count_if(Mask.begin(), Mask.end(), [Size](int M) {
7233     return M >= 0 && M % Size < Size / 2;
7234   });
7235   int NumHiInputs = std::count_if(
7236       Mask.begin(), Mask.end(), [Size](int M) { return M % Size >= Size / 2; });
7237
7238   bool UnpackLo = NumLoInputs >= NumHiInputs;
7239
7240   auto TryUnpack = [&](MVT UnpackVT, int Scale) {
7241     SmallVector<int, 32> V1Mask(Mask.size(), -1);
7242     SmallVector<int, 32> V2Mask(Mask.size(), -1);
7243
7244     for (int i = 0; i < Size; ++i) {
7245       if (Mask[i] < 0)
7246         continue;
7247
7248       // Each element of the unpack contains Scale elements from this mask.
7249       int UnpackIdx = i / Scale;
7250
7251       // We only handle the case where V1 feeds the first slots of the unpack.
7252       // We rely on canonicalization to ensure this is the case.
7253       if ((UnpackIdx % 2 == 0) != (Mask[i] < Size))
7254         return SDValue();
7255
7256       // Setup the mask for this input. The indexing is tricky as we have to
7257       // handle the unpack stride.
7258       SmallVectorImpl<int> &VMask = (UnpackIdx % 2 == 0) ? V1Mask : V2Mask;
7259       VMask[(UnpackIdx / 2) * Scale + i % Scale + (UnpackLo ? 0 : Size / 2)] =
7260           Mask[i] % Size;
7261     }
7262
7263     // If we will have to shuffle both inputs to use the unpack, check whether
7264     // we can just unpack first and shuffle the result. If so, skip this unpack.
7265     if ((NumLoInputs == 0 || NumHiInputs == 0) && !isNoopShuffleMask(V1Mask) &&
7266         !isNoopShuffleMask(V2Mask))
7267       return SDValue();
7268
7269     // Shuffle the inputs into place.
7270     V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
7271     V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
7272
7273     // Cast the inputs to the type we will use to unpack them.
7274     V1 = DAG.getNode(ISD::BITCAST, DL, UnpackVT, V1);
7275     V2 = DAG.getNode(ISD::BITCAST, DL, UnpackVT, V2);
7276
7277     // Unpack the inputs and cast the result back to the desired type.
7278     return DAG.getNode(ISD::BITCAST, DL, VT,
7279                        DAG.getNode(UnpackLo ? X86ISD::UNPCKL : X86ISD::UNPCKH,
7280                                    DL, UnpackVT, V1, V2));
7281   };
7282
7283   // We try each unpack from the largest to the smallest to try and find one
7284   // that fits this mask.
7285   int OrigNumElements = VT.getVectorNumElements();
7286   int OrigScalarSize = VT.getScalarSizeInBits();
7287   for (int ScalarSize = 64; ScalarSize >= OrigScalarSize; ScalarSize /= 2) {
7288     int Scale = ScalarSize / OrigScalarSize;
7289     int NumElements = OrigNumElements / Scale;
7290     MVT UnpackVT = MVT::getVectorVT(MVT::getIntegerVT(ScalarSize), NumElements);
7291     if (SDValue Unpack = TryUnpack(UnpackVT, Scale))
7292       return Unpack;
7293   }
7294
7295   // If none of the unpack-rooted lowerings worked (or were profitable) try an
7296   // initial unpack.
7297   if (NumLoInputs == 0 || NumHiInputs == 0) {
7298     assert((NumLoInputs > 0 || NumHiInputs > 0) &&
7299            "We have to have *some* inputs!");
7300     int HalfOffset = NumLoInputs == 0 ? Size / 2 : 0;
7301
7302     // FIXME: We could consider the total complexity of the permute of each
7303     // possible unpacking. Or at the least we should consider how many
7304     // half-crossings are created.
7305     // FIXME: We could consider commuting the unpacks.
7306
7307     SmallVector<int, 32> PermMask;
7308     PermMask.assign(Size, -1);
7309     for (int i = 0; i < Size; ++i) {
7310       if (Mask[i] < 0)
7311         continue;
7312
7313       assert(Mask[i] % Size >= HalfOffset && "Found input from wrong half!");
7314
7315       PermMask[i] =
7316           2 * ((Mask[i] % Size) - HalfOffset) + (Mask[i] < Size ? 0 : 1);
7317     }
7318     return DAG.getVectorShuffle(
7319         VT, DL, DAG.getNode(NumLoInputs == 0 ? X86ISD::UNPCKH : X86ISD::UNPCKL,
7320                             DL, VT, V1, V2),
7321         DAG.getUNDEF(VT), PermMask);
7322   }
7323
7324   return SDValue();
7325 }
7326
7327 /// \brief Handle lowering of 2-lane 64-bit floating point shuffles.
7328 ///
7329 /// This is the basis function for the 2-lane 64-bit shuffles as we have full
7330 /// support for floating point shuffles but not integer shuffles. These
7331 /// instructions will incur a domain crossing penalty on some chips though so
7332 /// it is better to avoid lowering through this for integer vectors where
7333 /// possible.
7334 static SDValue lowerV2F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7335                                        const X86Subtarget *Subtarget,
7336                                        SelectionDAG &DAG) {
7337   SDLoc DL(Op);
7338   assert(Op.getSimpleValueType() == MVT::v2f64 && "Bad shuffle type!");
7339   assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7340   assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7341   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7342   ArrayRef<int> Mask = SVOp->getMask();
7343   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7344
7345   if (isSingleInputShuffleMask(Mask)) {
7346     // Use low duplicate instructions for masks that match their pattern.
7347     if (Subtarget->hasSSE3())
7348       if (isShuffleEquivalent(V1, V2, Mask, {0, 0}))
7349         return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v2f64, V1);
7350
7351     // Straight shuffle of a single input vector. Simulate this by using the
7352     // single input as both of the "inputs" to this instruction..
7353     unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
7354
7355     if (Subtarget->hasAVX()) {
7356       // If we have AVX, we can use VPERMILPS which will allow folding a load
7357       // into the shuffle.
7358       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v2f64, V1,
7359                          DAG.getConstant(SHUFPDMask, MVT::i8));
7360     }
7361
7362     return DAG.getNode(X86ISD::SHUFP, SDLoc(Op), MVT::v2f64, V1, V1,
7363                        DAG.getConstant(SHUFPDMask, MVT::i8));
7364   }
7365   assert(Mask[0] >= 0 && Mask[0] < 2 && "Non-canonicalized blend!");
7366   assert(Mask[1] >= 2 && "Non-canonicalized blend!");
7367
7368   // If we have a single input, insert that into V1 if we can do so cheaply.
7369   if ((Mask[0] >= 2) + (Mask[1] >= 2) == 1) {
7370     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7371             DL, MVT::v2f64, V1, V2, Mask, Subtarget, DAG))
7372       return Insertion;
7373     // Try inverting the insertion since for v2 masks it is easy to do and we
7374     // can't reliably sort the mask one way or the other.
7375     int InverseMask[2] = {Mask[0] < 0 ? -1 : (Mask[0] ^ 2),
7376                           Mask[1] < 0 ? -1 : (Mask[1] ^ 2)};
7377     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7378             DL, MVT::v2f64, V2, V1, InverseMask, Subtarget, DAG))
7379       return Insertion;
7380   }
7381
7382   // Try to use one of the special instruction patterns to handle two common
7383   // blend patterns if a zero-blend above didn't work.
7384   if (isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
7385       isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7386     if (SDValue V1S = getScalarValueForVectorElement(V1, Mask[0], DAG))
7387       // We can either use a special instruction to load over the low double or
7388       // to move just the low double.
7389       return DAG.getNode(
7390           isShuffleFoldableLoad(V1S) ? X86ISD::MOVLPD : X86ISD::MOVSD,
7391           DL, MVT::v2f64, V2,
7392           DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64, V1S));
7393
7394   if (Subtarget->hasSSE41())
7395     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2f64, V1, V2, Mask,
7396                                                   Subtarget, DAG))
7397       return Blend;
7398
7399   // Use dedicated unpack instructions for masks that match their pattern.
7400   if (isShuffleEquivalent(V1, V2, Mask, {0, 2}))
7401     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2f64, V1, V2);
7402   if (isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7403     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2f64, V1, V2);
7404
7405   unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
7406   return DAG.getNode(X86ISD::SHUFP, SDLoc(Op), MVT::v2f64, V1, V2,
7407                      DAG.getConstant(SHUFPDMask, MVT::i8));
7408 }
7409
7410 /// \brief Handle lowering of 2-lane 64-bit integer shuffles.
7411 ///
7412 /// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
7413 /// the integer unit to minimize domain crossing penalties. However, for blends
7414 /// it falls back to the floating point shuffle operation with appropriate bit
7415 /// casting.
7416 static SDValue lowerV2I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7417                                        const X86Subtarget *Subtarget,
7418                                        SelectionDAG &DAG) {
7419   SDLoc DL(Op);
7420   assert(Op.getSimpleValueType() == MVT::v2i64 && "Bad shuffle type!");
7421   assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7422   assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7423   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7424   ArrayRef<int> Mask = SVOp->getMask();
7425   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7426
7427   if (isSingleInputShuffleMask(Mask)) {
7428     // Check for being able to broadcast a single element.
7429     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v2i64, V1,
7430                                                           Mask, Subtarget, DAG))
7431       return Broadcast;
7432
7433     // Straight shuffle of a single input vector. For everything from SSE2
7434     // onward this has a single fast instruction with no scary immediates.
7435     // We have to map the mask as it is actually a v4i32 shuffle instruction.
7436     V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V1);
7437     int WidenedMask[4] = {
7438         std::max(Mask[0], 0) * 2, std::max(Mask[0], 0) * 2 + 1,
7439         std::max(Mask[1], 0) * 2, std::max(Mask[1], 0) * 2 + 1};
7440     return DAG.getNode(
7441         ISD::BITCAST, DL, MVT::v2i64,
7442         DAG.getNode(X86ISD::PSHUFD, SDLoc(Op), MVT::v4i32, V1,
7443                     getV4X86ShuffleImm8ForMask(WidenedMask, DAG)));
7444   }
7445   assert(Mask[0] != -1 && "No undef lanes in multi-input v2 shuffles!");
7446   assert(Mask[1] != -1 && "No undef lanes in multi-input v2 shuffles!");
7447   assert(Mask[0] < 2 && "We sort V1 to be the first input.");
7448   assert(Mask[1] >= 2 && "We sort V2 to be the second input.");
7449
7450   // If we have a blend of two PACKUS operations an the blend aligns with the
7451   // low and half halves, we can just merge the PACKUS operations. This is
7452   // particularly important as it lets us merge shuffles that this routine itself
7453   // creates.
7454   auto GetPackNode = [](SDValue V) {
7455     while (V.getOpcode() == ISD::BITCAST)
7456       V = V.getOperand(0);
7457
7458     return V.getOpcode() == X86ISD::PACKUS ? V : SDValue();
7459   };
7460   if (SDValue V1Pack = GetPackNode(V1))
7461     if (SDValue V2Pack = GetPackNode(V2))
7462       return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7463                          DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8,
7464                                      Mask[0] == 0 ? V1Pack.getOperand(0)
7465                                                   : V1Pack.getOperand(1),
7466                                      Mask[1] == 2 ? V2Pack.getOperand(0)
7467                                                   : V2Pack.getOperand(1)));
7468
7469   // Try to use shift instructions.
7470   if (SDValue Shift =
7471           lowerVectorShuffleAsShift(DL, MVT::v2i64, V1, V2, Mask, DAG))
7472     return Shift;
7473
7474   // When loading a scalar and then shuffling it into a vector we can often do
7475   // the insertion cheaply.
7476   if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7477           DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
7478     return Insertion;
7479   // Try inverting the insertion since for v2 masks it is easy to do and we
7480   // can't reliably sort the mask one way or the other.
7481   int InverseMask[2] = {Mask[0] ^ 2, Mask[1] ^ 2};
7482   if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7483           DL, MVT::v2i64, V2, V1, InverseMask, Subtarget, DAG))
7484     return Insertion;
7485
7486   // We have different paths for blend lowering, but they all must use the
7487   // *exact* same predicate.
7488   bool IsBlendSupported = Subtarget->hasSSE41();
7489   if (IsBlendSupported)
7490     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2i64, V1, V2, Mask,
7491                                                   Subtarget, DAG))
7492       return Blend;
7493
7494   // Use dedicated unpack instructions for masks that match their pattern.
7495   if (isShuffleEquivalent(V1, V2, Mask, {0, 2}))
7496     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, V1, V2);
7497   if (isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7498     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2i64, V1, V2);
7499
7500   // Try to use byte rotation instructions.
7501   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
7502   if (Subtarget->hasSSSE3())
7503     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
7504             DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
7505       return Rotate;
7506
7507   // If we have direct support for blends, we should lower by decomposing into
7508   // a permute. That will be faster than the domain cross.
7509   if (IsBlendSupported)
7510     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v2i64, V1, V2,
7511                                                       Mask, DAG);
7512
7513   // We implement this with SHUFPD which is pretty lame because it will likely
7514   // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
7515   // However, all the alternatives are still more cycles and newer chips don't
7516   // have this problem. It would be really nice if x86 had better shuffles here.
7517   V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V1);
7518   V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V2);
7519   return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7520                      DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
7521 }
7522
7523 /// \brief Test whether this can be lowered with a single SHUFPS instruction.
7524 ///
7525 /// This is used to disable more specialized lowerings when the shufps lowering
7526 /// will happen to be efficient.
7527 static bool isSingleSHUFPSMask(ArrayRef<int> Mask) {
7528   // This routine only handles 128-bit shufps.
7529   assert(Mask.size() == 4 && "Unsupported mask size!");
7530
7531   // To lower with a single SHUFPS we need to have the low half and high half
7532   // each requiring a single input.
7533   if (Mask[0] != -1 && Mask[1] != -1 && (Mask[0] < 4) != (Mask[1] < 4))
7534     return false;
7535   if (Mask[2] != -1 && Mask[3] != -1 && (Mask[2] < 4) != (Mask[3] < 4))
7536     return false;
7537
7538   return true;
7539 }
7540
7541 /// \brief Lower a vector shuffle using the SHUFPS instruction.
7542 ///
7543 /// This is a helper routine dedicated to lowering vector shuffles using SHUFPS.
7544 /// It makes no assumptions about whether this is the *best* lowering, it simply
7545 /// uses it.
7546 static SDValue lowerVectorShuffleWithSHUFPS(SDLoc DL, MVT VT,
7547                                             ArrayRef<int> Mask, SDValue V1,
7548                                             SDValue V2, SelectionDAG &DAG) {
7549   SDValue LowV = V1, HighV = V2;
7550   int NewMask[4] = {Mask[0], Mask[1], Mask[2], Mask[3]};
7551
7552   int NumV2Elements =
7553       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7554
7555   if (NumV2Elements == 1) {
7556     int V2Index =
7557         std::find_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; }) -
7558         Mask.begin();
7559
7560     // Compute the index adjacent to V2Index and in the same half by toggling
7561     // the low bit.
7562     int V2AdjIndex = V2Index ^ 1;
7563
7564     if (Mask[V2AdjIndex] == -1) {
7565       // Handles all the cases where we have a single V2 element and an undef.
7566       // This will only ever happen in the high lanes because we commute the
7567       // vector otherwise.
7568       if (V2Index < 2)
7569         std::swap(LowV, HighV);
7570       NewMask[V2Index] -= 4;
7571     } else {
7572       // Handle the case where the V2 element ends up adjacent to a V1 element.
7573       // To make this work, blend them together as the first step.
7574       int V1Index = V2AdjIndex;
7575       int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
7576       V2 = DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
7577                        getV4X86ShuffleImm8ForMask(BlendMask, DAG));
7578
7579       // Now proceed to reconstruct the final blend as we have the necessary
7580       // high or low half formed.
7581       if (V2Index < 2) {
7582         LowV = V2;
7583         HighV = V1;
7584       } else {
7585         HighV = V2;
7586       }
7587       NewMask[V1Index] = 2; // We put the V1 element in V2[2].
7588       NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
7589     }
7590   } else if (NumV2Elements == 2) {
7591     if (Mask[0] < 4 && Mask[1] < 4) {
7592       // Handle the easy case where we have V1 in the low lanes and V2 in the
7593       // high lanes.
7594       NewMask[2] -= 4;
7595       NewMask[3] -= 4;
7596     } else if (Mask[2] < 4 && Mask[3] < 4) {
7597       // We also handle the reversed case because this utility may get called
7598       // when we detect a SHUFPS pattern but can't easily commute the shuffle to
7599       // arrange things in the right direction.
7600       NewMask[0] -= 4;
7601       NewMask[1] -= 4;
7602       HighV = V1;
7603       LowV = V2;
7604     } else {
7605       // We have a mixture of V1 and V2 in both low and high lanes. Rather than
7606       // trying to place elements directly, just blend them and set up the final
7607       // shuffle to place them.
7608
7609       // The first two blend mask elements are for V1, the second two are for
7610       // V2.
7611       int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
7612                           Mask[2] < 4 ? Mask[2] : Mask[3],
7613                           (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
7614                           (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
7615       V1 = DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
7616                        getV4X86ShuffleImm8ForMask(BlendMask, DAG));
7617
7618       // Now we do a normal shuffle of V1 by giving V1 as both operands to
7619       // a blend.
7620       LowV = HighV = V1;
7621       NewMask[0] = Mask[0] < 4 ? 0 : 2;
7622       NewMask[1] = Mask[0] < 4 ? 2 : 0;
7623       NewMask[2] = Mask[2] < 4 ? 1 : 3;
7624       NewMask[3] = Mask[2] < 4 ? 3 : 1;
7625     }
7626   }
7627   return DAG.getNode(X86ISD::SHUFP, DL, VT, LowV, HighV,
7628                      getV4X86ShuffleImm8ForMask(NewMask, DAG));
7629 }
7630
7631 /// \brief Lower 4-lane 32-bit floating point shuffles.
7632 ///
7633 /// Uses instructions exclusively from the floating point unit to minimize
7634 /// domain crossing penalties, as these are sufficient to implement all v4f32
7635 /// shuffles.
7636 static SDValue lowerV4F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7637                                        const X86Subtarget *Subtarget,
7638                                        SelectionDAG &DAG) {
7639   SDLoc DL(Op);
7640   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
7641   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7642   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7643   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7644   ArrayRef<int> Mask = SVOp->getMask();
7645   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7646
7647   int NumV2Elements =
7648       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7649
7650   if (NumV2Elements == 0) {
7651     // Check for being able to broadcast a single element.
7652     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f32, V1,
7653                                                           Mask, Subtarget, DAG))
7654       return Broadcast;
7655
7656     // Use even/odd duplicate instructions for masks that match their pattern.
7657     if (Subtarget->hasSSE3()) {
7658       if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
7659         return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v4f32, V1);
7660       if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3}))
7661         return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v4f32, V1);
7662     }
7663
7664     if (Subtarget->hasAVX()) {
7665       // If we have AVX, we can use VPERMILPS which will allow folding a load
7666       // into the shuffle.
7667       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f32, V1,
7668                          getV4X86ShuffleImm8ForMask(Mask, DAG));
7669     }
7670
7671     // Otherwise, use a straight shuffle of a single input vector. We pass the
7672     // input vector to both operands to simulate this with a SHUFPS.
7673     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
7674                        getV4X86ShuffleImm8ForMask(Mask, DAG));
7675   }
7676
7677   // There are special ways we can lower some single-element blends. However, we
7678   // have custom ways we can lower more complex single-element blends below that
7679   // we defer to if both this and BLENDPS fail to match, so restrict this to
7680   // when the V2 input is targeting element 0 of the mask -- that is the fast
7681   // case here.
7682   if (NumV2Elements == 1 && Mask[0] >= 4)
7683     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4f32, V1, V2,
7684                                                          Mask, Subtarget, DAG))
7685       return V;
7686
7687   if (Subtarget->hasSSE41()) {
7688     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f32, V1, V2, Mask,
7689                                                   Subtarget, DAG))
7690       return Blend;
7691
7692     // Use INSERTPS if we can complete the shuffle efficiently.
7693     if (SDValue V = lowerVectorShuffleAsInsertPS(Op, V1, V2, Mask, DAG))
7694       return V;
7695
7696     if (!isSingleSHUFPSMask(Mask))
7697       if (SDValue BlendPerm = lowerVectorShuffleAsBlendAndPermute(
7698               DL, MVT::v4f32, V1, V2, Mask, DAG))
7699         return BlendPerm;
7700   }
7701
7702   // Use dedicated unpack instructions for masks that match their pattern.
7703   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 1, 5}))
7704     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V1, V2);
7705   if (isShuffleEquivalent(V1, V2, Mask, {2, 6, 3, 7}))
7706     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V1, V2);
7707   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 5, 1}))
7708     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V2, V1);
7709   if (isShuffleEquivalent(V1, V2, Mask, {6, 2, 7, 3}))
7710     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V2, V1);
7711
7712   // Otherwise fall back to a SHUFPS lowering strategy.
7713   return lowerVectorShuffleWithSHUFPS(DL, MVT::v4f32, Mask, V1, V2, DAG);
7714 }
7715
7716 /// \brief Lower 4-lane i32 vector shuffles.
7717 ///
7718 /// We try to handle these with integer-domain shuffles where we can, but for
7719 /// blends we use the floating point domain blend instructions.
7720 static SDValue lowerV4I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7721                                        const X86Subtarget *Subtarget,
7722                                        SelectionDAG &DAG) {
7723   SDLoc DL(Op);
7724   assert(Op.getSimpleValueType() == MVT::v4i32 && "Bad shuffle type!");
7725   assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
7726   assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
7727   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7728   ArrayRef<int> Mask = SVOp->getMask();
7729   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7730
7731   // Whenever we can lower this as a zext, that instruction is strictly faster
7732   // than any alternative. It also allows us to fold memory operands into the
7733   // shuffle in many cases.
7734   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v4i32, V1, V2,
7735                                                          Mask, Subtarget, DAG))
7736     return ZExt;
7737
7738   int NumV2Elements =
7739       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7740
7741   if (NumV2Elements == 0) {
7742     // Check for being able to broadcast a single element.
7743     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i32, V1,
7744                                                           Mask, Subtarget, DAG))
7745       return Broadcast;
7746
7747     // Straight shuffle of a single input vector. For everything from SSE2
7748     // onward this has a single fast instruction with no scary immediates.
7749     // We coerce the shuffle pattern to be compatible with UNPCK instructions
7750     // but we aren't actually going to use the UNPCK instruction because doing
7751     // so prevents folding a load into this instruction or making a copy.
7752     const int UnpackLoMask[] = {0, 0, 1, 1};
7753     const int UnpackHiMask[] = {2, 2, 3, 3};
7754     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 1, 1}))
7755       Mask = UnpackLoMask;
7756     else if (isShuffleEquivalent(V1, V2, Mask, {2, 2, 3, 3}))
7757       Mask = UnpackHiMask;
7758
7759     return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
7760                        getV4X86ShuffleImm8ForMask(Mask, DAG));
7761   }
7762
7763   // Try to use shift instructions.
7764   if (SDValue Shift =
7765           lowerVectorShuffleAsShift(DL, MVT::v4i32, V1, V2, Mask, DAG))
7766     return Shift;
7767
7768   // There are special ways we can lower some single-element blends.
7769   if (NumV2Elements == 1)
7770     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4i32, V1, V2,
7771                                                          Mask, Subtarget, DAG))
7772       return V;
7773
7774   // We have different paths for blend lowering, but they all must use the
7775   // *exact* same predicate.
7776   bool IsBlendSupported = Subtarget->hasSSE41();
7777   if (IsBlendSupported)
7778     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i32, V1, V2, Mask,
7779                                                   Subtarget, DAG))
7780       return Blend;
7781
7782   if (SDValue Masked =
7783           lowerVectorShuffleAsBitMask(DL, MVT::v4i32, V1, V2, Mask, DAG))
7784     return Masked;
7785
7786   // Use dedicated unpack instructions for masks that match their pattern.
7787   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 1, 5}))
7788     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V1, V2);
7789   if (isShuffleEquivalent(V1, V2, Mask, {2, 6, 3, 7}))
7790     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V1, V2);
7791   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 5, 1}))
7792     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V2, V1);
7793   if (isShuffleEquivalent(V1, V2, Mask, {6, 2, 7, 3}))
7794     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V2, V1);
7795
7796   // Try to use byte rotation instructions.
7797   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
7798   if (Subtarget->hasSSSE3())
7799     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
7800             DL, MVT::v4i32, V1, V2, Mask, Subtarget, DAG))
7801       return Rotate;
7802
7803   // If we have direct support for blends, we should lower by decomposing into
7804   // a permute. That will be faster than the domain cross.
7805   if (IsBlendSupported)
7806     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i32, V1, V2,
7807                                                       Mask, DAG);
7808
7809   // Try to lower by permuting the inputs into an unpack instruction.
7810   if (SDValue Unpack =
7811           lowerVectorShuffleAsUnpack(DL, MVT::v4i32, V1, V2, Mask, DAG))
7812     return Unpack;
7813
7814   // We implement this with SHUFPS because it can blend from two vectors.
7815   // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
7816   // up the inputs, bypassing domain shift penalties that we would encur if we
7817   // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
7818   // relevant.
7819   return DAG.getNode(ISD::BITCAST, DL, MVT::v4i32,
7820                      DAG.getVectorShuffle(
7821                          MVT::v4f32, DL,
7822                          DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V1),
7823                          DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V2), Mask));
7824 }
7825
7826 /// \brief Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
7827 /// shuffle lowering, and the most complex part.
7828 ///
7829 /// The lowering strategy is to try to form pairs of input lanes which are
7830 /// targeted at the same half of the final vector, and then use a dword shuffle
7831 /// to place them onto the right half, and finally unpack the paired lanes into
7832 /// their final position.
7833 ///
7834 /// The exact breakdown of how to form these dword pairs and align them on the
7835 /// correct sides is really tricky. See the comments within the function for
7836 /// more of the details.
7837 ///
7838 /// This code also handles repeated 128-bit lanes of v8i16 shuffles, but each
7839 /// lane must shuffle the *exact* same way. In fact, you must pass a v8 Mask to
7840 /// this routine for it to work correctly. To shuffle a 256-bit or 512-bit i16
7841 /// vector, form the analogous 128-bit 8-element Mask.
7842 static SDValue lowerV8I16GeneralSingleInputVectorShuffle(
7843     SDLoc DL, MVT VT, SDValue V, MutableArrayRef<int> Mask,
7844     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7845   assert(VT.getScalarType() == MVT::i16 && "Bad input type!");
7846   MVT PSHUFDVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
7847
7848   assert(Mask.size() == 8 && "Shuffle mask length doen't match!");
7849   MutableArrayRef<int> LoMask = Mask.slice(0, 4);
7850   MutableArrayRef<int> HiMask = Mask.slice(4, 4);
7851
7852   SmallVector<int, 4> LoInputs;
7853   std::copy_if(LoMask.begin(), LoMask.end(), std::back_inserter(LoInputs),
7854                [](int M) { return M >= 0; });
7855   std::sort(LoInputs.begin(), LoInputs.end());
7856   LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()), LoInputs.end());
7857   SmallVector<int, 4> HiInputs;
7858   std::copy_if(HiMask.begin(), HiMask.end(), std::back_inserter(HiInputs),
7859                [](int M) { return M >= 0; });
7860   std::sort(HiInputs.begin(), HiInputs.end());
7861   HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()), HiInputs.end());
7862   int NumLToL =
7863       std::lower_bound(LoInputs.begin(), LoInputs.end(), 4) - LoInputs.begin();
7864   int NumHToL = LoInputs.size() - NumLToL;
7865   int NumLToH =
7866       std::lower_bound(HiInputs.begin(), HiInputs.end(), 4) - HiInputs.begin();
7867   int NumHToH = HiInputs.size() - NumLToH;
7868   MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
7869   MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
7870   MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
7871   MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
7872
7873   // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
7874   // such inputs we can swap two of the dwords across the half mark and end up
7875   // with <=2 inputs to each half in each half. Once there, we can fall through
7876   // to the generic code below. For example:
7877   //
7878   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
7879   // Mask:  [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
7880   //
7881   // However in some very rare cases we have a 1-into-3 or 3-into-1 on one half
7882   // and an existing 2-into-2 on the other half. In this case we may have to
7883   // pre-shuffle the 2-into-2 half to avoid turning it into a 3-into-1 or
7884   // 1-into-3 which could cause us to cycle endlessly fixing each side in turn.
7885   // Fortunately, we don't have to handle anything but a 2-into-2 pattern
7886   // because any other situation (including a 3-into-1 or 1-into-3 in the other
7887   // half than the one we target for fixing) will be fixed when we re-enter this
7888   // path. We will also combine away any sequence of PSHUFD instructions that
7889   // result into a single instruction. Here is an example of the tricky case:
7890   //
7891   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
7892   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -THIS-IS-BAD!!!!-> [5, 7, 1, 0, 4, 7, 5, 3]
7893   //
7894   // This now has a 1-into-3 in the high half! Instead, we do two shuffles:
7895   //
7896   // Input: [a, b, c, d, e, f, g, h] PSHUFHW[0,2,1,3]-> [a, b, c, d, e, g, f, h]
7897   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -----------------> [3, 7, 1, 0, 2, 7, 3, 6]
7898   //
7899   // Input: [a, b, c, d, e, g, f, h] -PSHUFD[0,2,1,3]-> [a, b, e, g, c, d, f, h]
7900   // Mask:  [3, 7, 1, 0, 2, 7, 3, 6] -----------------> [5, 7, 1, 0, 4, 7, 5, 6]
7901   //
7902   // The result is fine to be handled by the generic logic.
7903   auto balanceSides = [&](ArrayRef<int> AToAInputs, ArrayRef<int> BToAInputs,
7904                           ArrayRef<int> BToBInputs, ArrayRef<int> AToBInputs,
7905                           int AOffset, int BOffset) {
7906     assert((AToAInputs.size() == 3 || AToAInputs.size() == 1) &&
7907            "Must call this with A having 3 or 1 inputs from the A half.");
7908     assert((BToAInputs.size() == 1 || BToAInputs.size() == 3) &&
7909            "Must call this with B having 1 or 3 inputs from the B half.");
7910     assert(AToAInputs.size() + BToAInputs.size() == 4 &&
7911            "Must call this with either 3:1 or 1:3 inputs (summing to 4).");
7912
7913     // Compute the index of dword with only one word among the three inputs in
7914     // a half by taking the sum of the half with three inputs and subtracting
7915     // the sum of the actual three inputs. The difference is the remaining
7916     // slot.
7917     int ADWord, BDWord;
7918     int &TripleDWord = AToAInputs.size() == 3 ? ADWord : BDWord;
7919     int &OneInputDWord = AToAInputs.size() == 3 ? BDWord : ADWord;
7920     int TripleInputOffset = AToAInputs.size() == 3 ? AOffset : BOffset;
7921     ArrayRef<int> TripleInputs = AToAInputs.size() == 3 ? AToAInputs : BToAInputs;
7922     int OneInput = AToAInputs.size() == 3 ? BToAInputs[0] : AToAInputs[0];
7923     int TripleInputSum = 0 + 1 + 2 + 3 + (4 * TripleInputOffset);
7924     int TripleNonInputIdx =
7925         TripleInputSum - std::accumulate(TripleInputs.begin(), TripleInputs.end(), 0);
7926     TripleDWord = TripleNonInputIdx / 2;
7927
7928     // We use xor with one to compute the adjacent DWord to whichever one the
7929     // OneInput is in.
7930     OneInputDWord = (OneInput / 2) ^ 1;
7931
7932     // Check for one tricky case: We're fixing a 3<-1 or a 1<-3 shuffle for AToA
7933     // and BToA inputs. If there is also such a problem with the BToB and AToB
7934     // inputs, we don't try to fix it necessarily -- we'll recurse and see it in
7935     // the next pass. However, if we have a 2<-2 in the BToB and AToB inputs, it
7936     // is essential that we don't *create* a 3<-1 as then we might oscillate.
7937     if (BToBInputs.size() == 2 && AToBInputs.size() == 2) {
7938       // Compute how many inputs will be flipped by swapping these DWords. We
7939       // need
7940       // to balance this to ensure we don't form a 3-1 shuffle in the other
7941       // half.
7942       int NumFlippedAToBInputs =
7943           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord) +
7944           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord + 1);
7945       int NumFlippedBToBInputs =
7946           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord) +
7947           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord + 1);
7948       if ((NumFlippedAToBInputs == 1 &&
7949            (NumFlippedBToBInputs == 0 || NumFlippedBToBInputs == 2)) ||
7950           (NumFlippedBToBInputs == 1 &&
7951            (NumFlippedAToBInputs == 0 || NumFlippedAToBInputs == 2))) {
7952         // We choose whether to fix the A half or B half based on whether that
7953         // half has zero flipped inputs. At zero, we may not be able to fix it
7954         // with that half. We also bias towards fixing the B half because that
7955         // will more commonly be the high half, and we have to bias one way.
7956         auto FixFlippedInputs = [&V, &DL, &Mask, &DAG](int PinnedIdx, int DWord,
7957                                                        ArrayRef<int> Inputs) {
7958           int FixIdx = PinnedIdx ^ 1; // The adjacent slot to the pinned slot.
7959           bool IsFixIdxInput = std::find(Inputs.begin(), Inputs.end(),
7960                                          PinnedIdx ^ 1) != Inputs.end();
7961           // Determine whether the free index is in the flipped dword or the
7962           // unflipped dword based on where the pinned index is. We use this bit
7963           // in an xor to conditionally select the adjacent dword.
7964           int FixFreeIdx = 2 * (DWord ^ (PinnedIdx / 2 == DWord));
7965           bool IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
7966                                              FixFreeIdx) != Inputs.end();
7967           if (IsFixIdxInput == IsFixFreeIdxInput)
7968             FixFreeIdx += 1;
7969           IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
7970                                         FixFreeIdx) != Inputs.end();
7971           assert(IsFixIdxInput != IsFixFreeIdxInput &&
7972                  "We need to be changing the number of flipped inputs!");
7973           int PSHUFHalfMask[] = {0, 1, 2, 3};
7974           std::swap(PSHUFHalfMask[FixFreeIdx % 4], PSHUFHalfMask[FixIdx % 4]);
7975           V = DAG.getNode(FixIdx < 4 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW, DL,
7976                           MVT::v8i16, V,
7977                           getV4X86ShuffleImm8ForMask(PSHUFHalfMask, DAG));
7978
7979           for (int &M : Mask)
7980             if (M != -1 && M == FixIdx)
7981               M = FixFreeIdx;
7982             else if (M != -1 && M == FixFreeIdx)
7983               M = FixIdx;
7984         };
7985         if (NumFlippedBToBInputs != 0) {
7986           int BPinnedIdx =
7987               BToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
7988           FixFlippedInputs(BPinnedIdx, BDWord, BToBInputs);
7989         } else {
7990           assert(NumFlippedAToBInputs != 0 && "Impossible given predicates!");
7991           int APinnedIdx =
7992               AToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
7993           FixFlippedInputs(APinnedIdx, ADWord, AToBInputs);
7994         }
7995       }
7996     }
7997
7998     int PSHUFDMask[] = {0, 1, 2, 3};
7999     PSHUFDMask[ADWord] = BDWord;
8000     PSHUFDMask[BDWord] = ADWord;
8001     V = DAG.getNode(ISD::BITCAST, DL, VT,
8002                     DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT,
8003                                 DAG.getNode(ISD::BITCAST, DL, PSHUFDVT, V),
8004                                 getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
8005
8006     // Adjust the mask to match the new locations of A and B.
8007     for (int &M : Mask)
8008       if (M != -1 && M/2 == ADWord)
8009         M = 2 * BDWord + M % 2;
8010       else if (M != -1 && M/2 == BDWord)
8011         M = 2 * ADWord + M % 2;
8012
8013     // Recurse back into this routine to re-compute state now that this isn't
8014     // a 3 and 1 problem.
8015     return lowerV8I16GeneralSingleInputVectorShuffle(DL, VT, V, Mask, Subtarget,
8016                                                      DAG);
8017   };
8018   if ((NumLToL == 3 && NumHToL == 1) || (NumLToL == 1 && NumHToL == 3))
8019     return balanceSides(LToLInputs, HToLInputs, HToHInputs, LToHInputs, 0, 4);
8020   else if ((NumHToH == 3 && NumLToH == 1) || (NumHToH == 1 && NumLToH == 3))
8021     return balanceSides(HToHInputs, LToHInputs, LToLInputs, HToLInputs, 4, 0);
8022
8023   // At this point there are at most two inputs to the low and high halves from
8024   // each half. That means the inputs can always be grouped into dwords and
8025   // those dwords can then be moved to the correct half with a dword shuffle.
8026   // We use at most one low and one high word shuffle to collect these paired
8027   // inputs into dwords, and finally a dword shuffle to place them.
8028   int PSHUFLMask[4] = {-1, -1, -1, -1};
8029   int PSHUFHMask[4] = {-1, -1, -1, -1};
8030   int PSHUFDMask[4] = {-1, -1, -1, -1};
8031
8032   // First fix the masks for all the inputs that are staying in their
8033   // original halves. This will then dictate the targets of the cross-half
8034   // shuffles.
8035   auto fixInPlaceInputs =
8036       [&PSHUFDMask](ArrayRef<int> InPlaceInputs, ArrayRef<int> IncomingInputs,
8037                     MutableArrayRef<int> SourceHalfMask,
8038                     MutableArrayRef<int> HalfMask, int HalfOffset) {
8039     if (InPlaceInputs.empty())
8040       return;
8041     if (InPlaceInputs.size() == 1) {
8042       SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8043           InPlaceInputs[0] - HalfOffset;
8044       PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
8045       return;
8046     }
8047     if (IncomingInputs.empty()) {
8048       // Just fix all of the in place inputs.
8049       for (int Input : InPlaceInputs) {
8050         SourceHalfMask[Input - HalfOffset] = Input - HalfOffset;
8051         PSHUFDMask[Input / 2] = Input / 2;
8052       }
8053       return;
8054     }
8055
8056     assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!");
8057     SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8058         InPlaceInputs[0] - HalfOffset;
8059     // Put the second input next to the first so that they are packed into
8060     // a dword. We find the adjacent index by toggling the low bit.
8061     int AdjIndex = InPlaceInputs[0] ^ 1;
8062     SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
8063     std::replace(HalfMask.begin(), HalfMask.end(), InPlaceInputs[1], AdjIndex);
8064     PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
8065   };
8066   fixInPlaceInputs(LToLInputs, HToLInputs, PSHUFLMask, LoMask, 0);
8067   fixInPlaceInputs(HToHInputs, LToHInputs, PSHUFHMask, HiMask, 4);
8068
8069   // Now gather the cross-half inputs and place them into a free dword of
8070   // their target half.
8071   // FIXME: This operation could almost certainly be simplified dramatically to
8072   // look more like the 3-1 fixing operation.
8073   auto moveInputsToRightHalf = [&PSHUFDMask](
8074       MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
8075       MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
8076       MutableArrayRef<int> FinalSourceHalfMask, int SourceOffset,
8077       int DestOffset) {
8078     auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
8079       return SourceHalfMask[Word] != -1 && SourceHalfMask[Word] != Word;
8080     };
8081     auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
8082                                                int Word) {
8083       int LowWord = Word & ~1;
8084       int HighWord = Word | 1;
8085       return isWordClobbered(SourceHalfMask, LowWord) ||
8086              isWordClobbered(SourceHalfMask, HighWord);
8087     };
8088
8089     if (IncomingInputs.empty())
8090       return;
8091
8092     if (ExistingInputs.empty()) {
8093       // Map any dwords with inputs from them into the right half.
8094       for (int Input : IncomingInputs) {
8095         // If the source half mask maps over the inputs, turn those into
8096         // swaps and use the swapped lane.
8097         if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
8098           if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] == -1) {
8099             SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
8100                 Input - SourceOffset;
8101             // We have to swap the uses in our half mask in one sweep.
8102             for (int &M : HalfMask)
8103               if (M == SourceHalfMask[Input - SourceOffset] + SourceOffset)
8104                 M = Input;
8105               else if (M == Input)
8106                 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8107           } else {
8108             assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==
8109                        Input - SourceOffset &&
8110                    "Previous placement doesn't match!");
8111           }
8112           // Note that this correctly re-maps both when we do a swap and when
8113           // we observe the other side of the swap above. We rely on that to
8114           // avoid swapping the members of the input list directly.
8115           Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8116         }
8117
8118         // Map the input's dword into the correct half.
8119         if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] == -1)
8120           PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
8121         else
8122           assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==
8123                      Input / 2 &&
8124                  "Previous placement doesn't match!");
8125       }
8126
8127       // And just directly shift any other-half mask elements to be same-half
8128       // as we will have mirrored the dword containing the element into the
8129       // same position within that half.
8130       for (int &M : HalfMask)
8131         if (M >= SourceOffset && M < SourceOffset + 4) {
8132           M = M - SourceOffset + DestOffset;
8133           assert(M >= 0 && "This should never wrap below zero!");
8134         }
8135       return;
8136     }
8137
8138     // Ensure we have the input in a viable dword of its current half. This
8139     // is particularly tricky because the original position may be clobbered
8140     // by inputs being moved and *staying* in that half.
8141     if (IncomingInputs.size() == 1) {
8142       if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8143         int InputFixed = std::find(std::begin(SourceHalfMask),
8144                                    std::end(SourceHalfMask), -1) -
8145                          std::begin(SourceHalfMask) + SourceOffset;
8146         SourceHalfMask[InputFixed - SourceOffset] =
8147             IncomingInputs[0] - SourceOffset;
8148         std::replace(HalfMask.begin(), HalfMask.end(), IncomingInputs[0],
8149                      InputFixed);
8150         IncomingInputs[0] = InputFixed;
8151       }
8152     } else if (IncomingInputs.size() == 2) {
8153       if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
8154           isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8155         // We have two non-adjacent or clobbered inputs we need to extract from
8156         // the source half. To do this, we need to map them into some adjacent
8157         // dword slot in the source mask.
8158         int InputsFixed[2] = {IncomingInputs[0] - SourceOffset,
8159                               IncomingInputs[1] - SourceOffset};
8160
8161         // If there is a free slot in the source half mask adjacent to one of
8162         // the inputs, place the other input in it. We use (Index XOR 1) to
8163         // compute an adjacent index.
8164         if (!isWordClobbered(SourceHalfMask, InputsFixed[0]) &&
8165             SourceHalfMask[InputsFixed[0] ^ 1] == -1) {
8166           SourceHalfMask[InputsFixed[0]] = InputsFixed[0];
8167           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8168           InputsFixed[1] = InputsFixed[0] ^ 1;
8169         } else if (!isWordClobbered(SourceHalfMask, InputsFixed[1]) &&
8170                    SourceHalfMask[InputsFixed[1] ^ 1] == -1) {
8171           SourceHalfMask[InputsFixed[1]] = InputsFixed[1];
8172           SourceHalfMask[InputsFixed[1] ^ 1] = InputsFixed[0];
8173           InputsFixed[0] = InputsFixed[1] ^ 1;
8174         } else if (SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] == -1 &&
8175                    SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] == -1) {
8176           // The two inputs are in the same DWord but it is clobbered and the
8177           // adjacent DWord isn't used at all. Move both inputs to the free
8178           // slot.
8179           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] = InputsFixed[0];
8180           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] = InputsFixed[1];
8181           InputsFixed[0] = 2 * ((InputsFixed[0] / 2) ^ 1);
8182           InputsFixed[1] = 2 * ((InputsFixed[0] / 2) ^ 1) + 1;
8183         } else {
8184           // The only way we hit this point is if there is no clobbering
8185           // (because there are no off-half inputs to this half) and there is no
8186           // free slot adjacent to one of the inputs. In this case, we have to
8187           // swap an input with a non-input.
8188           for (int i = 0; i < 4; ++i)
8189             assert((SourceHalfMask[i] == -1 || SourceHalfMask[i] == i) &&
8190                    "We can't handle any clobbers here!");
8191           assert(InputsFixed[1] != (InputsFixed[0] ^ 1) &&
8192                  "Cannot have adjacent inputs here!");
8193
8194           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8195           SourceHalfMask[InputsFixed[1]] = InputsFixed[0] ^ 1;
8196
8197           // We also have to update the final source mask in this case because
8198           // it may need to undo the above swap.
8199           for (int &M : FinalSourceHalfMask)
8200             if (M == (InputsFixed[0] ^ 1) + SourceOffset)
8201               M = InputsFixed[1] + SourceOffset;
8202             else if (M == InputsFixed[1] + SourceOffset)
8203               M = (InputsFixed[0] ^ 1) + SourceOffset;
8204
8205           InputsFixed[1] = InputsFixed[0] ^ 1;
8206         }
8207
8208         // Point everything at the fixed inputs.
8209         for (int &M : HalfMask)
8210           if (M == IncomingInputs[0])
8211             M = InputsFixed[0] + SourceOffset;
8212           else if (M == IncomingInputs[1])
8213             M = InputsFixed[1] + SourceOffset;
8214
8215         IncomingInputs[0] = InputsFixed[0] + SourceOffset;
8216         IncomingInputs[1] = InputsFixed[1] + SourceOffset;
8217       }
8218     } else {
8219       llvm_unreachable("Unhandled input size!");
8220     }
8221
8222     // Now hoist the DWord down to the right half.
8223     int FreeDWord = (PSHUFDMask[DestOffset / 2] == -1 ? 0 : 1) + DestOffset / 2;
8224     assert(PSHUFDMask[FreeDWord] == -1 && "DWord not free");
8225     PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
8226     for (int &M : HalfMask)
8227       for (int Input : IncomingInputs)
8228         if (M == Input)
8229           M = FreeDWord * 2 + Input % 2;
8230   };
8231   moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask, HiMask,
8232                         /*SourceOffset*/ 4, /*DestOffset*/ 0);
8233   moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask, LoMask,
8234                         /*SourceOffset*/ 0, /*DestOffset*/ 4);
8235
8236   // Now enact all the shuffles we've computed to move the inputs into their
8237   // target half.
8238   if (!isNoopShuffleMask(PSHUFLMask))
8239     V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
8240                     getV4X86ShuffleImm8ForMask(PSHUFLMask, DAG));
8241   if (!isNoopShuffleMask(PSHUFHMask))
8242     V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
8243                     getV4X86ShuffleImm8ForMask(PSHUFHMask, DAG));
8244   if (!isNoopShuffleMask(PSHUFDMask))
8245     V = DAG.getNode(ISD::BITCAST, DL, VT,
8246                     DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT,
8247                                 DAG.getNode(ISD::BITCAST, DL, PSHUFDVT, V),
8248                                 getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
8249
8250   // At this point, each half should contain all its inputs, and we can then
8251   // just shuffle them into their final position.
8252   assert(std::count_if(LoMask.begin(), LoMask.end(),
8253                        [](int M) { return M >= 4; }) == 0 &&
8254          "Failed to lift all the high half inputs to the low mask!");
8255   assert(std::count_if(HiMask.begin(), HiMask.end(),
8256                        [](int M) { return M >= 0 && M < 4; }) == 0 &&
8257          "Failed to lift all the low half inputs to the high mask!");
8258
8259   // Do a half shuffle for the low mask.
8260   if (!isNoopShuffleMask(LoMask))
8261     V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
8262                     getV4X86ShuffleImm8ForMask(LoMask, DAG));
8263
8264   // Do a half shuffle with the high mask after shifting its values down.
8265   for (int &M : HiMask)
8266     if (M >= 0)
8267       M -= 4;
8268   if (!isNoopShuffleMask(HiMask))
8269     V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
8270                     getV4X86ShuffleImm8ForMask(HiMask, DAG));
8271
8272   return V;
8273 }
8274
8275 /// \brief Helper to form a PSHUFB-based shuffle+blend.
8276 static SDValue lowerVectorShuffleAsPSHUFB(SDLoc DL, MVT VT, SDValue V1,
8277                                           SDValue V2, ArrayRef<int> Mask,
8278                                           SelectionDAG &DAG, bool &V1InUse,
8279                                           bool &V2InUse) {
8280   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
8281   SDValue V1Mask[16];
8282   SDValue V2Mask[16];
8283   V1InUse = false;
8284   V2InUse = false;
8285
8286   int Size = Mask.size();
8287   int Scale = 16 / Size;
8288   for (int i = 0; i < 16; ++i) {
8289     if (Mask[i / Scale] == -1) {
8290       V1Mask[i] = V2Mask[i] = DAG.getUNDEF(MVT::i8);
8291     } else {
8292       const int ZeroMask = 0x80;
8293       int V1Idx = Mask[i / Scale] < Size ? Mask[i / Scale] * Scale + i % Scale
8294                                           : ZeroMask;
8295       int V2Idx = Mask[i / Scale] < Size
8296                       ? ZeroMask
8297                       : (Mask[i / Scale] - Size) * Scale + i % Scale;
8298       if (Zeroable[i / Scale])
8299         V1Idx = V2Idx = ZeroMask;
8300       V1Mask[i] = DAG.getConstant(V1Idx, MVT::i8);
8301       V2Mask[i] = DAG.getConstant(V2Idx, MVT::i8);
8302       V1InUse |= (ZeroMask != V1Idx);
8303       V2InUse |= (ZeroMask != V2Idx);
8304     }
8305   }
8306
8307   if (V1InUse)
8308     V1 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
8309                      DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, V1),
8310                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V1Mask));
8311   if (V2InUse)
8312     V2 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
8313                      DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, V2),
8314                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V2Mask));
8315
8316   // If we need shuffled inputs from both, blend the two.
8317   SDValue V;
8318   if (V1InUse && V2InUse)
8319     V = DAG.getNode(ISD::OR, DL, MVT::v16i8, V1, V2);
8320   else
8321     V = V1InUse ? V1 : V2;
8322
8323   // Cast the result back to the correct type.
8324   return DAG.getNode(ISD::BITCAST, DL, VT, V);
8325 }
8326
8327 /// \brief Generic lowering of 8-lane i16 shuffles.
8328 ///
8329 /// This handles both single-input shuffles and combined shuffle/blends with
8330 /// two inputs. The single input shuffles are immediately delegated to
8331 /// a dedicated lowering routine.
8332 ///
8333 /// The blends are lowered in one of three fundamental ways. If there are few
8334 /// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
8335 /// of the input is significantly cheaper when lowered as an interleaving of
8336 /// the two inputs, try to interleave them. Otherwise, blend the low and high
8337 /// halves of the inputs separately (making them have relatively few inputs)
8338 /// and then concatenate them.
8339 static SDValue lowerV8I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8340                                        const X86Subtarget *Subtarget,
8341                                        SelectionDAG &DAG) {
8342   SDLoc DL(Op);
8343   assert(Op.getSimpleValueType() == MVT::v8i16 && "Bad shuffle type!");
8344   assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
8345   assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
8346   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8347   ArrayRef<int> OrigMask = SVOp->getMask();
8348   int MaskStorage[8] = {OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
8349                         OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7]};
8350   MutableArrayRef<int> Mask(MaskStorage);
8351
8352   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
8353
8354   // Whenever we can lower this as a zext, that instruction is strictly faster
8355   // than any alternative.
8356   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
8357           DL, MVT::v8i16, V1, V2, OrigMask, Subtarget, DAG))
8358     return ZExt;
8359
8360   auto isV1 = [](int M) { return M >= 0 && M < 8; };
8361   (void)isV1;
8362   auto isV2 = [](int M) { return M >= 8; };
8363
8364   int NumV2Inputs = std::count_if(Mask.begin(), Mask.end(), isV2);
8365
8366   if (NumV2Inputs == 0) {
8367     // Check for being able to broadcast a single element.
8368     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i16, V1,
8369                                                           Mask, Subtarget, DAG))
8370       return Broadcast;
8371
8372     // Try to use shift instructions.
8373     if (SDValue Shift =
8374             lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V1, Mask, DAG))
8375       return Shift;
8376
8377     // Use dedicated unpack instructions for masks that match their pattern.
8378     if (isShuffleEquivalent(V1, V1, Mask, {0, 0, 1, 1, 2, 2, 3, 3}))
8379       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V1, V1);
8380     if (isShuffleEquivalent(V1, V1, Mask, {4, 4, 5, 5, 6, 6, 7, 7}))
8381       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V1, V1);
8382
8383     // Try to use byte rotation instructions.
8384     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(DL, MVT::v8i16, V1, V1,
8385                                                         Mask, Subtarget, DAG))
8386       return Rotate;
8387
8388     return lowerV8I16GeneralSingleInputVectorShuffle(DL, MVT::v8i16, V1, Mask,
8389                                                      Subtarget, DAG);
8390   }
8391
8392   assert(std::any_of(Mask.begin(), Mask.end(), isV1) &&
8393          "All single-input shuffles should be canonicalized to be V1-input "
8394          "shuffles.");
8395
8396   // Try to use shift instructions.
8397   if (SDValue Shift =
8398           lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V2, Mask, DAG))
8399     return Shift;
8400
8401   // There are special ways we can lower some single-element blends.
8402   if (NumV2Inputs == 1)
8403     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v8i16, V1, V2,
8404                                                          Mask, Subtarget, DAG))
8405       return V;
8406
8407   // We have different paths for blend lowering, but they all must use the
8408   // *exact* same predicate.
8409   bool IsBlendSupported = Subtarget->hasSSE41();
8410   if (IsBlendSupported)
8411     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i16, V1, V2, Mask,
8412                                                   Subtarget, DAG))
8413       return Blend;
8414
8415   if (SDValue Masked =
8416           lowerVectorShuffleAsBitMask(DL, MVT::v8i16, V1, V2, Mask, DAG))
8417     return Masked;
8418
8419   // Use dedicated unpack instructions for masks that match their pattern.
8420   if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 2, 10, 3, 11}))
8421     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V1, V2);
8422   if (isShuffleEquivalent(V1, V2, Mask, {4, 12, 5, 13, 6, 14, 7, 15}))
8423     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V1, V2);
8424
8425   // Try to use byte rotation instructions.
8426   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8427           DL, MVT::v8i16, V1, V2, Mask, Subtarget, DAG))
8428     return Rotate;
8429
8430   if (SDValue BitBlend =
8431           lowerVectorShuffleAsBitBlend(DL, MVT::v8i16, V1, V2, Mask, DAG))
8432     return BitBlend;
8433
8434   if (SDValue Unpack =
8435           lowerVectorShuffleAsUnpack(DL, MVT::v8i16, V1, V2, Mask, DAG))
8436     return Unpack;
8437
8438   // If we can't directly blend but can use PSHUFB, that will be better as it
8439   // can both shuffle and set up the inefficient blend.
8440   if (!IsBlendSupported && Subtarget->hasSSSE3()) {
8441     bool V1InUse, V2InUse;
8442     return lowerVectorShuffleAsPSHUFB(DL, MVT::v8i16, V1, V2, Mask, DAG,
8443                                       V1InUse, V2InUse);
8444   }
8445
8446   // We can always bit-blend if we have to so the fallback strategy is to
8447   // decompose into single-input permutes and blends.
8448   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i16, V1, V2,
8449                                                       Mask, DAG);
8450 }
8451
8452 /// \brief Check whether a compaction lowering can be done by dropping even
8453 /// elements and compute how many times even elements must be dropped.
8454 ///
8455 /// This handles shuffles which take every Nth element where N is a power of
8456 /// two. Example shuffle masks:
8457 ///
8458 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14,  0,  2,  4,  6,  8, 10, 12, 14
8459 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30
8460 ///  N = 2:  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12
8461 ///  N = 2:  0,  4,  8, 12, 16, 20, 24, 28,  0,  4,  8, 12, 16, 20, 24, 28
8462 ///  N = 3:  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8
8463 ///  N = 3:  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24
8464 ///
8465 /// Any of these lanes can of course be undef.
8466 ///
8467 /// This routine only supports N <= 3.
8468 /// FIXME: Evaluate whether either AVX or AVX-512 have any opportunities here
8469 /// for larger N.
8470 ///
8471 /// \returns N above, or the number of times even elements must be dropped if
8472 /// there is such a number. Otherwise returns zero.
8473 static int canLowerByDroppingEvenElements(ArrayRef<int> Mask) {
8474   // Figure out whether we're looping over two inputs or just one.
8475   bool IsSingleInput = isSingleInputShuffleMask(Mask);
8476
8477   // The modulus for the shuffle vector entries is based on whether this is
8478   // a single input or not.
8479   int ShuffleModulus = Mask.size() * (IsSingleInput ? 1 : 2);
8480   assert(isPowerOf2_32((uint32_t)ShuffleModulus) &&
8481          "We should only be called with masks with a power-of-2 size!");
8482
8483   uint64_t ModMask = (uint64_t)ShuffleModulus - 1;
8484
8485   // We track whether the input is viable for all power-of-2 strides 2^1, 2^2,
8486   // and 2^3 simultaneously. This is because we may have ambiguity with
8487   // partially undef inputs.
8488   bool ViableForN[3] = {true, true, true};
8489
8490   for (int i = 0, e = Mask.size(); i < e; ++i) {
8491     // Ignore undef lanes, we'll optimistically collapse them to the pattern we
8492     // want.
8493     if (Mask[i] == -1)
8494       continue;
8495
8496     bool IsAnyViable = false;
8497     for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
8498       if (ViableForN[j]) {
8499         uint64_t N = j + 1;
8500
8501         // The shuffle mask must be equal to (i * 2^N) % M.
8502         if ((uint64_t)Mask[i] == (((uint64_t)i << N) & ModMask))
8503           IsAnyViable = true;
8504         else
8505           ViableForN[j] = false;
8506       }
8507     // Early exit if we exhaust the possible powers of two.
8508     if (!IsAnyViable)
8509       break;
8510   }
8511
8512   for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
8513     if (ViableForN[j])
8514       return j + 1;
8515
8516   // Return 0 as there is no viable power of two.
8517   return 0;
8518 }
8519
8520 /// \brief Generic lowering of v16i8 shuffles.
8521 ///
8522 /// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
8523 /// detect any complexity reducing interleaving. If that doesn't help, it uses
8524 /// UNPCK to spread the i8 elements across two i16-element vectors, and uses
8525 /// the existing lowering for v8i16 blends on each half, finally PACK-ing them
8526 /// back together.
8527 static SDValue lowerV16I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8528                                        const X86Subtarget *Subtarget,
8529                                        SelectionDAG &DAG) {
8530   SDLoc DL(Op);
8531   assert(Op.getSimpleValueType() == MVT::v16i8 && "Bad shuffle type!");
8532   assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
8533   assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
8534   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8535   ArrayRef<int> Mask = SVOp->getMask();
8536   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
8537
8538   // Try to use shift instructions.
8539   if (SDValue Shift =
8540           lowerVectorShuffleAsShift(DL, MVT::v16i8, V1, V2, Mask, DAG))
8541     return Shift;
8542
8543   // Try to use byte rotation instructions.
8544   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8545           DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
8546     return Rotate;
8547
8548   // Try to use a zext lowering.
8549   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
8550           DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
8551     return ZExt;
8552
8553   int NumV2Elements =
8554       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 16; });
8555
8556   // For single-input shuffles, there are some nicer lowering tricks we can use.
8557   if (NumV2Elements == 0) {
8558     // Check for being able to broadcast a single element.
8559     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i8, V1,
8560                                                           Mask, Subtarget, DAG))
8561       return Broadcast;
8562
8563     // Check whether we can widen this to an i16 shuffle by duplicating bytes.
8564     // Notably, this handles splat and partial-splat shuffles more efficiently.
8565     // However, it only makes sense if the pre-duplication shuffle simplifies
8566     // things significantly. Currently, this means we need to be able to
8567     // express the pre-duplication shuffle as an i16 shuffle.
8568     //
8569     // FIXME: We should check for other patterns which can be widened into an
8570     // i16 shuffle as well.
8571     auto canWidenViaDuplication = [](ArrayRef<int> Mask) {
8572       for (int i = 0; i < 16; i += 2)
8573         if (Mask[i] != -1 && Mask[i + 1] != -1 && Mask[i] != Mask[i + 1])
8574           return false;
8575
8576       return true;
8577     };
8578     auto tryToWidenViaDuplication = [&]() -> SDValue {
8579       if (!canWidenViaDuplication(Mask))
8580         return SDValue();
8581       SmallVector<int, 4> LoInputs;
8582       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(LoInputs),
8583                    [](int M) { return M >= 0 && M < 8; });
8584       std::sort(LoInputs.begin(), LoInputs.end());
8585       LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()),
8586                      LoInputs.end());
8587       SmallVector<int, 4> HiInputs;
8588       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(HiInputs),
8589                    [](int M) { return M >= 8; });
8590       std::sort(HiInputs.begin(), HiInputs.end());
8591       HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()),
8592                      HiInputs.end());
8593
8594       bool TargetLo = LoInputs.size() >= HiInputs.size();
8595       ArrayRef<int> InPlaceInputs = TargetLo ? LoInputs : HiInputs;
8596       ArrayRef<int> MovingInputs = TargetLo ? HiInputs : LoInputs;
8597
8598       int PreDupI16Shuffle[] = {-1, -1, -1, -1, -1, -1, -1, -1};
8599       SmallDenseMap<int, int, 8> LaneMap;
8600       for (int I : InPlaceInputs) {
8601         PreDupI16Shuffle[I/2] = I/2;
8602         LaneMap[I] = I;
8603       }
8604       int j = TargetLo ? 0 : 4, je = j + 4;
8605       for (int i = 0, ie = MovingInputs.size(); i < ie; ++i) {
8606         // Check if j is already a shuffle of this input. This happens when
8607         // there are two adjacent bytes after we move the low one.
8608         if (PreDupI16Shuffle[j] != MovingInputs[i] / 2) {
8609           // If we haven't yet mapped the input, search for a slot into which
8610           // we can map it.
8611           while (j < je && PreDupI16Shuffle[j] != -1)
8612             ++j;
8613
8614           if (j == je)
8615             // We can't place the inputs into a single half with a simple i16 shuffle, so bail.
8616             return SDValue();
8617
8618           // Map this input with the i16 shuffle.
8619           PreDupI16Shuffle[j] = MovingInputs[i] / 2;
8620         }
8621
8622         // Update the lane map based on the mapping we ended up with.
8623         LaneMap[MovingInputs[i]] = 2 * j + MovingInputs[i] % 2;
8624       }
8625       V1 = DAG.getNode(
8626           ISD::BITCAST, DL, MVT::v16i8,
8627           DAG.getVectorShuffle(MVT::v8i16, DL,
8628                                DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1),
8629                                DAG.getUNDEF(MVT::v8i16), PreDupI16Shuffle));
8630
8631       // Unpack the bytes to form the i16s that will be shuffled into place.
8632       V1 = DAG.getNode(TargetLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
8633                        MVT::v16i8, V1, V1);
8634
8635       int PostDupI16Shuffle[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8636       for (int i = 0; i < 16; ++i)
8637         if (Mask[i] != -1) {
8638           int MappedMask = LaneMap[Mask[i]] - (TargetLo ? 0 : 8);
8639           assert(MappedMask < 8 && "Invalid v8 shuffle mask!");
8640           if (PostDupI16Shuffle[i / 2] == -1)
8641             PostDupI16Shuffle[i / 2] = MappedMask;
8642           else
8643             assert(PostDupI16Shuffle[i / 2] == MappedMask &&
8644                    "Conflicting entrties in the original shuffle!");
8645         }
8646       return DAG.getNode(
8647           ISD::BITCAST, DL, MVT::v16i8,
8648           DAG.getVectorShuffle(MVT::v8i16, DL,
8649                                DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1),
8650                                DAG.getUNDEF(MVT::v8i16), PostDupI16Shuffle));
8651     };
8652     if (SDValue V = tryToWidenViaDuplication())
8653       return V;
8654   }
8655
8656   // Use dedicated unpack instructions for masks that match their pattern.
8657   if (isShuffleEquivalent(V1, V2, Mask, {// Low half.
8658                                          0, 16, 1, 17, 2, 18, 3, 19,
8659                                          // High half.
8660                                          4, 20, 5, 21, 6, 22, 7, 23}))
8661     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V1, V2);
8662   if (isShuffleEquivalent(V1, V2, Mask, {// Low half.
8663                                          8, 24, 9, 25, 10, 26, 11, 27,
8664                                          // High half.
8665                                          12, 28, 13, 29, 14, 30, 15, 31}))
8666     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V1, V2);
8667
8668   // Check for SSSE3 which lets us lower all v16i8 shuffles much more directly
8669   // with PSHUFB. It is important to do this before we attempt to generate any
8670   // blends but after all of the single-input lowerings. If the single input
8671   // lowerings can find an instruction sequence that is faster than a PSHUFB, we
8672   // want to preserve that and we can DAG combine any longer sequences into
8673   // a PSHUFB in the end. But once we start blending from multiple inputs,
8674   // the complexity of DAG combining bad patterns back into PSHUFB is too high,
8675   // and there are *very* few patterns that would actually be faster than the
8676   // PSHUFB approach because of its ability to zero lanes.
8677   //
8678   // FIXME: The only exceptions to the above are blends which are exact
8679   // interleavings with direct instructions supporting them. We currently don't
8680   // handle those well here.
8681   if (Subtarget->hasSSSE3()) {
8682     bool V1InUse = false;
8683     bool V2InUse = false;
8684
8685     SDValue PSHUFB = lowerVectorShuffleAsPSHUFB(DL, MVT::v16i8, V1, V2, Mask,
8686                                                 DAG, V1InUse, V2InUse);
8687
8688     // If both V1 and V2 are in use and we can use a direct blend or an unpack,
8689     // do so. This avoids using them to handle blends-with-zero which is
8690     // important as a single pshufb is significantly faster for that.
8691     if (V1InUse && V2InUse) {
8692       if (Subtarget->hasSSE41())
8693         if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i8, V1, V2,
8694                                                       Mask, Subtarget, DAG))
8695           return Blend;
8696
8697       // We can use an unpack to do the blending rather than an or in some
8698       // cases. Even though the or may be (very minorly) more efficient, we
8699       // preference this lowering because there are common cases where part of
8700       // the complexity of the shuffles goes away when we do the final blend as
8701       // an unpack.
8702       // FIXME: It might be worth trying to detect if the unpack-feeding
8703       // shuffles will both be pshufb, in which case we shouldn't bother with
8704       // this.
8705       if (SDValue Unpack =
8706               lowerVectorShuffleAsUnpack(DL, MVT::v16i8, V1, V2, Mask, DAG))
8707         return Unpack;
8708     }
8709
8710     return PSHUFB;
8711   }
8712
8713   // There are special ways we can lower some single-element blends.
8714   if (NumV2Elements == 1)
8715     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v16i8, V1, V2,
8716                                                          Mask, Subtarget, DAG))
8717       return V;
8718
8719   if (SDValue BitBlend =
8720           lowerVectorShuffleAsBitBlend(DL, MVT::v16i8, V1, V2, Mask, DAG))
8721     return BitBlend;
8722
8723   // Check whether a compaction lowering can be done. This handles shuffles
8724   // which take every Nth element for some even N. See the helper function for
8725   // details.
8726   //
8727   // We special case these as they can be particularly efficiently handled with
8728   // the PACKUSB instruction on x86 and they show up in common patterns of
8729   // rearranging bytes to truncate wide elements.
8730   if (int NumEvenDrops = canLowerByDroppingEvenElements(Mask)) {
8731     // NumEvenDrops is the power of two stride of the elements. Another way of
8732     // thinking about it is that we need to drop the even elements this many
8733     // times to get the original input.
8734     bool IsSingleInput = isSingleInputShuffleMask(Mask);
8735
8736     // First we need to zero all the dropped bytes.
8737     assert(NumEvenDrops <= 3 &&
8738            "No support for dropping even elements more than 3 times.");
8739     // We use the mask type to pick which bytes are preserved based on how many
8740     // elements are dropped.
8741     MVT MaskVTs[] = { MVT::v8i16, MVT::v4i32, MVT::v2i64 };
8742     SDValue ByteClearMask =
8743         DAG.getNode(ISD::BITCAST, DL, MVT::v16i8,
8744                     DAG.getConstant(0xFF, MaskVTs[NumEvenDrops - 1]));
8745     V1 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V1, ByteClearMask);
8746     if (!IsSingleInput)
8747       V2 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V2, ByteClearMask);
8748
8749     // Now pack things back together.
8750     V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1);
8751     V2 = IsSingleInput ? V1 : DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V2);
8752     SDValue Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, V1, V2);
8753     for (int i = 1; i < NumEvenDrops; ++i) {
8754       Result = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, Result);
8755       Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, Result, Result);
8756     }
8757
8758     return Result;
8759   }
8760
8761   // Handle multi-input cases by blending single-input shuffles.
8762   if (NumV2Elements > 0)
8763     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v16i8, V1, V2,
8764                                                       Mask, DAG);
8765
8766   // The fallback path for single-input shuffles widens this into two v8i16
8767   // vectors with unpacks, shuffles those, and then pulls them back together
8768   // with a pack.
8769   SDValue V = V1;
8770
8771   int LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8772   int HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8773   for (int i = 0; i < 16; ++i)
8774     if (Mask[i] >= 0)
8775       (i < 8 ? LoBlendMask[i] : HiBlendMask[i % 8]) = Mask[i];
8776
8777   SDValue Zero = getZeroVector(MVT::v8i16, Subtarget, DAG, DL);
8778
8779   SDValue VLoHalf, VHiHalf;
8780   // Check if any of the odd lanes in the v16i8 are used. If not, we can mask
8781   // them out and avoid using UNPCK{L,H} to extract the elements of V as
8782   // i16s.
8783   if (std::none_of(std::begin(LoBlendMask), std::end(LoBlendMask),
8784                    [](int M) { return M >= 0 && M % 2 == 1; }) &&
8785       std::none_of(std::begin(HiBlendMask), std::end(HiBlendMask),
8786                    [](int M) { return M >= 0 && M % 2 == 1; })) {
8787     // Use a mask to drop the high bytes.
8788     VLoHalf = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V);
8789     VLoHalf = DAG.getNode(ISD::AND, DL, MVT::v8i16, VLoHalf,
8790                      DAG.getConstant(0x00FF, MVT::v8i16));
8791
8792     // This will be a single vector shuffle instead of a blend so nuke VHiHalf.
8793     VHiHalf = DAG.getUNDEF(MVT::v8i16);
8794
8795     // Squash the masks to point directly into VLoHalf.
8796     for (int &M : LoBlendMask)
8797       if (M >= 0)
8798         M /= 2;
8799     for (int &M : HiBlendMask)
8800       if (M >= 0)
8801         M /= 2;
8802   } else {
8803     // Otherwise just unpack the low half of V into VLoHalf and the high half into
8804     // VHiHalf so that we can blend them as i16s.
8805     VLoHalf = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
8806                      DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V, Zero));
8807     VHiHalf = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
8808                      DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V, Zero));
8809   }
8810
8811   SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, LoBlendMask);
8812   SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, HiBlendMask);
8813
8814   return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
8815 }
8816
8817 /// \brief Dispatching routine to lower various 128-bit x86 vector shuffles.
8818 ///
8819 /// This routine breaks down the specific type of 128-bit shuffle and
8820 /// dispatches to the lowering routines accordingly.
8821 static SDValue lower128BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8822                                         MVT VT, const X86Subtarget *Subtarget,
8823                                         SelectionDAG &DAG) {
8824   switch (VT.SimpleTy) {
8825   case MVT::v2i64:
8826     return lowerV2I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
8827   case MVT::v2f64:
8828     return lowerV2F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
8829   case MVT::v4i32:
8830     return lowerV4I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
8831   case MVT::v4f32:
8832     return lowerV4F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
8833   case MVT::v8i16:
8834     return lowerV8I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
8835   case MVT::v16i8:
8836     return lowerV16I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
8837
8838   default:
8839     llvm_unreachable("Unimplemented!");
8840   }
8841 }
8842
8843 /// \brief Helper function to test whether a shuffle mask could be
8844 /// simplified by widening the elements being shuffled.
8845 ///
8846 /// Appends the mask for wider elements in WidenedMask if valid. Otherwise
8847 /// leaves it in an unspecified state.
8848 ///
8849 /// NOTE: This must handle normal vector shuffle masks and *target* vector
8850 /// shuffle masks. The latter have the special property of a '-2' representing
8851 /// a zero-ed lane of a vector.
8852 static bool canWidenShuffleElements(ArrayRef<int> Mask,
8853                                     SmallVectorImpl<int> &WidenedMask) {
8854   for (int i = 0, Size = Mask.size(); i < Size; i += 2) {
8855     // If both elements are undef, its trivial.
8856     if (Mask[i] == SM_SentinelUndef && Mask[i + 1] == SM_SentinelUndef) {
8857       WidenedMask.push_back(SM_SentinelUndef);
8858       continue;
8859     }
8860
8861     // Check for an undef mask and a mask value properly aligned to fit with
8862     // a pair of values. If we find such a case, use the non-undef mask's value.
8863     if (Mask[i] == SM_SentinelUndef && Mask[i + 1] >= 0 && Mask[i + 1] % 2 == 1) {
8864       WidenedMask.push_back(Mask[i + 1] / 2);
8865       continue;
8866     }
8867     if (Mask[i + 1] == SM_SentinelUndef && Mask[i] >= 0 && Mask[i] % 2 == 0) {
8868       WidenedMask.push_back(Mask[i] / 2);
8869       continue;
8870     }
8871
8872     // When zeroing, we need to spread the zeroing across both lanes to widen.
8873     if (Mask[i] == SM_SentinelZero || Mask[i + 1] == SM_SentinelZero) {
8874       if ((Mask[i] == SM_SentinelZero || Mask[i] == SM_SentinelUndef) &&
8875           (Mask[i + 1] == SM_SentinelZero || Mask[i + 1] == SM_SentinelUndef)) {
8876         WidenedMask.push_back(SM_SentinelZero);
8877         continue;
8878       }
8879       return false;
8880     }
8881
8882     // Finally check if the two mask values are adjacent and aligned with
8883     // a pair.
8884     if (Mask[i] != SM_SentinelUndef && Mask[i] % 2 == 0 && Mask[i] + 1 == Mask[i + 1]) {
8885       WidenedMask.push_back(Mask[i] / 2);
8886       continue;
8887     }
8888
8889     // Otherwise we can't safely widen the elements used in this shuffle.
8890     return false;
8891   }
8892   assert(WidenedMask.size() == Mask.size() / 2 &&
8893          "Incorrect size of mask after widening the elements!");
8894
8895   return true;
8896 }
8897
8898 /// \brief Generic routine to split vector shuffle into half-sized shuffles.
8899 ///
8900 /// This routine just extracts two subvectors, shuffles them independently, and
8901 /// then concatenates them back together. This should work effectively with all
8902 /// AVX vector shuffle types.
8903 static SDValue splitAndLowerVectorShuffle(SDLoc DL, MVT VT, SDValue V1,
8904                                           SDValue V2, ArrayRef<int> Mask,
8905                                           SelectionDAG &DAG) {
8906   assert(VT.getSizeInBits() >= 256 &&
8907          "Only for 256-bit or wider vector shuffles!");
8908   assert(V1.getSimpleValueType() == VT && "Bad operand type!");
8909   assert(V2.getSimpleValueType() == VT && "Bad operand type!");
8910
8911   ArrayRef<int> LoMask = Mask.slice(0, Mask.size() / 2);
8912   ArrayRef<int> HiMask = Mask.slice(Mask.size() / 2);
8913
8914   int NumElements = VT.getVectorNumElements();
8915   int SplitNumElements = NumElements / 2;
8916   MVT ScalarVT = VT.getScalarType();
8917   MVT SplitVT = MVT::getVectorVT(ScalarVT, NumElements / 2);
8918
8919   // Rather than splitting build-vectors, just build two narrower build
8920   // vectors. This helps shuffling with splats and zeros.
8921   auto SplitVector = [&](SDValue V) {
8922     while (V.getOpcode() == ISD::BITCAST)
8923       V = V->getOperand(0);
8924
8925     MVT OrigVT = V.getSimpleValueType();
8926     int OrigNumElements = OrigVT.getVectorNumElements();
8927     int OrigSplitNumElements = OrigNumElements / 2;
8928     MVT OrigScalarVT = OrigVT.getScalarType();
8929     MVT OrigSplitVT = MVT::getVectorVT(OrigScalarVT, OrigNumElements / 2);
8930
8931     SDValue LoV, HiV;
8932
8933     auto *BV = dyn_cast<BuildVectorSDNode>(V);
8934     if (!BV) {
8935       LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
8936                         DAG.getIntPtrConstant(0));
8937       HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
8938                         DAG.getIntPtrConstant(OrigSplitNumElements));
8939     } else {
8940
8941       SmallVector<SDValue, 16> LoOps, HiOps;
8942       for (int i = 0; i < OrigSplitNumElements; ++i) {
8943         LoOps.push_back(BV->getOperand(i));
8944         HiOps.push_back(BV->getOperand(i + OrigSplitNumElements));
8945       }
8946       LoV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, LoOps);
8947       HiV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, HiOps);
8948     }
8949     return std::make_pair(DAG.getNode(ISD::BITCAST, DL, SplitVT, LoV),
8950                           DAG.getNode(ISD::BITCAST, DL, SplitVT, HiV));
8951   };
8952
8953   SDValue LoV1, HiV1, LoV2, HiV2;
8954   std::tie(LoV1, HiV1) = SplitVector(V1);
8955   std::tie(LoV2, HiV2) = SplitVector(V2);
8956
8957   // Now create two 4-way blends of these half-width vectors.
8958   auto HalfBlend = [&](ArrayRef<int> HalfMask) {
8959     bool UseLoV1 = false, UseHiV1 = false, UseLoV2 = false, UseHiV2 = false;
8960     SmallVector<int, 32> V1BlendMask, V2BlendMask, BlendMask;
8961     for (int i = 0; i < SplitNumElements; ++i) {
8962       int M = HalfMask[i];
8963       if (M >= NumElements) {
8964         if (M >= NumElements + SplitNumElements)
8965           UseHiV2 = true;
8966         else
8967           UseLoV2 = true;
8968         V2BlendMask.push_back(M - NumElements);
8969         V1BlendMask.push_back(-1);
8970         BlendMask.push_back(SplitNumElements + i);
8971       } else if (M >= 0) {
8972         if (M >= SplitNumElements)
8973           UseHiV1 = true;
8974         else
8975           UseLoV1 = true;
8976         V2BlendMask.push_back(-1);
8977         V1BlendMask.push_back(M);
8978         BlendMask.push_back(i);
8979       } else {
8980         V2BlendMask.push_back(-1);
8981         V1BlendMask.push_back(-1);
8982         BlendMask.push_back(-1);
8983       }
8984     }
8985
8986     // Because the lowering happens after all combining takes place, we need to
8987     // manually combine these blend masks as much as possible so that we create
8988     // a minimal number of high-level vector shuffle nodes.
8989
8990     // First try just blending the halves of V1 or V2.
8991     if (!UseLoV1 && !UseHiV1 && !UseLoV2 && !UseHiV2)
8992       return DAG.getUNDEF(SplitVT);
8993     if (!UseLoV2 && !UseHiV2)
8994       return DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
8995     if (!UseLoV1 && !UseHiV1)
8996       return DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
8997
8998     SDValue V1Blend, V2Blend;
8999     if (UseLoV1 && UseHiV1) {
9000       V1Blend =
9001         DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9002     } else {
9003       // We only use half of V1 so map the usage down into the final blend mask.
9004       V1Blend = UseLoV1 ? LoV1 : HiV1;
9005       for (int i = 0; i < SplitNumElements; ++i)
9006         if (BlendMask[i] >= 0 && BlendMask[i] < SplitNumElements)
9007           BlendMask[i] = V1BlendMask[i] - (UseLoV1 ? 0 : SplitNumElements);
9008     }
9009     if (UseLoV2 && UseHiV2) {
9010       V2Blend =
9011         DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9012     } else {
9013       // We only use half of V2 so map the usage down into the final blend mask.
9014       V2Blend = UseLoV2 ? LoV2 : HiV2;
9015       for (int i = 0; i < SplitNumElements; ++i)
9016         if (BlendMask[i] >= SplitNumElements)
9017           BlendMask[i] = V2BlendMask[i] + (UseLoV2 ? SplitNumElements : 0);
9018     }
9019     return DAG.getVectorShuffle(SplitVT, DL, V1Blend, V2Blend, BlendMask);
9020   };
9021   SDValue Lo = HalfBlend(LoMask);
9022   SDValue Hi = HalfBlend(HiMask);
9023   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
9024 }
9025
9026 /// \brief Either split a vector in halves or decompose the shuffles and the
9027 /// blend.
9028 ///
9029 /// This is provided as a good fallback for many lowerings of non-single-input
9030 /// shuffles with more than one 128-bit lane. In those cases, we want to select
9031 /// between splitting the shuffle into 128-bit components and stitching those
9032 /// back together vs. extracting the single-input shuffles and blending those
9033 /// results.
9034 static SDValue lowerVectorShuffleAsSplitOrBlend(SDLoc DL, MVT VT, SDValue V1,
9035                                                 SDValue V2, ArrayRef<int> Mask,
9036                                                 SelectionDAG &DAG) {
9037   assert(!isSingleInputShuffleMask(Mask) && "This routine must not be used to "
9038                                             "lower single-input shuffles as it "
9039                                             "could then recurse on itself.");
9040   int Size = Mask.size();
9041
9042   // If this can be modeled as a broadcast of two elements followed by a blend,
9043   // prefer that lowering. This is especially important because broadcasts can
9044   // often fold with memory operands.
9045   auto DoBothBroadcast = [&] {
9046     int V1BroadcastIdx = -1, V2BroadcastIdx = -1;
9047     for (int M : Mask)
9048       if (M >= Size) {
9049         if (V2BroadcastIdx == -1)
9050           V2BroadcastIdx = M - Size;
9051         else if (M - Size != V2BroadcastIdx)
9052           return false;
9053       } else if (M >= 0) {
9054         if (V1BroadcastIdx == -1)
9055           V1BroadcastIdx = M;
9056         else if (M != V1BroadcastIdx)
9057           return false;
9058       }
9059     return true;
9060   };
9061   if (DoBothBroadcast())
9062     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask,
9063                                                       DAG);
9064
9065   // If the inputs all stem from a single 128-bit lane of each input, then we
9066   // split them rather than blending because the split will decompose to
9067   // unusually few instructions.
9068   int LaneCount = VT.getSizeInBits() / 128;
9069   int LaneSize = Size / LaneCount;
9070   SmallBitVector LaneInputs[2];
9071   LaneInputs[0].resize(LaneCount, false);
9072   LaneInputs[1].resize(LaneCount, false);
9073   for (int i = 0; i < Size; ++i)
9074     if (Mask[i] >= 0)
9075       LaneInputs[Mask[i] / Size][(Mask[i] % Size) / LaneSize] = true;
9076   if (LaneInputs[0].count() <= 1 && LaneInputs[1].count() <= 1)
9077     return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9078
9079   // Otherwise, just fall back to decomposed shuffles and a blend. This requires
9080   // that the decomposed single-input shuffles don't end up here.
9081   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9082 }
9083
9084 /// \brief Lower a vector shuffle crossing multiple 128-bit lanes as
9085 /// a permutation and blend of those lanes.
9086 ///
9087 /// This essentially blends the out-of-lane inputs to each lane into the lane
9088 /// from a permuted copy of the vector. This lowering strategy results in four
9089 /// instructions in the worst case for a single-input cross lane shuffle which
9090 /// is lower than any other fully general cross-lane shuffle strategy I'm aware
9091 /// of. Special cases for each particular shuffle pattern should be handled
9092 /// prior to trying this lowering.
9093 static SDValue lowerVectorShuffleAsLanePermuteAndBlend(SDLoc DL, MVT VT,
9094                                                        SDValue V1, SDValue V2,
9095                                                        ArrayRef<int> Mask,
9096                                                        SelectionDAG &DAG) {
9097   // FIXME: This should probably be generalized for 512-bit vectors as well.
9098   assert(VT.getSizeInBits() == 256 && "Only for 256-bit vector shuffles!");
9099   int LaneSize = Mask.size() / 2;
9100
9101   // If there are only inputs from one 128-bit lane, splitting will in fact be
9102   // less expensive. The flags track whether the given lane contains an element
9103   // that crosses to another lane.
9104   bool LaneCrossing[2] = {false, false};
9105   for (int i = 0, Size = Mask.size(); i < Size; ++i)
9106     if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
9107       LaneCrossing[(Mask[i] % Size) / LaneSize] = true;
9108   if (!LaneCrossing[0] || !LaneCrossing[1])
9109     return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9110
9111   if (isSingleInputShuffleMask(Mask)) {
9112     SmallVector<int, 32> FlippedBlendMask;
9113     for (int i = 0, Size = Mask.size(); i < Size; ++i)
9114       FlippedBlendMask.push_back(
9115           Mask[i] < 0 ? -1 : (((Mask[i] % Size) / LaneSize == i / LaneSize)
9116                                   ? Mask[i]
9117                                   : Mask[i] % LaneSize +
9118                                         (i / LaneSize) * LaneSize + Size));
9119
9120     // Flip the vector, and blend the results which should now be in-lane. The
9121     // VPERM2X128 mask uses the low 2 bits for the low source and bits 4 and
9122     // 5 for the high source. The value 3 selects the high half of source 2 and
9123     // the value 2 selects the low half of source 2. We only use source 2 to
9124     // allow folding it into a memory operand.
9125     unsigned PERMMask = 3 | 2 << 4;
9126     SDValue Flipped = DAG.getNode(X86ISD::VPERM2X128, DL, VT, DAG.getUNDEF(VT),
9127                                   V1, DAG.getConstant(PERMMask, MVT::i8));
9128     return DAG.getVectorShuffle(VT, DL, V1, Flipped, FlippedBlendMask);
9129   }
9130
9131   // This now reduces to two single-input shuffles of V1 and V2 which at worst
9132   // will be handled by the above logic and a blend of the results, much like
9133   // other patterns in AVX.
9134   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9135 }
9136
9137 /// \brief Handle lowering 2-lane 128-bit shuffles.
9138 static SDValue lowerV2X128VectorShuffle(SDLoc DL, MVT VT, SDValue V1,
9139                                         SDValue V2, ArrayRef<int> Mask,
9140                                         const X86Subtarget *Subtarget,
9141                                         SelectionDAG &DAG) {
9142   // TODO: If minimizing size and one of the inputs is a zero vector and the
9143   // the zero vector has only one use, we could use a VPERM2X128 to save the
9144   // instruction bytes needed to explicitly generate the zero vector.
9145
9146   // Blends are faster and handle all the non-lane-crossing cases.
9147   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, VT, V1, V2, Mask,
9148                                                 Subtarget, DAG))
9149     return Blend;
9150
9151   bool IsV1Zero = ISD::isBuildVectorAllZeros(V1.getNode());
9152   bool IsV2Zero = ISD::isBuildVectorAllZeros(V2.getNode());
9153
9154   // If either input operand is a zero vector, use VPERM2X128 because its mask
9155   // allows us to replace the zero input with an implicit zero.
9156   if (!IsV1Zero && !IsV2Zero) {
9157     // Check for patterns which can be matched with a single insert of a 128-bit
9158     // subvector.
9159     bool OnlyUsesV1 = isShuffleEquivalent(V1, V2, Mask, {0, 1, 0, 1});
9160     if (OnlyUsesV1 || isShuffleEquivalent(V1, V2, Mask, {0, 1, 4, 5})) {
9161       MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(),
9162                                    VT.getVectorNumElements() / 2);
9163       SDValue LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V1,
9164                                 DAG.getIntPtrConstant(0));
9165       SDValue HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT,
9166                                 OnlyUsesV1 ? V1 : V2, DAG.getIntPtrConstant(0));
9167       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LoV, HiV);
9168     }
9169   }
9170
9171   // Otherwise form a 128-bit permutation. After accounting for undefs,
9172   // convert the 64-bit shuffle mask selection values into 128-bit
9173   // selection bits by dividing the indexes by 2 and shifting into positions
9174   // defined by a vperm2*128 instruction's immediate control byte.
9175
9176   // The immediate permute control byte looks like this:
9177   //    [1:0] - select 128 bits from sources for low half of destination
9178   //    [2]   - ignore
9179   //    [3]   - zero low half of destination
9180   //    [5:4] - select 128 bits from sources for high half of destination
9181   //    [6]   - ignore
9182   //    [7]   - zero high half of destination
9183
9184   int MaskLO = Mask[0];
9185   if (MaskLO == SM_SentinelUndef)
9186     MaskLO = Mask[1] == SM_SentinelUndef ? 0 : Mask[1];
9187
9188   int MaskHI = Mask[2];
9189   if (MaskHI == SM_SentinelUndef)
9190     MaskHI = Mask[3] == SM_SentinelUndef ? 0 : Mask[3];
9191
9192   unsigned PermMask = MaskLO / 2 | (MaskHI / 2) << 4;
9193
9194   // If either input is a zero vector, replace it with an undef input.
9195   // Shuffle mask values <  4 are selecting elements of V1.
9196   // Shuffle mask values >= 4 are selecting elements of V2.
9197   // Adjust each half of the permute mask by clearing the half that was
9198   // selecting the zero vector and setting the zero mask bit.
9199   if (IsV1Zero) {
9200     V1 = DAG.getUNDEF(VT);
9201     if (MaskLO < 4)
9202       PermMask = (PermMask & 0xf0) | 0x08;
9203     if (MaskHI < 4)
9204       PermMask = (PermMask & 0x0f) | 0x80;
9205   }
9206   if (IsV2Zero) {
9207     V2 = DAG.getUNDEF(VT);
9208     if (MaskLO >= 4)
9209       PermMask = (PermMask & 0xf0) | 0x08;
9210     if (MaskHI >= 4)
9211       PermMask = (PermMask & 0x0f) | 0x80;
9212   }
9213
9214   return DAG.getNode(X86ISD::VPERM2X128, DL, VT, V1, V2,
9215                      DAG.getConstant(PermMask, MVT::i8));
9216 }
9217
9218 /// \brief Lower a vector shuffle by first fixing the 128-bit lanes and then
9219 /// shuffling each lane.
9220 ///
9221 /// This will only succeed when the result of fixing the 128-bit lanes results
9222 /// in a single-input non-lane-crossing shuffle with a repeating shuffle mask in
9223 /// each 128-bit lanes. This handles many cases where we can quickly blend away
9224 /// the lane crosses early and then use simpler shuffles within each lane.
9225 ///
9226 /// FIXME: It might be worthwhile at some point to support this without
9227 /// requiring the 128-bit lane-relative shuffles to be repeating, but currently
9228 /// in x86 only floating point has interesting non-repeating shuffles, and even
9229 /// those are still *marginally* more expensive.
9230 static SDValue lowerVectorShuffleByMerging128BitLanes(
9231     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
9232     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
9233   assert(!isSingleInputShuffleMask(Mask) &&
9234          "This is only useful with multiple inputs.");
9235
9236   int Size = Mask.size();
9237   int LaneSize = 128 / VT.getScalarSizeInBits();
9238   int NumLanes = Size / LaneSize;
9239   assert(NumLanes > 1 && "Only handles 256-bit and wider shuffles.");
9240
9241   // See if we can build a hypothetical 128-bit lane-fixing shuffle mask. Also
9242   // check whether the in-128-bit lane shuffles share a repeating pattern.
9243   SmallVector<int, 4> Lanes;
9244   Lanes.resize(NumLanes, -1);
9245   SmallVector<int, 4> InLaneMask;
9246   InLaneMask.resize(LaneSize, -1);
9247   for (int i = 0; i < Size; ++i) {
9248     if (Mask[i] < 0)
9249       continue;
9250
9251     int j = i / LaneSize;
9252
9253     if (Lanes[j] < 0) {
9254       // First entry we've seen for this lane.
9255       Lanes[j] = Mask[i] / LaneSize;
9256     } else if (Lanes[j] != Mask[i] / LaneSize) {
9257       // This doesn't match the lane selected previously!
9258       return SDValue();
9259     }
9260
9261     // Check that within each lane we have a consistent shuffle mask.
9262     int k = i % LaneSize;
9263     if (InLaneMask[k] < 0) {
9264       InLaneMask[k] = Mask[i] % LaneSize;
9265     } else if (InLaneMask[k] != Mask[i] % LaneSize) {
9266       // This doesn't fit a repeating in-lane mask.
9267       return SDValue();
9268     }
9269   }
9270
9271   // First shuffle the lanes into place.
9272   MVT LaneVT = MVT::getVectorVT(VT.isFloatingPoint() ? MVT::f64 : MVT::i64,
9273                                 VT.getSizeInBits() / 64);
9274   SmallVector<int, 8> LaneMask;
9275   LaneMask.resize(NumLanes * 2, -1);
9276   for (int i = 0; i < NumLanes; ++i)
9277     if (Lanes[i] >= 0) {
9278       LaneMask[2 * i + 0] = 2*Lanes[i] + 0;
9279       LaneMask[2 * i + 1] = 2*Lanes[i] + 1;
9280     }
9281
9282   V1 = DAG.getNode(ISD::BITCAST, DL, LaneVT, V1);
9283   V2 = DAG.getNode(ISD::BITCAST, DL, LaneVT, V2);
9284   SDValue LaneShuffle = DAG.getVectorShuffle(LaneVT, DL, V1, V2, LaneMask);
9285
9286   // Cast it back to the type we actually want.
9287   LaneShuffle = DAG.getNode(ISD::BITCAST, DL, VT, LaneShuffle);
9288
9289   // Now do a simple shuffle that isn't lane crossing.
9290   SmallVector<int, 8> NewMask;
9291   NewMask.resize(Size, -1);
9292   for (int i = 0; i < Size; ++i)
9293     if (Mask[i] >= 0)
9294       NewMask[i] = (i / LaneSize) * LaneSize + Mask[i] % LaneSize;
9295   assert(!is128BitLaneCrossingShuffleMask(VT, NewMask) &&
9296          "Must not introduce lane crosses at this point!");
9297
9298   return DAG.getVectorShuffle(VT, DL, LaneShuffle, DAG.getUNDEF(VT), NewMask);
9299 }
9300
9301 /// \brief Test whether the specified input (0 or 1) is in-place blended by the
9302 /// given mask.
9303 ///
9304 /// This returns true if the elements from a particular input are already in the
9305 /// slot required by the given mask and require no permutation.
9306 static bool isShuffleMaskInputInPlace(int Input, ArrayRef<int> Mask) {
9307   assert((Input == 0 || Input == 1) && "Only two inputs to shuffles.");
9308   int Size = Mask.size();
9309   for (int i = 0; i < Size; ++i)
9310     if (Mask[i] >= 0 && Mask[i] / Size == Input && Mask[i] % Size != i)
9311       return false;
9312
9313   return true;
9314 }
9315
9316 /// \brief Handle lowering of 4-lane 64-bit floating point shuffles.
9317 ///
9318 /// Also ends up handling lowering of 4-lane 64-bit integer shuffles when AVX2
9319 /// isn't available.
9320 static SDValue lowerV4F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9321                                        const X86Subtarget *Subtarget,
9322                                        SelectionDAG &DAG) {
9323   SDLoc DL(Op);
9324   assert(V1.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
9325   assert(V2.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
9326   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9327   ArrayRef<int> Mask = SVOp->getMask();
9328   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
9329
9330   SmallVector<int, 4> WidenedMask;
9331   if (canWidenShuffleElements(Mask, WidenedMask))
9332     return lowerV2X128VectorShuffle(DL, MVT::v4f64, V1, V2, Mask, Subtarget,
9333                                     DAG);
9334
9335   if (isSingleInputShuffleMask(Mask)) {
9336     // Check for being able to broadcast a single element.
9337     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f64, V1,
9338                                                           Mask, Subtarget, DAG))
9339       return Broadcast;
9340
9341     // Use low duplicate instructions for masks that match their pattern.
9342     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
9343       return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v4f64, V1);
9344
9345     if (!is128BitLaneCrossingShuffleMask(MVT::v4f64, Mask)) {
9346       // Non-half-crossing single input shuffles can be lowerid with an
9347       // interleaved permutation.
9348       unsigned VPERMILPMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1) |
9349                               ((Mask[2] == 3) << 2) | ((Mask[3] == 3) << 3);
9350       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f64, V1,
9351                          DAG.getConstant(VPERMILPMask, MVT::i8));
9352     }
9353
9354     // With AVX2 we have direct support for this permutation.
9355     if (Subtarget->hasAVX2())
9356       return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4f64, V1,
9357                          getV4X86ShuffleImm8ForMask(Mask, DAG));
9358
9359     // Otherwise, fall back.
9360     return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v4f64, V1, V2, Mask,
9361                                                    DAG);
9362   }
9363
9364   // X86 has dedicated unpack instructions that can handle specific blend
9365   // operations: UNPCKH and UNPCKL.
9366   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 2, 6}))
9367     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V1, V2);
9368   if (isShuffleEquivalent(V1, V2, Mask, {1, 5, 3, 7}))
9369     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V1, V2);
9370   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 6, 2}))
9371     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V2, V1);
9372   if (isShuffleEquivalent(V1, V2, Mask, {5, 1, 7, 3}))
9373     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V2, V1);
9374
9375   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f64, V1, V2, Mask,
9376                                                 Subtarget, DAG))
9377     return Blend;
9378
9379   // Check if the blend happens to exactly fit that of SHUFPD.
9380   if ((Mask[0] == -1 || Mask[0] < 2) &&
9381       (Mask[1] == -1 || (Mask[1] >= 4 && Mask[1] < 6)) &&
9382       (Mask[2] == -1 || (Mask[2] >= 2 && Mask[2] < 4)) &&
9383       (Mask[3] == -1 || Mask[3] >= 6)) {
9384     unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 5) << 1) |
9385                           ((Mask[2] == 3) << 2) | ((Mask[3] == 7) << 3);
9386     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f64, V1, V2,
9387                        DAG.getConstant(SHUFPDMask, MVT::i8));
9388   }
9389   if ((Mask[0] == -1 || (Mask[0] >= 4 && Mask[0] < 6)) &&
9390       (Mask[1] == -1 || Mask[1] < 2) &&
9391       (Mask[2] == -1 || Mask[2] >= 6) &&
9392       (Mask[3] == -1 || (Mask[3] >= 2 && Mask[3] < 4))) {
9393     unsigned SHUFPDMask = (Mask[0] == 5) | ((Mask[1] == 1) << 1) |
9394                           ((Mask[2] == 7) << 2) | ((Mask[3] == 3) << 3);
9395     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f64, V2, V1,
9396                        DAG.getConstant(SHUFPDMask, MVT::i8));
9397   }
9398
9399   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9400   // shuffle. However, if we have AVX2 and either inputs are already in place,
9401   // we will be able to shuffle even across lanes the other input in a single
9402   // instruction so skip this pattern.
9403   if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
9404                                  isShuffleMaskInputInPlace(1, Mask))))
9405     if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9406             DL, MVT::v4f64, V1, V2, Mask, Subtarget, DAG))
9407       return Result;
9408
9409   // If we have AVX2 then we always want to lower with a blend because an v4 we
9410   // can fully permute the elements.
9411   if (Subtarget->hasAVX2())
9412     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4f64, V1, V2,
9413                                                       Mask, DAG);
9414
9415   // Otherwise fall back on generic lowering.
9416   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v4f64, V1, V2, Mask, DAG);
9417 }
9418
9419 /// \brief Handle lowering of 4-lane 64-bit integer shuffles.
9420 ///
9421 /// This routine is only called when we have AVX2 and thus a reasonable
9422 /// instruction set for v4i64 shuffling..
9423 static SDValue lowerV4I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9424                                        const X86Subtarget *Subtarget,
9425                                        SelectionDAG &DAG) {
9426   SDLoc DL(Op);
9427   assert(V1.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
9428   assert(V2.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
9429   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9430   ArrayRef<int> Mask = SVOp->getMask();
9431   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
9432   assert(Subtarget->hasAVX2() && "We can only lower v4i64 with AVX2!");
9433
9434   SmallVector<int, 4> WidenedMask;
9435   if (canWidenShuffleElements(Mask, WidenedMask))
9436     return lowerV2X128VectorShuffle(DL, MVT::v4i64, V1, V2, Mask, Subtarget,
9437                                     DAG);
9438
9439   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i64, V1, V2, Mask,
9440                                                 Subtarget, DAG))
9441     return Blend;
9442
9443   // Check for being able to broadcast a single element.
9444   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i64, V1,
9445                                                         Mask, Subtarget, DAG))
9446     return Broadcast;
9447
9448   // When the shuffle is mirrored between the 128-bit lanes of the unit, we can
9449   // use lower latency instructions that will operate on both 128-bit lanes.
9450   SmallVector<int, 2> RepeatedMask;
9451   if (is128BitLaneRepeatedShuffleMask(MVT::v4i64, Mask, RepeatedMask)) {
9452     if (isSingleInputShuffleMask(Mask)) {
9453       int PSHUFDMask[] = {-1, -1, -1, -1};
9454       for (int i = 0; i < 2; ++i)
9455         if (RepeatedMask[i] >= 0) {
9456           PSHUFDMask[2 * i] = 2 * RepeatedMask[i];
9457           PSHUFDMask[2 * i + 1] = 2 * RepeatedMask[i] + 1;
9458         }
9459       return DAG.getNode(
9460           ISD::BITCAST, DL, MVT::v4i64,
9461           DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32,
9462                       DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, V1),
9463                       getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
9464     }
9465   }
9466
9467   // AVX2 provides a direct instruction for permuting a single input across
9468   // lanes.
9469   if (isSingleInputShuffleMask(Mask))
9470     return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4i64, V1,
9471                        getV4X86ShuffleImm8ForMask(Mask, DAG));
9472
9473   // Try to use shift instructions.
9474   if (SDValue Shift =
9475           lowerVectorShuffleAsShift(DL, MVT::v4i64, V1, V2, Mask, DAG))
9476     return Shift;
9477
9478   // Use dedicated unpack instructions for masks that match their pattern.
9479   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 2, 6}))
9480     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V1, V2);
9481   if (isShuffleEquivalent(V1, V2, Mask, {1, 5, 3, 7}))
9482     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V1, V2);
9483   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 6, 2}))
9484     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V2, V1);
9485   if (isShuffleEquivalent(V1, V2, Mask, {5, 1, 7, 3}))
9486     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V2, V1);
9487
9488   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9489   // shuffle. However, if we have AVX2 and either inputs are already in place,
9490   // we will be able to shuffle even across lanes the other input in a single
9491   // instruction so skip this pattern.
9492   if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
9493                                  isShuffleMaskInputInPlace(1, Mask))))
9494     if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9495             DL, MVT::v4i64, V1, V2, Mask, Subtarget, DAG))
9496       return Result;
9497
9498   // Otherwise fall back on generic blend lowering.
9499   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i64, V1, V2,
9500                                                     Mask, DAG);
9501 }
9502
9503 /// \brief Handle lowering of 8-lane 32-bit floating point shuffles.
9504 ///
9505 /// Also ends up handling lowering of 8-lane 32-bit integer shuffles when AVX2
9506 /// isn't available.
9507 static SDValue lowerV8F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9508                                        const X86Subtarget *Subtarget,
9509                                        SelectionDAG &DAG) {
9510   SDLoc DL(Op);
9511   assert(V1.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
9512   assert(V2.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
9513   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9514   ArrayRef<int> Mask = SVOp->getMask();
9515   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9516
9517   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8f32, 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::v8f32, V1,
9523                                                         Mask, Subtarget, DAG))
9524     return Broadcast;
9525
9526   // If the shuffle mask is repeated in each 128-bit lane, we have many more
9527   // options to efficiently lower the shuffle.
9528   SmallVector<int, 4> RepeatedMask;
9529   if (is128BitLaneRepeatedShuffleMask(MVT::v8f32, Mask, RepeatedMask)) {
9530     assert(RepeatedMask.size() == 4 &&
9531            "Repeated masks must be half the mask width!");
9532
9533     // Use even/odd duplicate instructions for masks that match their pattern.
9534     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2, 4, 4, 6, 6}))
9535       return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v8f32, V1);
9536     if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3, 5, 5, 7, 7}))
9537       return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v8f32, V1);
9538
9539     if (isSingleInputShuffleMask(Mask))
9540       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v8f32, V1,
9541                          getV4X86ShuffleImm8ForMask(RepeatedMask, DAG));
9542
9543     // Use dedicated unpack instructions for masks that match their pattern.
9544     if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 4, 12, 5, 13}))
9545       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V1, V2);
9546     if (isShuffleEquivalent(V1, V2, Mask, {2, 10, 3, 11, 6, 14, 7, 15}))
9547       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V1, V2);
9548     if (isShuffleEquivalent(V1, V2, Mask, {8, 0, 9, 1, 12, 4, 13, 5}))
9549       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V2, V1);
9550     if (isShuffleEquivalent(V1, V2, Mask, {10, 2, 11, 3, 14, 6, 15, 7}))
9551       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V2, V1);
9552
9553     // Otherwise, fall back to a SHUFPS sequence. Here it is important that we
9554     // have already handled any direct blends. We also need to squash the
9555     // repeated mask into a simulated v4f32 mask.
9556     for (int i = 0; i < 4; ++i)
9557       if (RepeatedMask[i] >= 8)
9558         RepeatedMask[i] -= 4;
9559     return lowerVectorShuffleWithSHUFPS(DL, MVT::v8f32, RepeatedMask, V1, V2, DAG);
9560   }
9561
9562   // If we have a single input shuffle with different shuffle patterns in the
9563   // two 128-bit lanes use the variable mask to VPERMILPS.
9564   if (isSingleInputShuffleMask(Mask)) {
9565     SDValue VPermMask[8];
9566     for (int i = 0; i < 8; ++i)
9567       VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
9568                                  : DAG.getConstant(Mask[i], MVT::i32);
9569     if (!is128BitLaneCrossingShuffleMask(MVT::v8f32, Mask))
9570       return DAG.getNode(
9571           X86ISD::VPERMILPV, DL, MVT::v8f32, V1,
9572           DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask));
9573
9574     if (Subtarget->hasAVX2())
9575       return DAG.getNode(X86ISD::VPERMV, DL, MVT::v8f32,
9576                          DAG.getNode(ISD::BITCAST, DL, MVT::v8f32,
9577                                      DAG.getNode(ISD::BUILD_VECTOR, DL,
9578                                                  MVT::v8i32, VPermMask)),
9579                          V1);
9580
9581     // Otherwise, fall back.
9582     return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v8f32, V1, V2, Mask,
9583                                                    DAG);
9584   }
9585
9586   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9587   // shuffle.
9588   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9589           DL, MVT::v8f32, V1, V2, Mask, Subtarget, DAG))
9590     return Result;
9591
9592   // If we have AVX2 then we always want to lower with a blend because at v8 we
9593   // can fully permute the elements.
9594   if (Subtarget->hasAVX2())
9595     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8f32, V1, V2,
9596                                                       Mask, DAG);
9597
9598   // Otherwise fall back on generic lowering.
9599   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v8f32, V1, V2, Mask, DAG);
9600 }
9601
9602 /// \brief Handle lowering of 8-lane 32-bit integer shuffles.
9603 ///
9604 /// This routine is only called when we have AVX2 and thus a reasonable
9605 /// instruction set for v8i32 shuffling..
9606 static SDValue lowerV8I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9607                                        const X86Subtarget *Subtarget,
9608                                        SelectionDAG &DAG) {
9609   SDLoc DL(Op);
9610   assert(V1.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
9611   assert(V2.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
9612   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9613   ArrayRef<int> Mask = SVOp->getMask();
9614   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9615   assert(Subtarget->hasAVX2() && "We can only lower v8i32 with AVX2!");
9616
9617   // Whenever we can lower this as a zext, that instruction is strictly faster
9618   // than any alternative. It also allows us to fold memory operands into the
9619   // shuffle in many cases.
9620   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v8i32, V1, V2,
9621                                                          Mask, Subtarget, DAG))
9622     return ZExt;
9623
9624   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i32, V1, V2, Mask,
9625                                                 Subtarget, DAG))
9626     return Blend;
9627
9628   // Check for being able to broadcast a single element.
9629   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i32, V1,
9630                                                         Mask, Subtarget, DAG))
9631     return Broadcast;
9632
9633   // If the shuffle mask is repeated in each 128-bit lane we can use more
9634   // efficient instructions that mirror the shuffles across the two 128-bit
9635   // lanes.
9636   SmallVector<int, 4> RepeatedMask;
9637   if (is128BitLaneRepeatedShuffleMask(MVT::v8i32, Mask, RepeatedMask)) {
9638     assert(RepeatedMask.size() == 4 && "Unexpected repeated mask size!");
9639     if (isSingleInputShuffleMask(Mask))
9640       return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32, V1,
9641                          getV4X86ShuffleImm8ForMask(RepeatedMask, DAG));
9642
9643     // Use dedicated unpack instructions for masks that match their pattern.
9644     if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 4, 12, 5, 13}))
9645       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V1, V2);
9646     if (isShuffleEquivalent(V1, V2, Mask, {2, 10, 3, 11, 6, 14, 7, 15}))
9647       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V1, V2);
9648     if (isShuffleEquivalent(V1, V2, Mask, {8, 0, 9, 1, 12, 4, 13, 5}))
9649       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V2, V1);
9650     if (isShuffleEquivalent(V1, V2, Mask, {10, 2, 11, 3, 14, 6, 15, 7}))
9651       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V2, V1);
9652   }
9653
9654   // Try to use shift instructions.
9655   if (SDValue Shift =
9656           lowerVectorShuffleAsShift(DL, MVT::v8i32, V1, V2, Mask, DAG))
9657     return Shift;
9658
9659   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9660           DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
9661     return Rotate;
9662
9663   // If the shuffle patterns aren't repeated but it is a single input, directly
9664   // generate a cross-lane VPERMD instruction.
9665   if (isSingleInputShuffleMask(Mask)) {
9666     SDValue VPermMask[8];
9667     for (int i = 0; i < 8; ++i)
9668       VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
9669                                  : DAG.getConstant(Mask[i], MVT::i32);
9670     return DAG.getNode(
9671         X86ISD::VPERMV, DL, MVT::v8i32,
9672         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask), V1);
9673   }
9674
9675   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9676   // shuffle.
9677   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9678           DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
9679     return Result;
9680
9681   // Otherwise fall back on generic blend lowering.
9682   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i32, V1, V2,
9683                                                     Mask, DAG);
9684 }
9685
9686 /// \brief Handle lowering of 16-lane 16-bit integer shuffles.
9687 ///
9688 /// This routine is only called when we have AVX2 and thus a reasonable
9689 /// instruction set for v16i16 shuffling..
9690 static SDValue lowerV16I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9691                                         const X86Subtarget *Subtarget,
9692                                         SelectionDAG &DAG) {
9693   SDLoc DL(Op);
9694   assert(V1.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
9695   assert(V2.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
9696   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9697   ArrayRef<int> Mask = SVOp->getMask();
9698   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
9699   assert(Subtarget->hasAVX2() && "We can only lower v16i16 with AVX2!");
9700
9701   // Whenever we can lower this as a zext, that instruction is strictly faster
9702   // than any alternative. It also allows us to fold memory operands into the
9703   // shuffle in many cases.
9704   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v16i16, V1, V2,
9705                                                          Mask, Subtarget, DAG))
9706     return ZExt;
9707
9708   // Check for being able to broadcast a single element.
9709   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i16, V1,
9710                                                         Mask, Subtarget, DAG))
9711     return Broadcast;
9712
9713   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i16, V1, V2, Mask,
9714                                                 Subtarget, DAG))
9715     return Blend;
9716
9717   // Use dedicated unpack instructions for masks that match their pattern.
9718   if (isShuffleEquivalent(V1, V2, Mask,
9719                           {// First 128-bit lane:
9720                            0, 16, 1, 17, 2, 18, 3, 19,
9721                            // Second 128-bit lane:
9722                            8, 24, 9, 25, 10, 26, 11, 27}))
9723     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i16, V1, V2);
9724   if (isShuffleEquivalent(V1, V2, Mask,
9725                           {// First 128-bit lane:
9726                            4, 20, 5, 21, 6, 22, 7, 23,
9727                            // Second 128-bit lane:
9728                            12, 28, 13, 29, 14, 30, 15, 31}))
9729     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i16, V1, V2);
9730
9731   // Try to use shift instructions.
9732   if (SDValue Shift =
9733           lowerVectorShuffleAsShift(DL, MVT::v16i16, V1, V2, Mask, DAG))
9734     return Shift;
9735
9736   // Try to use byte rotation instructions.
9737   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9738           DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
9739     return Rotate;
9740
9741   if (isSingleInputShuffleMask(Mask)) {
9742     // There are no generalized cross-lane shuffle operations available on i16
9743     // element types.
9744     if (is128BitLaneCrossingShuffleMask(MVT::v16i16, Mask))
9745       return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v16i16, V1, V2,
9746                                                      Mask, DAG);
9747
9748     SmallVector<int, 8> RepeatedMask;
9749     if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
9750       // As this is a single-input shuffle, the repeated mask should be
9751       // a strictly valid v8i16 mask that we can pass through to the v8i16
9752       // lowering to handle even the v16 case.
9753       return lowerV8I16GeneralSingleInputVectorShuffle(
9754           DL, MVT::v16i16, V1, RepeatedMask, Subtarget, DAG);
9755     }
9756
9757     SDValue PSHUFBMask[32];
9758     for (int i = 0; i < 16; ++i) {
9759       if (Mask[i] == -1) {
9760         PSHUFBMask[2 * i] = PSHUFBMask[2 * i + 1] = DAG.getUNDEF(MVT::i8);
9761         continue;
9762       }
9763
9764       int M = i < 8 ? Mask[i] : Mask[i] - 8;
9765       assert(M >= 0 && M < 8 && "Invalid single-input mask!");
9766       PSHUFBMask[2 * i] = DAG.getConstant(2 * M, MVT::i8);
9767       PSHUFBMask[2 * i + 1] = DAG.getConstant(2 * M + 1, MVT::i8);
9768     }
9769     return DAG.getNode(
9770         ISD::BITCAST, DL, MVT::v16i16,
9771         DAG.getNode(
9772             X86ISD::PSHUFB, DL, MVT::v32i8,
9773             DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, V1),
9774             DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, PSHUFBMask)));
9775   }
9776
9777   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9778   // shuffle.
9779   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9780           DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
9781     return Result;
9782
9783   // Otherwise fall back on generic lowering.
9784   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v16i16, V1, V2, Mask, DAG);
9785 }
9786
9787 /// \brief Handle lowering of 32-lane 8-bit integer shuffles.
9788 ///
9789 /// This routine is only called when we have AVX2 and thus a reasonable
9790 /// instruction set for v32i8 shuffling..
9791 static SDValue lowerV32I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9792                                        const X86Subtarget *Subtarget,
9793                                        SelectionDAG &DAG) {
9794   SDLoc DL(Op);
9795   assert(V1.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
9796   assert(V2.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
9797   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9798   ArrayRef<int> Mask = SVOp->getMask();
9799   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
9800   assert(Subtarget->hasAVX2() && "We can only lower v32i8 with AVX2!");
9801
9802   // Whenever we can lower this as a zext, that instruction is strictly faster
9803   // than any alternative. It also allows us to fold memory operands into the
9804   // shuffle in many cases.
9805   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v32i8, V1, V2,
9806                                                          Mask, Subtarget, DAG))
9807     return ZExt;
9808
9809   // Check for being able to broadcast a single element.
9810   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v32i8, V1,
9811                                                         Mask, Subtarget, DAG))
9812     return Broadcast;
9813
9814   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v32i8, V1, V2, Mask,
9815                                                 Subtarget, DAG))
9816     return Blend;
9817
9818   // Use dedicated unpack instructions for masks that match their pattern.
9819   // Note that these are repeated 128-bit lane unpacks, not unpacks across all
9820   // 256-bit lanes.
9821   if (isShuffleEquivalent(
9822           V1, V2, Mask,
9823           {// First 128-bit lane:
9824            0, 32, 1, 33, 2, 34, 3, 35, 4, 36, 5, 37, 6, 38, 7, 39,
9825            // Second 128-bit lane:
9826            16, 48, 17, 49, 18, 50, 19, 51, 20, 52, 21, 53, 22, 54, 23, 55}))
9827     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v32i8, V1, V2);
9828   if (isShuffleEquivalent(
9829           V1, V2, Mask,
9830           {// First 128-bit lane:
9831            8, 40, 9, 41, 10, 42, 11, 43, 12, 44, 13, 45, 14, 46, 15, 47,
9832            // Second 128-bit lane:
9833            24, 56, 25, 57, 26, 58, 27, 59, 28, 60, 29, 61, 30, 62, 31, 63}))
9834     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v32i8, V1, V2);
9835
9836   // Try to use shift instructions.
9837   if (SDValue Shift =
9838           lowerVectorShuffleAsShift(DL, MVT::v32i8, V1, V2, Mask, DAG))
9839     return Shift;
9840
9841   // Try to use byte rotation instructions.
9842   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9843           DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
9844     return Rotate;
9845
9846   if (isSingleInputShuffleMask(Mask)) {
9847     // There are no generalized cross-lane shuffle operations available on i8
9848     // element types.
9849     if (is128BitLaneCrossingShuffleMask(MVT::v32i8, Mask))
9850       return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v32i8, V1, V2,
9851                                                      Mask, DAG);
9852
9853     SDValue PSHUFBMask[32];
9854     for (int i = 0; i < 32; ++i)
9855       PSHUFBMask[i] =
9856           Mask[i] < 0
9857               ? DAG.getUNDEF(MVT::i8)
9858               : DAG.getConstant(Mask[i] < 16 ? Mask[i] : Mask[i] - 16, MVT::i8);
9859
9860     return DAG.getNode(
9861         X86ISD::PSHUFB, DL, MVT::v32i8, V1,
9862         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, PSHUFBMask));
9863   }
9864
9865   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9866   // shuffle.
9867   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9868           DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
9869     return Result;
9870
9871   // Otherwise fall back on generic lowering.
9872   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v32i8, V1, V2, Mask, DAG);
9873 }
9874
9875 /// \brief High-level routine to lower various 256-bit x86 vector shuffles.
9876 ///
9877 /// This routine either breaks down the specific type of a 256-bit x86 vector
9878 /// shuffle or splits it into two 128-bit shuffles and fuses the results back
9879 /// together based on the available instructions.
9880 static SDValue lower256BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9881                                         MVT VT, const X86Subtarget *Subtarget,
9882                                         SelectionDAG &DAG) {
9883   SDLoc DL(Op);
9884   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9885   ArrayRef<int> Mask = SVOp->getMask();
9886
9887   // If we have a single input to the zero element, insert that into V1 if we
9888   // can do so cheaply.
9889   int NumElts = VT.getVectorNumElements();
9890   int NumV2Elements = std::count_if(Mask.begin(), Mask.end(), [NumElts](int M) {
9891     return M >= NumElts;
9892   });
9893   
9894   if (NumV2Elements == 1 && Mask[0] >= NumElts)
9895     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
9896                               DL, VT, V1, V2, Mask, Subtarget, DAG))
9897       return Insertion;
9898
9899   // There is a really nice hard cut-over between AVX1 and AVX2 that means we can
9900   // check for those subtargets here and avoid much of the subtarget querying in
9901   // the per-vector-type lowering routines. With AVX1 we have essentially *zero*
9902   // ability to manipulate a 256-bit vector with integer types. Since we'll use
9903   // floating point types there eventually, just immediately cast everything to
9904   // a float and operate entirely in that domain.
9905   if (VT.isInteger() && !Subtarget->hasAVX2()) {
9906     int ElementBits = VT.getScalarSizeInBits();
9907     if (ElementBits < 32)
9908       // No floating point type available, decompose into 128-bit vectors.
9909       return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9910
9911     MVT FpVT = MVT::getVectorVT(MVT::getFloatingPointVT(ElementBits),
9912                                 VT.getVectorNumElements());
9913     V1 = DAG.getNode(ISD::BITCAST, DL, FpVT, V1);
9914     V2 = DAG.getNode(ISD::BITCAST, DL, FpVT, V2);
9915     return DAG.getNode(ISD::BITCAST, DL, VT,
9916                        DAG.getVectorShuffle(FpVT, DL, V1, V2, Mask));
9917   }
9918
9919   switch (VT.SimpleTy) {
9920   case MVT::v4f64:
9921     return lowerV4F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9922   case MVT::v4i64:
9923     return lowerV4I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9924   case MVT::v8f32:
9925     return lowerV8F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9926   case MVT::v8i32:
9927     return lowerV8I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9928   case MVT::v16i16:
9929     return lowerV16I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
9930   case MVT::v32i8:
9931     return lowerV32I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
9932
9933   default:
9934     llvm_unreachable("Not a valid 256-bit x86 vector type!");
9935   }
9936 }
9937
9938 /// \brief Handle lowering of 8-lane 64-bit floating point shuffles.
9939 static SDValue lowerV8F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9940                                        const X86Subtarget *Subtarget,
9941                                        SelectionDAG &DAG) {
9942   SDLoc DL(Op);
9943   assert(V1.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
9944   assert(V2.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
9945   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9946   ArrayRef<int> Mask = SVOp->getMask();
9947   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9948
9949   // X86 has dedicated unpack instructions that can handle specific blend
9950   // operations: UNPCKH and UNPCKL.
9951   if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 2, 10, 4, 12, 6, 14}))
9952     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f64, V1, V2);
9953   if (isShuffleEquivalent(V1, V2, Mask, {1, 9, 3, 11, 5, 13, 7, 15}))
9954     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f64, V1, V2);
9955
9956   // FIXME: Implement direct support for this type!
9957   return splitAndLowerVectorShuffle(DL, MVT::v8f64, V1, V2, Mask, DAG);
9958 }
9959
9960 /// \brief Handle lowering of 16-lane 32-bit floating point shuffles.
9961 static SDValue lowerV16F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9962                                        const X86Subtarget *Subtarget,
9963                                        SelectionDAG &DAG) {
9964   SDLoc DL(Op);
9965   assert(V1.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
9966   assert(V2.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
9967   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9968   ArrayRef<int> Mask = SVOp->getMask();
9969   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
9970
9971   // Use dedicated unpack instructions for masks that match their pattern.
9972   if (isShuffleEquivalent(V1, V2, Mask,
9973                           {// First 128-bit lane.
9974                            0, 16, 1, 17, 4, 20, 5, 21,
9975                            // Second 128-bit lane.
9976                            8, 24, 9, 25, 12, 28, 13, 29}))
9977     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16f32, V1, V2);
9978   if (isShuffleEquivalent(V1, V2, Mask,
9979                           {// First 128-bit lane.
9980                            2, 18, 3, 19, 6, 22, 7, 23,
9981                            // Second 128-bit lane.
9982                            10, 26, 11, 27, 14, 30, 15, 31}))
9983     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16f32, V1, V2);
9984
9985   // FIXME: Implement direct support for this type!
9986   return splitAndLowerVectorShuffle(DL, MVT::v16f32, V1, V2, Mask, DAG);
9987 }
9988
9989 /// \brief Handle lowering of 8-lane 64-bit integer shuffles.
9990 static SDValue lowerV8I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9991                                        const X86Subtarget *Subtarget,
9992                                        SelectionDAG &DAG) {
9993   SDLoc DL(Op);
9994   assert(V1.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
9995   assert(V2.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
9996   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9997   ArrayRef<int> Mask = SVOp->getMask();
9998   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9999
10000   // X86 has dedicated unpack instructions that can handle specific blend
10001   // operations: UNPCKH and UNPCKL.
10002   if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 2, 10, 4, 12, 6, 14}))
10003     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i64, V1, V2);
10004   if (isShuffleEquivalent(V1, V2, Mask, {1, 9, 3, 11, 5, 13, 7, 15}))
10005     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i64, V1, V2);
10006
10007   // FIXME: Implement direct support for this type!
10008   return splitAndLowerVectorShuffle(DL, MVT::v8i64, V1, V2, Mask, DAG);
10009 }
10010
10011 /// \brief Handle lowering of 16-lane 32-bit integer shuffles.
10012 static SDValue lowerV16I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10013                                        const X86Subtarget *Subtarget,
10014                                        SelectionDAG &DAG) {
10015   SDLoc DL(Op);
10016   assert(V1.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
10017   assert(V2.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
10018   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10019   ArrayRef<int> Mask = SVOp->getMask();
10020   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10021
10022   // Use dedicated unpack instructions for masks that match their pattern.
10023   if (isShuffleEquivalent(V1, V2, Mask,
10024                           {// First 128-bit lane.
10025                            0, 16, 1, 17, 4, 20, 5, 21,
10026                            // Second 128-bit lane.
10027                            8, 24, 9, 25, 12, 28, 13, 29}))
10028     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i32, V1, V2);
10029   if (isShuffleEquivalent(V1, V2, Mask,
10030                           {// First 128-bit lane.
10031                            2, 18, 3, 19, 6, 22, 7, 23,
10032                            // Second 128-bit lane.
10033                            10, 26, 11, 27, 14, 30, 15, 31}))
10034     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i32, V1, V2);
10035
10036   // FIXME: Implement direct support for this type!
10037   return splitAndLowerVectorShuffle(DL, MVT::v16i32, V1, V2, Mask, DAG);
10038 }
10039
10040 /// \brief Handle lowering of 32-lane 16-bit integer shuffles.
10041 static SDValue lowerV32I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10042                                         const X86Subtarget *Subtarget,
10043                                         SelectionDAG &DAG) {
10044   SDLoc DL(Op);
10045   assert(V1.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10046   assert(V2.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10047   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10048   ArrayRef<int> Mask = SVOp->getMask();
10049   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
10050   assert(Subtarget->hasBWI() && "We can only lower v32i16 with AVX-512-BWI!");
10051
10052   // FIXME: Implement direct support for this type!
10053   return splitAndLowerVectorShuffle(DL, MVT::v32i16, V1, V2, Mask, DAG);
10054 }
10055
10056 /// \brief Handle lowering of 64-lane 8-bit integer shuffles.
10057 static SDValue lowerV64I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10058                                        const X86Subtarget *Subtarget,
10059                                        SelectionDAG &DAG) {
10060   SDLoc DL(Op);
10061   assert(V1.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10062   assert(V2.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10063   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10064   ArrayRef<int> Mask = SVOp->getMask();
10065   assert(Mask.size() == 64 && "Unexpected mask size for v64 shuffle!");
10066   assert(Subtarget->hasBWI() && "We can only lower v64i8 with AVX-512-BWI!");
10067
10068   // FIXME: Implement direct support for this type!
10069   return splitAndLowerVectorShuffle(DL, MVT::v64i8, V1, V2, Mask, DAG);
10070 }
10071
10072 /// \brief High-level routine to lower various 512-bit x86 vector shuffles.
10073 ///
10074 /// This routine either breaks down the specific type of a 512-bit x86 vector
10075 /// shuffle or splits it into two 256-bit shuffles and fuses the results back
10076 /// together based on the available instructions.
10077 static SDValue lower512BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10078                                         MVT VT, const X86Subtarget *Subtarget,
10079                                         SelectionDAG &DAG) {
10080   SDLoc DL(Op);
10081   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10082   ArrayRef<int> Mask = SVOp->getMask();
10083   assert(Subtarget->hasAVX512() &&
10084          "Cannot lower 512-bit vectors w/ basic ISA!");
10085
10086   // Check for being able to broadcast a single element.
10087   if (SDValue Broadcast =
10088           lowerVectorShuffleAsBroadcast(DL, VT, V1, Mask, Subtarget, DAG))
10089     return Broadcast;
10090
10091   // Dispatch to each element type for lowering. If we don't have supprot for
10092   // specific element type shuffles at 512 bits, immediately split them and
10093   // lower them. Each lowering routine of a given type is allowed to assume that
10094   // the requisite ISA extensions for that element type are available.
10095   switch (VT.SimpleTy) {
10096   case MVT::v8f64:
10097     return lowerV8F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10098   case MVT::v16f32:
10099     return lowerV16F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10100   case MVT::v8i64:
10101     return lowerV8I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10102   case MVT::v16i32:
10103     return lowerV16I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10104   case MVT::v32i16:
10105     if (Subtarget->hasBWI())
10106       return lowerV32I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
10107     break;
10108   case MVT::v64i8:
10109     if (Subtarget->hasBWI())
10110       return lowerV64I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
10111     break;
10112
10113   default:
10114     llvm_unreachable("Not a valid 512-bit x86 vector type!");
10115   }
10116
10117   // Otherwise fall back on splitting.
10118   return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10119 }
10120
10121 /// \brief Top-level lowering for x86 vector shuffles.
10122 ///
10123 /// This handles decomposition, canonicalization, and lowering of all x86
10124 /// vector shuffles. Most of the specific lowering strategies are encapsulated
10125 /// above in helper routines. The canonicalization attempts to widen shuffles
10126 /// to involve fewer lanes of wider elements, consolidate symmetric patterns
10127 /// s.t. only one of the two inputs needs to be tested, etc.
10128 static SDValue lowerVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
10129                                   SelectionDAG &DAG) {
10130   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10131   ArrayRef<int> Mask = SVOp->getMask();
10132   SDValue V1 = Op.getOperand(0);
10133   SDValue V2 = Op.getOperand(1);
10134   MVT VT = Op.getSimpleValueType();
10135   int NumElements = VT.getVectorNumElements();
10136   SDLoc dl(Op);
10137
10138   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
10139
10140   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
10141   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
10142   if (V1IsUndef && V2IsUndef)
10143     return DAG.getUNDEF(VT);
10144
10145   // When we create a shuffle node we put the UNDEF node to second operand,
10146   // but in some cases the first operand may be transformed to UNDEF.
10147   // In this case we should just commute the node.
10148   if (V1IsUndef)
10149     return DAG.getCommutedVectorShuffle(*SVOp);
10150
10151   // Check for non-undef masks pointing at an undef vector and make the masks
10152   // undef as well. This makes it easier to match the shuffle based solely on
10153   // the mask.
10154   if (V2IsUndef)
10155     for (int M : Mask)
10156       if (M >= NumElements) {
10157         SmallVector<int, 8> NewMask(Mask.begin(), Mask.end());
10158         for (int &M : NewMask)
10159           if (M >= NumElements)
10160             M = -1;
10161         return DAG.getVectorShuffle(VT, dl, V1, V2, NewMask);
10162       }
10163
10164   // We actually see shuffles that are entirely re-arrangements of a set of
10165   // zero inputs. This mostly happens while decomposing complex shuffles into
10166   // simple ones. Directly lower these as a buildvector of zeros.
10167   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
10168   if (Zeroable.all())
10169     return getZeroVector(VT, Subtarget, DAG, dl);
10170
10171   // Try to collapse shuffles into using a vector type with fewer elements but
10172   // wider element types. We cap this to not form integers or floating point
10173   // elements wider than 64 bits, but it might be interesting to form i128
10174   // integers to handle flipping the low and high halves of AVX 256-bit vectors.
10175   SmallVector<int, 16> WidenedMask;
10176   if (VT.getScalarSizeInBits() < 64 &&
10177       canWidenShuffleElements(Mask, WidenedMask)) {
10178     MVT NewEltVT = VT.isFloatingPoint()
10179                        ? MVT::getFloatingPointVT(VT.getScalarSizeInBits() * 2)
10180                        : MVT::getIntegerVT(VT.getScalarSizeInBits() * 2);
10181     MVT NewVT = MVT::getVectorVT(NewEltVT, VT.getVectorNumElements() / 2);
10182     // Make sure that the new vector type is legal. For example, v2f64 isn't
10183     // legal on SSE1.
10184     if (DAG.getTargetLoweringInfo().isTypeLegal(NewVT)) {
10185       V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
10186       V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
10187       return DAG.getNode(ISD::BITCAST, dl, VT,
10188                          DAG.getVectorShuffle(NewVT, dl, V1, V2, WidenedMask));
10189     }
10190   }
10191
10192   int NumV1Elements = 0, NumUndefElements = 0, NumV2Elements = 0;
10193   for (int M : SVOp->getMask())
10194     if (M < 0)
10195       ++NumUndefElements;
10196     else if (M < NumElements)
10197       ++NumV1Elements;
10198     else
10199       ++NumV2Elements;
10200
10201   // Commute the shuffle as needed such that more elements come from V1 than
10202   // V2. This allows us to match the shuffle pattern strictly on how many
10203   // elements come from V1 without handling the symmetric cases.
10204   if (NumV2Elements > NumV1Elements)
10205     return DAG.getCommutedVectorShuffle(*SVOp);
10206
10207   // When the number of V1 and V2 elements are the same, try to minimize the
10208   // number of uses of V2 in the low half of the vector. When that is tied,
10209   // ensure that the sum of indices for V1 is equal to or lower than the sum
10210   // indices for V2. When those are equal, try to ensure that the number of odd
10211   // indices for V1 is lower than the number of odd indices for V2.
10212   if (NumV1Elements == NumV2Elements) {
10213     int LowV1Elements = 0, LowV2Elements = 0;
10214     for (int M : SVOp->getMask().slice(0, NumElements / 2))
10215       if (M >= NumElements)
10216         ++LowV2Elements;
10217       else if (M >= 0)
10218         ++LowV1Elements;
10219     if (LowV2Elements > LowV1Elements) {
10220       return DAG.getCommutedVectorShuffle(*SVOp);
10221     } else if (LowV2Elements == LowV1Elements) {
10222       int SumV1Indices = 0, SumV2Indices = 0;
10223       for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
10224         if (SVOp->getMask()[i] >= NumElements)
10225           SumV2Indices += i;
10226         else if (SVOp->getMask()[i] >= 0)
10227           SumV1Indices += i;
10228       if (SumV2Indices < SumV1Indices) {
10229         return DAG.getCommutedVectorShuffle(*SVOp);
10230       } else if (SumV2Indices == SumV1Indices) {
10231         int NumV1OddIndices = 0, NumV2OddIndices = 0;
10232         for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
10233           if (SVOp->getMask()[i] >= NumElements)
10234             NumV2OddIndices += i % 2;
10235           else if (SVOp->getMask()[i] >= 0)
10236             NumV1OddIndices += i % 2;
10237         if (NumV2OddIndices < NumV1OddIndices)
10238           return DAG.getCommutedVectorShuffle(*SVOp);
10239       }
10240     }
10241   }
10242
10243   // For each vector width, delegate to a specialized lowering routine.
10244   if (VT.getSizeInBits() == 128)
10245     return lower128BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10246
10247   if (VT.getSizeInBits() == 256)
10248     return lower256BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10249
10250   // Force AVX-512 vectors to be scalarized for now.
10251   // FIXME: Implement AVX-512 support!
10252   if (VT.getSizeInBits() == 512)
10253     return lower512BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10254
10255   llvm_unreachable("Unimplemented!");
10256 }
10257
10258 // This function assumes its argument is a BUILD_VECTOR of constants or
10259 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
10260 // true.
10261 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
10262                                     unsigned &MaskValue) {
10263   MaskValue = 0;
10264   unsigned NumElems = BuildVector->getNumOperands();
10265   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
10266   unsigned NumLanes = (NumElems - 1) / 8 + 1;
10267   unsigned NumElemsInLane = NumElems / NumLanes;
10268
10269   // Blend for v16i16 should be symetric for the both lanes.
10270   for (unsigned i = 0; i < NumElemsInLane; ++i) {
10271     SDValue EltCond = BuildVector->getOperand(i);
10272     SDValue SndLaneEltCond =
10273         (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
10274
10275     int Lane1Cond = -1, Lane2Cond = -1;
10276     if (isa<ConstantSDNode>(EltCond))
10277       Lane1Cond = !isZero(EltCond);
10278     if (isa<ConstantSDNode>(SndLaneEltCond))
10279       Lane2Cond = !isZero(SndLaneEltCond);
10280
10281     if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
10282       // Lane1Cond != 0, means we want the first argument.
10283       // Lane1Cond == 0, means we want the second argument.
10284       // The encoding of this argument is 0 for the first argument, 1
10285       // for the second. Therefore, invert the condition.
10286       MaskValue |= !Lane1Cond << i;
10287     else if (Lane1Cond < 0)
10288       MaskValue |= !Lane2Cond << i;
10289     else
10290       return false;
10291   }
10292   return true;
10293 }
10294
10295 /// \brief Try to lower a VSELECT instruction to a vector shuffle.
10296 static SDValue lowerVSELECTtoVectorShuffle(SDValue Op,
10297                                            const X86Subtarget *Subtarget,
10298                                            SelectionDAG &DAG) {
10299   SDValue Cond = Op.getOperand(0);
10300   SDValue LHS = Op.getOperand(1);
10301   SDValue RHS = Op.getOperand(2);
10302   SDLoc dl(Op);
10303   MVT VT = Op.getSimpleValueType();
10304
10305   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
10306     return SDValue();
10307   auto *CondBV = cast<BuildVectorSDNode>(Cond);
10308
10309   // Only non-legal VSELECTs reach this lowering, convert those into generic
10310   // shuffles and re-use the shuffle lowering path for blends.
10311   SmallVector<int, 32> Mask;
10312   for (int i = 0, Size = VT.getVectorNumElements(); i < Size; ++i) {
10313     SDValue CondElt = CondBV->getOperand(i);
10314     Mask.push_back(
10315         isa<ConstantSDNode>(CondElt) ? i + (isZero(CondElt) ? Size : 0) : -1);
10316   }
10317   return DAG.getVectorShuffle(VT, dl, LHS, RHS, Mask);
10318 }
10319
10320 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
10321   // A vselect where all conditions and data are constants can be optimized into
10322   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
10323   if (ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(0).getNode()) &&
10324       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(1).getNode()) &&
10325       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(2).getNode()))
10326     return SDValue();
10327
10328   // Try to lower this to a blend-style vector shuffle. This can handle all
10329   // constant condition cases.
10330   if (SDValue BlendOp = lowerVSELECTtoVectorShuffle(Op, Subtarget, DAG))
10331     return BlendOp;
10332
10333   // Variable blends are only legal from SSE4.1 onward.
10334   if (!Subtarget->hasSSE41())
10335     return SDValue();
10336
10337   // Only some types will be legal on some subtargets. If we can emit a legal
10338   // VSELECT-matching blend, return Op, and but if we need to expand, return
10339   // a null value.
10340   switch (Op.getSimpleValueType().SimpleTy) {
10341   default:
10342     // Most of the vector types have blends past SSE4.1.
10343     return Op;
10344
10345   case MVT::v32i8:
10346     // The byte blends for AVX vectors were introduced only in AVX2.
10347     if (Subtarget->hasAVX2())
10348       return Op;
10349
10350     return SDValue();
10351
10352   case MVT::v8i16:
10353   case MVT::v16i16:
10354     // AVX-512 BWI and VLX features support VSELECT with i16 elements.
10355     if (Subtarget->hasBWI() && Subtarget->hasVLX())
10356       return Op;
10357
10358     // FIXME: We should custom lower this by fixing the condition and using i8
10359     // blends.
10360     return SDValue();
10361   }
10362 }
10363
10364 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
10365   MVT VT = Op.getSimpleValueType();
10366   SDLoc dl(Op);
10367
10368   if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
10369     return SDValue();
10370
10371   if (VT.getSizeInBits() == 8) {
10372     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
10373                                   Op.getOperand(0), Op.getOperand(1));
10374     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
10375                                   DAG.getValueType(VT));
10376     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10377   }
10378
10379   if (VT.getSizeInBits() == 16) {
10380     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10381     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
10382     if (Idx == 0)
10383       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
10384                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10385                                      DAG.getNode(ISD::BITCAST, dl,
10386                                                  MVT::v4i32,
10387                                                  Op.getOperand(0)),
10388                                      Op.getOperand(1)));
10389     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
10390                                   Op.getOperand(0), Op.getOperand(1));
10391     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
10392                                   DAG.getValueType(VT));
10393     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10394   }
10395
10396   if (VT == MVT::f32) {
10397     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
10398     // the result back to FR32 register. It's only worth matching if the
10399     // result has a single use which is a store or a bitcast to i32.  And in
10400     // the case of a store, it's not worth it if the index is a constant 0,
10401     // because a MOVSSmr can be used instead, which is smaller and faster.
10402     if (!Op.hasOneUse())
10403       return SDValue();
10404     SDNode *User = *Op.getNode()->use_begin();
10405     if ((User->getOpcode() != ISD::STORE ||
10406          (isa<ConstantSDNode>(Op.getOperand(1)) &&
10407           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
10408         (User->getOpcode() != ISD::BITCAST ||
10409          User->getValueType(0) != MVT::i32))
10410       return SDValue();
10411     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10412                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
10413                                               Op.getOperand(0)),
10414                                               Op.getOperand(1));
10415     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
10416   }
10417
10418   if (VT == MVT::i32 || VT == MVT::i64) {
10419     // ExtractPS/pextrq works with constant index.
10420     if (isa<ConstantSDNode>(Op.getOperand(1)))
10421       return Op;
10422   }
10423   return SDValue();
10424 }
10425
10426 /// Extract one bit from mask vector, like v16i1 or v8i1.
10427 /// AVX-512 feature.
10428 SDValue
10429 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
10430   SDValue Vec = Op.getOperand(0);
10431   SDLoc dl(Vec);
10432   MVT VecVT = Vec.getSimpleValueType();
10433   SDValue Idx = Op.getOperand(1);
10434   MVT EltVT = Op.getSimpleValueType();
10435
10436   assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
10437   assert((VecVT.getVectorNumElements() <= 16 || Subtarget->hasBWI()) &&
10438          "Unexpected vector type in ExtractBitFromMaskVector");
10439
10440   // variable index can't be handled in mask registers,
10441   // extend vector to VR512
10442   if (!isa<ConstantSDNode>(Idx)) {
10443     MVT ExtVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
10444     SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
10445     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
10446                               ExtVT.getVectorElementType(), Ext, Idx);
10447     return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
10448   }
10449
10450   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10451   const TargetRegisterClass* rc = getRegClassFor(VecVT);
10452   if (!Subtarget->hasDQI() && (VecVT.getVectorNumElements() <= 8))
10453     rc = getRegClassFor(MVT::v16i1);
10454   unsigned MaxSift = rc->getSize()*8 - 1;
10455   Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
10456                     DAG.getConstant(MaxSift - IdxVal, MVT::i8));
10457   Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
10458                     DAG.getConstant(MaxSift, MVT::i8));
10459   return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
10460                        DAG.getIntPtrConstant(0));
10461 }
10462
10463 SDValue
10464 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
10465                                            SelectionDAG &DAG) const {
10466   SDLoc dl(Op);
10467   SDValue Vec = Op.getOperand(0);
10468   MVT VecVT = Vec.getSimpleValueType();
10469   SDValue Idx = Op.getOperand(1);
10470
10471   if (Op.getSimpleValueType() == MVT::i1)
10472     return ExtractBitFromMaskVector(Op, DAG);
10473
10474   if (!isa<ConstantSDNode>(Idx)) {
10475     if (VecVT.is512BitVector() ||
10476         (VecVT.is256BitVector() && Subtarget->hasInt256() &&
10477          VecVT.getVectorElementType().getSizeInBits() == 32)) {
10478
10479       MVT MaskEltVT =
10480         MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
10481       MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
10482                                     MaskEltVT.getSizeInBits());
10483
10484       Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
10485       SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
10486                                 getZeroVector(MaskVT, Subtarget, DAG, dl),
10487                                 Idx, DAG.getConstant(0, getPointerTy()));
10488       SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
10489       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(),
10490                         Perm, DAG.getConstant(0, getPointerTy()));
10491     }
10492     return SDValue();
10493   }
10494
10495   // If this is a 256-bit vector result, first extract the 128-bit vector and
10496   // then extract the element from the 128-bit vector.
10497   if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
10498
10499     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10500     // Get the 128-bit vector.
10501     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
10502     MVT EltVT = VecVT.getVectorElementType();
10503
10504     unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
10505
10506     //if (IdxVal >= NumElems/2)
10507     //  IdxVal -= NumElems/2;
10508     IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
10509     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
10510                        DAG.getConstant(IdxVal, MVT::i32));
10511   }
10512
10513   assert(VecVT.is128BitVector() && "Unexpected vector length");
10514
10515   if (Subtarget->hasSSE41()) {
10516     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
10517     if (Res.getNode())
10518       return Res;
10519   }
10520
10521   MVT VT = Op.getSimpleValueType();
10522   // TODO: handle v16i8.
10523   if (VT.getSizeInBits() == 16) {
10524     SDValue Vec = Op.getOperand(0);
10525     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10526     if (Idx == 0)
10527       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
10528                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10529                                      DAG.getNode(ISD::BITCAST, dl,
10530                                                  MVT::v4i32, Vec),
10531                                      Op.getOperand(1)));
10532     // Transform it so it match pextrw which produces a 32-bit result.
10533     MVT EltVT = MVT::i32;
10534     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
10535                                   Op.getOperand(0), Op.getOperand(1));
10536     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
10537                                   DAG.getValueType(VT));
10538     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10539   }
10540
10541   if (VT.getSizeInBits() == 32) {
10542     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10543     if (Idx == 0)
10544       return Op;
10545
10546     // SHUFPS the element to the lowest double word, then movss.
10547     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
10548     MVT VVT = Op.getOperand(0).getSimpleValueType();
10549     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
10550                                        DAG.getUNDEF(VVT), Mask);
10551     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
10552                        DAG.getIntPtrConstant(0));
10553   }
10554
10555   if (VT.getSizeInBits() == 64) {
10556     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
10557     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
10558     //        to match extract_elt for f64.
10559     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10560     if (Idx == 0)
10561       return Op;
10562
10563     // UNPCKHPD the element to the lowest double word, then movsd.
10564     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
10565     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
10566     int Mask[2] = { 1, -1 };
10567     MVT VVT = Op.getOperand(0).getSimpleValueType();
10568     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
10569                                        DAG.getUNDEF(VVT), Mask);
10570     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
10571                        DAG.getIntPtrConstant(0));
10572   }
10573
10574   return SDValue();
10575 }
10576
10577 /// Insert one bit to mask vector, like v16i1 or v8i1.
10578 /// AVX-512 feature.
10579 SDValue
10580 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
10581   SDLoc dl(Op);
10582   SDValue Vec = Op.getOperand(0);
10583   SDValue Elt = Op.getOperand(1);
10584   SDValue Idx = Op.getOperand(2);
10585   MVT VecVT = Vec.getSimpleValueType();
10586
10587   if (!isa<ConstantSDNode>(Idx)) {
10588     // Non constant index. Extend source and destination,
10589     // insert element and then truncate the result.
10590     MVT ExtVecVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
10591     MVT ExtEltVT = (VecVT == MVT::v8i1 ?  MVT::i64 : MVT::i32);
10592     SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT,
10593       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
10594       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
10595     return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
10596   }
10597
10598   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10599   SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
10600   if (Vec.getOpcode() == ISD::UNDEF)
10601     return DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
10602                        DAG.getConstant(IdxVal, MVT::i8));
10603   const TargetRegisterClass* rc = getRegClassFor(VecVT);
10604   unsigned MaxSift = rc->getSize()*8 - 1;
10605   EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
10606                     DAG.getConstant(MaxSift, MVT::i8));
10607   EltInVec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, EltInVec,
10608                     DAG.getConstant(MaxSift - IdxVal, MVT::i8));
10609   return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
10610 }
10611
10612 SDValue X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
10613                                                   SelectionDAG &DAG) const {
10614   MVT VT = Op.getSimpleValueType();
10615   MVT EltVT = VT.getVectorElementType();
10616
10617   if (EltVT == MVT::i1)
10618     return InsertBitToMaskVector(Op, DAG);
10619
10620   SDLoc dl(Op);
10621   SDValue N0 = Op.getOperand(0);
10622   SDValue N1 = Op.getOperand(1);
10623   SDValue N2 = Op.getOperand(2);
10624   if (!isa<ConstantSDNode>(N2))
10625     return SDValue();
10626   auto *N2C = cast<ConstantSDNode>(N2);
10627   unsigned IdxVal = N2C->getZExtValue();
10628
10629   // If the vector is wider than 128 bits, extract the 128-bit subvector, insert
10630   // into that, and then insert the subvector back into the result.
10631   if (VT.is256BitVector() || VT.is512BitVector()) {
10632     // With a 256-bit vector, we can insert into the zero element efficiently
10633     // using a blend if we have AVX or AVX2 and the right data type.
10634     if (VT.is256BitVector() && IdxVal == 0) {
10635       // TODO: It is worthwhile to cast integer to floating point and back
10636       // and incur a domain crossing penalty if that's what we'll end up
10637       // doing anyway after extracting to a 128-bit vector.
10638       if ((Subtarget->hasAVX() && (EltVT == MVT::f64 || EltVT == MVT::f32)) ||
10639           (Subtarget->hasAVX2() && EltVT == MVT::i32)) {
10640         SDValue N1Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, N1);
10641         N2 = DAG.getIntPtrConstant(1);
10642         return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1Vec, N2);
10643       }
10644     }
10645     
10646     // Get the desired 128-bit vector chunk.
10647     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
10648
10649     // Insert the element into the desired chunk.
10650     unsigned NumEltsIn128 = 128 / EltVT.getSizeInBits();
10651     unsigned IdxIn128 = IdxVal - (IdxVal / NumEltsIn128) * NumEltsIn128;
10652
10653     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
10654                     DAG.getConstant(IdxIn128, MVT::i32));
10655
10656     // Insert the changed part back into the bigger vector
10657     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
10658   }
10659   assert(VT.is128BitVector() && "Only 128-bit vector types should be left!");
10660
10661   if (Subtarget->hasSSE41()) {
10662     if (EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) {
10663       unsigned Opc;
10664       if (VT == MVT::v8i16) {
10665         Opc = X86ISD::PINSRW;
10666       } else {
10667         assert(VT == MVT::v16i8);
10668         Opc = X86ISD::PINSRB;
10669       }
10670
10671       // Transform it so it match pinsr{b,w} which expects a GR32 as its second
10672       // argument.
10673       if (N1.getValueType() != MVT::i32)
10674         N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
10675       if (N2.getValueType() != MVT::i32)
10676         N2 = DAG.getIntPtrConstant(IdxVal);
10677       return DAG.getNode(Opc, dl, VT, N0, N1, N2);
10678     }
10679
10680     if (EltVT == MVT::f32) {
10681       // Bits [7:6] of the constant are the source select. This will always be
10682       //   zero here. The DAG Combiner may combine an extract_elt index into
10683       //   these bits. For example (insert (extract, 3), 2) could be matched by
10684       //   putting the '3' into bits [7:6] of X86ISD::INSERTPS.
10685       // Bits [5:4] of the constant are the destination select. This is the
10686       //   value of the incoming immediate.
10687       // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
10688       //   combine either bitwise AND or insert of float 0.0 to set these bits.
10689
10690       const Function *F = DAG.getMachineFunction().getFunction();
10691       bool MinSize = F->hasFnAttribute(Attribute::MinSize);
10692       if (IdxVal == 0 && (!MinSize || !MayFoldLoad(N1))) {
10693         // If this is an insertion of 32-bits into the low 32-bits of
10694         // a vector, we prefer to generate a blend with immediate rather
10695         // than an insertps. Blends are simpler operations in hardware and so
10696         // will always have equal or better performance than insertps.
10697         // But if optimizing for size and there's a load folding opportunity,
10698         // generate insertps because blendps does not have a 32-bit memory
10699         // operand form.
10700         N2 = DAG.getIntPtrConstant(1);
10701         N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
10702         return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1, N2);
10703       }
10704       N2 = DAG.getIntPtrConstant(IdxVal << 4);
10705       // Create this as a scalar to vector..
10706       N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
10707       return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
10708     }
10709
10710     if (EltVT == MVT::i32 || EltVT == MVT::i64) {
10711       // PINSR* works with constant index.
10712       return Op;
10713     }
10714   }
10715
10716   if (EltVT == MVT::i8)
10717     return SDValue();
10718
10719   if (EltVT.getSizeInBits() == 16) {
10720     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
10721     // as its second argument.
10722     if (N1.getValueType() != MVT::i32)
10723       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
10724     if (N2.getValueType() != MVT::i32)
10725       N2 = DAG.getIntPtrConstant(IdxVal);
10726     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
10727   }
10728   return SDValue();
10729 }
10730
10731 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
10732   SDLoc dl(Op);
10733   MVT OpVT = Op.getSimpleValueType();
10734
10735   // If this is a 256-bit vector result, first insert into a 128-bit
10736   // vector and then insert into the 256-bit vector.
10737   if (!OpVT.is128BitVector()) {
10738     // Insert into a 128-bit vector.
10739     unsigned SizeFactor = OpVT.getSizeInBits()/128;
10740     MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
10741                                  OpVT.getVectorNumElements() / SizeFactor);
10742
10743     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
10744
10745     // Insert the 128-bit vector.
10746     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
10747   }
10748
10749   if (OpVT == MVT::v1i64 &&
10750       Op.getOperand(0).getValueType() == MVT::i64)
10751     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
10752
10753   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
10754   assert(OpVT.is128BitVector() && "Expected an SSE type!");
10755   return DAG.getNode(ISD::BITCAST, dl, OpVT,
10756                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
10757 }
10758
10759 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
10760 // a simple subregister reference or explicit instructions to grab
10761 // upper bits of a vector.
10762 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
10763                                       SelectionDAG &DAG) {
10764   SDLoc dl(Op);
10765   SDValue In =  Op.getOperand(0);
10766   SDValue Idx = Op.getOperand(1);
10767   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10768   MVT ResVT   = Op.getSimpleValueType();
10769   MVT InVT    = In.getSimpleValueType();
10770
10771   if (Subtarget->hasFp256()) {
10772     if (ResVT.is128BitVector() &&
10773         (InVT.is256BitVector() || InVT.is512BitVector()) &&
10774         isa<ConstantSDNode>(Idx)) {
10775       return Extract128BitVector(In, IdxVal, DAG, dl);
10776     }
10777     if (ResVT.is256BitVector() && InVT.is512BitVector() &&
10778         isa<ConstantSDNode>(Idx)) {
10779       return Extract256BitVector(In, IdxVal, DAG, dl);
10780     }
10781   }
10782   return SDValue();
10783 }
10784
10785 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
10786 // simple superregister reference or explicit instructions to insert
10787 // the upper bits of a vector.
10788 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
10789                                      SelectionDAG &DAG) {
10790   if (!Subtarget->hasAVX())
10791     return SDValue();
10792
10793   SDLoc dl(Op);
10794   SDValue Vec = Op.getOperand(0);
10795   SDValue SubVec = Op.getOperand(1);
10796   SDValue Idx = Op.getOperand(2);
10797
10798   if (!isa<ConstantSDNode>(Idx))
10799     return SDValue();
10800
10801   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10802   MVT OpVT = Op.getSimpleValueType();
10803   MVT SubVecVT = SubVec.getSimpleValueType();
10804
10805   // Fold two 16-byte subvector loads into one 32-byte load:
10806   // (insert_subvector (insert_subvector undef, (load addr), 0),
10807   //                   (load addr + 16), Elts/2)
10808   // --> load32 addr
10809   if ((IdxVal == OpVT.getVectorNumElements() / 2) &&
10810       Vec.getOpcode() == ISD::INSERT_SUBVECTOR &&
10811       OpVT.is256BitVector() && SubVecVT.is128BitVector() &&
10812       !Subtarget->isUnalignedMem32Slow()) {
10813     SDValue SubVec2 = Vec.getOperand(1);
10814     if (auto *Idx2 = dyn_cast<ConstantSDNode>(Vec.getOperand(2))) {
10815       if (Idx2->getZExtValue() == 0) {
10816         SDValue Ops[] = { SubVec2, SubVec };
10817         SDValue LD = EltsFromConsecutiveLoads(OpVT, Ops, dl, DAG, false);
10818         if (LD.getNode())
10819           return LD;
10820       }
10821     }
10822   }
10823
10824   if ((OpVT.is256BitVector() || OpVT.is512BitVector()) &&
10825       SubVecVT.is128BitVector())
10826     return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
10827
10828   if (OpVT.is512BitVector() && SubVecVT.is256BitVector())
10829     return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
10830
10831   if (OpVT.getVectorElementType() == MVT::i1) {
10832     if (IdxVal == 0  && Vec.getOpcode() == ISD::UNDEF) // the operation is legal
10833       return Op;
10834     SDValue ZeroIdx = DAG.getIntPtrConstant(0);
10835     SDValue Undef = DAG.getUNDEF(OpVT);
10836     unsigned NumElems = OpVT.getVectorNumElements();
10837     SDValue ShiftBits = DAG.getConstant(NumElems/2, MVT::i8);
10838
10839     if (IdxVal == OpVT.getVectorNumElements() / 2) {
10840       // Zero upper bits of the Vec
10841       Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
10842       Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
10843
10844       SDValue Vec2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef,
10845                                  SubVec, ZeroIdx);
10846       Vec2 = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec2, ShiftBits);
10847       return DAG.getNode(ISD::OR, dl, OpVT, Vec, Vec2);
10848     }
10849     if (IdxVal == 0) {
10850       SDValue Vec2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef,
10851                                  SubVec, ZeroIdx);
10852       // Zero upper bits of the Vec2
10853       Vec2 = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec2, ShiftBits);
10854       Vec2 = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec2, ShiftBits);
10855       // Zero lower bits of the Vec
10856       Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
10857       Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
10858       // Merge them together
10859       return DAG.getNode(ISD::OR, dl, OpVT, Vec, Vec2);
10860     }
10861   }
10862   return SDValue();
10863 }
10864
10865 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
10866 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
10867 // one of the above mentioned nodes. It has to be wrapped because otherwise
10868 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
10869 // be used to form addressing mode. These wrapped nodes will be selected
10870 // into MOV32ri.
10871 SDValue
10872 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
10873   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
10874
10875   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10876   // global base reg.
10877   unsigned char OpFlag = 0;
10878   unsigned WrapperKind = X86ISD::Wrapper;
10879   CodeModel::Model M = DAG.getTarget().getCodeModel();
10880
10881   if (Subtarget->isPICStyleRIPRel() &&
10882       (M == CodeModel::Small || M == CodeModel::Kernel))
10883     WrapperKind = X86ISD::WrapperRIP;
10884   else if (Subtarget->isPICStyleGOT())
10885     OpFlag = X86II::MO_GOTOFF;
10886   else if (Subtarget->isPICStyleStubPIC())
10887     OpFlag = X86II::MO_PIC_BASE_OFFSET;
10888
10889   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
10890                                              CP->getAlignment(),
10891                                              CP->getOffset(), OpFlag);
10892   SDLoc DL(CP);
10893   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10894   // With PIC, the address is actually $g + Offset.
10895   if (OpFlag) {
10896     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10897                          DAG.getNode(X86ISD::GlobalBaseReg,
10898                                      SDLoc(), getPointerTy()),
10899                          Result);
10900   }
10901
10902   return Result;
10903 }
10904
10905 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
10906   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
10907
10908   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10909   // global base reg.
10910   unsigned char OpFlag = 0;
10911   unsigned WrapperKind = X86ISD::Wrapper;
10912   CodeModel::Model M = DAG.getTarget().getCodeModel();
10913
10914   if (Subtarget->isPICStyleRIPRel() &&
10915       (M == CodeModel::Small || M == CodeModel::Kernel))
10916     WrapperKind = X86ISD::WrapperRIP;
10917   else if (Subtarget->isPICStyleGOT())
10918     OpFlag = X86II::MO_GOTOFF;
10919   else if (Subtarget->isPICStyleStubPIC())
10920     OpFlag = X86II::MO_PIC_BASE_OFFSET;
10921
10922   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
10923                                           OpFlag);
10924   SDLoc DL(JT);
10925   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10926
10927   // With PIC, the address is actually $g + Offset.
10928   if (OpFlag)
10929     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10930                          DAG.getNode(X86ISD::GlobalBaseReg,
10931                                      SDLoc(), getPointerTy()),
10932                          Result);
10933
10934   return Result;
10935 }
10936
10937 SDValue
10938 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
10939   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
10940
10941   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10942   // global base reg.
10943   unsigned char OpFlag = 0;
10944   unsigned WrapperKind = X86ISD::Wrapper;
10945   CodeModel::Model M = DAG.getTarget().getCodeModel();
10946
10947   if (Subtarget->isPICStyleRIPRel() &&
10948       (M == CodeModel::Small || M == CodeModel::Kernel)) {
10949     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
10950       OpFlag = X86II::MO_GOTPCREL;
10951     WrapperKind = X86ISD::WrapperRIP;
10952   } else if (Subtarget->isPICStyleGOT()) {
10953     OpFlag = X86II::MO_GOT;
10954   } else if (Subtarget->isPICStyleStubPIC()) {
10955     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
10956   } else if (Subtarget->isPICStyleStubNoDynamic()) {
10957     OpFlag = X86II::MO_DARWIN_NONLAZY;
10958   }
10959
10960   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
10961
10962   SDLoc DL(Op);
10963   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10964
10965   // With PIC, the address is actually $g + Offset.
10966   if (DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
10967       !Subtarget->is64Bit()) {
10968     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10969                          DAG.getNode(X86ISD::GlobalBaseReg,
10970                                      SDLoc(), getPointerTy()),
10971                          Result);
10972   }
10973
10974   // For symbols that require a load from a stub to get the address, emit the
10975   // load.
10976   if (isGlobalStubReference(OpFlag))
10977     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
10978                          MachinePointerInfo::getGOT(), false, false, false, 0);
10979
10980   return Result;
10981 }
10982
10983 SDValue
10984 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
10985   // Create the TargetBlockAddressAddress node.
10986   unsigned char OpFlags =
10987     Subtarget->ClassifyBlockAddressReference();
10988   CodeModel::Model M = DAG.getTarget().getCodeModel();
10989   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
10990   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
10991   SDLoc dl(Op);
10992   SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
10993                                              OpFlags);
10994
10995   if (Subtarget->isPICStyleRIPRel() &&
10996       (M == CodeModel::Small || M == CodeModel::Kernel))
10997     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
10998   else
10999     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
11000
11001   // With PIC, the address is actually $g + Offset.
11002   if (isGlobalRelativeToPICBase(OpFlags)) {
11003     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
11004                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
11005                          Result);
11006   }
11007
11008   return Result;
11009 }
11010
11011 SDValue
11012 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
11013                                       int64_t Offset, SelectionDAG &DAG) const {
11014   // Create the TargetGlobalAddress node, folding in the constant
11015   // offset if it is legal.
11016   unsigned char OpFlags =
11017       Subtarget->ClassifyGlobalReference(GV, DAG.getTarget());
11018   CodeModel::Model M = DAG.getTarget().getCodeModel();
11019   SDValue Result;
11020   if (OpFlags == X86II::MO_NO_FLAG &&
11021       X86::isOffsetSuitableForCodeModel(Offset, M)) {
11022     // A direct static reference to a global.
11023     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
11024     Offset = 0;
11025   } else {
11026     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
11027   }
11028
11029   if (Subtarget->isPICStyleRIPRel() &&
11030       (M == CodeModel::Small || M == CodeModel::Kernel))
11031     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
11032   else
11033     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
11034
11035   // With PIC, the address is actually $g + Offset.
11036   if (isGlobalRelativeToPICBase(OpFlags)) {
11037     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
11038                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
11039                          Result);
11040   }
11041
11042   // For globals that require a load from a stub to get the address, emit the
11043   // load.
11044   if (isGlobalStubReference(OpFlags))
11045     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
11046                          MachinePointerInfo::getGOT(), false, false, false, 0);
11047
11048   // If there was a non-zero offset that we didn't fold, create an explicit
11049   // addition for it.
11050   if (Offset != 0)
11051     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
11052                          DAG.getConstant(Offset, getPointerTy()));
11053
11054   return Result;
11055 }
11056
11057 SDValue
11058 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
11059   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
11060   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
11061   return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
11062 }
11063
11064 static SDValue
11065 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
11066            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
11067            unsigned char OperandFlags, bool LocalDynamic = false) {
11068   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11069   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11070   SDLoc dl(GA);
11071   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11072                                            GA->getValueType(0),
11073                                            GA->getOffset(),
11074                                            OperandFlags);
11075
11076   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
11077                                            : X86ISD::TLSADDR;
11078
11079   if (InFlag) {
11080     SDValue Ops[] = { Chain,  TGA, *InFlag };
11081     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11082   } else {
11083     SDValue Ops[]  = { Chain, TGA };
11084     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11085   }
11086
11087   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
11088   MFI->setAdjustsStack(true);
11089   MFI->setHasCalls(true);
11090
11091   SDValue Flag = Chain.getValue(1);
11092   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
11093 }
11094
11095 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
11096 static SDValue
11097 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11098                                 const EVT PtrVT) {
11099   SDValue InFlag;
11100   SDLoc dl(GA);  // ? function entry point might be better
11101   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
11102                                    DAG.getNode(X86ISD::GlobalBaseReg,
11103                                                SDLoc(), PtrVT), InFlag);
11104   InFlag = Chain.getValue(1);
11105
11106   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
11107 }
11108
11109 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
11110 static SDValue
11111 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11112                                 const EVT PtrVT) {
11113   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
11114                     X86::RAX, X86II::MO_TLSGD);
11115 }
11116
11117 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
11118                                            SelectionDAG &DAG,
11119                                            const EVT PtrVT,
11120                                            bool is64Bit) {
11121   SDLoc dl(GA);
11122
11123   // Get the start address of the TLS block for this module.
11124   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
11125       .getInfo<X86MachineFunctionInfo>();
11126   MFI->incNumLocalDynamicTLSAccesses();
11127
11128   SDValue Base;
11129   if (is64Bit) {
11130     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
11131                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
11132   } else {
11133     SDValue InFlag;
11134     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
11135         DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
11136     InFlag = Chain.getValue(1);
11137     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
11138                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
11139   }
11140
11141   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
11142   // of Base.
11143
11144   // Build x@dtpoff.
11145   unsigned char OperandFlags = X86II::MO_DTPOFF;
11146   unsigned WrapperKind = X86ISD::Wrapper;
11147   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11148                                            GA->getValueType(0),
11149                                            GA->getOffset(), OperandFlags);
11150   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
11151
11152   // Add x@dtpoff with the base.
11153   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
11154 }
11155
11156 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
11157 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11158                                    const EVT PtrVT, TLSModel::Model model,
11159                                    bool is64Bit, bool isPIC) {
11160   SDLoc dl(GA);
11161
11162   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
11163   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
11164                                                          is64Bit ? 257 : 256));
11165
11166   SDValue ThreadPointer =
11167       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0),
11168                   MachinePointerInfo(Ptr), false, false, false, 0);
11169
11170   unsigned char OperandFlags = 0;
11171   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
11172   // initialexec.
11173   unsigned WrapperKind = X86ISD::Wrapper;
11174   if (model == TLSModel::LocalExec) {
11175     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
11176   } else if (model == TLSModel::InitialExec) {
11177     if (is64Bit) {
11178       OperandFlags = X86II::MO_GOTTPOFF;
11179       WrapperKind = X86ISD::WrapperRIP;
11180     } else {
11181       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
11182     }
11183   } else {
11184     llvm_unreachable("Unexpected model");
11185   }
11186
11187   // emit "addl x@ntpoff,%eax" (local exec)
11188   // or "addl x@indntpoff,%eax" (initial exec)
11189   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
11190   SDValue TGA =
11191       DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
11192                                  GA->getOffset(), OperandFlags);
11193   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
11194
11195   if (model == TLSModel::InitialExec) {
11196     if (isPIC && !is64Bit) {
11197       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
11198                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
11199                            Offset);
11200     }
11201
11202     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
11203                          MachinePointerInfo::getGOT(), false, false, false, 0);
11204   }
11205
11206   // The address of the thread local variable is the add of the thread
11207   // pointer with the offset of the variable.
11208   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
11209 }
11210
11211 SDValue
11212 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
11213
11214   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
11215   const GlobalValue *GV = GA->getGlobal();
11216
11217   if (Subtarget->isTargetELF()) {
11218     TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
11219
11220     switch (model) {
11221       case TLSModel::GeneralDynamic:
11222         if (Subtarget->is64Bit())
11223           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
11224         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
11225       case TLSModel::LocalDynamic:
11226         return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
11227                                            Subtarget->is64Bit());
11228       case TLSModel::InitialExec:
11229       case TLSModel::LocalExec:
11230         return LowerToTLSExecModel(
11231             GA, DAG, getPointerTy(), model, Subtarget->is64Bit(),
11232             DAG.getTarget().getRelocationModel() == Reloc::PIC_);
11233     }
11234     llvm_unreachable("Unknown TLS model.");
11235   }
11236
11237   if (Subtarget->isTargetDarwin()) {
11238     // Darwin only has one model of TLS.  Lower to that.
11239     unsigned char OpFlag = 0;
11240     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
11241                            X86ISD::WrapperRIP : X86ISD::Wrapper;
11242
11243     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11244     // global base reg.
11245     bool PIC32 = (DAG.getTarget().getRelocationModel() == Reloc::PIC_) &&
11246                  !Subtarget->is64Bit();
11247     if (PIC32)
11248       OpFlag = X86II::MO_TLVP_PIC_BASE;
11249     else
11250       OpFlag = X86II::MO_TLVP;
11251     SDLoc DL(Op);
11252     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
11253                                                 GA->getValueType(0),
11254                                                 GA->getOffset(), OpFlag);
11255     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
11256
11257     // With PIC32, the address is actually $g + Offset.
11258     if (PIC32)
11259       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11260                            DAG.getNode(X86ISD::GlobalBaseReg,
11261                                        SDLoc(), getPointerTy()),
11262                            Offset);
11263
11264     // Lowering the machine isd will make sure everything is in the right
11265     // location.
11266     SDValue Chain = DAG.getEntryNode();
11267     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11268     SDValue Args[] = { Chain, Offset };
11269     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
11270
11271     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
11272     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11273     MFI->setAdjustsStack(true);
11274
11275     // And our return value (tls address) is in the standard call return value
11276     // location.
11277     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
11278     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
11279                               Chain.getValue(1));
11280   }
11281
11282   if (Subtarget->isTargetKnownWindowsMSVC() ||
11283       Subtarget->isTargetWindowsGNU()) {
11284     // Just use the implicit TLS architecture
11285     // Need to generate someting similar to:
11286     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
11287     //                                  ; from TEB
11288     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
11289     //   mov     rcx, qword [rdx+rcx*8]
11290     //   mov     eax, .tls$:tlsvar
11291     //   [rax+rcx] contains the address
11292     // Windows 64bit: gs:0x58
11293     // Windows 32bit: fs:__tls_array
11294
11295     SDLoc dl(GA);
11296     SDValue Chain = DAG.getEntryNode();
11297
11298     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
11299     // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
11300     // use its literal value of 0x2C.
11301     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
11302                                         ? Type::getInt8PtrTy(*DAG.getContext(),
11303                                                              256)
11304                                         : Type::getInt32PtrTy(*DAG.getContext(),
11305                                                               257));
11306
11307     SDValue TlsArray =
11308         Subtarget->is64Bit()
11309             ? DAG.getIntPtrConstant(0x58)
11310             : (Subtarget->isTargetWindowsGNU()
11311                    ? DAG.getIntPtrConstant(0x2C)
11312                    : DAG.getExternalSymbol("_tls_array", getPointerTy()));
11313
11314     SDValue ThreadPointer =
11315         DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
11316                     MachinePointerInfo(Ptr), false, false, false, 0);
11317
11318     // Load the _tls_index variable
11319     SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
11320     if (Subtarget->is64Bit())
11321       IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
11322                            IDX, MachinePointerInfo(), MVT::i32,
11323                            false, false, false, 0);
11324     else
11325       IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
11326                         false, false, false, 0);
11327
11328     SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
11329                                     getPointerTy());
11330     IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
11331
11332     SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
11333     res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
11334                       false, false, false, 0);
11335
11336     // Get the offset of start of .tls section
11337     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11338                                              GA->getValueType(0),
11339                                              GA->getOffset(), X86II::MO_SECREL);
11340     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
11341
11342     // The address of the thread local variable is the add of the thread
11343     // pointer with the offset of the variable.
11344     return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
11345   }
11346
11347   llvm_unreachable("TLS not implemented for this target.");
11348 }
11349
11350 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
11351 /// and take a 2 x i32 value to shift plus a shift amount.
11352 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
11353   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
11354   MVT VT = Op.getSimpleValueType();
11355   unsigned VTBits = VT.getSizeInBits();
11356   SDLoc dl(Op);
11357   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
11358   SDValue ShOpLo = Op.getOperand(0);
11359   SDValue ShOpHi = Op.getOperand(1);
11360   SDValue ShAmt  = Op.getOperand(2);
11361   // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
11362   // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
11363   // during isel.
11364   SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
11365                                   DAG.getConstant(VTBits - 1, MVT::i8));
11366   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
11367                                      DAG.getConstant(VTBits - 1, MVT::i8))
11368                        : DAG.getConstant(0, VT);
11369
11370   SDValue Tmp2, Tmp3;
11371   if (Op.getOpcode() == ISD::SHL_PARTS) {
11372     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
11373     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
11374   } else {
11375     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
11376     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
11377   }
11378
11379   // If the shift amount is larger or equal than the width of a part we can't
11380   // rely on the results of shld/shrd. Insert a test and select the appropriate
11381   // values for large shift amounts.
11382   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
11383                                 DAG.getConstant(VTBits, MVT::i8));
11384   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11385                              AndNode, DAG.getConstant(0, MVT::i8));
11386
11387   SDValue Hi, Lo;
11388   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11389   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
11390   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
11391
11392   if (Op.getOpcode() == ISD::SHL_PARTS) {
11393     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
11394     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
11395   } else {
11396     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
11397     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
11398   }
11399
11400   SDValue Ops[2] = { Lo, Hi };
11401   return DAG.getMergeValues(Ops, dl);
11402 }
11403
11404 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
11405                                            SelectionDAG &DAG) const {
11406   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
11407   SDLoc dl(Op);
11408
11409   if (SrcVT.isVector()) {
11410     if (SrcVT.getVectorElementType() == MVT::i1) {
11411       MVT IntegerVT = MVT::getVectorVT(MVT::i32, SrcVT.getVectorNumElements());
11412       return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
11413                          DAG.getNode(ISD::SIGN_EXTEND, dl, IntegerVT,
11414                                      Op.getOperand(0)));
11415     }
11416     return SDValue();
11417   }
11418
11419   assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
11420          "Unknown SINT_TO_FP to lower!");
11421
11422   // These are really Legal; return the operand so the caller accepts it as
11423   // Legal.
11424   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
11425     return Op;
11426   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
11427       Subtarget->is64Bit()) {
11428     return Op;
11429   }
11430
11431   unsigned Size = SrcVT.getSizeInBits()/8;
11432   MachineFunction &MF = DAG.getMachineFunction();
11433   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
11434   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11435   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11436                                StackSlot,
11437                                MachinePointerInfo::getFixedStack(SSFI),
11438                                false, false, 0);
11439   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
11440 }
11441
11442 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
11443                                      SDValue StackSlot,
11444                                      SelectionDAG &DAG) const {
11445   // Build the FILD
11446   SDLoc DL(Op);
11447   SDVTList Tys;
11448   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
11449   if (useSSE)
11450     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
11451   else
11452     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
11453
11454   unsigned ByteSize = SrcVT.getSizeInBits()/8;
11455
11456   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
11457   MachineMemOperand *MMO;
11458   if (FI) {
11459     int SSFI = FI->getIndex();
11460     MMO =
11461       DAG.getMachineFunction()
11462       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11463                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
11464   } else {
11465     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
11466     StackSlot = StackSlot.getOperand(1);
11467   }
11468   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
11469   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
11470                                            X86ISD::FILD, DL,
11471                                            Tys, Ops, SrcVT, MMO);
11472
11473   if (useSSE) {
11474     Chain = Result.getValue(1);
11475     SDValue InFlag = Result.getValue(2);
11476
11477     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
11478     // shouldn't be necessary except that RFP cannot be live across
11479     // multiple blocks. When stackifier is fixed, they can be uncoupled.
11480     MachineFunction &MF = DAG.getMachineFunction();
11481     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
11482     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
11483     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11484     Tys = DAG.getVTList(MVT::Other);
11485     SDValue Ops[] = {
11486       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
11487     };
11488     MachineMemOperand *MMO =
11489       DAG.getMachineFunction()
11490       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11491                             MachineMemOperand::MOStore, SSFISize, SSFISize);
11492
11493     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
11494                                     Ops, Op.getValueType(), MMO);
11495     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
11496                          MachinePointerInfo::getFixedStack(SSFI),
11497                          false, false, false, 0);
11498   }
11499
11500   return Result;
11501 }
11502
11503 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
11504 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
11505                                                SelectionDAG &DAG) const {
11506   // This algorithm is not obvious. Here it is what we're trying to output:
11507   /*
11508      movq       %rax,  %xmm0
11509      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
11510      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
11511      #ifdef __SSE3__
11512        haddpd   %xmm0, %xmm0
11513      #else
11514        pshufd   $0x4e, %xmm0, %xmm1
11515        addpd    %xmm1, %xmm0
11516      #endif
11517   */
11518
11519   SDLoc dl(Op);
11520   LLVMContext *Context = DAG.getContext();
11521
11522   // Build some magic constants.
11523   static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
11524   Constant *C0 = ConstantDataVector::get(*Context, CV0);
11525   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
11526
11527   SmallVector<Constant*,2> CV1;
11528   CV1.push_back(
11529     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11530                                       APInt(64, 0x4330000000000000ULL))));
11531   CV1.push_back(
11532     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11533                                       APInt(64, 0x4530000000000000ULL))));
11534   Constant *C1 = ConstantVector::get(CV1);
11535   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
11536
11537   // Load the 64-bit value into an XMM register.
11538   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
11539                             Op.getOperand(0));
11540   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
11541                               MachinePointerInfo::getConstantPool(),
11542                               false, false, false, 16);
11543   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
11544                               DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
11545                               CLod0);
11546
11547   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
11548                               MachinePointerInfo::getConstantPool(),
11549                               false, false, false, 16);
11550   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
11551   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
11552   SDValue Result;
11553
11554   if (Subtarget->hasSSE3()) {
11555     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
11556     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
11557   } else {
11558     SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
11559     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
11560                                            S2F, 0x4E, DAG);
11561     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
11562                          DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
11563                          Sub);
11564   }
11565
11566   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
11567                      DAG.getIntPtrConstant(0));
11568 }
11569
11570 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
11571 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
11572                                                SelectionDAG &DAG) const {
11573   SDLoc dl(Op);
11574   // FP constant to bias correct the final result.
11575   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
11576                                    MVT::f64);
11577
11578   // Load the 32-bit value into an XMM register.
11579   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
11580                              Op.getOperand(0));
11581
11582   // Zero out the upper parts of the register.
11583   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
11584
11585   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
11586                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
11587                      DAG.getIntPtrConstant(0));
11588
11589   // Or the load with the bias.
11590   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
11591                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
11592                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
11593                                                    MVT::v2f64, Load)),
11594                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
11595                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
11596                                                    MVT::v2f64, Bias)));
11597   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
11598                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
11599                    DAG.getIntPtrConstant(0));
11600
11601   // Subtract the bias.
11602   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
11603
11604   // Handle final rounding.
11605   EVT DestVT = Op.getValueType();
11606
11607   if (DestVT.bitsLT(MVT::f64))
11608     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
11609                        DAG.getIntPtrConstant(0));
11610   if (DestVT.bitsGT(MVT::f64))
11611     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
11612
11613   // Handle final rounding.
11614   return Sub;
11615 }
11616
11617 static SDValue lowerUINT_TO_FP_vXi32(SDValue Op, SelectionDAG &DAG,
11618                                      const X86Subtarget &Subtarget) {
11619   // The algorithm is the following:
11620   // #ifdef __SSE4_1__
11621   //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
11622   //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
11623   //                                 (uint4) 0x53000000, 0xaa);
11624   // #else
11625   //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
11626   //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
11627   // #endif
11628   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
11629   //     return (float4) lo + fhi;
11630
11631   SDLoc DL(Op);
11632   SDValue V = Op->getOperand(0);
11633   EVT VecIntVT = V.getValueType();
11634   bool Is128 = VecIntVT == MVT::v4i32;
11635   EVT VecFloatVT = Is128 ? MVT::v4f32 : MVT::v8f32;
11636   // If we convert to something else than the supported type, e.g., to v4f64,
11637   // abort early.
11638   if (VecFloatVT != Op->getValueType(0))
11639     return SDValue();
11640
11641   unsigned NumElts = VecIntVT.getVectorNumElements();
11642   assert((VecIntVT == MVT::v4i32 || VecIntVT == MVT::v8i32) &&
11643          "Unsupported custom type");
11644   assert(NumElts <= 8 && "The size of the constant array must be fixed");
11645
11646   // In the #idef/#else code, we have in common:
11647   // - The vector of constants:
11648   // -- 0x4b000000
11649   // -- 0x53000000
11650   // - A shift:
11651   // -- v >> 16
11652
11653   // Create the splat vector for 0x4b000000.
11654   SDValue CstLow = DAG.getConstant(0x4b000000, MVT::i32);
11655   SDValue CstLowArray[] = {CstLow, CstLow, CstLow, CstLow,
11656                            CstLow, CstLow, CstLow, CstLow};
11657   SDValue VecCstLow = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
11658                                   makeArrayRef(&CstLowArray[0], NumElts));
11659   // Create the splat vector for 0x53000000.
11660   SDValue CstHigh = DAG.getConstant(0x53000000, MVT::i32);
11661   SDValue CstHighArray[] = {CstHigh, CstHigh, CstHigh, CstHigh,
11662                             CstHigh, CstHigh, CstHigh, CstHigh};
11663   SDValue VecCstHigh = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
11664                                    makeArrayRef(&CstHighArray[0], NumElts));
11665
11666   // Create the right shift.
11667   SDValue CstShift = DAG.getConstant(16, MVT::i32);
11668   SDValue CstShiftArray[] = {CstShift, CstShift, CstShift, CstShift,
11669                              CstShift, CstShift, CstShift, CstShift};
11670   SDValue VecCstShift = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
11671                                     makeArrayRef(&CstShiftArray[0], NumElts));
11672   SDValue HighShift = DAG.getNode(ISD::SRL, DL, VecIntVT, V, VecCstShift);
11673
11674   SDValue Low, High;
11675   if (Subtarget.hasSSE41()) {
11676     EVT VecI16VT = Is128 ? MVT::v8i16 : MVT::v16i16;
11677     //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
11678     SDValue VecCstLowBitcast =
11679         DAG.getNode(ISD::BITCAST, DL, VecI16VT, VecCstLow);
11680     SDValue VecBitcast = DAG.getNode(ISD::BITCAST, DL, VecI16VT, V);
11681     // Low will be bitcasted right away, so do not bother bitcasting back to its
11682     // original type.
11683     Low = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecBitcast,
11684                       VecCstLowBitcast, DAG.getConstant(0xaa, MVT::i32));
11685     //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
11686     //                                 (uint4) 0x53000000, 0xaa);
11687     SDValue VecCstHighBitcast =
11688         DAG.getNode(ISD::BITCAST, DL, VecI16VT, VecCstHigh);
11689     SDValue VecShiftBitcast =
11690         DAG.getNode(ISD::BITCAST, DL, VecI16VT, HighShift);
11691     // High will be bitcasted right away, so do not bother bitcasting back to
11692     // its original type.
11693     High = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecShiftBitcast,
11694                        VecCstHighBitcast, DAG.getConstant(0xaa, MVT::i32));
11695   } else {
11696     SDValue CstMask = DAG.getConstant(0xffff, MVT::i32);
11697     SDValue VecCstMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT, CstMask,
11698                                      CstMask, CstMask, CstMask);
11699     //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
11700     SDValue LowAnd = DAG.getNode(ISD::AND, DL, VecIntVT, V, VecCstMask);
11701     Low = DAG.getNode(ISD::OR, DL, VecIntVT, LowAnd, VecCstLow);
11702
11703     //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
11704     High = DAG.getNode(ISD::OR, DL, VecIntVT, HighShift, VecCstHigh);
11705   }
11706
11707   // Create the vector constant for -(0x1.0p39f + 0x1.0p23f).
11708   SDValue CstFAdd = DAG.getConstantFP(
11709       APFloat(APFloat::IEEEsingle, APInt(32, 0xD3000080)), MVT::f32);
11710   SDValue CstFAddArray[] = {CstFAdd, CstFAdd, CstFAdd, CstFAdd,
11711                             CstFAdd, CstFAdd, CstFAdd, CstFAdd};
11712   SDValue VecCstFAdd = DAG.getNode(ISD::BUILD_VECTOR, DL, VecFloatVT,
11713                                    makeArrayRef(&CstFAddArray[0], NumElts));
11714
11715   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
11716   SDValue HighBitcast = DAG.getNode(ISD::BITCAST, DL, VecFloatVT, High);
11717   SDValue FHigh =
11718       DAG.getNode(ISD::FADD, DL, VecFloatVT, HighBitcast, VecCstFAdd);
11719   //     return (float4) lo + fhi;
11720   SDValue LowBitcast = DAG.getNode(ISD::BITCAST, DL, VecFloatVT, Low);
11721   return DAG.getNode(ISD::FADD, DL, VecFloatVT, LowBitcast, FHigh);
11722 }
11723
11724 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
11725                                                SelectionDAG &DAG) const {
11726   SDValue N0 = Op.getOperand(0);
11727   MVT SVT = N0.getSimpleValueType();
11728   SDLoc dl(Op);
11729
11730   switch (SVT.SimpleTy) {
11731   default:
11732     llvm_unreachable("Custom UINT_TO_FP is not supported!");
11733   case MVT::v4i8:
11734   case MVT::v4i16:
11735   case MVT::v8i8:
11736   case MVT::v8i16: {
11737     MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
11738     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
11739                        DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
11740   }
11741   case MVT::v4i32:
11742   case MVT::v8i32:
11743     return lowerUINT_TO_FP_vXi32(Op, DAG, *Subtarget);
11744   }
11745   llvm_unreachable(nullptr);
11746 }
11747
11748 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
11749                                            SelectionDAG &DAG) const {
11750   SDValue N0 = Op.getOperand(0);
11751   SDLoc dl(Op);
11752
11753   if (Op.getValueType().isVector())
11754     return lowerUINT_TO_FP_vec(Op, DAG);
11755
11756   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
11757   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
11758   // the optimization here.
11759   if (DAG.SignBitIsZero(N0))
11760     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
11761
11762   MVT SrcVT = N0.getSimpleValueType();
11763   MVT DstVT = Op.getSimpleValueType();
11764   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
11765     return LowerUINT_TO_FP_i64(Op, DAG);
11766   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
11767     return LowerUINT_TO_FP_i32(Op, DAG);
11768   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
11769     return SDValue();
11770
11771   // Make a 64-bit buffer, and use it to build an FILD.
11772   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
11773   if (SrcVT == MVT::i32) {
11774     SDValue WordOff = DAG.getConstant(4, getPointerTy());
11775     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
11776                                      getPointerTy(), StackSlot, WordOff);
11777     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11778                                   StackSlot, MachinePointerInfo(),
11779                                   false, false, 0);
11780     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
11781                                   OffsetSlot, MachinePointerInfo(),
11782                                   false, false, 0);
11783     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
11784     return Fild;
11785   }
11786
11787   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
11788   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11789                                StackSlot, MachinePointerInfo(),
11790                                false, false, 0);
11791   // For i64 source, we need to add the appropriate power of 2 if the input
11792   // was negative.  This is the same as the optimization in
11793   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
11794   // we must be careful to do the computation in x87 extended precision, not
11795   // in SSE. (The generic code can't know it's OK to do this, or how to.)
11796   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
11797   MachineMemOperand *MMO =
11798     DAG.getMachineFunction()
11799     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11800                           MachineMemOperand::MOLoad, 8, 8);
11801
11802   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
11803   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
11804   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
11805                                          MVT::i64, MMO);
11806
11807   APInt FF(32, 0x5F800000ULL);
11808
11809   // Check whether the sign bit is set.
11810   SDValue SignSet = DAG.getSetCC(dl,
11811                                  getSetCCResultType(*DAG.getContext(), MVT::i64),
11812                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
11813                                  ISD::SETLT);
11814
11815   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
11816   SDValue FudgePtr = DAG.getConstantPool(
11817                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
11818                                          getPointerTy());
11819
11820   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
11821   SDValue Zero = DAG.getIntPtrConstant(0);
11822   SDValue Four = DAG.getIntPtrConstant(4);
11823   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
11824                                Zero, Four);
11825   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
11826
11827   // Load the value out, extending it from f32 to f80.
11828   // FIXME: Avoid the extend by constructing the right constant pool?
11829   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
11830                                  FudgePtr, MachinePointerInfo::getConstantPool(),
11831                                  MVT::f32, false, false, false, 4);
11832   // Extend everything to 80 bits to force it to be done on x87.
11833   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
11834   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
11835 }
11836
11837 std::pair<SDValue,SDValue>
11838 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
11839                                     bool IsSigned, bool IsReplace) const {
11840   SDLoc DL(Op);
11841
11842   EVT DstTy = Op.getValueType();
11843
11844   if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
11845     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
11846     DstTy = MVT::i64;
11847   }
11848
11849   assert(DstTy.getSimpleVT() <= MVT::i64 &&
11850          DstTy.getSimpleVT() >= MVT::i16 &&
11851          "Unknown FP_TO_INT to lower!");
11852
11853   // These are really Legal.
11854   if (DstTy == MVT::i32 &&
11855       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
11856     return std::make_pair(SDValue(), SDValue());
11857   if (Subtarget->is64Bit() &&
11858       DstTy == MVT::i64 &&
11859       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
11860     return std::make_pair(SDValue(), SDValue());
11861
11862   // We lower FP->int64 either into FISTP64 followed by a load from a temporary
11863   // stack slot, or into the FTOL runtime function.
11864   MachineFunction &MF = DAG.getMachineFunction();
11865   unsigned MemSize = DstTy.getSizeInBits()/8;
11866   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
11867   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11868
11869   unsigned Opc;
11870   if (!IsSigned && isIntegerTypeFTOL(DstTy))
11871     Opc = X86ISD::WIN_FTOL;
11872   else
11873     switch (DstTy.getSimpleVT().SimpleTy) {
11874     default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
11875     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
11876     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
11877     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
11878     }
11879
11880   SDValue Chain = DAG.getEntryNode();
11881   SDValue Value = Op.getOperand(0);
11882   EVT TheVT = Op.getOperand(0).getValueType();
11883   // FIXME This causes a redundant load/store if the SSE-class value is already
11884   // in memory, such as if it is on the callstack.
11885   if (isScalarFPTypeInSSEReg(TheVT)) {
11886     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
11887     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
11888                          MachinePointerInfo::getFixedStack(SSFI),
11889                          false, false, 0);
11890     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
11891     SDValue Ops[] = {
11892       Chain, StackSlot, DAG.getValueType(TheVT)
11893     };
11894
11895     MachineMemOperand *MMO =
11896       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11897                               MachineMemOperand::MOLoad, MemSize, MemSize);
11898     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
11899     Chain = Value.getValue(1);
11900     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
11901     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11902   }
11903
11904   MachineMemOperand *MMO =
11905     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11906                             MachineMemOperand::MOStore, MemSize, MemSize);
11907
11908   if (Opc != X86ISD::WIN_FTOL) {
11909     // Build the FP_TO_INT*_IN_MEM
11910     SDValue Ops[] = { Chain, Value, StackSlot };
11911     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
11912                                            Ops, DstTy, MMO);
11913     return std::make_pair(FIST, StackSlot);
11914   } else {
11915     SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
11916       DAG.getVTList(MVT::Other, MVT::Glue),
11917       Chain, Value);
11918     SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
11919       MVT::i32, ftol.getValue(1));
11920     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
11921       MVT::i32, eax.getValue(2));
11922     SDValue Ops[] = { eax, edx };
11923     SDValue pair = IsReplace
11924       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops)
11925       : DAG.getMergeValues(Ops, DL);
11926     return std::make_pair(pair, SDValue());
11927   }
11928 }
11929
11930 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
11931                               const X86Subtarget *Subtarget) {
11932   MVT VT = Op->getSimpleValueType(0);
11933   SDValue In = Op->getOperand(0);
11934   MVT InVT = In.getSimpleValueType();
11935   SDLoc dl(Op);
11936
11937   // Optimize vectors in AVX mode:
11938   //
11939   //   v8i16 -> v8i32
11940   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
11941   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
11942   //   Concat upper and lower parts.
11943   //
11944   //   v4i32 -> v4i64
11945   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
11946   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
11947   //   Concat upper and lower parts.
11948   //
11949
11950   if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
11951       ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
11952       ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
11953     return SDValue();
11954
11955   if (Subtarget->hasInt256())
11956     return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
11957
11958   SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
11959   SDValue Undef = DAG.getUNDEF(InVT);
11960   bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
11961   SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
11962   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
11963
11964   MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
11965                              VT.getVectorNumElements()/2);
11966
11967   OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
11968   OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
11969
11970   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
11971 }
11972
11973 static  SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
11974                                         SelectionDAG &DAG) {
11975   MVT VT = Op->getSimpleValueType(0);
11976   SDValue In = Op->getOperand(0);
11977   MVT InVT = In.getSimpleValueType();
11978   SDLoc DL(Op);
11979   unsigned int NumElts = VT.getVectorNumElements();
11980   if (NumElts != 8 && NumElts != 16)
11981     return SDValue();
11982
11983   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
11984     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
11985
11986   EVT ExtVT = (NumElts == 8)? MVT::v8i64 : MVT::v16i32;
11987   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11988   // Now we have only mask extension
11989   assert(InVT.getVectorElementType() == MVT::i1);
11990   SDValue Cst = DAG.getTargetConstant(1, ExtVT.getScalarType());
11991   const Constant *C = cast<ConstantSDNode>(Cst)->getConstantIntValue();
11992   SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
11993   unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
11994   SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
11995                            MachinePointerInfo::getConstantPool(),
11996                            false, false, false, Alignment);
11997
11998   SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, DL, ExtVT, In, Ld);
11999   if (VT.is512BitVector())
12000     return Brcst;
12001   return DAG.getNode(X86ISD::VTRUNC, DL, VT, Brcst);
12002 }
12003
12004 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
12005                                SelectionDAG &DAG) {
12006   if (Subtarget->hasFp256()) {
12007     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
12008     if (Res.getNode())
12009       return Res;
12010   }
12011
12012   return SDValue();
12013 }
12014
12015 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
12016                                 SelectionDAG &DAG) {
12017   SDLoc DL(Op);
12018   MVT VT = Op.getSimpleValueType();
12019   SDValue In = Op.getOperand(0);
12020   MVT SVT = In.getSimpleValueType();
12021
12022   if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
12023     return LowerZERO_EXTEND_AVX512(Op, DAG);
12024
12025   if (Subtarget->hasFp256()) {
12026     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
12027     if (Res.getNode())
12028       return Res;
12029   }
12030
12031   assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
12032          VT.getVectorNumElements() != SVT.getVectorNumElements());
12033   return SDValue();
12034 }
12035
12036 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
12037   SDLoc DL(Op);
12038   MVT VT = Op.getSimpleValueType();
12039   SDValue In = Op.getOperand(0);
12040   MVT InVT = In.getSimpleValueType();
12041
12042   if (VT == MVT::i1) {
12043     assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
12044            "Invalid scalar TRUNCATE operation");
12045     if (InVT.getSizeInBits() >= 32)
12046       return SDValue();
12047     In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
12048     return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
12049   }
12050   assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
12051          "Invalid TRUNCATE operation");
12052
12053   if (InVT.is512BitVector() || VT.getVectorElementType() == MVT::i1) {
12054     if (VT.getVectorElementType().getSizeInBits() >=8)
12055       return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
12056
12057     assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
12058     unsigned NumElts = InVT.getVectorNumElements();
12059     assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
12060     if (InVT.getSizeInBits() < 512) {
12061       MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
12062       In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
12063       InVT = ExtVT;
12064     }
12065
12066     SDValue Cst = DAG.getTargetConstant(1, InVT.getVectorElementType());
12067     const Constant *C = cast<ConstantSDNode>(Cst)->getConstantIntValue();
12068     SDValue CP = DAG.getConstantPool(C, getPointerTy());
12069     unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
12070     SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
12071                            MachinePointerInfo::getConstantPool(),
12072                            false, false, false, Alignment);
12073     SDValue OneV = DAG.getNode(X86ISD::VBROADCAST, DL, InVT, Ld);
12074     SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
12075     return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
12076   }
12077
12078   if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
12079     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
12080     if (Subtarget->hasInt256()) {
12081       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
12082       In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
12083       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
12084                                 ShufMask);
12085       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
12086                          DAG.getIntPtrConstant(0));
12087     }
12088
12089     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12090                                DAG.getIntPtrConstant(0));
12091     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12092                                DAG.getIntPtrConstant(2));
12093     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
12094     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
12095     static const int ShufMask[] = {0, 2, 4, 6};
12096     return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
12097   }
12098
12099   if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
12100     // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
12101     if (Subtarget->hasInt256()) {
12102       In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
12103
12104       SmallVector<SDValue,32> pshufbMask;
12105       for (unsigned i = 0; i < 2; ++i) {
12106         pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
12107         pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
12108         pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
12109         pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
12110         pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
12111         pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
12112         pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
12113         pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
12114         for (unsigned j = 0; j < 8; ++j)
12115           pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
12116       }
12117       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
12118       In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
12119       In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
12120
12121       static const int ShufMask[] = {0,  2,  -1,  -1};
12122       In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, DAG.getUNDEF(MVT::v4i64),
12123                                 &ShufMask[0]);
12124       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12125                        DAG.getIntPtrConstant(0));
12126       return DAG.getNode(ISD::BITCAST, DL, VT, In);
12127     }
12128
12129     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
12130                                DAG.getIntPtrConstant(0));
12131
12132     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
12133                                DAG.getIntPtrConstant(4));
12134
12135     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
12136     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
12137
12138     // The PSHUFB mask:
12139     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
12140                                    -1, -1, -1, -1, -1, -1, -1, -1};
12141
12142     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
12143     OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
12144     OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
12145
12146     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
12147     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
12148
12149     // The MOVLHPS Mask:
12150     static const int ShufMask2[] = {0, 1, 4, 5};
12151     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
12152     return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
12153   }
12154
12155   // Handle truncation of V256 to V128 using shuffles.
12156   if (!VT.is128BitVector() || !InVT.is256BitVector())
12157     return SDValue();
12158
12159   assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
12160
12161   unsigned NumElems = VT.getVectorNumElements();
12162   MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
12163
12164   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
12165   // Prepare truncation shuffle mask
12166   for (unsigned i = 0; i != NumElems; ++i)
12167     MaskVec[i] = i * 2;
12168   SDValue V = DAG.getVectorShuffle(NVT, DL,
12169                                    DAG.getNode(ISD::BITCAST, DL, NVT, In),
12170                                    DAG.getUNDEF(NVT), &MaskVec[0]);
12171   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
12172                      DAG.getIntPtrConstant(0));
12173 }
12174
12175 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
12176                                            SelectionDAG &DAG) const {
12177   assert(!Op.getSimpleValueType().isVector());
12178
12179   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
12180     /*IsSigned=*/ true, /*IsReplace=*/ false);
12181   SDValue FIST = Vals.first, StackSlot = Vals.second;
12182   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
12183   if (!FIST.getNode()) return Op;
12184
12185   if (StackSlot.getNode())
12186     // Load the result.
12187     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
12188                        FIST, StackSlot, MachinePointerInfo(),
12189                        false, false, false, 0);
12190
12191   // The node is the result.
12192   return FIST;
12193 }
12194
12195 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
12196                                            SelectionDAG &DAG) const {
12197   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
12198     /*IsSigned=*/ false, /*IsReplace=*/ false);
12199   SDValue FIST = Vals.first, StackSlot = Vals.second;
12200   assert(FIST.getNode() && "Unexpected failure");
12201
12202   if (StackSlot.getNode())
12203     // Load the result.
12204     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
12205                        FIST, StackSlot, MachinePointerInfo(),
12206                        false, false, false, 0);
12207
12208   // The node is the result.
12209   return FIST;
12210 }
12211
12212 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
12213   SDLoc DL(Op);
12214   MVT VT = Op.getSimpleValueType();
12215   SDValue In = Op.getOperand(0);
12216   MVT SVT = In.getSimpleValueType();
12217
12218   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
12219
12220   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
12221                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
12222                                  In, DAG.getUNDEF(SVT)));
12223 }
12224
12225 /// The only differences between FABS and FNEG are the mask and the logic op.
12226 /// FNEG also has a folding opportunity for FNEG(FABS(x)).
12227 static SDValue LowerFABSorFNEG(SDValue Op, SelectionDAG &DAG) {
12228   assert((Op.getOpcode() == ISD::FABS || Op.getOpcode() == ISD::FNEG) &&
12229          "Wrong opcode for lowering FABS or FNEG.");
12230
12231   bool IsFABS = (Op.getOpcode() == ISD::FABS);
12232
12233   // If this is a FABS and it has an FNEG user, bail out to fold the combination
12234   // into an FNABS. We'll lower the FABS after that if it is still in use.
12235   if (IsFABS)
12236     for (SDNode *User : Op->uses())
12237       if (User->getOpcode() == ISD::FNEG)
12238         return Op;
12239
12240   SDValue Op0 = Op.getOperand(0);
12241   bool IsFNABS = !IsFABS && (Op0.getOpcode() == ISD::FABS);
12242
12243   SDLoc dl(Op);
12244   MVT VT = Op.getSimpleValueType();
12245   // Assume scalar op for initialization; update for vector if needed.
12246   // Note that there are no scalar bitwise logical SSE/AVX instructions, so we
12247   // generate a 16-byte vector constant and logic op even for the scalar case.
12248   // Using a 16-byte mask allows folding the load of the mask with
12249   // the logic op, so it can save (~4 bytes) on code size.
12250   MVT EltVT = VT;
12251   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
12252   // FIXME: Use function attribute "OptimizeForSize" and/or CodeGenOpt::Level to
12253   // decide if we should generate a 16-byte constant mask when we only need 4 or
12254   // 8 bytes for the scalar case.
12255   if (VT.isVector()) {
12256     EltVT = VT.getVectorElementType();
12257     NumElts = VT.getVectorNumElements();
12258   }
12259
12260   unsigned EltBits = EltVT.getSizeInBits();
12261   LLVMContext *Context = DAG.getContext();
12262   // For FABS, mask is 0x7f...; for FNEG, mask is 0x80...
12263   APInt MaskElt =
12264     IsFABS ? APInt::getSignedMaxValue(EltBits) : APInt::getSignBit(EltBits);
12265   Constant *C = ConstantInt::get(*Context, MaskElt);
12266   C = ConstantVector::getSplat(NumElts, C);
12267   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12268   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
12269   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
12270   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
12271                              MachinePointerInfo::getConstantPool(),
12272                              false, false, false, Alignment);
12273
12274   if (VT.isVector()) {
12275     // For a vector, cast operands to a vector type, perform the logic op,
12276     // and cast the result back to the original value type.
12277     MVT VecVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
12278     SDValue MaskCasted = DAG.getNode(ISD::BITCAST, dl, VecVT, Mask);
12279     SDValue Operand = IsFNABS ?
12280       DAG.getNode(ISD::BITCAST, dl, VecVT, Op0.getOperand(0)) :
12281       DAG.getNode(ISD::BITCAST, dl, VecVT, Op0);
12282     unsigned BitOp = IsFABS ? ISD::AND : IsFNABS ? ISD::OR : ISD::XOR;
12283     return DAG.getNode(ISD::BITCAST, dl, VT,
12284                        DAG.getNode(BitOp, dl, VecVT, Operand, MaskCasted));
12285   }
12286
12287   // If not vector, then scalar.
12288   unsigned BitOp = IsFABS ? X86ISD::FAND : IsFNABS ? X86ISD::FOR : X86ISD::FXOR;
12289   SDValue Operand = IsFNABS ? Op0.getOperand(0) : Op0;
12290   return DAG.getNode(BitOp, dl, VT, Operand, Mask);
12291 }
12292
12293 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
12294   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12295   LLVMContext *Context = DAG.getContext();
12296   SDValue Op0 = Op.getOperand(0);
12297   SDValue Op1 = Op.getOperand(1);
12298   SDLoc dl(Op);
12299   MVT VT = Op.getSimpleValueType();
12300   MVT SrcVT = Op1.getSimpleValueType();
12301
12302   // If second operand is smaller, extend it first.
12303   if (SrcVT.bitsLT(VT)) {
12304     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
12305     SrcVT = VT;
12306   }
12307   // And if it is bigger, shrink it first.
12308   if (SrcVT.bitsGT(VT)) {
12309     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
12310     SrcVT = VT;
12311   }
12312
12313   // At this point the operands and the result should have the same
12314   // type, and that won't be f80 since that is not custom lowered.
12315
12316   const fltSemantics &Sem =
12317       VT == MVT::f64 ? APFloat::IEEEdouble : APFloat::IEEEsingle;
12318   const unsigned SizeInBits = VT.getSizeInBits();
12319
12320   SmallVector<Constant *, 4> CV(
12321       VT == MVT::f64 ? 2 : 4,
12322       ConstantFP::get(*Context, APFloat(Sem, APInt(SizeInBits, 0))));
12323
12324   // First, clear all bits but the sign bit from the second operand (sign).
12325   CV[0] = ConstantFP::get(*Context,
12326                           APFloat(Sem, APInt::getHighBitsSet(SizeInBits, 1)));
12327   Constant *C = ConstantVector::get(CV);
12328   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
12329   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
12330                               MachinePointerInfo::getConstantPool(),
12331                               false, false, false, 16);
12332   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
12333
12334   // Next, clear the sign bit from the first operand (magnitude).
12335   // If it's a constant, we can clear it here.
12336   if (ConstantFPSDNode *Op0CN = dyn_cast<ConstantFPSDNode>(Op0)) {
12337     APFloat APF = Op0CN->getValueAPF();
12338     // If the magnitude is a positive zero, the sign bit alone is enough.
12339     if (APF.isPosZero())
12340       return SignBit;
12341     APF.clearSign();
12342     CV[0] = ConstantFP::get(*Context, APF);
12343   } else {
12344     CV[0] = ConstantFP::get(
12345         *Context,
12346         APFloat(Sem, APInt::getLowBitsSet(SizeInBits, SizeInBits - 1)));
12347   }
12348   C = ConstantVector::get(CV);
12349   CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
12350   SDValue Val = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
12351                             MachinePointerInfo::getConstantPool(),
12352                             false, false, false, 16);
12353   // If the magnitude operand wasn't a constant, we need to AND out the sign.
12354   if (!isa<ConstantFPSDNode>(Op0))
12355     Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Val);
12356
12357   // OR the magnitude value with the sign bit.
12358   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
12359 }
12360
12361 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
12362   SDValue N0 = Op.getOperand(0);
12363   SDLoc dl(Op);
12364   MVT VT = Op.getSimpleValueType();
12365
12366   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
12367   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
12368                                   DAG.getConstant(1, VT));
12369   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
12370 }
12371
12372 // Check whether an OR'd tree is PTEST-able.
12373 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
12374                                       SelectionDAG &DAG) {
12375   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
12376
12377   if (!Subtarget->hasSSE41())
12378     return SDValue();
12379
12380   if (!Op->hasOneUse())
12381     return SDValue();
12382
12383   SDNode *N = Op.getNode();
12384   SDLoc DL(N);
12385
12386   SmallVector<SDValue, 8> Opnds;
12387   DenseMap<SDValue, unsigned> VecInMap;
12388   SmallVector<SDValue, 8> VecIns;
12389   EVT VT = MVT::Other;
12390
12391   // Recognize a special case where a vector is casted into wide integer to
12392   // test all 0s.
12393   Opnds.push_back(N->getOperand(0));
12394   Opnds.push_back(N->getOperand(1));
12395
12396   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
12397     SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
12398     // BFS traverse all OR'd operands.
12399     if (I->getOpcode() == ISD::OR) {
12400       Opnds.push_back(I->getOperand(0));
12401       Opnds.push_back(I->getOperand(1));
12402       // Re-evaluate the number of nodes to be traversed.
12403       e += 2; // 2 more nodes (LHS and RHS) are pushed.
12404       continue;
12405     }
12406
12407     // Quit if a non-EXTRACT_VECTOR_ELT
12408     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
12409       return SDValue();
12410
12411     // Quit if without a constant index.
12412     SDValue Idx = I->getOperand(1);
12413     if (!isa<ConstantSDNode>(Idx))
12414       return SDValue();
12415
12416     SDValue ExtractedFromVec = I->getOperand(0);
12417     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
12418     if (M == VecInMap.end()) {
12419       VT = ExtractedFromVec.getValueType();
12420       // Quit if not 128/256-bit vector.
12421       if (!VT.is128BitVector() && !VT.is256BitVector())
12422         return SDValue();
12423       // Quit if not the same type.
12424       if (VecInMap.begin() != VecInMap.end() &&
12425           VT != VecInMap.begin()->first.getValueType())
12426         return SDValue();
12427       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
12428       VecIns.push_back(ExtractedFromVec);
12429     }
12430     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
12431   }
12432
12433   assert((VT.is128BitVector() || VT.is256BitVector()) &&
12434          "Not extracted from 128-/256-bit vector.");
12435
12436   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
12437
12438   for (DenseMap<SDValue, unsigned>::const_iterator
12439         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
12440     // Quit if not all elements are used.
12441     if (I->second != FullMask)
12442       return SDValue();
12443   }
12444
12445   EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
12446
12447   // Cast all vectors into TestVT for PTEST.
12448   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
12449     VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
12450
12451   // If more than one full vectors are evaluated, OR them first before PTEST.
12452   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
12453     // Each iteration will OR 2 nodes and append the result until there is only
12454     // 1 node left, i.e. the final OR'd value of all vectors.
12455     SDValue LHS = VecIns[Slot];
12456     SDValue RHS = VecIns[Slot + 1];
12457     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
12458   }
12459
12460   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
12461                      VecIns.back(), VecIns.back());
12462 }
12463
12464 /// \brief return true if \c Op has a use that doesn't just read flags.
12465 static bool hasNonFlagsUse(SDValue Op) {
12466   for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
12467        ++UI) {
12468     SDNode *User = *UI;
12469     unsigned UOpNo = UI.getOperandNo();
12470     if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
12471       // Look pass truncate.
12472       UOpNo = User->use_begin().getOperandNo();
12473       User = *User->use_begin();
12474     }
12475
12476     if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
12477         !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
12478       return true;
12479   }
12480   return false;
12481 }
12482
12483 /// Emit nodes that will be selected as "test Op0,Op0", or something
12484 /// equivalent.
12485 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
12486                                     SelectionDAG &DAG) const {
12487   if (Op.getValueType() == MVT::i1) {
12488     SDValue ExtOp = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i8, Op);
12489     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, ExtOp,
12490                        DAG.getConstant(0, MVT::i8));
12491   }
12492   // CF and OF aren't always set the way we want. Determine which
12493   // of these we need.
12494   bool NeedCF = false;
12495   bool NeedOF = false;
12496   switch (X86CC) {
12497   default: break;
12498   case X86::COND_A: case X86::COND_AE:
12499   case X86::COND_B: case X86::COND_BE:
12500     NeedCF = true;
12501     break;
12502   case X86::COND_G: case X86::COND_GE:
12503   case X86::COND_L: case X86::COND_LE:
12504   case X86::COND_O: case X86::COND_NO: {
12505     // Check if we really need to set the
12506     // Overflow flag. If NoSignedWrap is present
12507     // that is not actually needed.
12508     switch (Op->getOpcode()) {
12509     case ISD::ADD:
12510     case ISD::SUB:
12511     case ISD::MUL:
12512     case ISD::SHL: {
12513       const BinaryWithFlagsSDNode *BinNode =
12514           cast<BinaryWithFlagsSDNode>(Op.getNode());
12515       if (BinNode->hasNoSignedWrap())
12516         break;
12517     }
12518     default:
12519       NeedOF = true;
12520       break;
12521     }
12522     break;
12523   }
12524   }
12525   // See if we can use the EFLAGS value from the operand instead of
12526   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
12527   // we prove that the arithmetic won't overflow, we can't use OF or CF.
12528   if (Op.getResNo() != 0 || NeedOF || NeedCF) {
12529     // Emit a CMP with 0, which is the TEST pattern.
12530     //if (Op.getValueType() == MVT::i1)
12531     //  return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
12532     //                     DAG.getConstant(0, MVT::i1));
12533     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
12534                        DAG.getConstant(0, Op.getValueType()));
12535   }
12536   unsigned Opcode = 0;
12537   unsigned NumOperands = 0;
12538
12539   // Truncate operations may prevent the merge of the SETCC instruction
12540   // and the arithmetic instruction before it. Attempt to truncate the operands
12541   // of the arithmetic instruction and use a reduced bit-width instruction.
12542   bool NeedTruncation = false;
12543   SDValue ArithOp = Op;
12544   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
12545     SDValue Arith = Op->getOperand(0);
12546     // Both the trunc and the arithmetic op need to have one user each.
12547     if (Arith->hasOneUse())
12548       switch (Arith.getOpcode()) {
12549         default: break;
12550         case ISD::ADD:
12551         case ISD::SUB:
12552         case ISD::AND:
12553         case ISD::OR:
12554         case ISD::XOR: {
12555           NeedTruncation = true;
12556           ArithOp = Arith;
12557         }
12558       }
12559   }
12560
12561   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
12562   // which may be the result of a CAST.  We use the variable 'Op', which is the
12563   // non-casted variable when we check for possible users.
12564   switch (ArithOp.getOpcode()) {
12565   case ISD::ADD:
12566     // Due to an isel shortcoming, be conservative if this add is likely to be
12567     // selected as part of a load-modify-store instruction. When the root node
12568     // in a match is a store, isel doesn't know how to remap non-chain non-flag
12569     // uses of other nodes in the match, such as the ADD in this case. This
12570     // leads to the ADD being left around and reselected, with the result being
12571     // two adds in the output.  Alas, even if none our users are stores, that
12572     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
12573     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
12574     // climbing the DAG back to the root, and it doesn't seem to be worth the
12575     // effort.
12576     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
12577          UE = Op.getNode()->use_end(); UI != UE; ++UI)
12578       if (UI->getOpcode() != ISD::CopyToReg &&
12579           UI->getOpcode() != ISD::SETCC &&
12580           UI->getOpcode() != ISD::STORE)
12581         goto default_case;
12582
12583     if (ConstantSDNode *C =
12584         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
12585       // An add of one will be selected as an INC.
12586       if (C->getAPIntValue() == 1 && !Subtarget->slowIncDec()) {
12587         Opcode = X86ISD::INC;
12588         NumOperands = 1;
12589         break;
12590       }
12591
12592       // An add of negative one (subtract of one) will be selected as a DEC.
12593       if (C->getAPIntValue().isAllOnesValue() && !Subtarget->slowIncDec()) {
12594         Opcode = X86ISD::DEC;
12595         NumOperands = 1;
12596         break;
12597       }
12598     }
12599
12600     // Otherwise use a regular EFLAGS-setting add.
12601     Opcode = X86ISD::ADD;
12602     NumOperands = 2;
12603     break;
12604   case ISD::SHL:
12605   case ISD::SRL:
12606     // If we have a constant logical shift that's only used in a comparison
12607     // against zero turn it into an equivalent AND. This allows turning it into
12608     // a TEST instruction later.
12609     if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
12610         isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
12611       EVT VT = Op.getValueType();
12612       unsigned BitWidth = VT.getSizeInBits();
12613       unsigned ShAmt = Op->getConstantOperandVal(1);
12614       if (ShAmt >= BitWidth) // Avoid undefined shifts.
12615         break;
12616       APInt Mask = ArithOp.getOpcode() == ISD::SRL
12617                        ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
12618                        : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
12619       if (!Mask.isSignedIntN(32)) // Avoid large immediates.
12620         break;
12621       SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
12622                                 DAG.getConstant(Mask, VT));
12623       DAG.ReplaceAllUsesWith(Op, New);
12624       Op = New;
12625     }
12626     break;
12627
12628   case ISD::AND:
12629     // If the primary and result isn't used, don't bother using X86ISD::AND,
12630     // because a TEST instruction will be better.
12631     if (!hasNonFlagsUse(Op))
12632       break;
12633     // FALL THROUGH
12634   case ISD::SUB:
12635   case ISD::OR:
12636   case ISD::XOR:
12637     // Due to the ISEL shortcoming noted above, be conservative if this op is
12638     // likely to be selected as part of a load-modify-store instruction.
12639     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
12640            UE = Op.getNode()->use_end(); UI != UE; ++UI)
12641       if (UI->getOpcode() == ISD::STORE)
12642         goto default_case;
12643
12644     // Otherwise use a regular EFLAGS-setting instruction.
12645     switch (ArithOp.getOpcode()) {
12646     default: llvm_unreachable("unexpected operator!");
12647     case ISD::SUB: Opcode = X86ISD::SUB; break;
12648     case ISD::XOR: Opcode = X86ISD::XOR; break;
12649     case ISD::AND: Opcode = X86ISD::AND; break;
12650     case ISD::OR: {
12651       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
12652         SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
12653         if (EFLAGS.getNode())
12654           return EFLAGS;
12655       }
12656       Opcode = X86ISD::OR;
12657       break;
12658     }
12659     }
12660
12661     NumOperands = 2;
12662     break;
12663   case X86ISD::ADD:
12664   case X86ISD::SUB:
12665   case X86ISD::INC:
12666   case X86ISD::DEC:
12667   case X86ISD::OR:
12668   case X86ISD::XOR:
12669   case X86ISD::AND:
12670     return SDValue(Op.getNode(), 1);
12671   default:
12672   default_case:
12673     break;
12674   }
12675
12676   // If we found that truncation is beneficial, perform the truncation and
12677   // update 'Op'.
12678   if (NeedTruncation) {
12679     EVT VT = Op.getValueType();
12680     SDValue WideVal = Op->getOperand(0);
12681     EVT WideVT = WideVal.getValueType();
12682     unsigned ConvertedOp = 0;
12683     // Use a target machine opcode to prevent further DAGCombine
12684     // optimizations that may separate the arithmetic operations
12685     // from the setcc node.
12686     switch (WideVal.getOpcode()) {
12687       default: break;
12688       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
12689       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
12690       case ISD::AND: ConvertedOp = X86ISD::AND; break;
12691       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
12692       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
12693     }
12694
12695     if (ConvertedOp) {
12696       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12697       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
12698         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
12699         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
12700         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
12701       }
12702     }
12703   }
12704
12705   if (Opcode == 0)
12706     // Emit a CMP with 0, which is the TEST pattern.
12707     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
12708                        DAG.getConstant(0, Op.getValueType()));
12709
12710   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
12711   SmallVector<SDValue, 4> Ops(Op->op_begin(), Op->op_begin() + NumOperands);
12712
12713   SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
12714   DAG.ReplaceAllUsesWith(Op, New);
12715   return SDValue(New.getNode(), 1);
12716 }
12717
12718 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
12719 /// equivalent.
12720 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
12721                                    SDLoc dl, SelectionDAG &DAG) const {
12722   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
12723     if (C->getAPIntValue() == 0)
12724       return EmitTest(Op0, X86CC, dl, DAG);
12725
12726      if (Op0.getValueType() == MVT::i1)
12727        llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
12728   }
12729
12730   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
12731        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
12732     // Do the comparison at i32 if it's smaller, besides the Atom case.
12733     // This avoids subregister aliasing issues. Keep the smaller reference
12734     // if we're optimizing for size, however, as that'll allow better folding
12735     // of memory operations.
12736     if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
12737         !DAG.getMachineFunction().getFunction()->hasFnAttribute(
12738             Attribute::MinSize) &&
12739         !Subtarget->isAtom()) {
12740       unsigned ExtendOp =
12741           isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
12742       Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
12743       Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
12744     }
12745     // Use SUB instead of CMP to enable CSE between SUB and CMP.
12746     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
12747     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
12748                               Op0, Op1);
12749     return SDValue(Sub.getNode(), 1);
12750   }
12751   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
12752 }
12753
12754 /// Convert a comparison if required by the subtarget.
12755 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
12756                                                  SelectionDAG &DAG) const {
12757   // If the subtarget does not support the FUCOMI instruction, floating-point
12758   // comparisons have to be converted.
12759   if (Subtarget->hasCMov() ||
12760       Cmp.getOpcode() != X86ISD::CMP ||
12761       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
12762       !Cmp.getOperand(1).getValueType().isFloatingPoint())
12763     return Cmp;
12764
12765   // The instruction selector will select an FUCOM instruction instead of
12766   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
12767   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
12768   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
12769   SDLoc dl(Cmp);
12770   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
12771   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
12772   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
12773                             DAG.getConstant(8, MVT::i8));
12774   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
12775   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
12776 }
12777
12778 /// The minimum architected relative accuracy is 2^-12. We need one
12779 /// Newton-Raphson step to have a good float result (24 bits of precision).
12780 SDValue X86TargetLowering::getRsqrtEstimate(SDValue Op,
12781                                             DAGCombinerInfo &DCI,
12782                                             unsigned &RefinementSteps,
12783                                             bool &UseOneConstNR) const {
12784   // FIXME: We should use instruction latency models to calculate the cost of
12785   // each potential sequence, but this is very hard to do reliably because
12786   // at least Intel's Core* chips have variable timing based on the number of
12787   // significant digits in the divisor and/or sqrt operand.
12788   if (!Subtarget->useSqrtEst())
12789     return SDValue();
12790
12791   EVT VT = Op.getValueType();
12792
12793   // SSE1 has rsqrtss and rsqrtps.
12794   // TODO: Add support for AVX512 (v16f32).
12795   // It is likely not profitable to do this for f64 because a double-precision
12796   // rsqrt estimate with refinement on x86 prior to FMA requires at least 16
12797   // instructions: convert to single, rsqrtss, convert back to double, refine
12798   // (3 steps = at least 13 insts). If an 'rsqrtsd' variant was added to the ISA
12799   // along with FMA, this could be a throughput win.
12800   if ((Subtarget->hasSSE1() && (VT == MVT::f32 || VT == MVT::v4f32)) ||
12801       (Subtarget->hasAVX() && VT == MVT::v8f32)) {
12802     RefinementSteps = 1;
12803     UseOneConstNR = false;
12804     return DCI.DAG.getNode(X86ISD::FRSQRT, SDLoc(Op), VT, Op);
12805   }
12806   return SDValue();
12807 }
12808
12809 /// The minimum architected relative accuracy is 2^-12. We need one
12810 /// Newton-Raphson step to have a good float result (24 bits of precision).
12811 SDValue X86TargetLowering::getRecipEstimate(SDValue Op,
12812                                             DAGCombinerInfo &DCI,
12813                                             unsigned &RefinementSteps) const {
12814   // FIXME: We should use instruction latency models to calculate the cost of
12815   // each potential sequence, but this is very hard to do reliably because
12816   // at least Intel's Core* chips have variable timing based on the number of
12817   // significant digits in the divisor.
12818   if (!Subtarget->useReciprocalEst())
12819     return SDValue();
12820
12821   EVT VT = Op.getValueType();
12822
12823   // SSE1 has rcpss and rcpps. AVX adds a 256-bit variant for rcpps.
12824   // TODO: Add support for AVX512 (v16f32).
12825   // It is likely not profitable to do this for f64 because a double-precision
12826   // reciprocal estimate with refinement on x86 prior to FMA requires
12827   // 15 instructions: convert to single, rcpss, convert back to double, refine
12828   // (3 steps = 12 insts). If an 'rcpsd' variant was added to the ISA
12829   // along with FMA, this could be a throughput win.
12830   if ((Subtarget->hasSSE1() && (VT == MVT::f32 || VT == MVT::v4f32)) ||
12831       (Subtarget->hasAVX() && VT == MVT::v8f32)) {
12832     RefinementSteps = ReciprocalEstimateRefinementSteps;
12833     return DCI.DAG.getNode(X86ISD::FRCP, SDLoc(Op), VT, Op);
12834   }
12835   return SDValue();
12836 }
12837
12838 /// If we have at least two divisions that use the same divisor, convert to
12839 /// multplication by a reciprocal. This may need to be adjusted for a given
12840 /// CPU if a division's cost is not at least twice the cost of a multiplication.
12841 /// This is because we still need one division to calculate the reciprocal and
12842 /// then we need two multiplies by that reciprocal as replacements for the
12843 /// original divisions.
12844 bool X86TargetLowering::combineRepeatedFPDivisors(unsigned NumUsers) const {
12845   return NumUsers > 1;
12846 }
12847
12848 static bool isAllOnes(SDValue V) {
12849   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
12850   return C && C->isAllOnesValue();
12851 }
12852
12853 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
12854 /// if it's possible.
12855 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
12856                                      SDLoc dl, SelectionDAG &DAG) const {
12857   SDValue Op0 = And.getOperand(0);
12858   SDValue Op1 = And.getOperand(1);
12859   if (Op0.getOpcode() == ISD::TRUNCATE)
12860     Op0 = Op0.getOperand(0);
12861   if (Op1.getOpcode() == ISD::TRUNCATE)
12862     Op1 = Op1.getOperand(0);
12863
12864   SDValue LHS, RHS;
12865   if (Op1.getOpcode() == ISD::SHL)
12866     std::swap(Op0, Op1);
12867   if (Op0.getOpcode() == ISD::SHL) {
12868     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
12869       if (And00C->getZExtValue() == 1) {
12870         // If we looked past a truncate, check that it's only truncating away
12871         // known zeros.
12872         unsigned BitWidth = Op0.getValueSizeInBits();
12873         unsigned AndBitWidth = And.getValueSizeInBits();
12874         if (BitWidth > AndBitWidth) {
12875           APInt Zeros, Ones;
12876           DAG.computeKnownBits(Op0, Zeros, Ones);
12877           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
12878             return SDValue();
12879         }
12880         LHS = Op1;
12881         RHS = Op0.getOperand(1);
12882       }
12883   } else if (Op1.getOpcode() == ISD::Constant) {
12884     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
12885     uint64_t AndRHSVal = AndRHS->getZExtValue();
12886     SDValue AndLHS = Op0;
12887
12888     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
12889       LHS = AndLHS.getOperand(0);
12890       RHS = AndLHS.getOperand(1);
12891     }
12892
12893     // Use BT if the immediate can't be encoded in a TEST instruction.
12894     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
12895       LHS = AndLHS;
12896       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
12897     }
12898   }
12899
12900   if (LHS.getNode()) {
12901     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
12902     // instruction.  Since the shift amount is in-range-or-undefined, we know
12903     // that doing a bittest on the i32 value is ok.  We extend to i32 because
12904     // the encoding for the i16 version is larger than the i32 version.
12905     // Also promote i16 to i32 for performance / code size reason.
12906     if (LHS.getValueType() == MVT::i8 ||
12907         LHS.getValueType() == MVT::i16)
12908       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
12909
12910     // If the operand types disagree, extend the shift amount to match.  Since
12911     // BT ignores high bits (like shifts) we can use anyextend.
12912     if (LHS.getValueType() != RHS.getValueType())
12913       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
12914
12915     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
12916     X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
12917     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12918                        DAG.getConstant(Cond, MVT::i8), BT);
12919   }
12920
12921   return SDValue();
12922 }
12923
12924 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
12925 /// mask CMPs.
12926 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
12927                               SDValue &Op1) {
12928   unsigned SSECC;
12929   bool Swap = false;
12930
12931   // SSE Condition code mapping:
12932   //  0 - EQ
12933   //  1 - LT
12934   //  2 - LE
12935   //  3 - UNORD
12936   //  4 - NEQ
12937   //  5 - NLT
12938   //  6 - NLE
12939   //  7 - ORD
12940   switch (SetCCOpcode) {
12941   default: llvm_unreachable("Unexpected SETCC condition");
12942   case ISD::SETOEQ:
12943   case ISD::SETEQ:  SSECC = 0; break;
12944   case ISD::SETOGT:
12945   case ISD::SETGT:  Swap = true; // Fallthrough
12946   case ISD::SETLT:
12947   case ISD::SETOLT: SSECC = 1; break;
12948   case ISD::SETOGE:
12949   case ISD::SETGE:  Swap = true; // Fallthrough
12950   case ISD::SETLE:
12951   case ISD::SETOLE: SSECC = 2; break;
12952   case ISD::SETUO:  SSECC = 3; break;
12953   case ISD::SETUNE:
12954   case ISD::SETNE:  SSECC = 4; break;
12955   case ISD::SETULE: Swap = true; // Fallthrough
12956   case ISD::SETUGE: SSECC = 5; break;
12957   case ISD::SETULT: Swap = true; // Fallthrough
12958   case ISD::SETUGT: SSECC = 6; break;
12959   case ISD::SETO:   SSECC = 7; break;
12960   case ISD::SETUEQ:
12961   case ISD::SETONE: SSECC = 8; break;
12962   }
12963   if (Swap)
12964     std::swap(Op0, Op1);
12965
12966   return SSECC;
12967 }
12968
12969 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
12970 // ones, and then concatenate the result back.
12971 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
12972   MVT VT = Op.getSimpleValueType();
12973
12974   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
12975          "Unsupported value type for operation");
12976
12977   unsigned NumElems = VT.getVectorNumElements();
12978   SDLoc dl(Op);
12979   SDValue CC = Op.getOperand(2);
12980
12981   // Extract the LHS vectors
12982   SDValue LHS = Op.getOperand(0);
12983   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
12984   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
12985
12986   // Extract the RHS vectors
12987   SDValue RHS = Op.getOperand(1);
12988   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
12989   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
12990
12991   // Issue the operation on the smaller types and concatenate the result back
12992   MVT EltVT = VT.getVectorElementType();
12993   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
12994   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
12995                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
12996                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
12997 }
12998
12999 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
13000                                      const X86Subtarget *Subtarget) {
13001   SDValue Op0 = Op.getOperand(0);
13002   SDValue Op1 = Op.getOperand(1);
13003   SDValue CC = Op.getOperand(2);
13004   MVT VT = Op.getSimpleValueType();
13005   SDLoc dl(Op);
13006
13007   assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 8 &&
13008          Op.getValueType().getScalarType() == MVT::i1 &&
13009          "Cannot set masked compare for this operation");
13010
13011   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13012   unsigned  Opc = 0;
13013   bool Unsigned = false;
13014   bool Swap = false;
13015   unsigned SSECC;
13016   switch (SetCCOpcode) {
13017   default: llvm_unreachable("Unexpected SETCC condition");
13018   case ISD::SETNE:  SSECC = 4; break;
13019   case ISD::SETEQ:  Opc = X86ISD::PCMPEQM; break;
13020   case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
13021   case ISD::SETLT:  Swap = true; //fall-through
13022   case ISD::SETGT:  Opc = X86ISD::PCMPGTM; break;
13023   case ISD::SETULT: SSECC = 1; Unsigned = true; break;
13024   case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
13025   case ISD::SETGE:  Swap = true; SSECC = 2; break; // LE + swap
13026   case ISD::SETULE: Unsigned = true; //fall-through
13027   case ISD::SETLE:  SSECC = 2; break;
13028   }
13029
13030   if (Swap)
13031     std::swap(Op0, Op1);
13032   if (Opc)
13033     return DAG.getNode(Opc, dl, VT, Op0, Op1);
13034   Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
13035   return DAG.getNode(Opc, dl, VT, Op0, Op1,
13036                      DAG.getConstant(SSECC, MVT::i8));
13037 }
13038
13039 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
13040 /// operand \p Op1.  If non-trivial (for example because it's not constant)
13041 /// return an empty value.
13042 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
13043 {
13044   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
13045   if (!BV)
13046     return SDValue();
13047
13048   MVT VT = Op1.getSimpleValueType();
13049   MVT EVT = VT.getVectorElementType();
13050   unsigned n = VT.getVectorNumElements();
13051   SmallVector<SDValue, 8> ULTOp1;
13052
13053   for (unsigned i = 0; i < n; ++i) {
13054     ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
13055     if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
13056       return SDValue();
13057
13058     // Avoid underflow.
13059     APInt Val = Elt->getAPIntValue();
13060     if (Val == 0)
13061       return SDValue();
13062
13063     ULTOp1.push_back(DAG.getConstant(Val - 1, EVT));
13064   }
13065
13066   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
13067 }
13068
13069 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
13070                            SelectionDAG &DAG) {
13071   SDValue Op0 = Op.getOperand(0);
13072   SDValue Op1 = Op.getOperand(1);
13073   SDValue CC = Op.getOperand(2);
13074   MVT VT = Op.getSimpleValueType();
13075   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13076   bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
13077   SDLoc dl(Op);
13078
13079   if (isFP) {
13080 #ifndef NDEBUG
13081     MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
13082     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
13083 #endif
13084
13085     unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
13086     unsigned Opc = X86ISD::CMPP;
13087     if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
13088       assert(VT.getVectorNumElements() <= 16);
13089       Opc = X86ISD::CMPM;
13090     }
13091     // In the two special cases we can't handle, emit two comparisons.
13092     if (SSECC == 8) {
13093       unsigned CC0, CC1;
13094       unsigned CombineOpc;
13095       if (SetCCOpcode == ISD::SETUEQ) {
13096         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
13097       } else {
13098         assert(SetCCOpcode == ISD::SETONE);
13099         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
13100       }
13101
13102       SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
13103                                  DAG.getConstant(CC0, MVT::i8));
13104       SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
13105                                  DAG.getConstant(CC1, MVT::i8));
13106       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
13107     }
13108     // Handle all other FP comparisons here.
13109     return DAG.getNode(Opc, dl, VT, Op0, Op1,
13110                        DAG.getConstant(SSECC, MVT::i8));
13111   }
13112
13113   // Break 256-bit integer vector compare into smaller ones.
13114   if (VT.is256BitVector() && !Subtarget->hasInt256())
13115     return Lower256IntVSETCC(Op, DAG);
13116
13117   bool MaskResult = (VT.getVectorElementType() == MVT::i1);
13118   EVT OpVT = Op1.getValueType();
13119   if (Subtarget->hasAVX512()) {
13120     if (Op1.getValueType().is512BitVector() ||
13121         (Subtarget->hasBWI() && Subtarget->hasVLX()) ||
13122         (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
13123       return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
13124
13125     // In AVX-512 architecture setcc returns mask with i1 elements,
13126     // But there is no compare instruction for i8 and i16 elements in KNL.
13127     // We are not talking about 512-bit operands in this case, these
13128     // types are illegal.
13129     if (MaskResult &&
13130         (OpVT.getVectorElementType().getSizeInBits() < 32 &&
13131          OpVT.getVectorElementType().getSizeInBits() >= 8))
13132       return DAG.getNode(ISD::TRUNCATE, dl, VT,
13133                          DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
13134   }
13135
13136   // We are handling one of the integer comparisons here.  Since SSE only has
13137   // GT and EQ comparisons for integer, swapping operands and multiple
13138   // operations may be required for some comparisons.
13139   unsigned Opc;
13140   bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
13141   bool Subus = false;
13142
13143   switch (SetCCOpcode) {
13144   default: llvm_unreachable("Unexpected SETCC condition");
13145   case ISD::SETNE:  Invert = true;
13146   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
13147   case ISD::SETLT:  Swap = true;
13148   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
13149   case ISD::SETGE:  Swap = true;
13150   case ISD::SETLE:  Opc = X86ISD::PCMPGT;
13151                     Invert = true; break;
13152   case ISD::SETULT: Swap = true;
13153   case ISD::SETUGT: Opc = X86ISD::PCMPGT;
13154                     FlipSigns = true; break;
13155   case ISD::SETUGE: Swap = true;
13156   case ISD::SETULE: Opc = X86ISD::PCMPGT;
13157                     FlipSigns = true; Invert = true; break;
13158   }
13159
13160   // Special case: Use min/max operations for SETULE/SETUGE
13161   MVT VET = VT.getVectorElementType();
13162   bool hasMinMax =
13163        (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
13164     || (Subtarget->hasSSE2()  && (VET == MVT::i8));
13165
13166   if (hasMinMax) {
13167     switch (SetCCOpcode) {
13168     default: break;
13169     case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
13170     case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
13171     }
13172
13173     if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
13174   }
13175
13176   bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
13177   if (!MinMax && hasSubus) {
13178     // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
13179     // Op0 u<= Op1:
13180     //   t = psubus Op0, Op1
13181     //   pcmpeq t, <0..0>
13182     switch (SetCCOpcode) {
13183     default: break;
13184     case ISD::SETULT: {
13185       // If the comparison is against a constant we can turn this into a
13186       // setule.  With psubus, setule does not require a swap.  This is
13187       // beneficial because the constant in the register is no longer
13188       // destructed as the destination so it can be hoisted out of a loop.
13189       // Only do this pre-AVX since vpcmp* is no longer destructive.
13190       if (Subtarget->hasAVX())
13191         break;
13192       SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
13193       if (ULEOp1.getNode()) {
13194         Op1 = ULEOp1;
13195         Subus = true; Invert = false; Swap = false;
13196       }
13197       break;
13198     }
13199     // Psubus is better than flip-sign because it requires no inversion.
13200     case ISD::SETUGE: Subus = true; Invert = false; Swap = true;  break;
13201     case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
13202     }
13203
13204     if (Subus) {
13205       Opc = X86ISD::SUBUS;
13206       FlipSigns = false;
13207     }
13208   }
13209
13210   if (Swap)
13211     std::swap(Op0, Op1);
13212
13213   // Check that the operation in question is available (most are plain SSE2,
13214   // but PCMPGTQ and PCMPEQQ have different requirements).
13215   if (VT == MVT::v2i64) {
13216     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
13217       assert(Subtarget->hasSSE2() && "Don't know how to lower!");
13218
13219       // First cast everything to the right type.
13220       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
13221       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
13222
13223       // Since SSE has no unsigned integer comparisons, we need to flip the sign
13224       // bits of the inputs before performing those operations. The lower
13225       // compare is always unsigned.
13226       SDValue SB;
13227       if (FlipSigns) {
13228         SB = DAG.getConstant(0x80000000U, MVT::v4i32);
13229       } else {
13230         SDValue Sign = DAG.getConstant(0x80000000U, MVT::i32);
13231         SDValue Zero = DAG.getConstant(0x00000000U, MVT::i32);
13232         SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
13233                          Sign, Zero, Sign, Zero);
13234       }
13235       Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
13236       Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
13237
13238       // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
13239       SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
13240       SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
13241
13242       // Create masks for only the low parts/high parts of the 64 bit integers.
13243       static const int MaskHi[] = { 1, 1, 3, 3 };
13244       static const int MaskLo[] = { 0, 0, 2, 2 };
13245       SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
13246       SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
13247       SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
13248
13249       SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
13250       Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
13251
13252       if (Invert)
13253         Result = DAG.getNOT(dl, Result, MVT::v4i32);
13254
13255       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
13256     }
13257
13258     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
13259       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
13260       // pcmpeqd + pshufd + pand.
13261       assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
13262
13263       // First cast everything to the right type.
13264       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
13265       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
13266
13267       // Do the compare.
13268       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
13269
13270       // Make sure the lower and upper halves are both all-ones.
13271       static const int Mask[] = { 1, 0, 3, 2 };
13272       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
13273       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
13274
13275       if (Invert)
13276         Result = DAG.getNOT(dl, Result, MVT::v4i32);
13277
13278       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
13279     }
13280   }
13281
13282   // Since SSE has no unsigned integer comparisons, we need to flip the sign
13283   // bits of the inputs before performing those operations.
13284   if (FlipSigns) {
13285     EVT EltVT = VT.getVectorElementType();
13286     SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), VT);
13287     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
13288     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
13289   }
13290
13291   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
13292
13293   // If the logical-not of the result is required, perform that now.
13294   if (Invert)
13295     Result = DAG.getNOT(dl, Result, VT);
13296
13297   if (MinMax)
13298     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
13299
13300   if (Subus)
13301     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
13302                          getZeroVector(VT, Subtarget, DAG, dl));
13303
13304   return Result;
13305 }
13306
13307 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
13308
13309   MVT VT = Op.getSimpleValueType();
13310
13311   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
13312
13313   assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
13314          && "SetCC type must be 8-bit or 1-bit integer");
13315   SDValue Op0 = Op.getOperand(0);
13316   SDValue Op1 = Op.getOperand(1);
13317   SDLoc dl(Op);
13318   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
13319
13320   // Optimize to BT if possible.
13321   // Lower (X & (1 << N)) == 0 to BT(X, N).
13322   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
13323   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
13324   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
13325       Op1.getOpcode() == ISD::Constant &&
13326       cast<ConstantSDNode>(Op1)->isNullValue() &&
13327       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13328     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
13329     if (NewSetCC.getNode()) {
13330       if (VT == MVT::i1)
13331         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewSetCC);
13332       return NewSetCC;
13333     }
13334   }
13335
13336   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
13337   // these.
13338   if (Op1.getOpcode() == ISD::Constant &&
13339       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
13340        cast<ConstantSDNode>(Op1)->isNullValue()) &&
13341       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13342
13343     // If the input is a setcc, then reuse the input setcc or use a new one with
13344     // the inverted condition.
13345     if (Op0.getOpcode() == X86ISD::SETCC) {
13346       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
13347       bool Invert = (CC == ISD::SETNE) ^
13348         cast<ConstantSDNode>(Op1)->isNullValue();
13349       if (!Invert)
13350         return Op0;
13351
13352       CCode = X86::GetOppositeBranchCondition(CCode);
13353       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13354                                   DAG.getConstant(CCode, MVT::i8),
13355                                   Op0.getOperand(1));
13356       if (VT == MVT::i1)
13357         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
13358       return SetCC;
13359     }
13360   }
13361   if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
13362       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
13363       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13364
13365     ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
13366     return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, MVT::i1), NewCC);
13367   }
13368
13369   bool isFP = Op1.getSimpleValueType().isFloatingPoint();
13370   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
13371   if (X86CC == X86::COND_INVALID)
13372     return SDValue();
13373
13374   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
13375   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
13376   SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13377                               DAG.getConstant(X86CC, MVT::i8), EFLAGS);
13378   if (VT == MVT::i1)
13379     return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
13380   return SetCC;
13381 }
13382
13383 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
13384 static bool isX86LogicalCmp(SDValue Op) {
13385   unsigned Opc = Op.getNode()->getOpcode();
13386   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
13387       Opc == X86ISD::SAHF)
13388     return true;
13389   if (Op.getResNo() == 1 &&
13390       (Opc == X86ISD::ADD ||
13391        Opc == X86ISD::SUB ||
13392        Opc == X86ISD::ADC ||
13393        Opc == X86ISD::SBB ||
13394        Opc == X86ISD::SMUL ||
13395        Opc == X86ISD::UMUL ||
13396        Opc == X86ISD::INC ||
13397        Opc == X86ISD::DEC ||
13398        Opc == X86ISD::OR ||
13399        Opc == X86ISD::XOR ||
13400        Opc == X86ISD::AND))
13401     return true;
13402
13403   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
13404     return true;
13405
13406   return false;
13407 }
13408
13409 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
13410   if (V.getOpcode() != ISD::TRUNCATE)
13411     return false;
13412
13413   SDValue VOp0 = V.getOperand(0);
13414   unsigned InBits = VOp0.getValueSizeInBits();
13415   unsigned Bits = V.getValueSizeInBits();
13416   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
13417 }
13418
13419 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
13420   bool addTest = true;
13421   SDValue Cond  = Op.getOperand(0);
13422   SDValue Op1 = Op.getOperand(1);
13423   SDValue Op2 = Op.getOperand(2);
13424   SDLoc DL(Op);
13425   EVT VT = Op1.getValueType();
13426   SDValue CC;
13427
13428   // Lower FP selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
13429   // are available or VBLENDV if AVX is available.
13430   // Otherwise FP cmovs get lowered into a less efficient branch sequence later.
13431   if (Cond.getOpcode() == ISD::SETCC &&
13432       ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
13433        (Subtarget->hasSSE1() && VT == MVT::f32)) &&
13434       VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
13435     SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
13436     int SSECC = translateX86FSETCC(
13437         cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
13438
13439     if (SSECC != 8) {
13440       if (Subtarget->hasAVX512()) {
13441         SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
13442                                   DAG.getConstant(SSECC, MVT::i8));
13443         return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
13444       }
13445
13446       SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
13447                                 DAG.getConstant(SSECC, MVT::i8));
13448
13449       // If we have AVX, we can use a variable vector select (VBLENDV) instead
13450       // of 3 logic instructions for size savings and potentially speed.
13451       // Unfortunately, there is no scalar form of VBLENDV.
13452
13453       // If either operand is a constant, don't try this. We can expect to
13454       // optimize away at least one of the logic instructions later in that
13455       // case, so that sequence would be faster than a variable blend.
13456
13457       // BLENDV was introduced with SSE 4.1, but the 2 register form implicitly
13458       // uses XMM0 as the selection register. That may need just as many
13459       // instructions as the AND/ANDN/OR sequence due to register moves, so
13460       // don't bother.
13461
13462       if (Subtarget->hasAVX() &&
13463           !isa<ConstantFPSDNode>(Op1) && !isa<ConstantFPSDNode>(Op2)) {
13464
13465         // Convert to vectors, do a VSELECT, and convert back to scalar.
13466         // All of the conversions should be optimized away.
13467
13468         EVT VecVT = VT == MVT::f32 ? MVT::v4f32 : MVT::v2f64;
13469         SDValue VOp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op1);
13470         SDValue VOp2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op2);
13471         SDValue VCmp = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Cmp);
13472
13473         EVT VCmpVT = VT == MVT::f32 ? MVT::v4i32 : MVT::v2i64;
13474         VCmp = DAG.getNode(ISD::BITCAST, DL, VCmpVT, VCmp);
13475
13476         SDValue VSel = DAG.getNode(ISD::VSELECT, DL, VecVT, VCmp, VOp1, VOp2);
13477
13478         return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
13479                            VSel, DAG.getIntPtrConstant(0));
13480       }
13481       SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
13482       SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
13483       return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
13484     }
13485   }
13486
13487   if (Cond.getOpcode() == ISD::SETCC) {
13488     SDValue NewCond = LowerSETCC(Cond, DAG);
13489     if (NewCond.getNode())
13490       Cond = NewCond;
13491   }
13492
13493   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
13494   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
13495   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
13496   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
13497   if (Cond.getOpcode() == X86ISD::SETCC &&
13498       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
13499       isZero(Cond.getOperand(1).getOperand(1))) {
13500     SDValue Cmp = Cond.getOperand(1);
13501
13502     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
13503
13504     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
13505         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
13506       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
13507
13508       SDValue CmpOp0 = Cmp.getOperand(0);
13509       // Apply further optimizations for special cases
13510       // (select (x != 0), -1, 0) -> neg & sbb
13511       // (select (x == 0), 0, -1) -> neg & sbb
13512       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
13513         if (YC->isNullValue() &&
13514             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
13515           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
13516           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
13517                                     DAG.getConstant(0, CmpOp0.getValueType()),
13518                                     CmpOp0);
13519           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
13520                                     DAG.getConstant(X86::COND_B, MVT::i8),
13521                                     SDValue(Neg.getNode(), 1));
13522           return Res;
13523         }
13524
13525       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
13526                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
13527       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
13528
13529       SDValue Res =   // Res = 0 or -1.
13530         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
13531                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
13532
13533       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
13534         Res = DAG.getNOT(DL, Res, Res.getValueType());
13535
13536       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
13537       if (!N2C || !N2C->isNullValue())
13538         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
13539       return Res;
13540     }
13541   }
13542
13543   // Look past (and (setcc_carry (cmp ...)), 1).
13544   if (Cond.getOpcode() == ISD::AND &&
13545       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
13546     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
13547     if (C && C->getAPIntValue() == 1)
13548       Cond = Cond.getOperand(0);
13549   }
13550
13551   // If condition flag is set by a X86ISD::CMP, then use it as the condition
13552   // setting operand in place of the X86ISD::SETCC.
13553   unsigned CondOpcode = Cond.getOpcode();
13554   if (CondOpcode == X86ISD::SETCC ||
13555       CondOpcode == X86ISD::SETCC_CARRY) {
13556     CC = Cond.getOperand(0);
13557
13558     SDValue Cmp = Cond.getOperand(1);
13559     unsigned Opc = Cmp.getOpcode();
13560     MVT VT = Op.getSimpleValueType();
13561
13562     bool IllegalFPCMov = false;
13563     if (VT.isFloatingPoint() && !VT.isVector() &&
13564         !isScalarFPTypeInSSEReg(VT))  // FPStack?
13565       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
13566
13567     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
13568         Opc == X86ISD::BT) { // FIXME
13569       Cond = Cmp;
13570       addTest = false;
13571     }
13572   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
13573              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
13574              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
13575               Cond.getOperand(0).getValueType() != MVT::i8)) {
13576     SDValue LHS = Cond.getOperand(0);
13577     SDValue RHS = Cond.getOperand(1);
13578     unsigned X86Opcode;
13579     unsigned X86Cond;
13580     SDVTList VTs;
13581     switch (CondOpcode) {
13582     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
13583     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
13584     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
13585     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
13586     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
13587     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
13588     default: llvm_unreachable("unexpected overflowing operator");
13589     }
13590     if (CondOpcode == ISD::UMULO)
13591       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
13592                           MVT::i32);
13593     else
13594       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
13595
13596     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
13597
13598     if (CondOpcode == ISD::UMULO)
13599       Cond = X86Op.getValue(2);
13600     else
13601       Cond = X86Op.getValue(1);
13602
13603     CC = DAG.getConstant(X86Cond, MVT::i8);
13604     addTest = false;
13605   }
13606
13607   if (addTest) {
13608     // Look pass the truncate if the high bits are known zero.
13609     if (isTruncWithZeroHighBitsInput(Cond, DAG))
13610         Cond = Cond.getOperand(0);
13611
13612     // We know the result of AND is compared against zero. Try to match
13613     // it to BT.
13614     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
13615       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
13616       if (NewSetCC.getNode()) {
13617         CC = NewSetCC.getOperand(0);
13618         Cond = NewSetCC.getOperand(1);
13619         addTest = false;
13620       }
13621     }
13622   }
13623
13624   if (addTest) {
13625     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
13626     Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
13627   }
13628
13629   // a <  b ? -1 :  0 -> RES = ~setcc_carry
13630   // a <  b ?  0 : -1 -> RES = setcc_carry
13631   // a >= b ? -1 :  0 -> RES = setcc_carry
13632   // a >= b ?  0 : -1 -> RES = ~setcc_carry
13633   if (Cond.getOpcode() == X86ISD::SUB) {
13634     Cond = ConvertCmpIfNecessary(Cond, DAG);
13635     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
13636
13637     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
13638         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
13639       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
13640                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
13641       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
13642         return DAG.getNOT(DL, Res, Res.getValueType());
13643       return Res;
13644     }
13645   }
13646
13647   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
13648   // widen the cmov and push the truncate through. This avoids introducing a new
13649   // branch during isel and doesn't add any extensions.
13650   if (Op.getValueType() == MVT::i8 &&
13651       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
13652     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
13653     if (T1.getValueType() == T2.getValueType() &&
13654         // Blacklist CopyFromReg to avoid partial register stalls.
13655         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
13656       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
13657       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
13658       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
13659     }
13660   }
13661
13662   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
13663   // condition is true.
13664   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
13665   SDValue Ops[] = { Op2, Op1, CC, Cond };
13666   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
13667 }
13668
13669 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op, const X86Subtarget *Subtarget,
13670                                        SelectionDAG &DAG) {
13671   MVT VT = Op->getSimpleValueType(0);
13672   SDValue In = Op->getOperand(0);
13673   MVT InVT = In.getSimpleValueType();
13674   MVT VTElt = VT.getVectorElementType();
13675   MVT InVTElt = InVT.getVectorElementType();
13676   SDLoc dl(Op);
13677
13678   // SKX processor
13679   if ((InVTElt == MVT::i1) &&
13680       (((Subtarget->hasBWI() && Subtarget->hasVLX() &&
13681         VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() <= 16)) ||
13682
13683        ((Subtarget->hasBWI() && VT.is512BitVector() &&
13684         VTElt.getSizeInBits() <= 16)) ||
13685
13686        ((Subtarget->hasDQI() && Subtarget->hasVLX() &&
13687         VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() >= 32)) ||
13688
13689        ((Subtarget->hasDQI() && VT.is512BitVector() &&
13690         VTElt.getSizeInBits() >= 32))))
13691     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
13692
13693   unsigned int NumElts = VT.getVectorNumElements();
13694
13695   if (NumElts != 8 && NumElts != 16)
13696     return SDValue();
13697
13698   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1) {
13699     if (In.getOpcode() == X86ISD::VSEXT || In.getOpcode() == X86ISD::VZEXT)
13700       return DAG.getNode(In.getOpcode(), dl, VT, In.getOperand(0));
13701     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
13702   }
13703
13704   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13705   assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
13706
13707   MVT ExtVT = (NumElts == 8) ? MVT::v8i64 : MVT::v16i32;
13708   Constant *C = ConstantInt::get(*DAG.getContext(),
13709     APInt::getAllOnesValue(ExtVT.getScalarType().getSizeInBits()));
13710
13711   SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
13712   unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
13713   SDValue Ld = DAG.getLoad(ExtVT.getScalarType(), dl, DAG.getEntryNode(), CP,
13714                           MachinePointerInfo::getConstantPool(),
13715                           false, false, false, Alignment);
13716   SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, dl, ExtVT, In, Ld);
13717   if (VT.is512BitVector())
13718     return Brcst;
13719   return DAG.getNode(X86ISD::VTRUNC, dl, VT, Brcst);
13720 }
13721
13722 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
13723                                 SelectionDAG &DAG) {
13724   MVT VT = Op->getSimpleValueType(0);
13725   SDValue In = Op->getOperand(0);
13726   MVT InVT = In.getSimpleValueType();
13727   SDLoc dl(Op);
13728
13729   if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
13730     return LowerSIGN_EXTEND_AVX512(Op, Subtarget, DAG);
13731
13732   if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
13733       (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
13734       (VT != MVT::v16i16 || InVT != MVT::v16i8))
13735     return SDValue();
13736
13737   if (Subtarget->hasInt256())
13738     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
13739
13740   // Optimize vectors in AVX mode
13741   // Sign extend  v8i16 to v8i32 and
13742   //              v4i32 to v4i64
13743   //
13744   // Divide input vector into two parts
13745   // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
13746   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
13747   // concat the vectors to original VT
13748
13749   unsigned NumElems = InVT.getVectorNumElements();
13750   SDValue Undef = DAG.getUNDEF(InVT);
13751
13752   SmallVector<int,8> ShufMask1(NumElems, -1);
13753   for (unsigned i = 0; i != NumElems/2; ++i)
13754     ShufMask1[i] = i;
13755
13756   SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
13757
13758   SmallVector<int,8> ShufMask2(NumElems, -1);
13759   for (unsigned i = 0; i != NumElems/2; ++i)
13760     ShufMask2[i] = i + NumElems/2;
13761
13762   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
13763
13764   MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
13765                                 VT.getVectorNumElements()/2);
13766
13767   OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
13768   OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
13769
13770   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
13771 }
13772
13773 // Lower vector extended loads using a shuffle. If SSSE3 is not available we
13774 // may emit an illegal shuffle but the expansion is still better than scalar
13775 // code. We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise
13776 // we'll emit a shuffle and a arithmetic shift.
13777 // FIXME: Is the expansion actually better than scalar code? It doesn't seem so.
13778 // TODO: It is possible to support ZExt by zeroing the undef values during
13779 // the shuffle phase or after the shuffle.
13780 static SDValue LowerExtendedLoad(SDValue Op, const X86Subtarget *Subtarget,
13781                                  SelectionDAG &DAG) {
13782   MVT RegVT = Op.getSimpleValueType();
13783   assert(RegVT.isVector() && "We only custom lower vector sext loads.");
13784   assert(RegVT.isInteger() &&
13785          "We only custom lower integer vector sext loads.");
13786
13787   // Nothing useful we can do without SSE2 shuffles.
13788   assert(Subtarget->hasSSE2() && "We only custom lower sext loads with SSE2.");
13789
13790   LoadSDNode *Ld = cast<LoadSDNode>(Op.getNode());
13791   SDLoc dl(Ld);
13792   EVT MemVT = Ld->getMemoryVT();
13793   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13794   unsigned RegSz = RegVT.getSizeInBits();
13795
13796   ISD::LoadExtType Ext = Ld->getExtensionType();
13797
13798   assert((Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)
13799          && "Only anyext and sext are currently implemented.");
13800   assert(MemVT != RegVT && "Cannot extend to the same type");
13801   assert(MemVT.isVector() && "Must load a vector from memory");
13802
13803   unsigned NumElems = RegVT.getVectorNumElements();
13804   unsigned MemSz = MemVT.getSizeInBits();
13805   assert(RegSz > MemSz && "Register size must be greater than the mem size");
13806
13807   if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256()) {
13808     // The only way in which we have a legal 256-bit vector result but not the
13809     // integer 256-bit operations needed to directly lower a sextload is if we
13810     // have AVX1 but not AVX2. In that case, we can always emit a sextload to
13811     // a 128-bit vector and a normal sign_extend to 256-bits that should get
13812     // correctly legalized. We do this late to allow the canonical form of
13813     // sextload to persist throughout the rest of the DAG combiner -- it wants
13814     // to fold together any extensions it can, and so will fuse a sign_extend
13815     // of an sextload into a sextload targeting a wider value.
13816     SDValue Load;
13817     if (MemSz == 128) {
13818       // Just switch this to a normal load.
13819       assert(TLI.isTypeLegal(MemVT) && "If the memory type is a 128-bit type, "
13820                                        "it must be a legal 128-bit vector "
13821                                        "type!");
13822       Load = DAG.getLoad(MemVT, dl, Ld->getChain(), Ld->getBasePtr(),
13823                   Ld->getPointerInfo(), Ld->isVolatile(), Ld->isNonTemporal(),
13824                   Ld->isInvariant(), Ld->getAlignment());
13825     } else {
13826       assert(MemSz < 128 &&
13827              "Can't extend a type wider than 128 bits to a 256 bit vector!");
13828       // Do an sext load to a 128-bit vector type. We want to use the same
13829       // number of elements, but elements half as wide. This will end up being
13830       // recursively lowered by this routine, but will succeed as we definitely
13831       // have all the necessary features if we're using AVX1.
13832       EVT HalfEltVT =
13833           EVT::getIntegerVT(*DAG.getContext(), RegVT.getScalarSizeInBits() / 2);
13834       EVT HalfVecVT = EVT::getVectorVT(*DAG.getContext(), HalfEltVT, NumElems);
13835       Load =
13836           DAG.getExtLoad(Ext, dl, HalfVecVT, Ld->getChain(), Ld->getBasePtr(),
13837                          Ld->getPointerInfo(), MemVT, Ld->isVolatile(),
13838                          Ld->isNonTemporal(), Ld->isInvariant(),
13839                          Ld->getAlignment());
13840     }
13841
13842     // Replace chain users with the new chain.
13843     assert(Load->getNumValues() == 2 && "Loads must carry a chain!");
13844     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Load.getValue(1));
13845
13846     // Finally, do a normal sign-extend to the desired register.
13847     return DAG.getSExtOrTrunc(Load, dl, RegVT);
13848   }
13849
13850   // All sizes must be a power of two.
13851   assert(isPowerOf2_32(RegSz * MemSz * NumElems) &&
13852          "Non-power-of-two elements are not custom lowered!");
13853
13854   // Attempt to load the original value using scalar loads.
13855   // Find the largest scalar type that divides the total loaded size.
13856   MVT SclrLoadTy = MVT::i8;
13857   for (MVT Tp : MVT::integer_valuetypes()) {
13858     if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
13859       SclrLoadTy = Tp;
13860     }
13861   }
13862
13863   // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
13864   if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
13865       (64 <= MemSz))
13866     SclrLoadTy = MVT::f64;
13867
13868   // Calculate the number of scalar loads that we need to perform
13869   // in order to load our vector from memory.
13870   unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
13871
13872   assert((Ext != ISD::SEXTLOAD || NumLoads == 1) &&
13873          "Can only lower sext loads with a single scalar load!");
13874
13875   unsigned loadRegZize = RegSz;
13876   if (Ext == ISD::SEXTLOAD && RegSz == 256)
13877     loadRegZize /= 2;
13878
13879   // Represent our vector as a sequence of elements which are the
13880   // largest scalar that we can load.
13881   EVT LoadUnitVecVT = EVT::getVectorVT(
13882       *DAG.getContext(), SclrLoadTy, loadRegZize / SclrLoadTy.getSizeInBits());
13883
13884   // Represent the data using the same element type that is stored in
13885   // memory. In practice, we ''widen'' MemVT.
13886   EVT WideVecVT =
13887       EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
13888                        loadRegZize / MemVT.getScalarType().getSizeInBits());
13889
13890   assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
13891          "Invalid vector type");
13892
13893   // We can't shuffle using an illegal type.
13894   assert(TLI.isTypeLegal(WideVecVT) &&
13895          "We only lower types that form legal widened vector types");
13896
13897   SmallVector<SDValue, 8> Chains;
13898   SDValue Ptr = Ld->getBasePtr();
13899   SDValue Increment =
13900       DAG.getConstant(SclrLoadTy.getSizeInBits() / 8, TLI.getPointerTy());
13901   SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
13902
13903   for (unsigned i = 0; i < NumLoads; ++i) {
13904     // Perform a single load.
13905     SDValue ScalarLoad =
13906         DAG.getLoad(SclrLoadTy, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
13907                     Ld->isVolatile(), Ld->isNonTemporal(), Ld->isInvariant(),
13908                     Ld->getAlignment());
13909     Chains.push_back(ScalarLoad.getValue(1));
13910     // Create the first element type using SCALAR_TO_VECTOR in order to avoid
13911     // another round of DAGCombining.
13912     if (i == 0)
13913       Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
13914     else
13915       Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
13916                         ScalarLoad, DAG.getIntPtrConstant(i));
13917
13918     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
13919   }
13920
13921   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
13922
13923   // Bitcast the loaded value to a vector of the original element type, in
13924   // the size of the target vector type.
13925   SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
13926   unsigned SizeRatio = RegSz / MemSz;
13927
13928   if (Ext == ISD::SEXTLOAD) {
13929     // If we have SSE4.1, we can directly emit a VSEXT node.
13930     if (Subtarget->hasSSE41()) {
13931       SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
13932       DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
13933       return Sext;
13934     }
13935
13936     // Otherwise we'll shuffle the small elements in the high bits of the
13937     // larger type and perform an arithmetic shift. If the shift is not legal
13938     // it's better to scalarize.
13939     assert(TLI.isOperationLegalOrCustom(ISD::SRA, RegVT) &&
13940            "We can't implement a sext load without an arithmetic right shift!");
13941
13942     // Redistribute the loaded elements into the different locations.
13943     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
13944     for (unsigned i = 0; i != NumElems; ++i)
13945       ShuffleVec[i * SizeRatio + SizeRatio - 1] = i;
13946
13947     SDValue Shuff = DAG.getVectorShuffle(
13948         WideVecVT, dl, SlicedVec, DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
13949
13950     Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
13951
13952     // Build the arithmetic shift.
13953     unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
13954                    MemVT.getVectorElementType().getSizeInBits();
13955     Shuff =
13956         DAG.getNode(ISD::SRA, dl, RegVT, Shuff, DAG.getConstant(Amt, RegVT));
13957
13958     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
13959     return Shuff;
13960   }
13961
13962   // Redistribute the loaded elements into the different locations.
13963   SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
13964   for (unsigned i = 0; i != NumElems; ++i)
13965     ShuffleVec[i * SizeRatio] = i;
13966
13967   SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
13968                                        DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
13969
13970   // Bitcast to the requested type.
13971   Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
13972   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
13973   return Shuff;
13974 }
13975
13976 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
13977 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
13978 // from the AND / OR.
13979 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
13980   Opc = Op.getOpcode();
13981   if (Opc != ISD::OR && Opc != ISD::AND)
13982     return false;
13983   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
13984           Op.getOperand(0).hasOneUse() &&
13985           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
13986           Op.getOperand(1).hasOneUse());
13987 }
13988
13989 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
13990 // 1 and that the SETCC node has a single use.
13991 static bool isXor1OfSetCC(SDValue Op) {
13992   if (Op.getOpcode() != ISD::XOR)
13993     return false;
13994   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
13995   if (N1C && N1C->getAPIntValue() == 1) {
13996     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
13997       Op.getOperand(0).hasOneUse();
13998   }
13999   return false;
14000 }
14001
14002 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
14003   bool addTest = true;
14004   SDValue Chain = Op.getOperand(0);
14005   SDValue Cond  = Op.getOperand(1);
14006   SDValue Dest  = Op.getOperand(2);
14007   SDLoc dl(Op);
14008   SDValue CC;
14009   bool Inverted = false;
14010
14011   if (Cond.getOpcode() == ISD::SETCC) {
14012     // Check for setcc([su]{add,sub,mul}o == 0).
14013     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
14014         isa<ConstantSDNode>(Cond.getOperand(1)) &&
14015         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
14016         Cond.getOperand(0).getResNo() == 1 &&
14017         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
14018          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
14019          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
14020          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
14021          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
14022          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
14023       Inverted = true;
14024       Cond = Cond.getOperand(0);
14025     } else {
14026       SDValue NewCond = LowerSETCC(Cond, DAG);
14027       if (NewCond.getNode())
14028         Cond = NewCond;
14029     }
14030   }
14031 #if 0
14032   // FIXME: LowerXALUO doesn't handle these!!
14033   else if (Cond.getOpcode() == X86ISD::ADD  ||
14034            Cond.getOpcode() == X86ISD::SUB  ||
14035            Cond.getOpcode() == X86ISD::SMUL ||
14036            Cond.getOpcode() == X86ISD::UMUL)
14037     Cond = LowerXALUO(Cond, DAG);
14038 #endif
14039
14040   // Look pass (and (setcc_carry (cmp ...)), 1).
14041   if (Cond.getOpcode() == ISD::AND &&
14042       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
14043     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
14044     if (C && C->getAPIntValue() == 1)
14045       Cond = Cond.getOperand(0);
14046   }
14047
14048   // If condition flag is set by a X86ISD::CMP, then use it as the condition
14049   // setting operand in place of the X86ISD::SETCC.
14050   unsigned CondOpcode = Cond.getOpcode();
14051   if (CondOpcode == X86ISD::SETCC ||
14052       CondOpcode == X86ISD::SETCC_CARRY) {
14053     CC = Cond.getOperand(0);
14054
14055     SDValue Cmp = Cond.getOperand(1);
14056     unsigned Opc = Cmp.getOpcode();
14057     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
14058     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
14059       Cond = Cmp;
14060       addTest = false;
14061     } else {
14062       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
14063       default: break;
14064       case X86::COND_O:
14065       case X86::COND_B:
14066         // These can only come from an arithmetic instruction with overflow,
14067         // e.g. SADDO, UADDO.
14068         Cond = Cond.getNode()->getOperand(1);
14069         addTest = false;
14070         break;
14071       }
14072     }
14073   }
14074   CondOpcode = Cond.getOpcode();
14075   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
14076       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
14077       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
14078        Cond.getOperand(0).getValueType() != MVT::i8)) {
14079     SDValue LHS = Cond.getOperand(0);
14080     SDValue RHS = Cond.getOperand(1);
14081     unsigned X86Opcode;
14082     unsigned X86Cond;
14083     SDVTList VTs;
14084     // Keep this in sync with LowerXALUO, otherwise we might create redundant
14085     // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
14086     // X86ISD::INC).
14087     switch (CondOpcode) {
14088     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
14089     case ISD::SADDO:
14090       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
14091         if (C->isOne()) {
14092           X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
14093           break;
14094         }
14095       X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
14096     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
14097     case ISD::SSUBO:
14098       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
14099         if (C->isOne()) {
14100           X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
14101           break;
14102         }
14103       X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
14104     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
14105     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
14106     default: llvm_unreachable("unexpected overflowing operator");
14107     }
14108     if (Inverted)
14109       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
14110     if (CondOpcode == ISD::UMULO)
14111       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
14112                           MVT::i32);
14113     else
14114       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
14115
14116     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
14117
14118     if (CondOpcode == ISD::UMULO)
14119       Cond = X86Op.getValue(2);
14120     else
14121       Cond = X86Op.getValue(1);
14122
14123     CC = DAG.getConstant(X86Cond, MVT::i8);
14124     addTest = false;
14125   } else {
14126     unsigned CondOpc;
14127     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
14128       SDValue Cmp = Cond.getOperand(0).getOperand(1);
14129       if (CondOpc == ISD::OR) {
14130         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
14131         // two branches instead of an explicit OR instruction with a
14132         // separate test.
14133         if (Cmp == Cond.getOperand(1).getOperand(1) &&
14134             isX86LogicalCmp(Cmp)) {
14135           CC = Cond.getOperand(0).getOperand(0);
14136           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14137                               Chain, Dest, CC, Cmp);
14138           CC = Cond.getOperand(1).getOperand(0);
14139           Cond = Cmp;
14140           addTest = false;
14141         }
14142       } else { // ISD::AND
14143         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
14144         // two branches instead of an explicit AND instruction with a
14145         // separate test. However, we only do this if this block doesn't
14146         // have a fall-through edge, because this requires an explicit
14147         // jmp when the condition is false.
14148         if (Cmp == Cond.getOperand(1).getOperand(1) &&
14149             isX86LogicalCmp(Cmp) &&
14150             Op.getNode()->hasOneUse()) {
14151           X86::CondCode CCode =
14152             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
14153           CCode = X86::GetOppositeBranchCondition(CCode);
14154           CC = DAG.getConstant(CCode, MVT::i8);
14155           SDNode *User = *Op.getNode()->use_begin();
14156           // Look for an unconditional branch following this conditional branch.
14157           // We need this because we need to reverse the successors in order
14158           // to implement FCMP_OEQ.
14159           if (User->getOpcode() == ISD::BR) {
14160             SDValue FalseBB = User->getOperand(1);
14161             SDNode *NewBR =
14162               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14163             assert(NewBR == User);
14164             (void)NewBR;
14165             Dest = FalseBB;
14166
14167             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14168                                 Chain, Dest, CC, Cmp);
14169             X86::CondCode CCode =
14170               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
14171             CCode = X86::GetOppositeBranchCondition(CCode);
14172             CC = DAG.getConstant(CCode, MVT::i8);
14173             Cond = Cmp;
14174             addTest = false;
14175           }
14176         }
14177       }
14178     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
14179       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
14180       // It should be transformed during dag combiner except when the condition
14181       // is set by a arithmetics with overflow node.
14182       X86::CondCode CCode =
14183         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
14184       CCode = X86::GetOppositeBranchCondition(CCode);
14185       CC = DAG.getConstant(CCode, MVT::i8);
14186       Cond = Cond.getOperand(0).getOperand(1);
14187       addTest = false;
14188     } else if (Cond.getOpcode() == ISD::SETCC &&
14189                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
14190       // For FCMP_OEQ, we can emit
14191       // two branches instead of an explicit AND instruction with a
14192       // separate test. However, we only do this if this block doesn't
14193       // have a fall-through edge, because this requires an explicit
14194       // jmp when the condition is false.
14195       if (Op.getNode()->hasOneUse()) {
14196         SDNode *User = *Op.getNode()->use_begin();
14197         // Look for an unconditional branch following this conditional branch.
14198         // We need this because we need to reverse the successors in order
14199         // to implement FCMP_OEQ.
14200         if (User->getOpcode() == ISD::BR) {
14201           SDValue FalseBB = User->getOperand(1);
14202           SDNode *NewBR =
14203             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14204           assert(NewBR == User);
14205           (void)NewBR;
14206           Dest = FalseBB;
14207
14208           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
14209                                     Cond.getOperand(0), Cond.getOperand(1));
14210           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14211           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
14212           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14213                               Chain, Dest, CC, Cmp);
14214           CC = DAG.getConstant(X86::COND_P, MVT::i8);
14215           Cond = Cmp;
14216           addTest = false;
14217         }
14218       }
14219     } else if (Cond.getOpcode() == ISD::SETCC &&
14220                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
14221       // For FCMP_UNE, we can emit
14222       // two branches instead of an explicit AND instruction with a
14223       // separate test. However, we only do this if this block doesn't
14224       // have a fall-through edge, because this requires an explicit
14225       // jmp when the condition is false.
14226       if (Op.getNode()->hasOneUse()) {
14227         SDNode *User = *Op.getNode()->use_begin();
14228         // Look for an unconditional branch following this conditional branch.
14229         // We need this because we need to reverse the successors in order
14230         // to implement FCMP_UNE.
14231         if (User->getOpcode() == ISD::BR) {
14232           SDValue FalseBB = User->getOperand(1);
14233           SDNode *NewBR =
14234             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14235           assert(NewBR == User);
14236           (void)NewBR;
14237
14238           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
14239                                     Cond.getOperand(0), Cond.getOperand(1));
14240           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14241           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
14242           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14243                               Chain, Dest, CC, Cmp);
14244           CC = DAG.getConstant(X86::COND_NP, MVT::i8);
14245           Cond = Cmp;
14246           addTest = false;
14247           Dest = FalseBB;
14248         }
14249       }
14250     }
14251   }
14252
14253   if (addTest) {
14254     // Look pass the truncate if the high bits are known zero.
14255     if (isTruncWithZeroHighBitsInput(Cond, DAG))
14256         Cond = Cond.getOperand(0);
14257
14258     // We know the result of AND is compared against zero. Try to match
14259     // it to BT.
14260     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
14261       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
14262       if (NewSetCC.getNode()) {
14263         CC = NewSetCC.getOperand(0);
14264         Cond = NewSetCC.getOperand(1);
14265         addTest = false;
14266       }
14267     }
14268   }
14269
14270   if (addTest) {
14271     X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
14272     CC = DAG.getConstant(X86Cond, MVT::i8);
14273     Cond = EmitTest(Cond, X86Cond, dl, DAG);
14274   }
14275   Cond = ConvertCmpIfNecessary(Cond, DAG);
14276   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14277                      Chain, Dest, CC, Cond);
14278 }
14279
14280 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
14281 // Calls to _alloca are needed to probe the stack when allocating more than 4k
14282 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
14283 // that the guard pages used by the OS virtual memory manager are allocated in
14284 // correct sequence.
14285 SDValue
14286 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
14287                                            SelectionDAG &DAG) const {
14288   MachineFunction &MF = DAG.getMachineFunction();
14289   bool SplitStack = MF.shouldSplitStack();
14290   bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMachO()) ||
14291                SplitStack;
14292   SDLoc dl(Op);
14293
14294   if (!Lower) {
14295     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14296     SDNode* Node = Op.getNode();
14297
14298     unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
14299     assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
14300         " not tell us which reg is the stack pointer!");
14301     EVT VT = Node->getValueType(0);
14302     SDValue Tmp1 = SDValue(Node, 0);
14303     SDValue Tmp2 = SDValue(Node, 1);
14304     SDValue Tmp3 = Node->getOperand(2);
14305     SDValue Chain = Tmp1.getOperand(0);
14306
14307     // Chain the dynamic stack allocation so that it doesn't modify the stack
14308     // pointer when other instructions are using the stack.
14309     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true),
14310         SDLoc(Node));
14311
14312     SDValue Size = Tmp2.getOperand(1);
14313     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
14314     Chain = SP.getValue(1);
14315     unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
14316     const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
14317     unsigned StackAlign = TFI.getStackAlignment();
14318     Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
14319     if (Align > StackAlign)
14320       Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
14321           DAG.getConstant(-(uint64_t)Align, VT));
14322     Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
14323
14324     Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, true),
14325         DAG.getIntPtrConstant(0, true), SDValue(),
14326         SDLoc(Node));
14327
14328     SDValue Ops[2] = { Tmp1, Tmp2 };
14329     return DAG.getMergeValues(Ops, dl);
14330   }
14331
14332   // Get the inputs.
14333   SDValue Chain = Op.getOperand(0);
14334   SDValue Size  = Op.getOperand(1);
14335   unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
14336   EVT VT = Op.getNode()->getValueType(0);
14337
14338   bool Is64Bit = Subtarget->is64Bit();
14339   EVT SPTy = getPointerTy();
14340
14341   if (SplitStack) {
14342     MachineRegisterInfo &MRI = MF.getRegInfo();
14343
14344     if (Is64Bit) {
14345       // The 64 bit implementation of segmented stacks needs to clobber both r10
14346       // r11. This makes it impossible to use it along with nested parameters.
14347       const Function *F = MF.getFunction();
14348
14349       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
14350            I != E; ++I)
14351         if (I->hasNestAttr())
14352           report_fatal_error("Cannot use segmented stacks with functions that "
14353                              "have nested arguments.");
14354     }
14355
14356     const TargetRegisterClass *AddrRegClass =
14357       getRegClassFor(getPointerTy());
14358     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
14359     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
14360     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
14361                                 DAG.getRegister(Vreg, SPTy));
14362     SDValue Ops1[2] = { Value, Chain };
14363     return DAG.getMergeValues(Ops1, dl);
14364   } else {
14365     SDValue Flag;
14366     const unsigned Reg = (Subtarget->isTarget64BitLP64() ? X86::RAX : X86::EAX);
14367
14368     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
14369     Flag = Chain.getValue(1);
14370     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
14371
14372     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
14373
14374     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
14375     unsigned SPReg = RegInfo->getStackRegister();
14376     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
14377     Chain = SP.getValue(1);
14378
14379     if (Align) {
14380       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
14381                        DAG.getConstant(-(uint64_t)Align, VT));
14382       Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
14383     }
14384
14385     SDValue Ops1[2] = { SP, Chain };
14386     return DAG.getMergeValues(Ops1, dl);
14387   }
14388 }
14389
14390 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
14391   MachineFunction &MF = DAG.getMachineFunction();
14392   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
14393
14394   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
14395   SDLoc DL(Op);
14396
14397   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
14398     // vastart just stores the address of the VarArgsFrameIndex slot into the
14399     // memory location argument.
14400     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
14401                                    getPointerTy());
14402     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
14403                         MachinePointerInfo(SV), false, false, 0);
14404   }
14405
14406   // __va_list_tag:
14407   //   gp_offset         (0 - 6 * 8)
14408   //   fp_offset         (48 - 48 + 8 * 16)
14409   //   overflow_arg_area (point to parameters coming in memory).
14410   //   reg_save_area
14411   SmallVector<SDValue, 8> MemOps;
14412   SDValue FIN = Op.getOperand(1);
14413   // Store gp_offset
14414   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
14415                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
14416                                                MVT::i32),
14417                                FIN, MachinePointerInfo(SV), false, false, 0);
14418   MemOps.push_back(Store);
14419
14420   // Store fp_offset
14421   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
14422                     FIN, DAG.getIntPtrConstant(4));
14423   Store = DAG.getStore(Op.getOperand(0), DL,
14424                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
14425                                        MVT::i32),
14426                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
14427   MemOps.push_back(Store);
14428
14429   // Store ptr to overflow_arg_area
14430   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
14431                     FIN, DAG.getIntPtrConstant(4));
14432   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
14433                                     getPointerTy());
14434   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
14435                        MachinePointerInfo(SV, 8),
14436                        false, false, 0);
14437   MemOps.push_back(Store);
14438
14439   // Store ptr to reg_save_area.
14440   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
14441                     FIN, DAG.getIntPtrConstant(8));
14442   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
14443                                     getPointerTy());
14444   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
14445                        MachinePointerInfo(SV, 16), false, false, 0);
14446   MemOps.push_back(Store);
14447   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
14448 }
14449
14450 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
14451   assert(Subtarget->is64Bit() &&
14452          "LowerVAARG only handles 64-bit va_arg!");
14453   assert((Subtarget->isTargetLinux() ||
14454           Subtarget->isTargetDarwin()) &&
14455           "Unhandled target in LowerVAARG");
14456   assert(Op.getNode()->getNumOperands() == 4);
14457   SDValue Chain = Op.getOperand(0);
14458   SDValue SrcPtr = Op.getOperand(1);
14459   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
14460   unsigned Align = Op.getConstantOperandVal(3);
14461   SDLoc dl(Op);
14462
14463   EVT ArgVT = Op.getNode()->getValueType(0);
14464   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
14465   uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
14466   uint8_t ArgMode;
14467
14468   // Decide which area this value should be read from.
14469   // TODO: Implement the AMD64 ABI in its entirety. This simple
14470   // selection mechanism works only for the basic types.
14471   if (ArgVT == MVT::f80) {
14472     llvm_unreachable("va_arg for f80 not yet implemented");
14473   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
14474     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
14475   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
14476     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
14477   } else {
14478     llvm_unreachable("Unhandled argument type in LowerVAARG");
14479   }
14480
14481   if (ArgMode == 2) {
14482     // Sanity Check: Make sure using fp_offset makes sense.
14483     assert(!DAG.getTarget().Options.UseSoftFloat &&
14484            !(DAG.getMachineFunction().getFunction()->hasFnAttribute(
14485                Attribute::NoImplicitFloat)) &&
14486            Subtarget->hasSSE1());
14487   }
14488
14489   // Insert VAARG_64 node into the DAG
14490   // VAARG_64 returns two values: Variable Argument Address, Chain
14491   SDValue InstOps[] = {Chain, SrcPtr, DAG.getConstant(ArgSize, MVT::i32),
14492                        DAG.getConstant(ArgMode, MVT::i8),
14493                        DAG.getConstant(Align, MVT::i32)};
14494   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
14495   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
14496                                           VTs, InstOps, MVT::i64,
14497                                           MachinePointerInfo(SV),
14498                                           /*Align=*/0,
14499                                           /*Volatile=*/false,
14500                                           /*ReadMem=*/true,
14501                                           /*WriteMem=*/true);
14502   Chain = VAARG.getValue(1);
14503
14504   // Load the next argument and return it
14505   return DAG.getLoad(ArgVT, dl,
14506                      Chain,
14507                      VAARG,
14508                      MachinePointerInfo(),
14509                      false, false, false, 0);
14510 }
14511
14512 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
14513                            SelectionDAG &DAG) {
14514   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
14515   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
14516   SDValue Chain = Op.getOperand(0);
14517   SDValue DstPtr = Op.getOperand(1);
14518   SDValue SrcPtr = Op.getOperand(2);
14519   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
14520   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
14521   SDLoc DL(Op);
14522
14523   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
14524                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
14525                        false, false,
14526                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
14527 }
14528
14529 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
14530 // amount is a constant. Takes immediate version of shift as input.
14531 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
14532                                           SDValue SrcOp, uint64_t ShiftAmt,
14533                                           SelectionDAG &DAG) {
14534   MVT ElementType = VT.getVectorElementType();
14535
14536   // Fold this packed shift into its first operand if ShiftAmt is 0.
14537   if (ShiftAmt == 0)
14538     return SrcOp;
14539
14540   // Check for ShiftAmt >= element width
14541   if (ShiftAmt >= ElementType.getSizeInBits()) {
14542     if (Opc == X86ISD::VSRAI)
14543       ShiftAmt = ElementType.getSizeInBits() - 1;
14544     else
14545       return DAG.getConstant(0, VT);
14546   }
14547
14548   assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
14549          && "Unknown target vector shift-by-constant node");
14550
14551   // Fold this packed vector shift into a build vector if SrcOp is a
14552   // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
14553   if (VT == SrcOp.getSimpleValueType() &&
14554       ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
14555     SmallVector<SDValue, 8> Elts;
14556     unsigned NumElts = SrcOp->getNumOperands();
14557     ConstantSDNode *ND;
14558
14559     switch(Opc) {
14560     default: llvm_unreachable(nullptr);
14561     case X86ISD::VSHLI:
14562       for (unsigned i=0; i!=NumElts; ++i) {
14563         SDValue CurrentOp = SrcOp->getOperand(i);
14564         if (CurrentOp->getOpcode() == ISD::UNDEF) {
14565           Elts.push_back(CurrentOp);
14566           continue;
14567         }
14568         ND = cast<ConstantSDNode>(CurrentOp);
14569         const APInt &C = ND->getAPIntValue();
14570         Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), ElementType));
14571       }
14572       break;
14573     case X86ISD::VSRLI:
14574       for (unsigned i=0; i!=NumElts; ++i) {
14575         SDValue CurrentOp = SrcOp->getOperand(i);
14576         if (CurrentOp->getOpcode() == ISD::UNDEF) {
14577           Elts.push_back(CurrentOp);
14578           continue;
14579         }
14580         ND = cast<ConstantSDNode>(CurrentOp);
14581         const APInt &C = ND->getAPIntValue();
14582         Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), ElementType));
14583       }
14584       break;
14585     case X86ISD::VSRAI:
14586       for (unsigned i=0; i!=NumElts; ++i) {
14587         SDValue CurrentOp = SrcOp->getOperand(i);
14588         if (CurrentOp->getOpcode() == ISD::UNDEF) {
14589           Elts.push_back(CurrentOp);
14590           continue;
14591         }
14592         ND = cast<ConstantSDNode>(CurrentOp);
14593         const APInt &C = ND->getAPIntValue();
14594         Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), ElementType));
14595       }
14596       break;
14597     }
14598
14599     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
14600   }
14601
14602   return DAG.getNode(Opc, dl, VT, SrcOp, DAG.getConstant(ShiftAmt, MVT::i8));
14603 }
14604
14605 // getTargetVShiftNode - Handle vector element shifts where the shift amount
14606 // may or may not be a constant. Takes immediate version of shift as input.
14607 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
14608                                    SDValue SrcOp, SDValue ShAmt,
14609                                    SelectionDAG &DAG) {
14610   MVT SVT = ShAmt.getSimpleValueType();
14611   assert((SVT == MVT::i32 || SVT == MVT::i64) && "Unexpected value type!");
14612
14613   // Catch shift-by-constant.
14614   if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
14615     return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
14616                                       CShAmt->getZExtValue(), DAG);
14617
14618   // Change opcode to non-immediate version
14619   switch (Opc) {
14620     default: llvm_unreachable("Unknown target vector shift node");
14621     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
14622     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
14623     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
14624   }
14625
14626   const X86Subtarget &Subtarget =
14627       static_cast<const X86Subtarget &>(DAG.getSubtarget());
14628   if (Subtarget.hasSSE41() && ShAmt.getOpcode() == ISD::ZERO_EXTEND &&
14629       ShAmt.getOperand(0).getSimpleValueType() == MVT::i16) {
14630     // Let the shuffle legalizer expand this shift amount node.
14631     SDValue Op0 = ShAmt.getOperand(0);
14632     Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(Op0), MVT::v8i16, Op0);
14633     ShAmt = getShuffleVectorZeroOrUndef(Op0, 0, true, &Subtarget, DAG);
14634   } else {
14635     // Need to build a vector containing shift amount.
14636     // SSE/AVX packed shifts only use the lower 64-bit of the shift count.
14637     SmallVector<SDValue, 4> ShOps;
14638     ShOps.push_back(ShAmt);
14639     if (SVT == MVT::i32) {
14640       ShOps.push_back(DAG.getConstant(0, SVT));
14641       ShOps.push_back(DAG.getUNDEF(SVT));
14642     }
14643     ShOps.push_back(DAG.getUNDEF(SVT));
14644
14645     MVT BVT = SVT == MVT::i32 ? MVT::v4i32 : MVT::v2i64;
14646     ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, BVT, ShOps);
14647   }
14648
14649   // The return type has to be a 128-bit type with the same element
14650   // type as the input type.
14651   MVT EltVT = VT.getVectorElementType();
14652   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
14653
14654   ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
14655   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
14656 }
14657
14658 /// \brief Return (and \p Op, \p Mask) for compare instructions or
14659 /// (vselect \p Mask, \p Op, \p PreservedSrc) for others along with the
14660 /// necessary casting for \p Mask when lowering masking intrinsics.
14661 static SDValue getVectorMaskingNode(SDValue Op, SDValue Mask,
14662                                     SDValue PreservedSrc,
14663                                     const X86Subtarget *Subtarget,
14664                                     SelectionDAG &DAG) {
14665     EVT VT = Op.getValueType();
14666     EVT MaskVT = EVT::getVectorVT(*DAG.getContext(),
14667                                   MVT::i1, VT.getVectorNumElements());
14668     EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
14669                                      Mask.getValueType().getSizeInBits());
14670     SDLoc dl(Op);
14671
14672     assert(MaskVT.isSimple() && "invalid mask type");
14673
14674     if (isAllOnes(Mask))
14675       return Op;
14676
14677     // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
14678     // are extracted by EXTRACT_SUBVECTOR.
14679     SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
14680                               DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
14681                               DAG.getIntPtrConstant(0));
14682
14683     switch (Op.getOpcode()) {
14684       default: break;
14685       case X86ISD::PCMPEQM:
14686       case X86ISD::PCMPGTM:
14687       case X86ISD::CMPM:
14688       case X86ISD::CMPMU:
14689         return DAG.getNode(ISD::AND, dl, VT, Op, VMask);
14690     }
14691     if (PreservedSrc.getOpcode() == ISD::UNDEF)
14692       PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
14693     return DAG.getNode(ISD::VSELECT, dl, VT, VMask, Op, PreservedSrc);
14694 }
14695
14696 /// \brief Creates an SDNode for a predicated scalar operation.
14697 /// \returns (X86vselect \p Mask, \p Op, \p PreservedSrc).
14698 /// The mask is comming as MVT::i8 and it should be truncated
14699 /// to MVT::i1 while lowering masking intrinsics.
14700 /// The main difference between ScalarMaskingNode and VectorMaskingNode is using
14701 /// "X86select" instead of "vselect". We just can't create the "vselect" node for
14702 /// a scalar instruction.
14703 static SDValue getScalarMaskingNode(SDValue Op, SDValue Mask,
14704                                     SDValue PreservedSrc,
14705                                     const X86Subtarget *Subtarget,
14706                                     SelectionDAG &DAG) {
14707     if (isAllOnes(Mask))
14708       return Op;
14709
14710     EVT VT = Op.getValueType();
14711     SDLoc dl(Op);
14712     // The mask should be of type MVT::i1
14713     SDValue IMask = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Mask);
14714
14715     if (PreservedSrc.getOpcode() == ISD::UNDEF)
14716       PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
14717     return DAG.getNode(X86ISD::SELECT, dl, VT, IMask, Op, PreservedSrc);
14718 }
14719
14720 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
14721                                        SelectionDAG &DAG) {
14722   SDLoc dl(Op);
14723   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
14724   EVT VT = Op.getValueType();
14725   const IntrinsicData* IntrData = getIntrinsicWithoutChain(IntNo);
14726   if (IntrData) {
14727     switch(IntrData->Type) {
14728     case INTR_TYPE_1OP:
14729       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1));
14730     case INTR_TYPE_2OP:
14731       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
14732         Op.getOperand(2));
14733     case INTR_TYPE_3OP:
14734       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
14735         Op.getOperand(2), Op.getOperand(3));
14736     case INTR_TYPE_1OP_MASK_RM: {
14737       SDValue Src = Op.getOperand(1);
14738       SDValue Src0 = Op.getOperand(2);
14739       SDValue Mask = Op.getOperand(3);
14740       SDValue RoundingMode = Op.getOperand(4);
14741       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src,
14742                                               RoundingMode),
14743                                   Mask, Src0, Subtarget, DAG);
14744     }
14745     case INTR_TYPE_SCALAR_MASK_RM: {
14746       SDValue Src1 = Op.getOperand(1);
14747       SDValue Src2 = Op.getOperand(2);
14748       SDValue Src0 = Op.getOperand(3);
14749       SDValue Mask = Op.getOperand(4);
14750       // There are 2 kinds of intrinsics in this group:
14751       // (1) With supress-all-exceptions (sae) - 6 operands
14752       // (2) With rounding mode and sae - 7 operands.
14753       if (Op.getNumOperands() == 6) {
14754         SDValue Sae  = Op.getOperand(5);
14755         return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2,
14756                                                 Sae),
14757                                     Mask, Src0, Subtarget, DAG);
14758       }
14759       assert(Op.getNumOperands() == 7 && "Unexpected intrinsic form");
14760       SDValue RoundingMode  = Op.getOperand(5);
14761       SDValue Sae  = Op.getOperand(6);
14762       return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2,
14763                                               RoundingMode, Sae),
14764                                   Mask, Src0, Subtarget, DAG);
14765     }
14766     case INTR_TYPE_2OP_MASK: {
14767       SDValue Src1 = Op.getOperand(1);
14768       SDValue Src2 = Op.getOperand(2);
14769       SDValue PassThru = Op.getOperand(3);
14770       SDValue Mask = Op.getOperand(4);
14771       // We specify 2 possible opcodes for intrinsics with rounding modes.
14772       // First, we check if the intrinsic may have non-default rounding mode,
14773       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
14774       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
14775       if (IntrWithRoundingModeOpcode != 0) {
14776         SDValue Rnd = Op.getOperand(5);
14777         unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
14778         if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
14779           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
14780                                       dl, Op.getValueType(),
14781                                       Src1, Src2, Rnd),
14782                                       Mask, PassThru, Subtarget, DAG);
14783         }
14784       }
14785       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
14786                                               Src1,Src2),
14787                                   Mask, PassThru, Subtarget, DAG);
14788     }
14789     case FMA_OP_MASK: {
14790       SDValue Src1 = Op.getOperand(1);
14791       SDValue Src2 = Op.getOperand(2);
14792       SDValue Src3 = Op.getOperand(3);
14793       SDValue Mask = Op.getOperand(4);
14794       // We specify 2 possible opcodes for intrinsics with rounding modes.
14795       // First, we check if the intrinsic may have non-default rounding mode,
14796       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
14797       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
14798       if (IntrWithRoundingModeOpcode != 0) {
14799         SDValue Rnd = Op.getOperand(5);
14800         if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
14801             X86::STATIC_ROUNDING::CUR_DIRECTION)
14802           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
14803                                                   dl, Op.getValueType(),
14804                                                   Src1, Src2, Src3, Rnd),
14805                                       Mask, Src1, Subtarget, DAG);
14806       }
14807       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0,
14808                                               dl, Op.getValueType(),
14809                                               Src1, Src2, Src3),
14810                                   Mask, Src1, Subtarget, DAG);
14811     }
14812     case CMP_MASK:
14813     case CMP_MASK_CC: {
14814       // Comparison intrinsics with masks.
14815       // Example of transformation:
14816       // (i8 (int_x86_avx512_mask_pcmpeq_q_128
14817       //             (v2i64 %a), (v2i64 %b), (i8 %mask))) ->
14818       // (i8 (bitcast
14819       //   (v8i1 (insert_subvector undef,
14820       //           (v2i1 (and (PCMPEQM %a, %b),
14821       //                      (extract_subvector
14822       //                         (v8i1 (bitcast %mask)), 0))), 0))))
14823       EVT VT = Op.getOperand(1).getValueType();
14824       EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
14825                                     VT.getVectorNumElements());
14826       SDValue Mask = Op.getOperand((IntrData->Type == CMP_MASK_CC) ? 4 : 3);
14827       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
14828                                        Mask.getValueType().getSizeInBits());
14829       SDValue Cmp;
14830       if (IntrData->Type == CMP_MASK_CC) {
14831         Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
14832                     Op.getOperand(2), Op.getOperand(3));
14833       } else {
14834         assert(IntrData->Type == CMP_MASK && "Unexpected intrinsic type!");
14835         Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
14836                     Op.getOperand(2));
14837       }
14838       SDValue CmpMask = getVectorMaskingNode(Cmp, Mask,
14839                                              DAG.getTargetConstant(0, MaskVT),
14840                                              Subtarget, DAG);
14841       SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, BitcastVT,
14842                                 DAG.getUNDEF(BitcastVT), CmpMask,
14843                                 DAG.getIntPtrConstant(0));
14844       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
14845     }
14846     case COMI: { // Comparison intrinsics
14847       ISD::CondCode CC = (ISD::CondCode)IntrData->Opc1;
14848       SDValue LHS = Op.getOperand(1);
14849       SDValue RHS = Op.getOperand(2);
14850       unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
14851       assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
14852       SDValue Cond = DAG.getNode(IntrData->Opc0, dl, MVT::i32, LHS, RHS);
14853       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14854                                   DAG.getConstant(X86CC, MVT::i8), Cond);
14855       return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
14856     }
14857     case VSHIFT:
14858       return getTargetVShiftNode(IntrData->Opc0, dl, Op.getSimpleValueType(),
14859                                  Op.getOperand(1), Op.getOperand(2), DAG);
14860     case VSHIFT_MASK:
14861       return getVectorMaskingNode(getTargetVShiftNode(IntrData->Opc0, dl,
14862                                                       Op.getSimpleValueType(),
14863                                                       Op.getOperand(1),
14864                                                       Op.getOperand(2), DAG),
14865                                   Op.getOperand(4), Op.getOperand(3), Subtarget,
14866                                   DAG);
14867     case COMPRESS_EXPAND_IN_REG: {
14868       SDValue Mask = Op.getOperand(3);
14869       SDValue DataToCompress = Op.getOperand(1);
14870       SDValue PassThru = Op.getOperand(2);
14871       if (isAllOnes(Mask)) // return data as is
14872         return Op.getOperand(1);
14873       EVT VT = Op.getValueType();
14874       EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
14875                                     VT.getVectorNumElements());
14876       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
14877                                        Mask.getValueType().getSizeInBits());
14878       SDLoc dl(Op);
14879       SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
14880                                   DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
14881                                   DAG.getIntPtrConstant(0));
14882
14883       return DAG.getNode(IntrData->Opc0, dl, VT, VMask, DataToCompress,
14884                          PassThru);
14885     }
14886     case BLEND: {
14887       SDValue Mask = Op.getOperand(3);
14888       EVT VT = Op.getValueType();
14889       EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
14890                                     VT.getVectorNumElements());
14891       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
14892                                        Mask.getValueType().getSizeInBits());
14893       SDLoc dl(Op);
14894       SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
14895                                   DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
14896                                   DAG.getIntPtrConstant(0));
14897       return DAG.getNode(IntrData->Opc0, dl, VT, VMask, Op.getOperand(1),
14898                          Op.getOperand(2));
14899     }
14900     default:
14901       break;
14902     }
14903   }
14904
14905   switch (IntNo) {
14906   default: return SDValue();    // Don't custom lower most intrinsics.
14907
14908   case Intrinsic::x86_avx2_permd:
14909   case Intrinsic::x86_avx2_permps:
14910     // Operands intentionally swapped. Mask is last operand to intrinsic,
14911     // but second operand for node/instruction.
14912     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
14913                        Op.getOperand(2), Op.getOperand(1));
14914
14915   case Intrinsic::x86_avx512_mask_valign_q_512:
14916   case Intrinsic::x86_avx512_mask_valign_d_512:
14917     // Vector source operands are swapped.
14918     return getVectorMaskingNode(DAG.getNode(X86ISD::VALIGN, dl,
14919                                             Op.getValueType(), Op.getOperand(2),
14920                                             Op.getOperand(1),
14921                                             Op.getOperand(3)),
14922                                 Op.getOperand(5), Op.getOperand(4),
14923                                 Subtarget, DAG);
14924
14925   // ptest and testp intrinsics. The intrinsic these come from are designed to
14926   // return an integer value, not just an instruction so lower it to the ptest
14927   // or testp pattern and a setcc for the result.
14928   case Intrinsic::x86_sse41_ptestz:
14929   case Intrinsic::x86_sse41_ptestc:
14930   case Intrinsic::x86_sse41_ptestnzc:
14931   case Intrinsic::x86_avx_ptestz_256:
14932   case Intrinsic::x86_avx_ptestc_256:
14933   case Intrinsic::x86_avx_ptestnzc_256:
14934   case Intrinsic::x86_avx_vtestz_ps:
14935   case Intrinsic::x86_avx_vtestc_ps:
14936   case Intrinsic::x86_avx_vtestnzc_ps:
14937   case Intrinsic::x86_avx_vtestz_pd:
14938   case Intrinsic::x86_avx_vtestc_pd:
14939   case Intrinsic::x86_avx_vtestnzc_pd:
14940   case Intrinsic::x86_avx_vtestz_ps_256:
14941   case Intrinsic::x86_avx_vtestc_ps_256:
14942   case Intrinsic::x86_avx_vtestnzc_ps_256:
14943   case Intrinsic::x86_avx_vtestz_pd_256:
14944   case Intrinsic::x86_avx_vtestc_pd_256:
14945   case Intrinsic::x86_avx_vtestnzc_pd_256: {
14946     bool IsTestPacked = false;
14947     unsigned X86CC;
14948     switch (IntNo) {
14949     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
14950     case Intrinsic::x86_avx_vtestz_ps:
14951     case Intrinsic::x86_avx_vtestz_pd:
14952     case Intrinsic::x86_avx_vtestz_ps_256:
14953     case Intrinsic::x86_avx_vtestz_pd_256:
14954       IsTestPacked = true; // Fallthrough
14955     case Intrinsic::x86_sse41_ptestz:
14956     case Intrinsic::x86_avx_ptestz_256:
14957       // ZF = 1
14958       X86CC = X86::COND_E;
14959       break;
14960     case Intrinsic::x86_avx_vtestc_ps:
14961     case Intrinsic::x86_avx_vtestc_pd:
14962     case Intrinsic::x86_avx_vtestc_ps_256:
14963     case Intrinsic::x86_avx_vtestc_pd_256:
14964       IsTestPacked = true; // Fallthrough
14965     case Intrinsic::x86_sse41_ptestc:
14966     case Intrinsic::x86_avx_ptestc_256:
14967       // CF = 1
14968       X86CC = X86::COND_B;
14969       break;
14970     case Intrinsic::x86_avx_vtestnzc_ps:
14971     case Intrinsic::x86_avx_vtestnzc_pd:
14972     case Intrinsic::x86_avx_vtestnzc_ps_256:
14973     case Intrinsic::x86_avx_vtestnzc_pd_256:
14974       IsTestPacked = true; // Fallthrough
14975     case Intrinsic::x86_sse41_ptestnzc:
14976     case Intrinsic::x86_avx_ptestnzc_256:
14977       // ZF and CF = 0
14978       X86CC = X86::COND_A;
14979       break;
14980     }
14981
14982     SDValue LHS = Op.getOperand(1);
14983     SDValue RHS = Op.getOperand(2);
14984     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
14985     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
14986     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
14987     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
14988     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
14989   }
14990   case Intrinsic::x86_avx512_kortestz_w:
14991   case Intrinsic::x86_avx512_kortestc_w: {
14992     unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
14993     SDValue LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(1));
14994     SDValue RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(2));
14995     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
14996     SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
14997     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
14998     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
14999   }
15000
15001   case Intrinsic::x86_sse42_pcmpistria128:
15002   case Intrinsic::x86_sse42_pcmpestria128:
15003   case Intrinsic::x86_sse42_pcmpistric128:
15004   case Intrinsic::x86_sse42_pcmpestric128:
15005   case Intrinsic::x86_sse42_pcmpistrio128:
15006   case Intrinsic::x86_sse42_pcmpestrio128:
15007   case Intrinsic::x86_sse42_pcmpistris128:
15008   case Intrinsic::x86_sse42_pcmpestris128:
15009   case Intrinsic::x86_sse42_pcmpistriz128:
15010   case Intrinsic::x86_sse42_pcmpestriz128: {
15011     unsigned Opcode;
15012     unsigned X86CC;
15013     switch (IntNo) {
15014     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
15015     case Intrinsic::x86_sse42_pcmpistria128:
15016       Opcode = X86ISD::PCMPISTRI;
15017       X86CC = X86::COND_A;
15018       break;
15019     case Intrinsic::x86_sse42_pcmpestria128:
15020       Opcode = X86ISD::PCMPESTRI;
15021       X86CC = X86::COND_A;
15022       break;
15023     case Intrinsic::x86_sse42_pcmpistric128:
15024       Opcode = X86ISD::PCMPISTRI;
15025       X86CC = X86::COND_B;
15026       break;
15027     case Intrinsic::x86_sse42_pcmpestric128:
15028       Opcode = X86ISD::PCMPESTRI;
15029       X86CC = X86::COND_B;
15030       break;
15031     case Intrinsic::x86_sse42_pcmpistrio128:
15032       Opcode = X86ISD::PCMPISTRI;
15033       X86CC = X86::COND_O;
15034       break;
15035     case Intrinsic::x86_sse42_pcmpestrio128:
15036       Opcode = X86ISD::PCMPESTRI;
15037       X86CC = X86::COND_O;
15038       break;
15039     case Intrinsic::x86_sse42_pcmpistris128:
15040       Opcode = X86ISD::PCMPISTRI;
15041       X86CC = X86::COND_S;
15042       break;
15043     case Intrinsic::x86_sse42_pcmpestris128:
15044       Opcode = X86ISD::PCMPESTRI;
15045       X86CC = X86::COND_S;
15046       break;
15047     case Intrinsic::x86_sse42_pcmpistriz128:
15048       Opcode = X86ISD::PCMPISTRI;
15049       X86CC = X86::COND_E;
15050       break;
15051     case Intrinsic::x86_sse42_pcmpestriz128:
15052       Opcode = X86ISD::PCMPESTRI;
15053       X86CC = X86::COND_E;
15054       break;
15055     }
15056     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
15057     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
15058     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
15059     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15060                                 DAG.getConstant(X86CC, MVT::i8),
15061                                 SDValue(PCMP.getNode(), 1));
15062     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15063   }
15064
15065   case Intrinsic::x86_sse42_pcmpistri128:
15066   case Intrinsic::x86_sse42_pcmpestri128: {
15067     unsigned Opcode;
15068     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
15069       Opcode = X86ISD::PCMPISTRI;
15070     else
15071       Opcode = X86ISD::PCMPESTRI;
15072
15073     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
15074     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
15075     return DAG.getNode(Opcode, dl, VTs, NewOps);
15076   }
15077   }
15078 }
15079
15080 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15081                               SDValue Src, SDValue Mask, SDValue Base,
15082                               SDValue Index, SDValue ScaleOp, SDValue Chain,
15083                               const X86Subtarget * Subtarget) {
15084   SDLoc dl(Op);
15085   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15086   assert(C && "Invalid scale type");
15087   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
15088   EVT MaskVT = MVT::getVectorVT(MVT::i1,
15089                              Index.getSimpleValueType().getVectorNumElements());
15090   SDValue MaskInReg;
15091   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15092   if (MaskC)
15093     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
15094   else
15095     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
15096   SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
15097   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
15098   SDValue Segment = DAG.getRegister(0, MVT::i32);
15099   if (Src.getOpcode() == ISD::UNDEF)
15100     Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
15101   SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
15102   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
15103   SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
15104   return DAG.getMergeValues(RetOps, dl);
15105 }
15106
15107 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15108                                SDValue Src, SDValue Mask, SDValue Base,
15109                                SDValue Index, SDValue ScaleOp, SDValue Chain) {
15110   SDLoc dl(Op);
15111   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15112   assert(C && "Invalid scale type");
15113   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
15114   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
15115   SDValue Segment = DAG.getRegister(0, MVT::i32);
15116   EVT MaskVT = MVT::getVectorVT(MVT::i1,
15117                              Index.getSimpleValueType().getVectorNumElements());
15118   SDValue MaskInReg;
15119   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15120   if (MaskC)
15121     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
15122   else
15123     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
15124   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
15125   SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
15126   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
15127   return SDValue(Res, 1);
15128 }
15129
15130 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15131                                SDValue Mask, SDValue Base, SDValue Index,
15132                                SDValue ScaleOp, SDValue Chain) {
15133   SDLoc dl(Op);
15134   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15135   assert(C && "Invalid scale type");
15136   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
15137   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
15138   SDValue Segment = DAG.getRegister(0, MVT::i32);
15139   EVT MaskVT =
15140     MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
15141   SDValue MaskInReg;
15142   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15143   if (MaskC)
15144     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
15145   else
15146     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
15147   //SDVTList VTs = DAG.getVTList(MVT::Other);
15148   SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
15149   SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
15150   return SDValue(Res, 0);
15151 }
15152
15153 // getReadPerformanceCounter - Handles the lowering of builtin intrinsics that
15154 // read performance monitor counters (x86_rdpmc).
15155 static void getReadPerformanceCounter(SDNode *N, SDLoc DL,
15156                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
15157                               SmallVectorImpl<SDValue> &Results) {
15158   assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
15159   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
15160   SDValue LO, HI;
15161
15162   // The ECX register is used to select the index of the performance counter
15163   // to read.
15164   SDValue Chain = DAG.getCopyToReg(N->getOperand(0), DL, X86::ECX,
15165                                    N->getOperand(2));
15166   SDValue rd = DAG.getNode(X86ISD::RDPMC_DAG, DL, Tys, Chain);
15167
15168   // Reads the content of a 64-bit performance counter and returns it in the
15169   // registers EDX:EAX.
15170   if (Subtarget->is64Bit()) {
15171     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
15172     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
15173                             LO.getValue(2));
15174   } else {
15175     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
15176     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
15177                             LO.getValue(2));
15178   }
15179   Chain = HI.getValue(1);
15180
15181   if (Subtarget->is64Bit()) {
15182     // The EAX register is loaded with the low-order 32 bits. The EDX register
15183     // is loaded with the supported high-order bits of the counter.
15184     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
15185                               DAG.getConstant(32, MVT::i8));
15186     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
15187     Results.push_back(Chain);
15188     return;
15189   }
15190
15191   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
15192   SDValue Ops[] = { LO, HI };
15193   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
15194   Results.push_back(Pair);
15195   Results.push_back(Chain);
15196 }
15197
15198 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
15199 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
15200 // also used to custom lower READCYCLECOUNTER nodes.
15201 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
15202                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
15203                               SmallVectorImpl<SDValue> &Results) {
15204   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
15205   SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
15206   SDValue LO, HI;
15207
15208   // The processor's time-stamp counter (a 64-bit MSR) is stored into the
15209   // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
15210   // and the EAX register is loaded with the low-order 32 bits.
15211   if (Subtarget->is64Bit()) {
15212     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
15213     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
15214                             LO.getValue(2));
15215   } else {
15216     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
15217     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
15218                             LO.getValue(2));
15219   }
15220   SDValue Chain = HI.getValue(1);
15221
15222   if (Opcode == X86ISD::RDTSCP_DAG) {
15223     assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
15224
15225     // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
15226     // the ECX register. Add 'ecx' explicitly to the chain.
15227     SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
15228                                      HI.getValue(2));
15229     // Explicitly store the content of ECX at the location passed in input
15230     // to the 'rdtscp' intrinsic.
15231     Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
15232                          MachinePointerInfo(), false, false, 0);
15233   }
15234
15235   if (Subtarget->is64Bit()) {
15236     // The EDX register is loaded with the high-order 32 bits of the MSR, and
15237     // the EAX register is loaded with the low-order 32 bits.
15238     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
15239                               DAG.getConstant(32, MVT::i8));
15240     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
15241     Results.push_back(Chain);
15242     return;
15243   }
15244
15245   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
15246   SDValue Ops[] = { LO, HI };
15247   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
15248   Results.push_back(Pair);
15249   Results.push_back(Chain);
15250 }
15251
15252 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
15253                                      SelectionDAG &DAG) {
15254   SmallVector<SDValue, 2> Results;
15255   SDLoc DL(Op);
15256   getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
15257                           Results);
15258   return DAG.getMergeValues(Results, DL);
15259 }
15260
15261
15262 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
15263                                       SelectionDAG &DAG) {
15264   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
15265
15266   const IntrinsicData* IntrData = getIntrinsicWithChain(IntNo);
15267   if (!IntrData)
15268     return SDValue();
15269
15270   SDLoc dl(Op);
15271   switch(IntrData->Type) {
15272   default:
15273     llvm_unreachable("Unknown Intrinsic Type");
15274     break;
15275   case RDSEED:
15276   case RDRAND: {
15277     // Emit the node with the right value type.
15278     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
15279     SDValue Result = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
15280
15281     // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
15282     // Otherwise return the value from Rand, which is always 0, casted to i32.
15283     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
15284                       DAG.getConstant(1, Op->getValueType(1)),
15285                       DAG.getConstant(X86::COND_B, MVT::i32),
15286                       SDValue(Result.getNode(), 1) };
15287     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
15288                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
15289                                   Ops);
15290
15291     // Return { result, isValid, chain }.
15292     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
15293                        SDValue(Result.getNode(), 2));
15294   }
15295   case GATHER: {
15296   //gather(v1, mask, index, base, scale);
15297     SDValue Chain = Op.getOperand(0);
15298     SDValue Src   = Op.getOperand(2);
15299     SDValue Base  = Op.getOperand(3);
15300     SDValue Index = Op.getOperand(4);
15301     SDValue Mask  = Op.getOperand(5);
15302     SDValue Scale = Op.getOperand(6);
15303     return getGatherNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain,
15304                           Subtarget);
15305   }
15306   case SCATTER: {
15307   //scatter(base, mask, index, v1, scale);
15308     SDValue Chain = Op.getOperand(0);
15309     SDValue Base  = Op.getOperand(2);
15310     SDValue Mask  = Op.getOperand(3);
15311     SDValue Index = Op.getOperand(4);
15312     SDValue Src   = Op.getOperand(5);
15313     SDValue Scale = Op.getOperand(6);
15314     return getScatterNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain);
15315   }
15316   case PREFETCH: {
15317     SDValue Hint = Op.getOperand(6);
15318     unsigned HintVal = cast<ConstantSDNode>(Hint)->getZExtValue();
15319     assert(HintVal < 2 && "Wrong prefetch hint in intrinsic: should be 0 or 1");
15320     unsigned Opcode = (HintVal ? IntrData->Opc1 : IntrData->Opc0);
15321     SDValue Chain = Op.getOperand(0);
15322     SDValue Mask  = Op.getOperand(2);
15323     SDValue Index = Op.getOperand(3);
15324     SDValue Base  = Op.getOperand(4);
15325     SDValue Scale = Op.getOperand(5);
15326     return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
15327   }
15328   // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
15329   case RDTSC: {
15330     SmallVector<SDValue, 2> Results;
15331     getReadTimeStampCounter(Op.getNode(), dl, IntrData->Opc0, DAG, Subtarget, Results);
15332     return DAG.getMergeValues(Results, dl);
15333   }
15334   // Read Performance Monitoring Counters.
15335   case RDPMC: {
15336     SmallVector<SDValue, 2> Results;
15337     getReadPerformanceCounter(Op.getNode(), dl, DAG, Subtarget, Results);
15338     return DAG.getMergeValues(Results, dl);
15339   }
15340   // XTEST intrinsics.
15341   case XTEST: {
15342     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
15343     SDValue InTrans = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
15344     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15345                                 DAG.getConstant(X86::COND_NE, MVT::i8),
15346                                 InTrans);
15347     SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
15348     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
15349                        Ret, SDValue(InTrans.getNode(), 1));
15350   }
15351   // ADC/ADCX/SBB
15352   case ADX: {
15353     SmallVector<SDValue, 2> Results;
15354     SDVTList CFVTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
15355     SDVTList VTs = DAG.getVTList(Op.getOperand(3)->getValueType(0), MVT::Other);
15356     SDValue GenCF = DAG.getNode(X86ISD::ADD, dl, CFVTs, Op.getOperand(2),
15357                                 DAG.getConstant(-1, MVT::i8));
15358     SDValue Res = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(3),
15359                               Op.getOperand(4), GenCF.getValue(1));
15360     SDValue Store = DAG.getStore(Op.getOperand(0), dl, Res.getValue(0),
15361                                  Op.getOperand(5), MachinePointerInfo(),
15362                                  false, false, 0);
15363     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15364                                 DAG.getConstant(X86::COND_B, MVT::i8),
15365                                 Res.getValue(1));
15366     Results.push_back(SetCC);
15367     Results.push_back(Store);
15368     return DAG.getMergeValues(Results, dl);
15369   }
15370   case COMPRESS_TO_MEM: {
15371     SDLoc dl(Op);
15372     SDValue Mask = Op.getOperand(4);
15373     SDValue DataToCompress = Op.getOperand(3);
15374     SDValue Addr = Op.getOperand(2);
15375     SDValue Chain = Op.getOperand(0);
15376
15377     if (isAllOnes(Mask)) // return just a store
15378       return DAG.getStore(Chain, dl, DataToCompress, Addr,
15379                           MachinePointerInfo(), false, false, 0);
15380
15381     EVT VT = DataToCompress.getValueType();
15382     EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15383                                   VT.getVectorNumElements());
15384     EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15385                                      Mask.getValueType().getSizeInBits());
15386     SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15387                                 DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
15388                                 DAG.getIntPtrConstant(0));
15389
15390     SDValue Compressed =  DAG.getNode(IntrData->Opc0, dl, VT, VMask,
15391                                       DataToCompress, DAG.getUNDEF(VT));
15392     return DAG.getStore(Chain, dl, Compressed, Addr,
15393                         MachinePointerInfo(), false, false, 0);
15394   }
15395   case EXPAND_FROM_MEM: {
15396     SDLoc dl(Op);
15397     SDValue Mask = Op.getOperand(4);
15398     SDValue PathThru = Op.getOperand(3);
15399     SDValue Addr = Op.getOperand(2);
15400     SDValue Chain = Op.getOperand(0);
15401     EVT VT = Op.getValueType();
15402
15403     if (isAllOnes(Mask)) // return just a load
15404       return DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(), false, false,
15405                          false, 0);
15406     EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15407                                   VT.getVectorNumElements());
15408     EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15409                                      Mask.getValueType().getSizeInBits());
15410     SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15411                                 DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
15412                                 DAG.getIntPtrConstant(0));
15413
15414     SDValue DataToExpand = DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(),
15415                                    false, false, false, 0);
15416
15417     SDValue Results[] = {
15418         DAG.getNode(IntrData->Opc0, dl, VT, VMask, DataToExpand, PathThru),
15419         Chain};
15420     return DAG.getMergeValues(Results, dl);
15421   }
15422   }
15423 }
15424
15425 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
15426                                            SelectionDAG &DAG) const {
15427   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
15428   MFI->setReturnAddressIsTaken(true);
15429
15430   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
15431     return SDValue();
15432
15433   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15434   SDLoc dl(Op);
15435   EVT PtrVT = getPointerTy();
15436
15437   if (Depth > 0) {
15438     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
15439     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15440     SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
15441     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
15442                        DAG.getNode(ISD::ADD, dl, PtrVT,
15443                                    FrameAddr, Offset),
15444                        MachinePointerInfo(), false, false, false, 0);
15445   }
15446
15447   // Just load the return address.
15448   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
15449   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
15450                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
15451 }
15452
15453 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
15454   MachineFunction &MF = DAG.getMachineFunction();
15455   MachineFrameInfo *MFI = MF.getFrameInfo();
15456   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
15457   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15458   EVT VT = Op.getValueType();
15459
15460   MFI->setFrameAddressIsTaken(true);
15461
15462   if (MF.getTarget().getMCAsmInfo()->usesWindowsCFI()) {
15463     // Depth > 0 makes no sense on targets which use Windows unwind codes.  It
15464     // is not possible to crawl up the stack without looking at the unwind codes
15465     // simultaneously.
15466     int FrameAddrIndex = FuncInfo->getFAIndex();
15467     if (!FrameAddrIndex) {
15468       // Set up a frame object for the return address.
15469       unsigned SlotSize = RegInfo->getSlotSize();
15470       FrameAddrIndex = MF.getFrameInfo()->CreateFixedObject(
15471           SlotSize, /*Offset=*/INT64_MIN, /*IsImmutable=*/false);
15472       FuncInfo->setFAIndex(FrameAddrIndex);
15473     }
15474     return DAG.getFrameIndex(FrameAddrIndex, VT);
15475   }
15476
15477   unsigned FrameReg =
15478       RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
15479   SDLoc dl(Op);  // FIXME probably not meaningful
15480   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15481   assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
15482           (FrameReg == X86::EBP && VT == MVT::i32)) &&
15483          "Invalid Frame Register!");
15484   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
15485   while (Depth--)
15486     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
15487                             MachinePointerInfo(),
15488                             false, false, false, 0);
15489   return FrameAddr;
15490 }
15491
15492 // FIXME? Maybe this could be a TableGen attribute on some registers and
15493 // this table could be generated automatically from RegInfo.
15494 unsigned X86TargetLowering::getRegisterByName(const char* RegName,
15495                                               EVT VT) const {
15496   unsigned Reg = StringSwitch<unsigned>(RegName)
15497                        .Case("esp", X86::ESP)
15498                        .Case("rsp", X86::RSP)
15499                        .Default(0);
15500   if (Reg)
15501     return Reg;
15502   report_fatal_error("Invalid register name global variable");
15503 }
15504
15505 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
15506                                                      SelectionDAG &DAG) const {
15507   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15508   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
15509 }
15510
15511 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
15512   SDValue Chain     = Op.getOperand(0);
15513   SDValue Offset    = Op.getOperand(1);
15514   SDValue Handler   = Op.getOperand(2);
15515   SDLoc dl      (Op);
15516
15517   EVT PtrVT = getPointerTy();
15518   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15519   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
15520   assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
15521           (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
15522          "Invalid Frame Register!");
15523   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
15524   unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
15525
15526   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
15527                                  DAG.getIntPtrConstant(RegInfo->getSlotSize()));
15528   StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
15529   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
15530                        false, false, 0);
15531   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
15532
15533   return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
15534                      DAG.getRegister(StoreAddrReg, PtrVT));
15535 }
15536
15537 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
15538                                                SelectionDAG &DAG) const {
15539   SDLoc DL(Op);
15540   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
15541                      DAG.getVTList(MVT::i32, MVT::Other),
15542                      Op.getOperand(0), Op.getOperand(1));
15543 }
15544
15545 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
15546                                                 SelectionDAG &DAG) const {
15547   SDLoc DL(Op);
15548   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
15549                      Op.getOperand(0), Op.getOperand(1));
15550 }
15551
15552 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
15553   return Op.getOperand(0);
15554 }
15555
15556 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
15557                                                 SelectionDAG &DAG) const {
15558   SDValue Root = Op.getOperand(0);
15559   SDValue Trmp = Op.getOperand(1); // trampoline
15560   SDValue FPtr = Op.getOperand(2); // nested function
15561   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
15562   SDLoc dl (Op);
15563
15564   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
15565   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
15566
15567   if (Subtarget->is64Bit()) {
15568     SDValue OutChains[6];
15569
15570     // Large code-model.
15571     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
15572     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
15573
15574     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
15575     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
15576
15577     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
15578
15579     // Load the pointer to the nested function into R11.
15580     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
15581     SDValue Addr = Trmp;
15582     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
15583                                 Addr, MachinePointerInfo(TrmpAddr),
15584                                 false, false, 0);
15585
15586     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15587                        DAG.getConstant(2, MVT::i64));
15588     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
15589                                 MachinePointerInfo(TrmpAddr, 2),
15590                                 false, false, 2);
15591
15592     // Load the 'nest' parameter value into R10.
15593     // R10 is specified in X86CallingConv.td
15594     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
15595     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15596                        DAG.getConstant(10, MVT::i64));
15597     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
15598                                 Addr, MachinePointerInfo(TrmpAddr, 10),
15599                                 false, false, 0);
15600
15601     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15602                        DAG.getConstant(12, MVT::i64));
15603     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
15604                                 MachinePointerInfo(TrmpAddr, 12),
15605                                 false, false, 2);
15606
15607     // Jump to the nested function.
15608     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
15609     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15610                        DAG.getConstant(20, MVT::i64));
15611     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
15612                                 Addr, MachinePointerInfo(TrmpAddr, 20),
15613                                 false, false, 0);
15614
15615     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
15616     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15617                        DAG.getConstant(22, MVT::i64));
15618     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
15619                                 MachinePointerInfo(TrmpAddr, 22),
15620                                 false, false, 0);
15621
15622     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
15623   } else {
15624     const Function *Func =
15625       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
15626     CallingConv::ID CC = Func->getCallingConv();
15627     unsigned NestReg;
15628
15629     switch (CC) {
15630     default:
15631       llvm_unreachable("Unsupported calling convention");
15632     case CallingConv::C:
15633     case CallingConv::X86_StdCall: {
15634       // Pass 'nest' parameter in ECX.
15635       // Must be kept in sync with X86CallingConv.td
15636       NestReg = X86::ECX;
15637
15638       // Check that ECX wasn't needed by an 'inreg' parameter.
15639       FunctionType *FTy = Func->getFunctionType();
15640       const AttributeSet &Attrs = Func->getAttributes();
15641
15642       if (!Attrs.isEmpty() && !Func->isVarArg()) {
15643         unsigned InRegCount = 0;
15644         unsigned Idx = 1;
15645
15646         for (FunctionType::param_iterator I = FTy->param_begin(),
15647              E = FTy->param_end(); I != E; ++I, ++Idx)
15648           if (Attrs.hasAttribute(Idx, Attribute::InReg))
15649             // FIXME: should only count parameters that are lowered to integers.
15650             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
15651
15652         if (InRegCount > 2) {
15653           report_fatal_error("Nest register in use - reduce number of inreg"
15654                              " parameters!");
15655         }
15656       }
15657       break;
15658     }
15659     case CallingConv::X86_FastCall:
15660     case CallingConv::X86_ThisCall:
15661     case CallingConv::Fast:
15662       // Pass 'nest' parameter in EAX.
15663       // Must be kept in sync with X86CallingConv.td
15664       NestReg = X86::EAX;
15665       break;
15666     }
15667
15668     SDValue OutChains[4];
15669     SDValue Addr, Disp;
15670
15671     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15672                        DAG.getConstant(10, MVT::i32));
15673     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
15674
15675     // This is storing the opcode for MOV32ri.
15676     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
15677     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
15678     OutChains[0] = DAG.getStore(Root, dl,
15679                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
15680                                 Trmp, MachinePointerInfo(TrmpAddr),
15681                                 false, false, 0);
15682
15683     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15684                        DAG.getConstant(1, MVT::i32));
15685     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
15686                                 MachinePointerInfo(TrmpAddr, 1),
15687                                 false, false, 1);
15688
15689     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
15690     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15691                        DAG.getConstant(5, MVT::i32));
15692     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
15693                                 MachinePointerInfo(TrmpAddr, 5),
15694                                 false, false, 1);
15695
15696     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15697                        DAG.getConstant(6, MVT::i32));
15698     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
15699                                 MachinePointerInfo(TrmpAddr, 6),
15700                                 false, false, 1);
15701
15702     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
15703   }
15704 }
15705
15706 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
15707                                             SelectionDAG &DAG) const {
15708   /*
15709    The rounding mode is in bits 11:10 of FPSR, and has the following
15710    settings:
15711      00 Round to nearest
15712      01 Round to -inf
15713      10 Round to +inf
15714      11 Round to 0
15715
15716   FLT_ROUNDS, on the other hand, expects the following:
15717     -1 Undefined
15718      0 Round to 0
15719      1 Round to nearest
15720      2 Round to +inf
15721      3 Round to -inf
15722
15723   To perform the conversion, we do:
15724     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
15725   */
15726
15727   MachineFunction &MF = DAG.getMachineFunction();
15728   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
15729   unsigned StackAlignment = TFI.getStackAlignment();
15730   MVT VT = Op.getSimpleValueType();
15731   SDLoc DL(Op);
15732
15733   // Save FP Control Word to stack slot
15734   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
15735   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
15736
15737   MachineMemOperand *MMO =
15738    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
15739                            MachineMemOperand::MOStore, 2, 2);
15740
15741   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
15742   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
15743                                           DAG.getVTList(MVT::Other),
15744                                           Ops, MVT::i16, MMO);
15745
15746   // Load FP Control Word from stack slot
15747   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
15748                             MachinePointerInfo(), false, false, false, 0);
15749
15750   // Transform as necessary
15751   SDValue CWD1 =
15752     DAG.getNode(ISD::SRL, DL, MVT::i16,
15753                 DAG.getNode(ISD::AND, DL, MVT::i16,
15754                             CWD, DAG.getConstant(0x800, MVT::i16)),
15755                 DAG.getConstant(11, MVT::i8));
15756   SDValue CWD2 =
15757     DAG.getNode(ISD::SRL, DL, MVT::i16,
15758                 DAG.getNode(ISD::AND, DL, MVT::i16,
15759                             CWD, DAG.getConstant(0x400, MVT::i16)),
15760                 DAG.getConstant(9, MVT::i8));
15761
15762   SDValue RetVal =
15763     DAG.getNode(ISD::AND, DL, MVT::i16,
15764                 DAG.getNode(ISD::ADD, DL, MVT::i16,
15765                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
15766                             DAG.getConstant(1, MVT::i16)),
15767                 DAG.getConstant(3, MVT::i16));
15768
15769   return DAG.getNode((VT.getSizeInBits() < 16 ?
15770                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
15771 }
15772
15773 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
15774   MVT VT = Op.getSimpleValueType();
15775   EVT OpVT = VT;
15776   unsigned NumBits = VT.getSizeInBits();
15777   SDLoc dl(Op);
15778
15779   Op = Op.getOperand(0);
15780   if (VT == MVT::i8) {
15781     // Zero extend to i32 since there is not an i8 bsr.
15782     OpVT = MVT::i32;
15783     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
15784   }
15785
15786   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
15787   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
15788   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
15789
15790   // If src is zero (i.e. bsr sets ZF), returns NumBits.
15791   SDValue Ops[] = {
15792     Op,
15793     DAG.getConstant(NumBits+NumBits-1, OpVT),
15794     DAG.getConstant(X86::COND_E, MVT::i8),
15795     Op.getValue(1)
15796   };
15797   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
15798
15799   // Finally xor with NumBits-1.
15800   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
15801
15802   if (VT == MVT::i8)
15803     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
15804   return Op;
15805 }
15806
15807 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
15808   MVT VT = Op.getSimpleValueType();
15809   EVT OpVT = VT;
15810   unsigned NumBits = VT.getSizeInBits();
15811   SDLoc dl(Op);
15812
15813   Op = Op.getOperand(0);
15814   if (VT == MVT::i8) {
15815     // Zero extend to i32 since there is not an i8 bsr.
15816     OpVT = MVT::i32;
15817     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
15818   }
15819
15820   // Issue a bsr (scan bits in reverse).
15821   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
15822   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
15823
15824   // And xor with NumBits-1.
15825   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
15826
15827   if (VT == MVT::i8)
15828     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
15829   return Op;
15830 }
15831
15832 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
15833   MVT VT = Op.getSimpleValueType();
15834   unsigned NumBits = VT.getSizeInBits();
15835   SDLoc dl(Op);
15836   Op = Op.getOperand(0);
15837
15838   // Issue a bsf (scan bits forward) which also sets EFLAGS.
15839   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
15840   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
15841
15842   // If src is zero (i.e. bsf sets ZF), returns NumBits.
15843   SDValue Ops[] = {
15844     Op,
15845     DAG.getConstant(NumBits, VT),
15846     DAG.getConstant(X86::COND_E, MVT::i8),
15847     Op.getValue(1)
15848   };
15849   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
15850 }
15851
15852 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
15853 // ones, and then concatenate the result back.
15854 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
15855   MVT VT = Op.getSimpleValueType();
15856
15857   assert(VT.is256BitVector() && VT.isInteger() &&
15858          "Unsupported value type for operation");
15859
15860   unsigned NumElems = VT.getVectorNumElements();
15861   SDLoc dl(Op);
15862
15863   // Extract the LHS vectors
15864   SDValue LHS = Op.getOperand(0);
15865   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
15866   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
15867
15868   // Extract the RHS vectors
15869   SDValue RHS = Op.getOperand(1);
15870   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
15871   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
15872
15873   MVT EltVT = VT.getVectorElementType();
15874   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
15875
15876   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
15877                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
15878                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
15879 }
15880
15881 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
15882   assert(Op.getSimpleValueType().is256BitVector() &&
15883          Op.getSimpleValueType().isInteger() &&
15884          "Only handle AVX 256-bit vector integer operation");
15885   return Lower256IntArith(Op, DAG);
15886 }
15887
15888 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
15889   assert(Op.getSimpleValueType().is256BitVector() &&
15890          Op.getSimpleValueType().isInteger() &&
15891          "Only handle AVX 256-bit vector integer operation");
15892   return Lower256IntArith(Op, DAG);
15893 }
15894
15895 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
15896                         SelectionDAG &DAG) {
15897   SDLoc dl(Op);
15898   MVT VT = Op.getSimpleValueType();
15899
15900   // Decompose 256-bit ops into smaller 128-bit ops.
15901   if (VT.is256BitVector() && !Subtarget->hasInt256())
15902     return Lower256IntArith(Op, DAG);
15903
15904   SDValue A = Op.getOperand(0);
15905   SDValue B = Op.getOperand(1);
15906
15907   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
15908   if (VT == MVT::v4i32) {
15909     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
15910            "Should not custom lower when pmuldq is available!");
15911
15912     // Extract the odd parts.
15913     static const int UnpackMask[] = { 1, -1, 3, -1 };
15914     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
15915     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
15916
15917     // Multiply the even parts.
15918     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
15919     // Now multiply odd parts.
15920     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
15921
15922     Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
15923     Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
15924
15925     // Merge the two vectors back together with a shuffle. This expands into 2
15926     // shuffles.
15927     static const int ShufMask[] = { 0, 4, 2, 6 };
15928     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
15929   }
15930
15931   assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
15932          "Only know how to lower V2I64/V4I64/V8I64 multiply");
15933
15934   //  Ahi = psrlqi(a, 32);
15935   //  Bhi = psrlqi(b, 32);
15936   //
15937   //  AloBlo = pmuludq(a, b);
15938   //  AloBhi = pmuludq(a, Bhi);
15939   //  AhiBlo = pmuludq(Ahi, b);
15940
15941   //  AloBhi = psllqi(AloBhi, 32);
15942   //  AhiBlo = psllqi(AhiBlo, 32);
15943   //  return AloBlo + AloBhi + AhiBlo;
15944
15945   SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
15946   SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
15947
15948   // Bit cast to 32-bit vectors for MULUDQ
15949   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
15950                                   (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
15951   A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
15952   B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
15953   Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
15954   Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
15955
15956   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
15957   SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
15958   SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
15959
15960   AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
15961   AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
15962
15963   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
15964   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
15965 }
15966
15967 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
15968   assert(Subtarget->isTargetWin64() && "Unexpected target");
15969   EVT VT = Op.getValueType();
15970   assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
15971          "Unexpected return type for lowering");
15972
15973   RTLIB::Libcall LC;
15974   bool isSigned;
15975   switch (Op->getOpcode()) {
15976   default: llvm_unreachable("Unexpected request for libcall!");
15977   case ISD::SDIV:      isSigned = true;  LC = RTLIB::SDIV_I128;    break;
15978   case ISD::UDIV:      isSigned = false; LC = RTLIB::UDIV_I128;    break;
15979   case ISD::SREM:      isSigned = true;  LC = RTLIB::SREM_I128;    break;
15980   case ISD::UREM:      isSigned = false; LC = RTLIB::UREM_I128;    break;
15981   case ISD::SDIVREM:   isSigned = true;  LC = RTLIB::SDIVREM_I128; break;
15982   case ISD::UDIVREM:   isSigned = false; LC = RTLIB::UDIVREM_I128; break;
15983   }
15984
15985   SDLoc dl(Op);
15986   SDValue InChain = DAG.getEntryNode();
15987
15988   TargetLowering::ArgListTy Args;
15989   TargetLowering::ArgListEntry Entry;
15990   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
15991     EVT ArgVT = Op->getOperand(i).getValueType();
15992     assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
15993            "Unexpected argument type for lowering");
15994     SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
15995     Entry.Node = StackPtr;
15996     InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
15997                            false, false, 16);
15998     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
15999     Entry.Ty = PointerType::get(ArgTy,0);
16000     Entry.isSExt = false;
16001     Entry.isZExt = false;
16002     Args.push_back(Entry);
16003   }
16004
16005   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
16006                                          getPointerTy());
16007
16008   TargetLowering::CallLoweringInfo CLI(DAG);
16009   CLI.setDebugLoc(dl).setChain(InChain)
16010     .setCallee(getLibcallCallingConv(LC),
16011                static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
16012                Callee, std::move(Args), 0)
16013     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
16014
16015   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
16016   return DAG.getNode(ISD::BITCAST, dl, VT, CallInfo.first);
16017 }
16018
16019 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
16020                              SelectionDAG &DAG) {
16021   SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
16022   EVT VT = Op0.getValueType();
16023   SDLoc dl(Op);
16024
16025   assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
16026          (VT == MVT::v8i32 && Subtarget->hasInt256()));
16027
16028   // PMULxD operations multiply each even value (starting at 0) of LHS with
16029   // the related value of RHS and produce a widen result.
16030   // E.g., PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
16031   // => <2 x i64> <ae|cg>
16032   //
16033   // In other word, to have all the results, we need to perform two PMULxD:
16034   // 1. one with the even values.
16035   // 2. one with the odd values.
16036   // To achieve #2, with need to place the odd values at an even position.
16037   //
16038   // Place the odd value at an even position (basically, shift all values 1
16039   // step to the left):
16040   const int Mask[] = {1, -1, 3, -1, 5, -1, 7, -1};
16041   // <a|b|c|d> => <b|undef|d|undef>
16042   SDValue Odd0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
16043   // <e|f|g|h> => <f|undef|h|undef>
16044   SDValue Odd1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
16045
16046   // Emit two multiplies, one for the lower 2 ints and one for the higher 2
16047   // ints.
16048   MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
16049   bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
16050   unsigned Opcode =
16051       (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
16052   // PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
16053   // => <2 x i64> <ae|cg>
16054   SDValue Mul1 = DAG.getNode(ISD::BITCAST, dl, VT,
16055                              DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
16056   // PMULUDQ <4 x i32> <b|undef|d|undef>, <4 x i32> <f|undef|h|undef>
16057   // => <2 x i64> <bf|dh>
16058   SDValue Mul2 = DAG.getNode(ISD::BITCAST, dl, VT,
16059                              DAG.getNode(Opcode, dl, MulVT, Odd0, Odd1));
16060
16061   // Shuffle it back into the right order.
16062   SDValue Highs, Lows;
16063   if (VT == MVT::v8i32) {
16064     const int HighMask[] = {1, 9, 3, 11, 5, 13, 7, 15};
16065     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
16066     const int LowMask[] = {0, 8, 2, 10, 4, 12, 6, 14};
16067     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
16068   } else {
16069     const int HighMask[] = {1, 5, 3, 7};
16070     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
16071     const int LowMask[] = {0, 4, 2, 6};
16072     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
16073   }
16074
16075   // If we have a signed multiply but no PMULDQ fix up the high parts of a
16076   // unsigned multiply.
16077   if (IsSigned && !Subtarget->hasSSE41()) {
16078     SDValue ShAmt =
16079         DAG.getConstant(31, DAG.getTargetLoweringInfo().getShiftAmountTy(VT));
16080     SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
16081                              DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
16082     SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
16083                              DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
16084
16085     SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
16086     Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
16087   }
16088
16089   // The first result of MUL_LOHI is actually the low value, followed by the
16090   // high value.
16091   SDValue Ops[] = {Lows, Highs};
16092   return DAG.getMergeValues(Ops, dl);
16093 }
16094
16095 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
16096                                          const X86Subtarget *Subtarget) {
16097   MVT VT = Op.getSimpleValueType();
16098   SDLoc dl(Op);
16099   SDValue R = Op.getOperand(0);
16100   SDValue Amt = Op.getOperand(1);
16101
16102   // Optimize shl/srl/sra with constant shift amount.
16103   if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
16104     if (auto *ShiftConst = BVAmt->getConstantSplatNode()) {
16105       uint64_t ShiftAmt = ShiftConst->getZExtValue();
16106
16107       if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
16108           (Subtarget->hasInt256() &&
16109            (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16)) ||
16110           (Subtarget->hasAVX512() &&
16111            (VT == MVT::v8i64 || VT == MVT::v16i32))) {
16112         if (Op.getOpcode() == ISD::SHL)
16113           return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
16114                                             DAG);
16115         if (Op.getOpcode() == ISD::SRL)
16116           return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
16117                                             DAG);
16118         if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
16119           return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
16120                                             DAG);
16121       }
16122
16123       if (VT == MVT::v16i8 || (Subtarget->hasInt256() && VT == MVT::v32i8)) {
16124         unsigned NumElts = VT.getVectorNumElements();
16125         MVT ShiftVT = MVT::getVectorVT(MVT::i16, NumElts / 2);
16126
16127         if (Op.getOpcode() == ISD::SHL) {
16128           // Make a large shift.
16129           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, ShiftVT,
16130                                                    R, ShiftAmt, DAG);
16131           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
16132           // Zero out the rightmost bits.
16133           SmallVector<SDValue, 32> V(
16134               NumElts, DAG.getConstant(uint8_t(-1U << ShiftAmt), MVT::i8));
16135           return DAG.getNode(ISD::AND, dl, VT, SHL,
16136                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
16137         }
16138         if (Op.getOpcode() == ISD::SRL) {
16139           // Make a large shift.
16140           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ShiftVT,
16141                                                    R, ShiftAmt, DAG);
16142           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
16143           // Zero out the leftmost bits.
16144           SmallVector<SDValue, 32> V(
16145               NumElts, DAG.getConstant(uint8_t(-1U) >> ShiftAmt, MVT::i8));
16146           return DAG.getNode(ISD::AND, dl, VT, SRL,
16147                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
16148         }
16149         if (Op.getOpcode() == ISD::SRA) {
16150           if (ShiftAmt == 7) {
16151             // R s>> 7  ===  R s< 0
16152             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
16153             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
16154           }
16155
16156           // R s>> a === ((R u>> a) ^ m) - m
16157           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
16158           SmallVector<SDValue, 32> V(NumElts,
16159                                      DAG.getConstant(128 >> ShiftAmt, MVT::i8));
16160           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
16161           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
16162           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
16163           return Res;
16164         }
16165         llvm_unreachable("Unknown shift opcode.");
16166       }
16167     }
16168   }
16169
16170   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
16171   if (!Subtarget->is64Bit() &&
16172       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
16173       Amt.getOpcode() == ISD::BITCAST &&
16174       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
16175     Amt = Amt.getOperand(0);
16176     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
16177                      VT.getVectorNumElements();
16178     unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
16179     uint64_t ShiftAmt = 0;
16180     for (unsigned i = 0; i != Ratio; ++i) {
16181       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
16182       if (!C)
16183         return SDValue();
16184       // 6 == Log2(64)
16185       ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
16186     }
16187     // Check remaining shift amounts.
16188     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
16189       uint64_t ShAmt = 0;
16190       for (unsigned j = 0; j != Ratio; ++j) {
16191         ConstantSDNode *C =
16192           dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
16193         if (!C)
16194           return SDValue();
16195         // 6 == Log2(64)
16196         ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
16197       }
16198       if (ShAmt != ShiftAmt)
16199         return SDValue();
16200     }
16201     switch (Op.getOpcode()) {
16202     default:
16203       llvm_unreachable("Unknown shift opcode!");
16204     case ISD::SHL:
16205       return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
16206                                         DAG);
16207     case ISD::SRL:
16208       return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
16209                                         DAG);
16210     case ISD::SRA:
16211       return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
16212                                         DAG);
16213     }
16214   }
16215
16216   return SDValue();
16217 }
16218
16219 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
16220                                         const X86Subtarget* Subtarget) {
16221   MVT VT = Op.getSimpleValueType();
16222   SDLoc dl(Op);
16223   SDValue R = Op.getOperand(0);
16224   SDValue Amt = Op.getOperand(1);
16225
16226   if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
16227       VT == MVT::v4i32 || VT == MVT::v8i16 ||
16228       (Subtarget->hasInt256() &&
16229        ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
16230         VT == MVT::v8i32 || VT == MVT::v16i16)) ||
16231        (Subtarget->hasAVX512() && (VT == MVT::v8i64 || VT == MVT::v16i32))) {
16232     SDValue BaseShAmt;
16233     EVT EltVT = VT.getVectorElementType();
16234
16235     if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Amt)) {
16236       // Check if this build_vector node is doing a splat.
16237       // If so, then set BaseShAmt equal to the splat value.
16238       BaseShAmt = BV->getSplatValue();
16239       if (BaseShAmt && BaseShAmt.getOpcode() == ISD::UNDEF)
16240         BaseShAmt = SDValue();
16241     } else {
16242       if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
16243         Amt = Amt.getOperand(0);
16244
16245       ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(Amt);
16246       if (SVN && SVN->isSplat()) {
16247         unsigned SplatIdx = (unsigned)SVN->getSplatIndex();
16248         SDValue InVec = Amt.getOperand(0);
16249         if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
16250           assert((SplatIdx < InVec.getValueType().getVectorNumElements()) &&
16251                  "Unexpected shuffle index found!");
16252           BaseShAmt = InVec.getOperand(SplatIdx);
16253         } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
16254            if (ConstantSDNode *C =
16255                dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
16256              if (C->getZExtValue() == SplatIdx)
16257                BaseShAmt = InVec.getOperand(1);
16258            }
16259         }
16260
16261         if (!BaseShAmt)
16262           // Avoid introducing an extract element from a shuffle.
16263           BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, InVec,
16264                                     DAG.getIntPtrConstant(SplatIdx));
16265       }
16266     }
16267
16268     if (BaseShAmt.getNode()) {
16269       assert(EltVT.bitsLE(MVT::i64) && "Unexpected element type!");
16270       if (EltVT != MVT::i64 && EltVT.bitsGT(MVT::i32))
16271         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, BaseShAmt);
16272       else if (EltVT.bitsLT(MVT::i32))
16273         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
16274
16275       switch (Op.getOpcode()) {
16276       default:
16277         llvm_unreachable("Unknown shift opcode!");
16278       case ISD::SHL:
16279         switch (VT.SimpleTy) {
16280         default: return SDValue();
16281         case MVT::v2i64:
16282         case MVT::v4i32:
16283         case MVT::v8i16:
16284         case MVT::v4i64:
16285         case MVT::v8i32:
16286         case MVT::v16i16:
16287         case MVT::v16i32:
16288         case MVT::v8i64:
16289           return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
16290         }
16291       case ISD::SRA:
16292         switch (VT.SimpleTy) {
16293         default: return SDValue();
16294         case MVT::v4i32:
16295         case MVT::v8i16:
16296         case MVT::v8i32:
16297         case MVT::v16i16:
16298         case MVT::v16i32:
16299         case MVT::v8i64:
16300           return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
16301         }
16302       case ISD::SRL:
16303         switch (VT.SimpleTy) {
16304         default: return SDValue();
16305         case MVT::v2i64:
16306         case MVT::v4i32:
16307         case MVT::v8i16:
16308         case MVT::v4i64:
16309         case MVT::v8i32:
16310         case MVT::v16i16:
16311         case MVT::v16i32:
16312         case MVT::v8i64:
16313           return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
16314         }
16315       }
16316     }
16317   }
16318
16319   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
16320   if (!Subtarget->is64Bit() &&
16321       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64) ||
16322       (Subtarget->hasAVX512() && VT == MVT::v8i64)) &&
16323       Amt.getOpcode() == ISD::BITCAST &&
16324       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
16325     Amt = Amt.getOperand(0);
16326     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
16327                      VT.getVectorNumElements();
16328     std::vector<SDValue> Vals(Ratio);
16329     for (unsigned i = 0; i != Ratio; ++i)
16330       Vals[i] = Amt.getOperand(i);
16331     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
16332       for (unsigned j = 0; j != Ratio; ++j)
16333         if (Vals[j] != Amt.getOperand(i + j))
16334           return SDValue();
16335     }
16336     switch (Op.getOpcode()) {
16337     default:
16338       llvm_unreachable("Unknown shift opcode!");
16339     case ISD::SHL:
16340       return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
16341     case ISD::SRL:
16342       return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
16343     case ISD::SRA:
16344       return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
16345     }
16346   }
16347
16348   return SDValue();
16349 }
16350
16351 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
16352                           SelectionDAG &DAG) {
16353   MVT VT = Op.getSimpleValueType();
16354   SDLoc dl(Op);
16355   SDValue R = Op.getOperand(0);
16356   SDValue Amt = Op.getOperand(1);
16357
16358   assert(VT.isVector() && "Custom lowering only for vector shifts!");
16359   assert(Subtarget->hasSSE2() && "Only custom lower when we have SSE2!");
16360
16361   if (SDValue V = LowerScalarImmediateShift(Op, DAG, Subtarget))
16362     return V;
16363
16364   if (SDValue V = LowerScalarVariableShift(Op, DAG, Subtarget))
16365       return V;
16366
16367   if (Subtarget->hasAVX512() && (VT == MVT::v16i32 || VT == MVT::v8i64))
16368     return Op;
16369
16370   // AVX2 has VPSLLV/VPSRAV/VPSRLV.
16371   if (Subtarget->hasInt256()) {
16372     if (Op.getOpcode() == ISD::SRL &&
16373         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
16374          VT == MVT::v4i64 || VT == MVT::v8i32))
16375       return Op;
16376     if (Op.getOpcode() == ISD::SHL &&
16377         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
16378          VT == MVT::v4i64 || VT == MVT::v8i32))
16379       return Op;
16380     if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
16381       return Op;
16382   }
16383
16384   // 2i64 vector logical shifts can efficiently avoid scalarization - do the
16385   // shifts per-lane and then shuffle the partial results back together.
16386   if (VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) {
16387     // Splat the shift amounts so the scalar shifts above will catch it.
16388     SDValue Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {0, 0});
16389     SDValue Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {1, 1});
16390     SDValue R0 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt0);
16391     SDValue R1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt1);
16392     return DAG.getVectorShuffle(VT, dl, R0, R1, {0, 3});
16393   }
16394
16395   // If possible, lower this packed shift into a vector multiply instead of
16396   // expanding it into a sequence of scalar shifts.
16397   // Do this only if the vector shift count is a constant build_vector.
16398   if (Op.getOpcode() == ISD::SHL &&
16399       (VT == MVT::v8i16 || VT == MVT::v4i32 ||
16400        (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
16401       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
16402     SmallVector<SDValue, 8> Elts;
16403     EVT SVT = VT.getScalarType();
16404     unsigned SVTBits = SVT.getSizeInBits();
16405     const APInt &One = APInt(SVTBits, 1);
16406     unsigned NumElems = VT.getVectorNumElements();
16407
16408     for (unsigned i=0; i !=NumElems; ++i) {
16409       SDValue Op = Amt->getOperand(i);
16410       if (Op->getOpcode() == ISD::UNDEF) {
16411         Elts.push_back(Op);
16412         continue;
16413       }
16414
16415       ConstantSDNode *ND = cast<ConstantSDNode>(Op);
16416       const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
16417       uint64_t ShAmt = C.getZExtValue();
16418       if (ShAmt >= SVTBits) {
16419         Elts.push_back(DAG.getUNDEF(SVT));
16420         continue;
16421       }
16422       Elts.push_back(DAG.getConstant(One.shl(ShAmt), SVT));
16423     }
16424     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
16425     return DAG.getNode(ISD::MUL, dl, VT, R, BV);
16426   }
16427
16428   // Lower SHL with variable shift amount.
16429   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
16430     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
16431
16432     Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
16433     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
16434     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
16435     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
16436   }
16437
16438   // If possible, lower this shift as a sequence of two shifts by
16439   // constant plus a MOVSS/MOVSD instead of scalarizing it.
16440   // Example:
16441   //   (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
16442   //
16443   // Could be rewritten as:
16444   //   (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
16445   //
16446   // The advantage is that the two shifts from the example would be
16447   // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
16448   // the vector shift into four scalar shifts plus four pairs of vector
16449   // insert/extract.
16450   if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
16451       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
16452     unsigned TargetOpcode = X86ISD::MOVSS;
16453     bool CanBeSimplified;
16454     // The splat value for the first packed shift (the 'X' from the example).
16455     SDValue Amt1 = Amt->getOperand(0);
16456     // The splat value for the second packed shift (the 'Y' from the example).
16457     SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
16458                                         Amt->getOperand(2);
16459
16460     // See if it is possible to replace this node with a sequence of
16461     // two shifts followed by a MOVSS/MOVSD
16462     if (VT == MVT::v4i32) {
16463       // Check if it is legal to use a MOVSS.
16464       CanBeSimplified = Amt2 == Amt->getOperand(2) &&
16465                         Amt2 == Amt->getOperand(3);
16466       if (!CanBeSimplified) {
16467         // Otherwise, check if we can still simplify this node using a MOVSD.
16468         CanBeSimplified = Amt1 == Amt->getOperand(1) &&
16469                           Amt->getOperand(2) == Amt->getOperand(3);
16470         TargetOpcode = X86ISD::MOVSD;
16471         Amt2 = Amt->getOperand(2);
16472       }
16473     } else {
16474       // Do similar checks for the case where the machine value type
16475       // is MVT::v8i16.
16476       CanBeSimplified = Amt1 == Amt->getOperand(1);
16477       for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
16478         CanBeSimplified = Amt2 == Amt->getOperand(i);
16479
16480       if (!CanBeSimplified) {
16481         TargetOpcode = X86ISD::MOVSD;
16482         CanBeSimplified = true;
16483         Amt2 = Amt->getOperand(4);
16484         for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
16485           CanBeSimplified = Amt1 == Amt->getOperand(i);
16486         for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
16487           CanBeSimplified = Amt2 == Amt->getOperand(j);
16488       }
16489     }
16490
16491     if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
16492         isa<ConstantSDNode>(Amt2)) {
16493       // Replace this node with two shifts followed by a MOVSS/MOVSD.
16494       EVT CastVT = MVT::v4i32;
16495       SDValue Splat1 =
16496         DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), VT);
16497       SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
16498       SDValue Splat2 =
16499         DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), VT);
16500       SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
16501       if (TargetOpcode == X86ISD::MOVSD)
16502         CastVT = MVT::v2i64;
16503       SDValue BitCast1 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift1);
16504       SDValue BitCast2 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift2);
16505       SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
16506                                             BitCast1, DAG);
16507       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
16508     }
16509   }
16510
16511   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
16512     assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
16513
16514     // a = a << 5;
16515     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
16516     Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
16517
16518     // Turn 'a' into a mask suitable for VSELECT
16519     SDValue VSelM = DAG.getConstant(0x80, VT);
16520     SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
16521     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
16522
16523     SDValue CM1 = DAG.getConstant(0x0f, VT);
16524     SDValue CM2 = DAG.getConstant(0x3f, VT);
16525
16526     // r = VSELECT(r, psllw(r & (char16)15, 4), a);
16527     SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
16528     M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 4, DAG);
16529     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
16530     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
16531
16532     // a += a
16533     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
16534     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
16535     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
16536
16537     // r = VSELECT(r, psllw(r & (char16)63, 2), a);
16538     M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
16539     M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 2, DAG);
16540     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
16541     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
16542
16543     // a += a
16544     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
16545     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
16546     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
16547
16548     // return VSELECT(r, r+r, a);
16549     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
16550                     DAG.getNode(ISD::ADD, dl, VT, R, R), R);
16551     return R;
16552   }
16553
16554   // It's worth extending once and using the v8i32 shifts for 16-bit types, but
16555   // the extra overheads to get from v16i8 to v8i32 make the existing SSE
16556   // solution better.
16557   if (Subtarget->hasInt256() && VT == MVT::v8i16) {
16558     MVT NewVT = VT == MVT::v8i16 ? MVT::v8i32 : MVT::v16i16;
16559     unsigned ExtOpc =
16560         Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
16561     R = DAG.getNode(ExtOpc, dl, NewVT, R);
16562     Amt = DAG.getNode(ISD::ANY_EXTEND, dl, NewVT, Amt);
16563     return DAG.getNode(ISD::TRUNCATE, dl, VT,
16564                        DAG.getNode(Op.getOpcode(), dl, NewVT, R, Amt));
16565   }
16566
16567   // Decompose 256-bit shifts into smaller 128-bit shifts.
16568   if (VT.is256BitVector()) {
16569     unsigned NumElems = VT.getVectorNumElements();
16570     MVT EltVT = VT.getVectorElementType();
16571     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
16572
16573     // Extract the two vectors
16574     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
16575     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
16576
16577     // Recreate the shift amount vectors
16578     SDValue Amt1, Amt2;
16579     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
16580       // Constant shift amount
16581       SmallVector<SDValue, 8> Ops(Amt->op_begin(), Amt->op_begin() + NumElems);
16582       ArrayRef<SDValue> Amt1Csts = makeArrayRef(Ops).slice(0, NumElems / 2);
16583       ArrayRef<SDValue> Amt2Csts = makeArrayRef(Ops).slice(NumElems / 2);
16584
16585       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
16586       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
16587     } else {
16588       // Variable shift amount
16589       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
16590       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
16591     }
16592
16593     // Issue new vector shifts for the smaller types
16594     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
16595     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
16596
16597     // Concatenate the result back
16598     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
16599   }
16600
16601   return SDValue();
16602 }
16603
16604 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
16605   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
16606   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
16607   // looks for this combo and may remove the "setcc" instruction if the "setcc"
16608   // has only one use.
16609   SDNode *N = Op.getNode();
16610   SDValue LHS = N->getOperand(0);
16611   SDValue RHS = N->getOperand(1);
16612   unsigned BaseOp = 0;
16613   unsigned Cond = 0;
16614   SDLoc DL(Op);
16615   switch (Op.getOpcode()) {
16616   default: llvm_unreachable("Unknown ovf instruction!");
16617   case ISD::SADDO:
16618     // A subtract of one will be selected as a INC. Note that INC doesn't
16619     // set CF, so we can't do this for UADDO.
16620     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
16621       if (C->isOne()) {
16622         BaseOp = X86ISD::INC;
16623         Cond = X86::COND_O;
16624         break;
16625       }
16626     BaseOp = X86ISD::ADD;
16627     Cond = X86::COND_O;
16628     break;
16629   case ISD::UADDO:
16630     BaseOp = X86ISD::ADD;
16631     Cond = X86::COND_B;
16632     break;
16633   case ISD::SSUBO:
16634     // A subtract of one will be selected as a DEC. Note that DEC doesn't
16635     // set CF, so we can't do this for USUBO.
16636     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
16637       if (C->isOne()) {
16638         BaseOp = X86ISD::DEC;
16639         Cond = X86::COND_O;
16640         break;
16641       }
16642     BaseOp = X86ISD::SUB;
16643     Cond = X86::COND_O;
16644     break;
16645   case ISD::USUBO:
16646     BaseOp = X86ISD::SUB;
16647     Cond = X86::COND_B;
16648     break;
16649   case ISD::SMULO:
16650     BaseOp = N->getValueType(0) == MVT::i8 ? X86ISD::SMUL8 : X86ISD::SMUL;
16651     Cond = X86::COND_O;
16652     break;
16653   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
16654     if (N->getValueType(0) == MVT::i8) {
16655       BaseOp = X86ISD::UMUL8;
16656       Cond = X86::COND_O;
16657       break;
16658     }
16659     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
16660                                  MVT::i32);
16661     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
16662
16663     SDValue SetCC =
16664       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
16665                   DAG.getConstant(X86::COND_O, MVT::i32),
16666                   SDValue(Sum.getNode(), 2));
16667
16668     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
16669   }
16670   }
16671
16672   // Also sets EFLAGS.
16673   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
16674   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
16675
16676   SDValue SetCC =
16677     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
16678                 DAG.getConstant(Cond, MVT::i32),
16679                 SDValue(Sum.getNode(), 1));
16680
16681   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
16682 }
16683
16684 /// Returns true if the operand type is exactly twice the native width, and
16685 /// the corresponding cmpxchg8b or cmpxchg16b instruction is available.
16686 /// Used to know whether to use cmpxchg8/16b when expanding atomic operations
16687 /// (otherwise we leave them alone to become __sync_fetch_and_... calls).
16688 bool X86TargetLowering::needsCmpXchgNb(const Type *MemType) const {
16689   unsigned OpWidth = MemType->getPrimitiveSizeInBits();
16690
16691   if (OpWidth == 64)
16692     return !Subtarget->is64Bit(); // FIXME this should be Subtarget.hasCmpxchg8b
16693   else if (OpWidth == 128)
16694     return Subtarget->hasCmpxchg16b();
16695   else
16696     return false;
16697 }
16698
16699 bool X86TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
16700   return needsCmpXchgNb(SI->getValueOperand()->getType());
16701 }
16702
16703 // Note: this turns large loads into lock cmpxchg8b/16b.
16704 // FIXME: On 32 bits x86, fild/movq might be faster than lock cmpxchg8b.
16705 bool X86TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
16706   auto PTy = cast<PointerType>(LI->getPointerOperand()->getType());
16707   return needsCmpXchgNb(PTy->getElementType());
16708 }
16709
16710 TargetLoweringBase::AtomicRMWExpansionKind
16711 X86TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
16712   unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
16713   const Type *MemType = AI->getType();
16714
16715   // If the operand is too big, we must see if cmpxchg8/16b is available
16716   // and default to library calls otherwise.
16717   if (MemType->getPrimitiveSizeInBits() > NativeWidth) {
16718     return needsCmpXchgNb(MemType) ? AtomicRMWExpansionKind::CmpXChg
16719                                    : AtomicRMWExpansionKind::None;
16720   }
16721
16722   AtomicRMWInst::BinOp Op = AI->getOperation();
16723   switch (Op) {
16724   default:
16725     llvm_unreachable("Unknown atomic operation");
16726   case AtomicRMWInst::Xchg:
16727   case AtomicRMWInst::Add:
16728   case AtomicRMWInst::Sub:
16729     // It's better to use xadd, xsub or xchg for these in all cases.
16730     return AtomicRMWExpansionKind::None;
16731   case AtomicRMWInst::Or:
16732   case AtomicRMWInst::And:
16733   case AtomicRMWInst::Xor:
16734     // If the atomicrmw's result isn't actually used, we can just add a "lock"
16735     // prefix to a normal instruction for these operations.
16736     return !AI->use_empty() ? AtomicRMWExpansionKind::CmpXChg
16737                             : AtomicRMWExpansionKind::None;
16738   case AtomicRMWInst::Nand:
16739   case AtomicRMWInst::Max:
16740   case AtomicRMWInst::Min:
16741   case AtomicRMWInst::UMax:
16742   case AtomicRMWInst::UMin:
16743     // These always require a non-trivial set of data operations on x86. We must
16744     // use a cmpxchg loop.
16745     return AtomicRMWExpansionKind::CmpXChg;
16746   }
16747 }
16748
16749 static bool hasMFENCE(const X86Subtarget& Subtarget) {
16750   // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
16751   // no-sse2). There isn't any reason to disable it if the target processor
16752   // supports it.
16753   return Subtarget.hasSSE2() || Subtarget.is64Bit();
16754 }
16755
16756 LoadInst *
16757 X86TargetLowering::lowerIdempotentRMWIntoFencedLoad(AtomicRMWInst *AI) const {
16758   unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
16759   const Type *MemType = AI->getType();
16760   // Accesses larger than the native width are turned into cmpxchg/libcalls, so
16761   // there is no benefit in turning such RMWs into loads, and it is actually
16762   // harmful as it introduces a mfence.
16763   if (MemType->getPrimitiveSizeInBits() > NativeWidth)
16764     return nullptr;
16765
16766   auto Builder = IRBuilder<>(AI);
16767   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
16768   auto SynchScope = AI->getSynchScope();
16769   // We must restrict the ordering to avoid generating loads with Release or
16770   // ReleaseAcquire orderings.
16771   auto Order = AtomicCmpXchgInst::getStrongestFailureOrdering(AI->getOrdering());
16772   auto Ptr = AI->getPointerOperand();
16773
16774   // Before the load we need a fence. Here is an example lifted from
16775   // http://www.hpl.hp.com/techreports/2012/HPL-2012-68.pdf showing why a fence
16776   // is required:
16777   // Thread 0:
16778   //   x.store(1, relaxed);
16779   //   r1 = y.fetch_add(0, release);
16780   // Thread 1:
16781   //   y.fetch_add(42, acquire);
16782   //   r2 = x.load(relaxed);
16783   // r1 = r2 = 0 is impossible, but becomes possible if the idempotent rmw is
16784   // lowered to just a load without a fence. A mfence flushes the store buffer,
16785   // making the optimization clearly correct.
16786   // FIXME: it is required if isAtLeastRelease(Order) but it is not clear
16787   // otherwise, we might be able to be more agressive on relaxed idempotent
16788   // rmw. In practice, they do not look useful, so we don't try to be
16789   // especially clever.
16790   if (SynchScope == SingleThread) {
16791     // FIXME: we could just insert an X86ISD::MEMBARRIER here, except we are at
16792     // the IR level, so we must wrap it in an intrinsic.
16793     return nullptr;
16794   } else if (hasMFENCE(*Subtarget)) {
16795     Function *MFence = llvm::Intrinsic::getDeclaration(M,
16796             Intrinsic::x86_sse2_mfence);
16797     Builder.CreateCall(MFence);
16798   } else {
16799     // FIXME: it might make sense to use a locked operation here but on a
16800     // different cache-line to prevent cache-line bouncing. In practice it
16801     // is probably a small win, and x86 processors without mfence are rare
16802     // enough that we do not bother.
16803     return nullptr;
16804   }
16805
16806   // Finally we can emit the atomic load.
16807   LoadInst *Loaded = Builder.CreateAlignedLoad(Ptr,
16808           AI->getType()->getPrimitiveSizeInBits());
16809   Loaded->setAtomic(Order, SynchScope);
16810   AI->replaceAllUsesWith(Loaded);
16811   AI->eraseFromParent();
16812   return Loaded;
16813 }
16814
16815 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
16816                                  SelectionDAG &DAG) {
16817   SDLoc dl(Op);
16818   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
16819     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
16820   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
16821     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
16822
16823   // The only fence that needs an instruction is a sequentially-consistent
16824   // cross-thread fence.
16825   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
16826     if (hasMFENCE(*Subtarget))
16827       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
16828
16829     SDValue Chain = Op.getOperand(0);
16830     SDValue Zero = DAG.getConstant(0, MVT::i32);
16831     SDValue Ops[] = {
16832       DAG.getRegister(X86::ESP, MVT::i32), // Base
16833       DAG.getTargetConstant(1, MVT::i8),   // Scale
16834       DAG.getRegister(0, MVT::i32),        // Index
16835       DAG.getTargetConstant(0, MVT::i32),  // Disp
16836       DAG.getRegister(0, MVT::i32),        // Segment.
16837       Zero,
16838       Chain
16839     };
16840     SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
16841     return SDValue(Res, 0);
16842   }
16843
16844   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
16845   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
16846 }
16847
16848 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
16849                              SelectionDAG &DAG) {
16850   MVT T = Op.getSimpleValueType();
16851   SDLoc DL(Op);
16852   unsigned Reg = 0;
16853   unsigned size = 0;
16854   switch(T.SimpleTy) {
16855   default: llvm_unreachable("Invalid value type!");
16856   case MVT::i8:  Reg = X86::AL;  size = 1; break;
16857   case MVT::i16: Reg = X86::AX;  size = 2; break;
16858   case MVT::i32: Reg = X86::EAX; size = 4; break;
16859   case MVT::i64:
16860     assert(Subtarget->is64Bit() && "Node not type legal!");
16861     Reg = X86::RAX; size = 8;
16862     break;
16863   }
16864   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
16865                                   Op.getOperand(2), SDValue());
16866   SDValue Ops[] = { cpIn.getValue(0),
16867                     Op.getOperand(1),
16868                     Op.getOperand(3),
16869                     DAG.getTargetConstant(size, MVT::i8),
16870                     cpIn.getValue(1) };
16871   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
16872   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
16873   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
16874                                            Ops, T, MMO);
16875
16876   SDValue cpOut =
16877     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
16878   SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
16879                                       MVT::i32, cpOut.getValue(2));
16880   SDValue Success = DAG.getNode(X86ISD::SETCC, DL, Op->getValueType(1),
16881                                 DAG.getConstant(X86::COND_E, MVT::i8), EFLAGS);
16882
16883   DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), cpOut);
16884   DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
16885   DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), EFLAGS.getValue(1));
16886   return SDValue();
16887 }
16888
16889 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
16890                             SelectionDAG &DAG) {
16891   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
16892   MVT DstVT = Op.getSimpleValueType();
16893
16894   if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
16895     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
16896     if (DstVT != MVT::f64)
16897       // This conversion needs to be expanded.
16898       return SDValue();
16899
16900     SDValue InVec = Op->getOperand(0);
16901     SDLoc dl(Op);
16902     unsigned NumElts = SrcVT.getVectorNumElements();
16903     EVT SVT = SrcVT.getVectorElementType();
16904
16905     // Widen the vector in input in the case of MVT::v2i32.
16906     // Example: from MVT::v2i32 to MVT::v4i32.
16907     SmallVector<SDValue, 16> Elts;
16908     for (unsigned i = 0, e = NumElts; i != e; ++i)
16909       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
16910                                  DAG.getIntPtrConstant(i)));
16911
16912     // Explicitly mark the extra elements as Undef.
16913     Elts.append(NumElts, DAG.getUNDEF(SVT));
16914
16915     EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
16916     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
16917     SDValue ToV2F64 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, BV);
16918     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
16919                        DAG.getIntPtrConstant(0));
16920   }
16921
16922   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
16923          Subtarget->hasMMX() && "Unexpected custom BITCAST");
16924   assert((DstVT == MVT::i64 ||
16925           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
16926          "Unexpected custom BITCAST");
16927   // i64 <=> MMX conversions are Legal.
16928   if (SrcVT==MVT::i64 && DstVT.isVector())
16929     return Op;
16930   if (DstVT==MVT::i64 && SrcVT.isVector())
16931     return Op;
16932   // MMX <=> MMX conversions are Legal.
16933   if (SrcVT.isVector() && DstVT.isVector())
16934     return Op;
16935   // All other conversions need to be expanded.
16936   return SDValue();
16937 }
16938
16939 static SDValue LowerCTPOP(SDValue Op, const X86Subtarget *Subtarget,
16940                           SelectionDAG &DAG) {
16941   SDNode *Node = Op.getNode();
16942   SDLoc dl(Node);
16943
16944   Op = Op.getOperand(0);
16945   EVT VT = Op.getValueType();
16946   assert((VT.is128BitVector() || VT.is256BitVector()) &&
16947          "CTPOP lowering only implemented for 128/256-bit wide vector types");
16948
16949   unsigned NumElts = VT.getVectorNumElements();
16950   EVT EltVT = VT.getVectorElementType();
16951   unsigned Len = EltVT.getSizeInBits();
16952
16953   // This is the vectorized version of the "best" algorithm from
16954   // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
16955   // with a minor tweak to use a series of adds + shifts instead of vector
16956   // multiplications. Implemented for the v2i64, v4i64, v4i32, v8i32 types:
16957   //
16958   //  v2i64, v4i64, v4i32 => Only profitable w/ popcnt disabled
16959   //  v8i32 => Always profitable
16960   //
16961   // FIXME: There a couple of possible improvements:
16962   //
16963   // 1) Support for i8 and i16 vectors (needs measurements if popcnt enabled).
16964   // 2) Use strategies from http://wm.ite.pl/articles/sse-popcount.html
16965   //
16966   assert(EltVT.isInteger() && (Len == 32 || Len == 64) && Len % 8 == 0 &&
16967          "CTPOP not implemented for this vector element type.");
16968
16969   // X86 canonicalize ANDs to vXi64, generate the appropriate bitcasts to avoid
16970   // extra legalization.
16971   bool NeedsBitcast = EltVT == MVT::i32;
16972   MVT BitcastVT = VT.is256BitVector() ? MVT::v4i64 : MVT::v2i64;
16973
16974   SDValue Cst55 = DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x55)), EltVT);
16975   SDValue Cst33 = DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x33)), EltVT);
16976   SDValue Cst0F = DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x0F)), EltVT);
16977
16978   // v = v - ((v >> 1) & 0x55555555...)
16979   SmallVector<SDValue, 8> Ones(NumElts, DAG.getConstant(1, EltVT));
16980   SDValue OnesV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ones);
16981   SDValue Srl = DAG.getNode(ISD::SRL, dl, VT, Op, OnesV);
16982   if (NeedsBitcast)
16983     Srl = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Srl);
16984
16985   SmallVector<SDValue, 8> Mask55(NumElts, Cst55);
16986   SDValue M55 = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Mask55);
16987   if (NeedsBitcast)
16988     M55 = DAG.getNode(ISD::BITCAST, dl, BitcastVT, M55);
16989
16990   SDValue And = DAG.getNode(ISD::AND, dl, Srl.getValueType(), Srl, M55);
16991   if (VT != And.getValueType())
16992     And = DAG.getNode(ISD::BITCAST, dl, VT, And);
16993   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, Op, And);
16994
16995   // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...)
16996   SmallVector<SDValue, 8> Mask33(NumElts, Cst33);
16997   SDValue M33 = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Mask33);
16998   SmallVector<SDValue, 8> Twos(NumElts, DAG.getConstant(2, EltVT));
16999   SDValue TwosV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Twos);
17000
17001   Srl = DAG.getNode(ISD::SRL, dl, VT, Sub, TwosV);
17002   if (NeedsBitcast) {
17003     Srl = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Srl);
17004     M33 = DAG.getNode(ISD::BITCAST, dl, BitcastVT, M33);
17005     Sub = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Sub);
17006   }
17007
17008   SDValue AndRHS = DAG.getNode(ISD::AND, dl, M33.getValueType(), Srl, M33);
17009   SDValue AndLHS = DAG.getNode(ISD::AND, dl, M33.getValueType(), Sub, M33);
17010   if (VT != AndRHS.getValueType()) {
17011     AndRHS = DAG.getNode(ISD::BITCAST, dl, VT, AndRHS);
17012     AndLHS = DAG.getNode(ISD::BITCAST, dl, VT, AndLHS);
17013   }
17014   SDValue Add = DAG.getNode(ISD::ADD, dl, VT, AndLHS, AndRHS);
17015
17016   // v = (v + (v >> 4)) & 0x0F0F0F0F...
17017   SmallVector<SDValue, 8> Fours(NumElts, DAG.getConstant(4, EltVT));
17018   SDValue FoursV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Fours);
17019   Srl = DAG.getNode(ISD::SRL, dl, VT, Add, FoursV);
17020   Add = DAG.getNode(ISD::ADD, dl, VT, Add, Srl);
17021
17022   SmallVector<SDValue, 8> Mask0F(NumElts, Cst0F);
17023   SDValue M0F = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Mask0F);
17024   if (NeedsBitcast) {
17025     Add = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Add);
17026     M0F = DAG.getNode(ISD::BITCAST, dl, BitcastVT, M0F);
17027   }
17028   And = DAG.getNode(ISD::AND, dl, M0F.getValueType(), Add, M0F);
17029   if (VT != And.getValueType())
17030     And = DAG.getNode(ISD::BITCAST, dl, VT, And);
17031
17032   // The algorithm mentioned above uses:
17033   //    v = (v * 0x01010101...) >> (Len - 8)
17034   //
17035   // Change it to use vector adds + vector shifts which yield faster results on
17036   // Haswell than using vector integer multiplication.
17037   //
17038   // For i32 elements:
17039   //    v = v + (v >> 8)
17040   //    v = v + (v >> 16)
17041   //
17042   // For i64 elements:
17043   //    v = v + (v >> 8)
17044   //    v = v + (v >> 16)
17045   //    v = v + (v >> 32)
17046   //
17047   Add = And;
17048   SmallVector<SDValue, 8> Csts;
17049   for (unsigned i = 8; i <= Len/2; i *= 2) {
17050     Csts.assign(NumElts, DAG.getConstant(i, EltVT));
17051     SDValue CstsV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Csts);
17052     Srl = DAG.getNode(ISD::SRL, dl, VT, Add, CstsV);
17053     Add = DAG.getNode(ISD::ADD, dl, VT, Add, Srl);
17054     Csts.clear();
17055   }
17056
17057   // The result is on the least significant 6-bits on i32 and 7-bits on i64.
17058   SDValue Cst3F = DAG.getConstant(APInt(Len, Len == 32 ? 0x3F : 0x7F), EltVT);
17059   SmallVector<SDValue, 8> Cst3FV(NumElts, Cst3F);
17060   SDValue M3F = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Cst3FV);
17061   if (NeedsBitcast) {
17062     Add = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Add);
17063     M3F = DAG.getNode(ISD::BITCAST, dl, BitcastVT, M3F);
17064   }
17065   And = DAG.getNode(ISD::AND, dl, M3F.getValueType(), Add, M3F);
17066   if (VT != And.getValueType())
17067     And = DAG.getNode(ISD::BITCAST, dl, VT, And);
17068
17069   return And;
17070 }
17071
17072 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
17073   SDNode *Node = Op.getNode();
17074   SDLoc dl(Node);
17075   EVT T = Node->getValueType(0);
17076   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
17077                               DAG.getConstant(0, T), Node->getOperand(2));
17078   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
17079                        cast<AtomicSDNode>(Node)->getMemoryVT(),
17080                        Node->getOperand(0),
17081                        Node->getOperand(1), negOp,
17082                        cast<AtomicSDNode>(Node)->getMemOperand(),
17083                        cast<AtomicSDNode>(Node)->getOrdering(),
17084                        cast<AtomicSDNode>(Node)->getSynchScope());
17085 }
17086
17087 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
17088   SDNode *Node = Op.getNode();
17089   SDLoc dl(Node);
17090   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
17091
17092   // Convert seq_cst store -> xchg
17093   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
17094   // FIXME: On 32-bit, store -> fist or movq would be more efficient
17095   //        (The only way to get a 16-byte store is cmpxchg16b)
17096   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
17097   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
17098       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
17099     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
17100                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
17101                                  Node->getOperand(0),
17102                                  Node->getOperand(1), Node->getOperand(2),
17103                                  cast<AtomicSDNode>(Node)->getMemOperand(),
17104                                  cast<AtomicSDNode>(Node)->getOrdering(),
17105                                  cast<AtomicSDNode>(Node)->getSynchScope());
17106     return Swap.getValue(1);
17107   }
17108   // Other atomic stores have a simple pattern.
17109   return Op;
17110 }
17111
17112 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
17113   EVT VT = Op.getNode()->getSimpleValueType(0);
17114
17115   // Let legalize expand this if it isn't a legal type yet.
17116   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
17117     return SDValue();
17118
17119   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
17120
17121   unsigned Opc;
17122   bool ExtraOp = false;
17123   switch (Op.getOpcode()) {
17124   default: llvm_unreachable("Invalid code");
17125   case ISD::ADDC: Opc = X86ISD::ADD; break;
17126   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
17127   case ISD::SUBC: Opc = X86ISD::SUB; break;
17128   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
17129   }
17130
17131   if (!ExtraOp)
17132     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
17133                        Op.getOperand(1));
17134   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
17135                      Op.getOperand(1), Op.getOperand(2));
17136 }
17137
17138 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
17139                             SelectionDAG &DAG) {
17140   assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
17141
17142   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
17143   // which returns the values as { float, float } (in XMM0) or
17144   // { double, double } (which is returned in XMM0, XMM1).
17145   SDLoc dl(Op);
17146   SDValue Arg = Op.getOperand(0);
17147   EVT ArgVT = Arg.getValueType();
17148   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
17149
17150   TargetLowering::ArgListTy Args;
17151   TargetLowering::ArgListEntry Entry;
17152
17153   Entry.Node = Arg;
17154   Entry.Ty = ArgTy;
17155   Entry.isSExt = false;
17156   Entry.isZExt = false;
17157   Args.push_back(Entry);
17158
17159   bool isF64 = ArgVT == MVT::f64;
17160   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
17161   // the small struct {f32, f32} is returned in (eax, edx). For f64,
17162   // the results are returned via SRet in memory.
17163   const char *LibcallName =  isF64 ? "__sincos_stret" : "__sincosf_stret";
17164   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17165   SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy());
17166
17167   Type *RetTy = isF64
17168     ? (Type*)StructType::get(ArgTy, ArgTy, nullptr)
17169     : (Type*)VectorType::get(ArgTy, 4);
17170
17171   TargetLowering::CallLoweringInfo CLI(DAG);
17172   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
17173     .setCallee(CallingConv::C, RetTy, Callee, std::move(Args), 0);
17174
17175   std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
17176
17177   if (isF64)
17178     // Returned in xmm0 and xmm1.
17179     return CallResult.first;
17180
17181   // Returned in bits 0:31 and 32:64 xmm0.
17182   SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
17183                                CallResult.first, DAG.getIntPtrConstant(0));
17184   SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
17185                                CallResult.first, DAG.getIntPtrConstant(1));
17186   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
17187   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
17188 }
17189
17190 /// LowerOperation - Provide custom lowering hooks for some operations.
17191 ///
17192 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
17193   switch (Op.getOpcode()) {
17194   default: llvm_unreachable("Should not custom lower this!");
17195   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
17196   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
17197     return LowerCMP_SWAP(Op, Subtarget, DAG);
17198   case ISD::CTPOP:              return LowerCTPOP(Op, Subtarget, DAG);
17199   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
17200   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
17201   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
17202   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, Subtarget, DAG);
17203   case ISD::VECTOR_SHUFFLE:     return lowerVectorShuffle(Op, Subtarget, DAG);
17204   case ISD::VSELECT:            return LowerVSELECT(Op, DAG);
17205   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
17206   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
17207   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
17208   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
17209   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
17210   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
17211   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
17212   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
17213   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
17214   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
17215   case ISD::SHL_PARTS:
17216   case ISD::SRA_PARTS:
17217   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
17218   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
17219   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
17220   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
17221   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, Subtarget, DAG);
17222   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, Subtarget, DAG);
17223   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, Subtarget, DAG);
17224   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
17225   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
17226   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
17227   case ISD::LOAD:               return LowerExtendedLoad(Op, Subtarget, DAG);
17228   case ISD::FABS:
17229   case ISD::FNEG:               return LowerFABSorFNEG(Op, DAG);
17230   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
17231   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
17232   case ISD::SETCC:              return LowerSETCC(Op, DAG);
17233   case ISD::SELECT:             return LowerSELECT(Op, DAG);
17234   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
17235   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
17236   case ISD::VASTART:            return LowerVASTART(Op, DAG);
17237   case ISD::VAARG:              return LowerVAARG(Op, DAG);
17238   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
17239   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, Subtarget, DAG);
17240   case ISD::INTRINSIC_VOID:
17241   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
17242   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
17243   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
17244   case ISD::FRAME_TO_ARGS_OFFSET:
17245                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
17246   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
17247   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
17248   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
17249   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
17250   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
17251   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
17252   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
17253   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
17254   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
17255   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
17256   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
17257   case ISD::UMUL_LOHI:
17258   case ISD::SMUL_LOHI:          return LowerMUL_LOHI(Op, Subtarget, DAG);
17259   case ISD::SRA:
17260   case ISD::SRL:
17261   case ISD::SHL:                return LowerShift(Op, Subtarget, DAG);
17262   case ISD::SADDO:
17263   case ISD::UADDO:
17264   case ISD::SSUBO:
17265   case ISD::USUBO:
17266   case ISD::SMULO:
17267   case ISD::UMULO:              return LowerXALUO(Op, DAG);
17268   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
17269   case ISD::BITCAST:            return LowerBITCAST(Op, Subtarget, DAG);
17270   case ISD::ADDC:
17271   case ISD::ADDE:
17272   case ISD::SUBC:
17273   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
17274   case ISD::ADD:                return LowerADD(Op, DAG);
17275   case ISD::SUB:                return LowerSUB(Op, DAG);
17276   case ISD::FSINCOS:            return LowerFSINCOS(Op, Subtarget, DAG);
17277   }
17278 }
17279
17280 /// ReplaceNodeResults - Replace a node with an illegal result type
17281 /// with a new node built out of custom code.
17282 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
17283                                            SmallVectorImpl<SDValue>&Results,
17284                                            SelectionDAG &DAG) const {
17285   SDLoc dl(N);
17286   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17287   switch (N->getOpcode()) {
17288   default:
17289     llvm_unreachable("Do not know how to custom type legalize this operation!");
17290   // We might have generated v2f32 FMIN/FMAX operations. Widen them to v4f32.
17291   case X86ISD::FMINC:
17292   case X86ISD::FMIN:
17293   case X86ISD::FMAXC:
17294   case X86ISD::FMAX: {
17295     EVT VT = N->getValueType(0);
17296     if (VT != MVT::v2f32)
17297       llvm_unreachable("Unexpected type (!= v2f32) on FMIN/FMAX.");
17298     SDValue UNDEF = DAG.getUNDEF(VT);
17299     SDValue LHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
17300                               N->getOperand(0), UNDEF);
17301     SDValue RHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
17302                               N->getOperand(1), UNDEF);
17303     Results.push_back(DAG.getNode(N->getOpcode(), dl, MVT::v4f32, LHS, RHS));
17304     return;
17305   }
17306   case ISD::SIGN_EXTEND_INREG:
17307   case ISD::ADDC:
17308   case ISD::ADDE:
17309   case ISD::SUBC:
17310   case ISD::SUBE:
17311     // We don't want to expand or promote these.
17312     return;
17313   case ISD::SDIV:
17314   case ISD::UDIV:
17315   case ISD::SREM:
17316   case ISD::UREM:
17317   case ISD::SDIVREM:
17318   case ISD::UDIVREM: {
17319     SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
17320     Results.push_back(V);
17321     return;
17322   }
17323   case ISD::FP_TO_SINT:
17324   case ISD::FP_TO_UINT: {
17325     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
17326
17327     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
17328       return;
17329
17330     std::pair<SDValue,SDValue> Vals =
17331         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
17332     SDValue FIST = Vals.first, StackSlot = Vals.second;
17333     if (FIST.getNode()) {
17334       EVT VT = N->getValueType(0);
17335       // Return a load from the stack slot.
17336       if (StackSlot.getNode())
17337         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
17338                                       MachinePointerInfo(),
17339                                       false, false, false, 0));
17340       else
17341         Results.push_back(FIST);
17342     }
17343     return;
17344   }
17345   case ISD::UINT_TO_FP: {
17346     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
17347     if (N->getOperand(0).getValueType() != MVT::v2i32 ||
17348         N->getValueType(0) != MVT::v2f32)
17349       return;
17350     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
17351                                  N->getOperand(0));
17352     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
17353                                      MVT::f64);
17354     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
17355     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
17356                              DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
17357     Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
17358     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
17359     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
17360     return;
17361   }
17362   case ISD::FP_ROUND: {
17363     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
17364         return;
17365     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
17366     Results.push_back(V);
17367     return;
17368   }
17369   case ISD::INTRINSIC_W_CHAIN: {
17370     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
17371     switch (IntNo) {
17372     default : llvm_unreachable("Do not know how to custom type "
17373                                "legalize this intrinsic operation!");
17374     case Intrinsic::x86_rdtsc:
17375       return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
17376                                      Results);
17377     case Intrinsic::x86_rdtscp:
17378       return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
17379                                      Results);
17380     case Intrinsic::x86_rdpmc:
17381       return getReadPerformanceCounter(N, dl, DAG, Subtarget, Results);
17382     }
17383   }
17384   case ISD::READCYCLECOUNTER: {
17385     return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
17386                                    Results);
17387   }
17388   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
17389     EVT T = N->getValueType(0);
17390     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
17391     bool Regs64bit = T == MVT::i128;
17392     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
17393     SDValue cpInL, cpInH;
17394     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
17395                         DAG.getConstant(0, HalfT));
17396     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
17397                         DAG.getConstant(1, HalfT));
17398     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
17399                              Regs64bit ? X86::RAX : X86::EAX,
17400                              cpInL, SDValue());
17401     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
17402                              Regs64bit ? X86::RDX : X86::EDX,
17403                              cpInH, cpInL.getValue(1));
17404     SDValue swapInL, swapInH;
17405     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
17406                           DAG.getConstant(0, HalfT));
17407     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
17408                           DAG.getConstant(1, HalfT));
17409     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
17410                                Regs64bit ? X86::RBX : X86::EBX,
17411                                swapInL, cpInH.getValue(1));
17412     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
17413                                Regs64bit ? X86::RCX : X86::ECX,
17414                                swapInH, swapInL.getValue(1));
17415     SDValue Ops[] = { swapInH.getValue(0),
17416                       N->getOperand(1),
17417                       swapInH.getValue(1) };
17418     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
17419     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
17420     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
17421                                   X86ISD::LCMPXCHG8_DAG;
17422     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
17423     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
17424                                         Regs64bit ? X86::RAX : X86::EAX,
17425                                         HalfT, Result.getValue(1));
17426     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
17427                                         Regs64bit ? X86::RDX : X86::EDX,
17428                                         HalfT, cpOutL.getValue(2));
17429     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
17430
17431     SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
17432                                         MVT::i32, cpOutH.getValue(2));
17433     SDValue Success =
17434         DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
17435                     DAG.getConstant(X86::COND_E, MVT::i8), EFLAGS);
17436     Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
17437
17438     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
17439     Results.push_back(Success);
17440     Results.push_back(EFLAGS.getValue(1));
17441     return;
17442   }
17443   case ISD::ATOMIC_SWAP:
17444   case ISD::ATOMIC_LOAD_ADD:
17445   case ISD::ATOMIC_LOAD_SUB:
17446   case ISD::ATOMIC_LOAD_AND:
17447   case ISD::ATOMIC_LOAD_OR:
17448   case ISD::ATOMIC_LOAD_XOR:
17449   case ISD::ATOMIC_LOAD_NAND:
17450   case ISD::ATOMIC_LOAD_MIN:
17451   case ISD::ATOMIC_LOAD_MAX:
17452   case ISD::ATOMIC_LOAD_UMIN:
17453   case ISD::ATOMIC_LOAD_UMAX:
17454   case ISD::ATOMIC_LOAD: {
17455     // Delegate to generic TypeLegalization. Situations we can really handle
17456     // should have already been dealt with by AtomicExpandPass.cpp.
17457     break;
17458   }
17459   case ISD::BITCAST: {
17460     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
17461     EVT DstVT = N->getValueType(0);
17462     EVT SrcVT = N->getOperand(0)->getValueType(0);
17463
17464     if (SrcVT != MVT::f64 ||
17465         (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
17466       return;
17467
17468     unsigned NumElts = DstVT.getVectorNumElements();
17469     EVT SVT = DstVT.getVectorElementType();
17470     EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
17471     SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
17472                                    MVT::v2f64, N->getOperand(0));
17473     SDValue ToVecInt = DAG.getNode(ISD::BITCAST, dl, WiderVT, Expanded);
17474
17475     if (ExperimentalVectorWideningLegalization) {
17476       // If we are legalizing vectors by widening, we already have the desired
17477       // legal vector type, just return it.
17478       Results.push_back(ToVecInt);
17479       return;
17480     }
17481
17482     SmallVector<SDValue, 8> Elts;
17483     for (unsigned i = 0, e = NumElts; i != e; ++i)
17484       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
17485                                    ToVecInt, DAG.getIntPtrConstant(i)));
17486
17487     Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
17488   }
17489   }
17490 }
17491
17492 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
17493   switch (Opcode) {
17494   default: return nullptr;
17495   case X86ISD::BSF:                return "X86ISD::BSF";
17496   case X86ISD::BSR:                return "X86ISD::BSR";
17497   case X86ISD::SHLD:               return "X86ISD::SHLD";
17498   case X86ISD::SHRD:               return "X86ISD::SHRD";
17499   case X86ISD::FAND:               return "X86ISD::FAND";
17500   case X86ISD::FANDN:              return "X86ISD::FANDN";
17501   case X86ISD::FOR:                return "X86ISD::FOR";
17502   case X86ISD::FXOR:               return "X86ISD::FXOR";
17503   case X86ISD::FSRL:               return "X86ISD::FSRL";
17504   case X86ISD::FILD:               return "X86ISD::FILD";
17505   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
17506   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
17507   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
17508   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
17509   case X86ISD::FLD:                return "X86ISD::FLD";
17510   case X86ISD::FST:                return "X86ISD::FST";
17511   case X86ISD::CALL:               return "X86ISD::CALL";
17512   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
17513   case X86ISD::RDTSCP_DAG:         return "X86ISD::RDTSCP_DAG";
17514   case X86ISD::RDPMC_DAG:          return "X86ISD::RDPMC_DAG";
17515   case X86ISD::BT:                 return "X86ISD::BT";
17516   case X86ISD::CMP:                return "X86ISD::CMP";
17517   case X86ISD::COMI:               return "X86ISD::COMI";
17518   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
17519   case X86ISD::CMPM:               return "X86ISD::CMPM";
17520   case X86ISD::CMPMU:              return "X86ISD::CMPMU";
17521   case X86ISD::SETCC:              return "X86ISD::SETCC";
17522   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
17523   case X86ISD::FSETCC:             return "X86ISD::FSETCC";
17524   case X86ISD::CMOV:               return "X86ISD::CMOV";
17525   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
17526   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
17527   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
17528   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
17529   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
17530   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
17531   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
17532   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
17533   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
17534   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
17535   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
17536   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
17537   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
17538   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
17539   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
17540   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
17541   case X86ISD::SHRUNKBLEND:        return "X86ISD::SHRUNKBLEND";
17542   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
17543   case X86ISD::HADD:               return "X86ISD::HADD";
17544   case X86ISD::HSUB:               return "X86ISD::HSUB";
17545   case X86ISD::FHADD:              return "X86ISD::FHADD";
17546   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
17547   case X86ISD::UMAX:               return "X86ISD::UMAX";
17548   case X86ISD::UMIN:               return "X86ISD::UMIN";
17549   case X86ISD::SMAX:               return "X86ISD::SMAX";
17550   case X86ISD::SMIN:               return "X86ISD::SMIN";
17551   case X86ISD::FMAX:               return "X86ISD::FMAX";
17552   case X86ISD::FMIN:               return "X86ISD::FMIN";
17553   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
17554   case X86ISD::FMINC:              return "X86ISD::FMINC";
17555   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
17556   case X86ISD::FRCP:               return "X86ISD::FRCP";
17557   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
17558   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
17559   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
17560   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
17561   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
17562   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
17563   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
17564   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
17565   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
17566   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
17567   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
17568   case X86ISD::LCMPXCHG16_DAG:     return "X86ISD::LCMPXCHG16_DAG";
17569   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
17570   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
17571   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
17572   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
17573   case X86ISD::VTRUNC:             return "X86ISD::VTRUNC";
17574   case X86ISD::VTRUNCM:            return "X86ISD::VTRUNCM";
17575   case X86ISD::VINSERT:            return "X86ISD::VINSERT";
17576   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
17577   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
17578   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
17579   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
17580   case X86ISD::VSHL:               return "X86ISD::VSHL";
17581   case X86ISD::VSRL:               return "X86ISD::VSRL";
17582   case X86ISD::VSRA:               return "X86ISD::VSRA";
17583   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
17584   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
17585   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
17586   case X86ISD::CMPP:               return "X86ISD::CMPP";
17587   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
17588   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
17589   case X86ISD::PCMPEQM:            return "X86ISD::PCMPEQM";
17590   case X86ISD::PCMPGTM:            return "X86ISD::PCMPGTM";
17591   case X86ISD::ADD:                return "X86ISD::ADD";
17592   case X86ISD::SUB:                return "X86ISD::SUB";
17593   case X86ISD::ADC:                return "X86ISD::ADC";
17594   case X86ISD::SBB:                return "X86ISD::SBB";
17595   case X86ISD::SMUL:               return "X86ISD::SMUL";
17596   case X86ISD::UMUL:               return "X86ISD::UMUL";
17597   case X86ISD::SMUL8:              return "X86ISD::SMUL8";
17598   case X86ISD::UMUL8:              return "X86ISD::UMUL8";
17599   case X86ISD::SDIVREM8_SEXT_HREG: return "X86ISD::SDIVREM8_SEXT_HREG";
17600   case X86ISD::UDIVREM8_ZEXT_HREG: return "X86ISD::UDIVREM8_ZEXT_HREG";
17601   case X86ISD::INC:                return "X86ISD::INC";
17602   case X86ISD::DEC:                return "X86ISD::DEC";
17603   case X86ISD::OR:                 return "X86ISD::OR";
17604   case X86ISD::XOR:                return "X86ISD::XOR";
17605   case X86ISD::AND:                return "X86ISD::AND";
17606   case X86ISD::BEXTR:              return "X86ISD::BEXTR";
17607   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
17608   case X86ISD::PTEST:              return "X86ISD::PTEST";
17609   case X86ISD::TESTP:              return "X86ISD::TESTP";
17610   case X86ISD::TESTM:              return "X86ISD::TESTM";
17611   case X86ISD::TESTNM:             return "X86ISD::TESTNM";
17612   case X86ISD::KORTEST:            return "X86ISD::KORTEST";
17613   case X86ISD::PACKSS:             return "X86ISD::PACKSS";
17614   case X86ISD::PACKUS:             return "X86ISD::PACKUS";
17615   case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
17616   case X86ISD::VALIGN:             return "X86ISD::VALIGN";
17617   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
17618   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
17619   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
17620   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
17621   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
17622   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
17623   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
17624   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
17625   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
17626   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
17627   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
17628   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
17629   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
17630   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
17631   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
17632   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
17633   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
17634   case X86ISD::VBROADCASTM:        return "X86ISD::VBROADCASTM";
17635   case X86ISD::VEXTRACT:           return "X86ISD::VEXTRACT";
17636   case X86ISD::VPERMILPI:          return "X86ISD::VPERMILPI";
17637   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
17638   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
17639   case X86ISD::VPERMV3:            return "X86ISD::VPERMV3";
17640   case X86ISD::VPERMIV3:           return "X86ISD::VPERMIV3";
17641   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
17642   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
17643   case X86ISD::PMULDQ:             return "X86ISD::PMULDQ";
17644   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
17645   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
17646   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
17647   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
17648   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
17649   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
17650   case X86ISD::SAHF:               return "X86ISD::SAHF";
17651   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
17652   case X86ISD::RDSEED:             return "X86ISD::RDSEED";
17653   case X86ISD::FMADD:              return "X86ISD::FMADD";
17654   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
17655   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
17656   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
17657   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
17658   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
17659   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
17660   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
17661   case X86ISD::XTEST:              return "X86ISD::XTEST";
17662   case X86ISD::COMPRESS:           return "X86ISD::COMPRESS";
17663   case X86ISD::EXPAND:             return "X86ISD::EXPAND";
17664   case X86ISD::SELECT:             return "X86ISD::SELECT";
17665   case X86ISD::ADDSUB:             return "X86ISD::ADDSUB";
17666   case X86ISD::RCP28:              return "X86ISD::RCP28";
17667   case X86ISD::RSQRT28:            return "X86ISD::RSQRT28";
17668   case X86ISD::FADD_RND:           return "X86ISD::FADD_RND";
17669   case X86ISD::FSUB_RND:           return "X86ISD::FSUB_RND";
17670   case X86ISD::FMUL_RND:           return "X86ISD::FMUL_RND";
17671   case X86ISD::FDIV_RND:           return "X86ISD::FDIV_RND";
17672   }
17673 }
17674
17675 // isLegalAddressingMode - Return true if the addressing mode represented
17676 // by AM is legal for this target, for a load/store of the specified type.
17677 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
17678                                               Type *Ty) const {
17679   // X86 supports extremely general addressing modes.
17680   CodeModel::Model M = getTargetMachine().getCodeModel();
17681   Reloc::Model R = getTargetMachine().getRelocationModel();
17682
17683   // X86 allows a sign-extended 32-bit immediate field as a displacement.
17684   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
17685     return false;
17686
17687   if (AM.BaseGV) {
17688     unsigned GVFlags =
17689       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
17690
17691     // If a reference to this global requires an extra load, we can't fold it.
17692     if (isGlobalStubReference(GVFlags))
17693       return false;
17694
17695     // If BaseGV requires a register for the PIC base, we cannot also have a
17696     // BaseReg specified.
17697     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
17698       return false;
17699
17700     // If lower 4G is not available, then we must use rip-relative addressing.
17701     if ((M != CodeModel::Small || R != Reloc::Static) &&
17702         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
17703       return false;
17704   }
17705
17706   switch (AM.Scale) {
17707   case 0:
17708   case 1:
17709   case 2:
17710   case 4:
17711   case 8:
17712     // These scales always work.
17713     break;
17714   case 3:
17715   case 5:
17716   case 9:
17717     // These scales are formed with basereg+scalereg.  Only accept if there is
17718     // no basereg yet.
17719     if (AM.HasBaseReg)
17720       return false;
17721     break;
17722   default:  // Other stuff never works.
17723     return false;
17724   }
17725
17726   return true;
17727 }
17728
17729 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
17730   unsigned Bits = Ty->getScalarSizeInBits();
17731
17732   // 8-bit shifts are always expensive, but versions with a scalar amount aren't
17733   // particularly cheaper than those without.
17734   if (Bits == 8)
17735     return false;
17736
17737   // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
17738   // variable shifts just as cheap as scalar ones.
17739   if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
17740     return false;
17741
17742   // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
17743   // fully general vector.
17744   return true;
17745 }
17746
17747 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
17748   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
17749     return false;
17750   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
17751   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
17752   return NumBits1 > NumBits2;
17753 }
17754
17755 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
17756   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
17757     return false;
17758
17759   if (!isTypeLegal(EVT::getEVT(Ty1)))
17760     return false;
17761
17762   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
17763
17764   // Assuming the caller doesn't have a zeroext or signext return parameter,
17765   // truncation all the way down to i1 is valid.
17766   return true;
17767 }
17768
17769 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
17770   return isInt<32>(Imm);
17771 }
17772
17773 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
17774   // Can also use sub to handle negated immediates.
17775   return isInt<32>(Imm);
17776 }
17777
17778 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
17779   if (!VT1.isInteger() || !VT2.isInteger())
17780     return false;
17781   unsigned NumBits1 = VT1.getSizeInBits();
17782   unsigned NumBits2 = VT2.getSizeInBits();
17783   return NumBits1 > NumBits2;
17784 }
17785
17786 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
17787   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
17788   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
17789 }
17790
17791 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
17792   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
17793   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
17794 }
17795
17796 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
17797   EVT VT1 = Val.getValueType();
17798   if (isZExtFree(VT1, VT2))
17799     return true;
17800
17801   if (Val.getOpcode() != ISD::LOAD)
17802     return false;
17803
17804   if (!VT1.isSimple() || !VT1.isInteger() ||
17805       !VT2.isSimple() || !VT2.isInteger())
17806     return false;
17807
17808   switch (VT1.getSimpleVT().SimpleTy) {
17809   default: break;
17810   case MVT::i8:
17811   case MVT::i16:
17812   case MVT::i32:
17813     // X86 has 8, 16, and 32-bit zero-extending loads.
17814     return true;
17815   }
17816
17817   return false;
17818 }
17819
17820 bool X86TargetLowering::isVectorLoadExtDesirable(SDValue) const { return true; }
17821
17822 bool
17823 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
17824   if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
17825     return false;
17826
17827   VT = VT.getScalarType();
17828
17829   if (!VT.isSimple())
17830     return false;
17831
17832   switch (VT.getSimpleVT().SimpleTy) {
17833   case MVT::f32:
17834   case MVT::f64:
17835     return true;
17836   default:
17837     break;
17838   }
17839
17840   return false;
17841 }
17842
17843 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
17844   // i16 instructions are longer (0x66 prefix) and potentially slower.
17845   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
17846 }
17847
17848 /// isShuffleMaskLegal - Targets can use this to indicate that they only
17849 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
17850 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
17851 /// are assumed to be legal.
17852 bool
17853 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
17854                                       EVT VT) const {
17855   if (!VT.isSimple())
17856     return false;
17857
17858   // Very little shuffling can be done for 64-bit vectors right now.
17859   if (VT.getSizeInBits() == 64)
17860     return false;
17861
17862   // We only care that the types being shuffled are legal. The lowering can
17863   // handle any possible shuffle mask that results.
17864   return isTypeLegal(VT.getSimpleVT());
17865 }
17866
17867 bool
17868 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
17869                                           EVT VT) const {
17870   // Just delegate to the generic legality, clear masks aren't special.
17871   return isShuffleMaskLegal(Mask, VT);
17872 }
17873
17874 //===----------------------------------------------------------------------===//
17875 //                           X86 Scheduler Hooks
17876 //===----------------------------------------------------------------------===//
17877
17878 /// Utility function to emit xbegin specifying the start of an RTM region.
17879 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
17880                                      const TargetInstrInfo *TII) {
17881   DebugLoc DL = MI->getDebugLoc();
17882
17883   const BasicBlock *BB = MBB->getBasicBlock();
17884   MachineFunction::iterator I = MBB;
17885   ++I;
17886
17887   // For the v = xbegin(), we generate
17888   //
17889   // thisMBB:
17890   //  xbegin sinkMBB
17891   //
17892   // mainMBB:
17893   //  eax = -1
17894   //
17895   // sinkMBB:
17896   //  v = eax
17897
17898   MachineBasicBlock *thisMBB = MBB;
17899   MachineFunction *MF = MBB->getParent();
17900   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
17901   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
17902   MF->insert(I, mainMBB);
17903   MF->insert(I, sinkMBB);
17904
17905   // Transfer the remainder of BB and its successor edges to sinkMBB.
17906   sinkMBB->splice(sinkMBB->begin(), MBB,
17907                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
17908   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
17909
17910   // thisMBB:
17911   //  xbegin sinkMBB
17912   //  # fallthrough to mainMBB
17913   //  # abortion to sinkMBB
17914   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
17915   thisMBB->addSuccessor(mainMBB);
17916   thisMBB->addSuccessor(sinkMBB);
17917
17918   // mainMBB:
17919   //  EAX = -1
17920   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
17921   mainMBB->addSuccessor(sinkMBB);
17922
17923   // sinkMBB:
17924   // EAX is live into the sinkMBB
17925   sinkMBB->addLiveIn(X86::EAX);
17926   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
17927           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
17928     .addReg(X86::EAX);
17929
17930   MI->eraseFromParent();
17931   return sinkMBB;
17932 }
17933
17934 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
17935 // or XMM0_V32I8 in AVX all of this code can be replaced with that
17936 // in the .td file.
17937 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
17938                                        const TargetInstrInfo *TII) {
17939   unsigned Opc;
17940   switch (MI->getOpcode()) {
17941   default: llvm_unreachable("illegal opcode!");
17942   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
17943   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
17944   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
17945   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
17946   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
17947   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
17948   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
17949   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
17950   }
17951
17952   DebugLoc dl = MI->getDebugLoc();
17953   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
17954
17955   unsigned NumArgs = MI->getNumOperands();
17956   for (unsigned i = 1; i < NumArgs; ++i) {
17957     MachineOperand &Op = MI->getOperand(i);
17958     if (!(Op.isReg() && Op.isImplicit()))
17959       MIB.addOperand(Op);
17960   }
17961   if (MI->hasOneMemOperand())
17962     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
17963
17964   BuildMI(*BB, MI, dl,
17965     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
17966     .addReg(X86::XMM0);
17967
17968   MI->eraseFromParent();
17969   return BB;
17970 }
17971
17972 // FIXME: Custom handling because TableGen doesn't support multiple implicit
17973 // defs in an instruction pattern
17974 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
17975                                        const TargetInstrInfo *TII) {
17976   unsigned Opc;
17977   switch (MI->getOpcode()) {
17978   default: llvm_unreachable("illegal opcode!");
17979   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
17980   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
17981   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
17982   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
17983   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
17984   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
17985   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
17986   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
17987   }
17988
17989   DebugLoc dl = MI->getDebugLoc();
17990   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
17991
17992   unsigned NumArgs = MI->getNumOperands(); // remove the results
17993   for (unsigned i = 1; i < NumArgs; ++i) {
17994     MachineOperand &Op = MI->getOperand(i);
17995     if (!(Op.isReg() && Op.isImplicit()))
17996       MIB.addOperand(Op);
17997   }
17998   if (MI->hasOneMemOperand())
17999     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
18000
18001   BuildMI(*BB, MI, dl,
18002     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
18003     .addReg(X86::ECX);
18004
18005   MI->eraseFromParent();
18006   return BB;
18007 }
18008
18009 static MachineBasicBlock *EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
18010                                       const X86Subtarget *Subtarget) {
18011   DebugLoc dl = MI->getDebugLoc();
18012   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18013   // Address into RAX/EAX, other two args into ECX, EDX.
18014   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
18015   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
18016   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
18017   for (int i = 0; i < X86::AddrNumOperands; ++i)
18018     MIB.addOperand(MI->getOperand(i));
18019
18020   unsigned ValOps = X86::AddrNumOperands;
18021   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
18022     .addReg(MI->getOperand(ValOps).getReg());
18023   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
18024     .addReg(MI->getOperand(ValOps+1).getReg());
18025
18026   // The instruction doesn't actually take any operands though.
18027   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
18028
18029   MI->eraseFromParent(); // The pseudo is gone now.
18030   return BB;
18031 }
18032
18033 MachineBasicBlock *
18034 X86TargetLowering::EmitVAARG64WithCustomInserter(MachineInstr *MI,
18035                                                  MachineBasicBlock *MBB) const {
18036   // Emit va_arg instruction on X86-64.
18037
18038   // Operands to this pseudo-instruction:
18039   // 0  ) Output        : destination address (reg)
18040   // 1-5) Input         : va_list address (addr, i64mem)
18041   // 6  ) ArgSize       : Size (in bytes) of vararg type
18042   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
18043   // 8  ) Align         : Alignment of type
18044   // 9  ) EFLAGS (implicit-def)
18045
18046   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
18047   static_assert(X86::AddrNumOperands == 5,
18048                 "VAARG_64 assumes 5 address operands");
18049
18050   unsigned DestReg = MI->getOperand(0).getReg();
18051   MachineOperand &Base = MI->getOperand(1);
18052   MachineOperand &Scale = MI->getOperand(2);
18053   MachineOperand &Index = MI->getOperand(3);
18054   MachineOperand &Disp = MI->getOperand(4);
18055   MachineOperand &Segment = MI->getOperand(5);
18056   unsigned ArgSize = MI->getOperand(6).getImm();
18057   unsigned ArgMode = MI->getOperand(7).getImm();
18058   unsigned Align = MI->getOperand(8).getImm();
18059
18060   // Memory Reference
18061   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
18062   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
18063   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
18064
18065   // Machine Information
18066   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18067   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
18068   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
18069   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
18070   DebugLoc DL = MI->getDebugLoc();
18071
18072   // struct va_list {
18073   //   i32   gp_offset
18074   //   i32   fp_offset
18075   //   i64   overflow_area (address)
18076   //   i64   reg_save_area (address)
18077   // }
18078   // sizeof(va_list) = 24
18079   // alignment(va_list) = 8
18080
18081   unsigned TotalNumIntRegs = 6;
18082   unsigned TotalNumXMMRegs = 8;
18083   bool UseGPOffset = (ArgMode == 1);
18084   bool UseFPOffset = (ArgMode == 2);
18085   unsigned MaxOffset = TotalNumIntRegs * 8 +
18086                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
18087
18088   /* Align ArgSize to a multiple of 8 */
18089   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
18090   bool NeedsAlign = (Align > 8);
18091
18092   MachineBasicBlock *thisMBB = MBB;
18093   MachineBasicBlock *overflowMBB;
18094   MachineBasicBlock *offsetMBB;
18095   MachineBasicBlock *endMBB;
18096
18097   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
18098   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
18099   unsigned OffsetReg = 0;
18100
18101   if (!UseGPOffset && !UseFPOffset) {
18102     // If we only pull from the overflow region, we don't create a branch.
18103     // We don't need to alter control flow.
18104     OffsetDestReg = 0; // unused
18105     OverflowDestReg = DestReg;
18106
18107     offsetMBB = nullptr;
18108     overflowMBB = thisMBB;
18109     endMBB = thisMBB;
18110   } else {
18111     // First emit code to check if gp_offset (or fp_offset) is below the bound.
18112     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
18113     // If not, pull from overflow_area. (branch to overflowMBB)
18114     //
18115     //       thisMBB
18116     //         |     .
18117     //         |        .
18118     //     offsetMBB   overflowMBB
18119     //         |        .
18120     //         |     .
18121     //        endMBB
18122
18123     // Registers for the PHI in endMBB
18124     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
18125     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
18126
18127     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
18128     MachineFunction *MF = MBB->getParent();
18129     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18130     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18131     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18132
18133     MachineFunction::iterator MBBIter = MBB;
18134     ++MBBIter;
18135
18136     // Insert the new basic blocks
18137     MF->insert(MBBIter, offsetMBB);
18138     MF->insert(MBBIter, overflowMBB);
18139     MF->insert(MBBIter, endMBB);
18140
18141     // Transfer the remainder of MBB and its successor edges to endMBB.
18142     endMBB->splice(endMBB->begin(), thisMBB,
18143                    std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
18144     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
18145
18146     // Make offsetMBB and overflowMBB successors of thisMBB
18147     thisMBB->addSuccessor(offsetMBB);
18148     thisMBB->addSuccessor(overflowMBB);
18149
18150     // endMBB is a successor of both offsetMBB and overflowMBB
18151     offsetMBB->addSuccessor(endMBB);
18152     overflowMBB->addSuccessor(endMBB);
18153
18154     // Load the offset value into a register
18155     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
18156     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
18157       .addOperand(Base)
18158       .addOperand(Scale)
18159       .addOperand(Index)
18160       .addDisp(Disp, UseFPOffset ? 4 : 0)
18161       .addOperand(Segment)
18162       .setMemRefs(MMOBegin, MMOEnd);
18163
18164     // Check if there is enough room left to pull this argument.
18165     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
18166       .addReg(OffsetReg)
18167       .addImm(MaxOffset + 8 - ArgSizeA8);
18168
18169     // Branch to "overflowMBB" if offset >= max
18170     // Fall through to "offsetMBB" otherwise
18171     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
18172       .addMBB(overflowMBB);
18173   }
18174
18175   // In offsetMBB, emit code to use the reg_save_area.
18176   if (offsetMBB) {
18177     assert(OffsetReg != 0);
18178
18179     // Read the reg_save_area address.
18180     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
18181     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
18182       .addOperand(Base)
18183       .addOperand(Scale)
18184       .addOperand(Index)
18185       .addDisp(Disp, 16)
18186       .addOperand(Segment)
18187       .setMemRefs(MMOBegin, MMOEnd);
18188
18189     // Zero-extend the offset
18190     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
18191       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
18192         .addImm(0)
18193         .addReg(OffsetReg)
18194         .addImm(X86::sub_32bit);
18195
18196     // Add the offset to the reg_save_area to get the final address.
18197     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
18198       .addReg(OffsetReg64)
18199       .addReg(RegSaveReg);
18200
18201     // Compute the offset for the next argument
18202     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
18203     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
18204       .addReg(OffsetReg)
18205       .addImm(UseFPOffset ? 16 : 8);
18206
18207     // Store it back into the va_list.
18208     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
18209       .addOperand(Base)
18210       .addOperand(Scale)
18211       .addOperand(Index)
18212       .addDisp(Disp, UseFPOffset ? 4 : 0)
18213       .addOperand(Segment)
18214       .addReg(NextOffsetReg)
18215       .setMemRefs(MMOBegin, MMOEnd);
18216
18217     // Jump to endMBB
18218     BuildMI(offsetMBB, DL, TII->get(X86::JMP_1))
18219       .addMBB(endMBB);
18220   }
18221
18222   //
18223   // Emit code to use overflow area
18224   //
18225
18226   // Load the overflow_area address into a register.
18227   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
18228   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
18229     .addOperand(Base)
18230     .addOperand(Scale)
18231     .addOperand(Index)
18232     .addDisp(Disp, 8)
18233     .addOperand(Segment)
18234     .setMemRefs(MMOBegin, MMOEnd);
18235
18236   // If we need to align it, do so. Otherwise, just copy the address
18237   // to OverflowDestReg.
18238   if (NeedsAlign) {
18239     // Align the overflow address
18240     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
18241     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
18242
18243     // aligned_addr = (addr + (align-1)) & ~(align-1)
18244     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
18245       .addReg(OverflowAddrReg)
18246       .addImm(Align-1);
18247
18248     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
18249       .addReg(TmpReg)
18250       .addImm(~(uint64_t)(Align-1));
18251   } else {
18252     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
18253       .addReg(OverflowAddrReg);
18254   }
18255
18256   // Compute the next overflow address after this argument.
18257   // (the overflow address should be kept 8-byte aligned)
18258   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
18259   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
18260     .addReg(OverflowDestReg)
18261     .addImm(ArgSizeA8);
18262
18263   // Store the new overflow address.
18264   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
18265     .addOperand(Base)
18266     .addOperand(Scale)
18267     .addOperand(Index)
18268     .addDisp(Disp, 8)
18269     .addOperand(Segment)
18270     .addReg(NextAddrReg)
18271     .setMemRefs(MMOBegin, MMOEnd);
18272
18273   // If we branched, emit the PHI to the front of endMBB.
18274   if (offsetMBB) {
18275     BuildMI(*endMBB, endMBB->begin(), DL,
18276             TII->get(X86::PHI), DestReg)
18277       .addReg(OffsetDestReg).addMBB(offsetMBB)
18278       .addReg(OverflowDestReg).addMBB(overflowMBB);
18279   }
18280
18281   // Erase the pseudo instruction
18282   MI->eraseFromParent();
18283
18284   return endMBB;
18285 }
18286
18287 MachineBasicBlock *
18288 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
18289                                                  MachineInstr *MI,
18290                                                  MachineBasicBlock *MBB) const {
18291   // Emit code to save XMM registers to the stack. The ABI says that the
18292   // number of registers to save is given in %al, so it's theoretically
18293   // possible to do an indirect jump trick to avoid saving all of them,
18294   // however this code takes a simpler approach and just executes all
18295   // of the stores if %al is non-zero. It's less code, and it's probably
18296   // easier on the hardware branch predictor, and stores aren't all that
18297   // expensive anyway.
18298
18299   // Create the new basic blocks. One block contains all the XMM stores,
18300   // and one block is the final destination regardless of whether any
18301   // stores were performed.
18302   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
18303   MachineFunction *F = MBB->getParent();
18304   MachineFunction::iterator MBBIter = MBB;
18305   ++MBBIter;
18306   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
18307   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
18308   F->insert(MBBIter, XMMSaveMBB);
18309   F->insert(MBBIter, EndMBB);
18310
18311   // Transfer the remainder of MBB and its successor edges to EndMBB.
18312   EndMBB->splice(EndMBB->begin(), MBB,
18313                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
18314   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
18315
18316   // The original block will now fall through to the XMM save block.
18317   MBB->addSuccessor(XMMSaveMBB);
18318   // The XMMSaveMBB will fall through to the end block.
18319   XMMSaveMBB->addSuccessor(EndMBB);
18320
18321   // Now add the instructions.
18322   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18323   DebugLoc DL = MI->getDebugLoc();
18324
18325   unsigned CountReg = MI->getOperand(0).getReg();
18326   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
18327   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
18328
18329   if (!Subtarget->isTargetWin64()) {
18330     // If %al is 0, branch around the XMM save block.
18331     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
18332     BuildMI(MBB, DL, TII->get(X86::JE_1)).addMBB(EndMBB);
18333     MBB->addSuccessor(EndMBB);
18334   }
18335
18336   // Make sure the last operand is EFLAGS, which gets clobbered by the branch
18337   // that was just emitted, but clearly shouldn't be "saved".
18338   assert((MI->getNumOperands() <= 3 ||
18339           !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
18340           MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
18341          && "Expected last argument to be EFLAGS");
18342   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
18343   // In the XMM save block, save all the XMM argument registers.
18344   for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
18345     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
18346     MachineMemOperand *MMO =
18347       F->getMachineMemOperand(
18348           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
18349         MachineMemOperand::MOStore,
18350         /*Size=*/16, /*Align=*/16);
18351     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
18352       .addFrameIndex(RegSaveFrameIndex)
18353       .addImm(/*Scale=*/1)
18354       .addReg(/*IndexReg=*/0)
18355       .addImm(/*Disp=*/Offset)
18356       .addReg(/*Segment=*/0)
18357       .addReg(MI->getOperand(i).getReg())
18358       .addMemOperand(MMO);
18359   }
18360
18361   MI->eraseFromParent();   // The pseudo instruction is gone now.
18362
18363   return EndMBB;
18364 }
18365
18366 // The EFLAGS operand of SelectItr might be missing a kill marker
18367 // because there were multiple uses of EFLAGS, and ISel didn't know
18368 // which to mark. Figure out whether SelectItr should have had a
18369 // kill marker, and set it if it should. Returns the correct kill
18370 // marker value.
18371 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
18372                                      MachineBasicBlock* BB,
18373                                      const TargetRegisterInfo* TRI) {
18374   // Scan forward through BB for a use/def of EFLAGS.
18375   MachineBasicBlock::iterator miI(std::next(SelectItr));
18376   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
18377     const MachineInstr& mi = *miI;
18378     if (mi.readsRegister(X86::EFLAGS))
18379       return false;
18380     if (mi.definesRegister(X86::EFLAGS))
18381       break; // Should have kill-flag - update below.
18382   }
18383
18384   // If we hit the end of the block, check whether EFLAGS is live into a
18385   // successor.
18386   if (miI == BB->end()) {
18387     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
18388                                           sEnd = BB->succ_end();
18389          sItr != sEnd; ++sItr) {
18390       MachineBasicBlock* succ = *sItr;
18391       if (succ->isLiveIn(X86::EFLAGS))
18392         return false;
18393     }
18394   }
18395
18396   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
18397   // out. SelectMI should have a kill flag on EFLAGS.
18398   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
18399   return true;
18400 }
18401
18402 MachineBasicBlock *
18403 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
18404                                      MachineBasicBlock *BB) const {
18405   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18406   DebugLoc DL = MI->getDebugLoc();
18407
18408   // To "insert" a SELECT_CC instruction, we actually have to insert the
18409   // diamond control-flow pattern.  The incoming instruction knows the
18410   // destination vreg to set, the condition code register to branch on, the
18411   // true/false values to select between, and a branch opcode to use.
18412   const BasicBlock *LLVM_BB = BB->getBasicBlock();
18413   MachineFunction::iterator It = BB;
18414   ++It;
18415
18416   //  thisMBB:
18417   //  ...
18418   //   TrueVal = ...
18419   //   cmpTY ccX, r1, r2
18420   //   bCC copy1MBB
18421   //   fallthrough --> copy0MBB
18422   MachineBasicBlock *thisMBB = BB;
18423   MachineFunction *F = BB->getParent();
18424
18425   // We also lower double CMOVs:
18426   //   (CMOV (CMOV F, T, cc1), T, cc2)
18427   // to two successives branches.  For that, we look for another CMOV as the
18428   // following instruction.
18429   //
18430   // Without this, we would add a PHI between the two jumps, which ends up
18431   // creating a few copies all around. For instance, for
18432   //
18433   //    (sitofp (zext (fcmp une)))
18434   //
18435   // we would generate:
18436   //
18437   //         ucomiss %xmm1, %xmm0
18438   //         movss  <1.0f>, %xmm0
18439   //         movaps  %xmm0, %xmm1
18440   //         jne     .LBB5_2
18441   //         xorps   %xmm1, %xmm1
18442   // .LBB5_2:
18443   //         jp      .LBB5_4
18444   //         movaps  %xmm1, %xmm0
18445   // .LBB5_4:
18446   //         retq
18447   //
18448   // because this custom-inserter would have generated:
18449   //
18450   //   A
18451   //   | \
18452   //   |  B
18453   //   | /
18454   //   C
18455   //   | \
18456   //   |  D
18457   //   | /
18458   //   E
18459   //
18460   // A: X = ...; Y = ...
18461   // B: empty
18462   // C: Z = PHI [X, A], [Y, B]
18463   // D: empty
18464   // E: PHI [X, C], [Z, D]
18465   //
18466   // If we lower both CMOVs in a single step, we can instead generate:
18467   //
18468   //   A
18469   //   | \
18470   //   |  C
18471   //   | /|
18472   //   |/ |
18473   //   |  |
18474   //   |  D
18475   //   | /
18476   //   E
18477   //
18478   // A: X = ...; Y = ...
18479   // D: empty
18480   // E: PHI [X, A], [X, C], [Y, D]
18481   //
18482   // Which, in our sitofp/fcmp example, gives us something like:
18483   //
18484   //         ucomiss %xmm1, %xmm0
18485   //         movss  <1.0f>, %xmm0
18486   //         jne     .LBB5_4
18487   //         jp      .LBB5_4
18488   //         xorps   %xmm0, %xmm0
18489   // .LBB5_4:
18490   //         retq
18491   //
18492   MachineInstr *NextCMOV = nullptr;
18493   MachineBasicBlock::iterator NextMIIt =
18494       std::next(MachineBasicBlock::iterator(MI));
18495   if (NextMIIt != BB->end() && NextMIIt->getOpcode() == MI->getOpcode() &&
18496       NextMIIt->getOperand(2).getReg() == MI->getOperand(2).getReg() &&
18497       NextMIIt->getOperand(1).getReg() == MI->getOperand(0).getReg())
18498     NextCMOV = &*NextMIIt;
18499
18500   MachineBasicBlock *jcc1MBB = nullptr;
18501
18502   // If we have a double CMOV, we lower it to two successive branches to
18503   // the same block.  EFLAGS is used by both, so mark it as live in the second.
18504   if (NextCMOV) {
18505     jcc1MBB = F->CreateMachineBasicBlock(LLVM_BB);
18506     F->insert(It, jcc1MBB);
18507     jcc1MBB->addLiveIn(X86::EFLAGS);
18508   }
18509
18510   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
18511   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
18512   F->insert(It, copy0MBB);
18513   F->insert(It, sinkMBB);
18514
18515   // If the EFLAGS register isn't dead in the terminator, then claim that it's
18516   // live into the sink and copy blocks.
18517   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
18518
18519   MachineInstr *LastEFLAGSUser = NextCMOV ? NextCMOV : MI;
18520   if (!LastEFLAGSUser->killsRegister(X86::EFLAGS) &&
18521       !checkAndUpdateEFLAGSKill(LastEFLAGSUser, BB, TRI)) {
18522     copy0MBB->addLiveIn(X86::EFLAGS);
18523     sinkMBB->addLiveIn(X86::EFLAGS);
18524   }
18525
18526   // Transfer the remainder of BB and its successor edges to sinkMBB.
18527   sinkMBB->splice(sinkMBB->begin(), BB,
18528                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
18529   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
18530
18531   // Add the true and fallthrough blocks as its successors.
18532   if (NextCMOV) {
18533     // The fallthrough block may be jcc1MBB, if we have a double CMOV.
18534     BB->addSuccessor(jcc1MBB);
18535
18536     // In that case, jcc1MBB will itself fallthrough the copy0MBB, and
18537     // jump to the sinkMBB.
18538     jcc1MBB->addSuccessor(copy0MBB);
18539     jcc1MBB->addSuccessor(sinkMBB);
18540   } else {
18541     BB->addSuccessor(copy0MBB);
18542   }
18543
18544   // The true block target of the first (or only) branch is always sinkMBB.
18545   BB->addSuccessor(sinkMBB);
18546
18547   // Create the conditional branch instruction.
18548   unsigned Opc =
18549     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
18550   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
18551
18552   if (NextCMOV) {
18553     unsigned Opc2 = X86::GetCondBranchFromCond(
18554         (X86::CondCode)NextCMOV->getOperand(3).getImm());
18555     BuildMI(jcc1MBB, DL, TII->get(Opc2)).addMBB(sinkMBB);
18556   }
18557
18558   //  copy0MBB:
18559   //   %FalseValue = ...
18560   //   # fallthrough to sinkMBB
18561   copy0MBB->addSuccessor(sinkMBB);
18562
18563   //  sinkMBB:
18564   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
18565   //  ...
18566   MachineInstrBuilder MIB =
18567       BuildMI(*sinkMBB, sinkMBB->begin(), DL, TII->get(X86::PHI),
18568               MI->getOperand(0).getReg())
18569           .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
18570           .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
18571
18572   // If we have a double CMOV, the second Jcc provides the same incoming
18573   // value as the first Jcc (the True operand of the SELECT_CC/CMOV nodes).
18574   if (NextCMOV) {
18575     MIB.addReg(MI->getOperand(2).getReg()).addMBB(jcc1MBB);
18576     // Copy the PHI result to the register defined by the second CMOV.
18577     BuildMI(*sinkMBB, std::next(MachineBasicBlock::iterator(MIB.getInstr())),
18578             DL, TII->get(TargetOpcode::COPY), NextCMOV->getOperand(0).getReg())
18579         .addReg(MI->getOperand(0).getReg());
18580     NextCMOV->eraseFromParent();
18581   }
18582
18583   MI->eraseFromParent();   // The pseudo instruction is gone now.
18584   return sinkMBB;
18585 }
18586
18587 MachineBasicBlock *
18588 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI,
18589                                         MachineBasicBlock *BB) const {
18590   MachineFunction *MF = BB->getParent();
18591   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18592   DebugLoc DL = MI->getDebugLoc();
18593   const BasicBlock *LLVM_BB = BB->getBasicBlock();
18594
18595   assert(MF->shouldSplitStack());
18596
18597   const bool Is64Bit = Subtarget->is64Bit();
18598   const bool IsLP64 = Subtarget->isTarget64BitLP64();
18599
18600   const unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
18601   const unsigned TlsOffset = IsLP64 ? 0x70 : Is64Bit ? 0x40 : 0x30;
18602
18603   // BB:
18604   //  ... [Till the alloca]
18605   // If stacklet is not large enough, jump to mallocMBB
18606   //
18607   // bumpMBB:
18608   //  Allocate by subtracting from RSP
18609   //  Jump to continueMBB
18610   //
18611   // mallocMBB:
18612   //  Allocate by call to runtime
18613   //
18614   // continueMBB:
18615   //  ...
18616   //  [rest of original BB]
18617   //
18618
18619   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18620   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18621   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18622
18623   MachineRegisterInfo &MRI = MF->getRegInfo();
18624   const TargetRegisterClass *AddrRegClass =
18625     getRegClassFor(getPointerTy());
18626
18627   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
18628     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
18629     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
18630     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
18631     sizeVReg = MI->getOperand(1).getReg(),
18632     physSPReg = IsLP64 || Subtarget->isTargetNaCl64() ? X86::RSP : X86::ESP;
18633
18634   MachineFunction::iterator MBBIter = BB;
18635   ++MBBIter;
18636
18637   MF->insert(MBBIter, bumpMBB);
18638   MF->insert(MBBIter, mallocMBB);
18639   MF->insert(MBBIter, continueMBB);
18640
18641   continueMBB->splice(continueMBB->begin(), BB,
18642                       std::next(MachineBasicBlock::iterator(MI)), BB->end());
18643   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
18644
18645   // Add code to the main basic block to check if the stack limit has been hit,
18646   // and if so, jump to mallocMBB otherwise to bumpMBB.
18647   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
18648   BuildMI(BB, DL, TII->get(IsLP64 ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
18649     .addReg(tmpSPVReg).addReg(sizeVReg);
18650   BuildMI(BB, DL, TII->get(IsLP64 ? X86::CMP64mr:X86::CMP32mr))
18651     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
18652     .addReg(SPLimitVReg);
18653   BuildMI(BB, DL, TII->get(X86::JG_1)).addMBB(mallocMBB);
18654
18655   // bumpMBB simply decreases the stack pointer, since we know the current
18656   // stacklet has enough space.
18657   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
18658     .addReg(SPLimitVReg);
18659   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
18660     .addReg(SPLimitVReg);
18661   BuildMI(bumpMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
18662
18663   // Calls into a routine in libgcc to allocate more space from the heap.
18664   const uint32_t *RegMask =
18665       Subtarget->getRegisterInfo()->getCallPreservedMask(*MF, CallingConv::C);
18666   if (IsLP64) {
18667     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
18668       .addReg(sizeVReg);
18669     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
18670       .addExternalSymbol("__morestack_allocate_stack_space")
18671       .addRegMask(RegMask)
18672       .addReg(X86::RDI, RegState::Implicit)
18673       .addReg(X86::RAX, RegState::ImplicitDefine);
18674   } else if (Is64Bit) {
18675     BuildMI(mallocMBB, DL, TII->get(X86::MOV32rr), X86::EDI)
18676       .addReg(sizeVReg);
18677     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
18678       .addExternalSymbol("__morestack_allocate_stack_space")
18679       .addRegMask(RegMask)
18680       .addReg(X86::EDI, RegState::Implicit)
18681       .addReg(X86::EAX, RegState::ImplicitDefine);
18682   } else {
18683     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
18684       .addImm(12);
18685     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
18686     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
18687       .addExternalSymbol("__morestack_allocate_stack_space")
18688       .addRegMask(RegMask)
18689       .addReg(X86::EAX, RegState::ImplicitDefine);
18690   }
18691
18692   if (!Is64Bit)
18693     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
18694       .addImm(16);
18695
18696   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
18697     .addReg(IsLP64 ? X86::RAX : X86::EAX);
18698   BuildMI(mallocMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
18699
18700   // Set up the CFG correctly.
18701   BB->addSuccessor(bumpMBB);
18702   BB->addSuccessor(mallocMBB);
18703   mallocMBB->addSuccessor(continueMBB);
18704   bumpMBB->addSuccessor(continueMBB);
18705
18706   // Take care of the PHI nodes.
18707   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
18708           MI->getOperand(0).getReg())
18709     .addReg(mallocPtrVReg).addMBB(mallocMBB)
18710     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
18711
18712   // Delete the original pseudo instruction.
18713   MI->eraseFromParent();
18714
18715   // And we're done.
18716   return continueMBB;
18717 }
18718
18719 MachineBasicBlock *
18720 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
18721                                         MachineBasicBlock *BB) const {
18722   DebugLoc DL = MI->getDebugLoc();
18723
18724   assert(!Subtarget->isTargetMachO());
18725
18726   X86FrameLowering::emitStackProbeCall(*BB->getParent(), *BB, MI, DL);
18727
18728   MI->eraseFromParent();   // The pseudo instruction is gone now.
18729   return BB;
18730 }
18731
18732 MachineBasicBlock *
18733 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
18734                                       MachineBasicBlock *BB) const {
18735   // This is pretty easy.  We're taking the value that we received from
18736   // our load from the relocation, sticking it in either RDI (x86-64)
18737   // or EAX and doing an indirect call.  The return value will then
18738   // be in the normal return register.
18739   MachineFunction *F = BB->getParent();
18740   const X86InstrInfo *TII = Subtarget->getInstrInfo();
18741   DebugLoc DL = MI->getDebugLoc();
18742
18743   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
18744   assert(MI->getOperand(3).isGlobal() && "This should be a global");
18745
18746   // Get a register mask for the lowered call.
18747   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
18748   // proper register mask.
18749   const uint32_t *RegMask =
18750       Subtarget->getRegisterInfo()->getCallPreservedMask(*F, CallingConv::C);
18751   if (Subtarget->is64Bit()) {
18752     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
18753                                       TII->get(X86::MOV64rm), X86::RDI)
18754     .addReg(X86::RIP)
18755     .addImm(0).addReg(0)
18756     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
18757                       MI->getOperand(3).getTargetFlags())
18758     .addReg(0);
18759     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
18760     addDirectMem(MIB, X86::RDI);
18761     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
18762   } else if (F->getTarget().getRelocationModel() != Reloc::PIC_) {
18763     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
18764                                       TII->get(X86::MOV32rm), X86::EAX)
18765     .addReg(0)
18766     .addImm(0).addReg(0)
18767     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
18768                       MI->getOperand(3).getTargetFlags())
18769     .addReg(0);
18770     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
18771     addDirectMem(MIB, X86::EAX);
18772     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
18773   } else {
18774     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
18775                                       TII->get(X86::MOV32rm), X86::EAX)
18776     .addReg(TII->getGlobalBaseReg(F))
18777     .addImm(0).addReg(0)
18778     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
18779                       MI->getOperand(3).getTargetFlags())
18780     .addReg(0);
18781     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
18782     addDirectMem(MIB, X86::EAX);
18783     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
18784   }
18785
18786   MI->eraseFromParent(); // The pseudo instruction is gone now.
18787   return BB;
18788 }
18789
18790 MachineBasicBlock *
18791 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
18792                                     MachineBasicBlock *MBB) const {
18793   DebugLoc DL = MI->getDebugLoc();
18794   MachineFunction *MF = MBB->getParent();
18795   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18796   MachineRegisterInfo &MRI = MF->getRegInfo();
18797
18798   const BasicBlock *BB = MBB->getBasicBlock();
18799   MachineFunction::iterator I = MBB;
18800   ++I;
18801
18802   // Memory Reference
18803   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
18804   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
18805
18806   unsigned DstReg;
18807   unsigned MemOpndSlot = 0;
18808
18809   unsigned CurOp = 0;
18810
18811   DstReg = MI->getOperand(CurOp++).getReg();
18812   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
18813   assert(RC->hasType(MVT::i32) && "Invalid destination!");
18814   unsigned mainDstReg = MRI.createVirtualRegister(RC);
18815   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
18816
18817   MemOpndSlot = CurOp;
18818
18819   MVT PVT = getPointerTy();
18820   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
18821          "Invalid Pointer Size!");
18822
18823   // For v = setjmp(buf), we generate
18824   //
18825   // thisMBB:
18826   //  buf[LabelOffset] = restoreMBB
18827   //  SjLjSetup restoreMBB
18828   //
18829   // mainMBB:
18830   //  v_main = 0
18831   //
18832   // sinkMBB:
18833   //  v = phi(main, restore)
18834   //
18835   // restoreMBB:
18836   //  if base pointer being used, load it from frame
18837   //  v_restore = 1
18838
18839   MachineBasicBlock *thisMBB = MBB;
18840   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
18841   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
18842   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
18843   MF->insert(I, mainMBB);
18844   MF->insert(I, sinkMBB);
18845   MF->push_back(restoreMBB);
18846
18847   MachineInstrBuilder MIB;
18848
18849   // Transfer the remainder of BB and its successor edges to sinkMBB.
18850   sinkMBB->splice(sinkMBB->begin(), MBB,
18851                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
18852   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
18853
18854   // thisMBB:
18855   unsigned PtrStoreOpc = 0;
18856   unsigned LabelReg = 0;
18857   const int64_t LabelOffset = 1 * PVT.getStoreSize();
18858   Reloc::Model RM = MF->getTarget().getRelocationModel();
18859   bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
18860                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
18861
18862   // Prepare IP either in reg or imm.
18863   if (!UseImmLabel) {
18864     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
18865     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
18866     LabelReg = MRI.createVirtualRegister(PtrRC);
18867     if (Subtarget->is64Bit()) {
18868       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
18869               .addReg(X86::RIP)
18870               .addImm(0)
18871               .addReg(0)
18872               .addMBB(restoreMBB)
18873               .addReg(0);
18874     } else {
18875       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
18876       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
18877               .addReg(XII->getGlobalBaseReg(MF))
18878               .addImm(0)
18879               .addReg(0)
18880               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
18881               .addReg(0);
18882     }
18883   } else
18884     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
18885   // Store IP
18886   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
18887   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
18888     if (i == X86::AddrDisp)
18889       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
18890     else
18891       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
18892   }
18893   if (!UseImmLabel)
18894     MIB.addReg(LabelReg);
18895   else
18896     MIB.addMBB(restoreMBB);
18897   MIB.setMemRefs(MMOBegin, MMOEnd);
18898   // Setup
18899   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
18900           .addMBB(restoreMBB);
18901
18902   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
18903   MIB.addRegMask(RegInfo->getNoPreservedMask());
18904   thisMBB->addSuccessor(mainMBB);
18905   thisMBB->addSuccessor(restoreMBB);
18906
18907   // mainMBB:
18908   //  EAX = 0
18909   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
18910   mainMBB->addSuccessor(sinkMBB);
18911
18912   // sinkMBB:
18913   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
18914           TII->get(X86::PHI), DstReg)
18915     .addReg(mainDstReg).addMBB(mainMBB)
18916     .addReg(restoreDstReg).addMBB(restoreMBB);
18917
18918   // restoreMBB:
18919   if (RegInfo->hasBasePointer(*MF)) {
18920     const bool Uses64BitFramePtr =
18921         Subtarget->isTarget64BitLP64() || Subtarget->isTargetNaCl64();
18922     X86MachineFunctionInfo *X86FI = MF->getInfo<X86MachineFunctionInfo>();
18923     X86FI->setRestoreBasePointer(MF);
18924     unsigned FramePtr = RegInfo->getFrameRegister(*MF);
18925     unsigned BasePtr = RegInfo->getBaseRegister();
18926     unsigned Opm = Uses64BitFramePtr ? X86::MOV64rm : X86::MOV32rm;
18927     addRegOffset(BuildMI(restoreMBB, DL, TII->get(Opm), BasePtr),
18928                  FramePtr, true, X86FI->getRestoreBasePointerOffset())
18929       .setMIFlag(MachineInstr::FrameSetup);
18930   }
18931   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
18932   BuildMI(restoreMBB, DL, TII->get(X86::JMP_1)).addMBB(sinkMBB);
18933   restoreMBB->addSuccessor(sinkMBB);
18934
18935   MI->eraseFromParent();
18936   return sinkMBB;
18937 }
18938
18939 MachineBasicBlock *
18940 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
18941                                      MachineBasicBlock *MBB) const {
18942   DebugLoc DL = MI->getDebugLoc();
18943   MachineFunction *MF = MBB->getParent();
18944   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18945   MachineRegisterInfo &MRI = MF->getRegInfo();
18946
18947   // Memory Reference
18948   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
18949   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
18950
18951   MVT PVT = getPointerTy();
18952   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
18953          "Invalid Pointer Size!");
18954
18955   const TargetRegisterClass *RC =
18956     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
18957   unsigned Tmp = MRI.createVirtualRegister(RC);
18958   // Since FP is only updated here but NOT referenced, it's treated as GPR.
18959   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
18960   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
18961   unsigned SP = RegInfo->getStackRegister();
18962
18963   MachineInstrBuilder MIB;
18964
18965   const int64_t LabelOffset = 1 * PVT.getStoreSize();
18966   const int64_t SPOffset = 2 * PVT.getStoreSize();
18967
18968   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
18969   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
18970
18971   // Reload FP
18972   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
18973   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
18974     MIB.addOperand(MI->getOperand(i));
18975   MIB.setMemRefs(MMOBegin, MMOEnd);
18976   // Reload IP
18977   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
18978   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
18979     if (i == X86::AddrDisp)
18980       MIB.addDisp(MI->getOperand(i), LabelOffset);
18981     else
18982       MIB.addOperand(MI->getOperand(i));
18983   }
18984   MIB.setMemRefs(MMOBegin, MMOEnd);
18985   // Reload SP
18986   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
18987   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
18988     if (i == X86::AddrDisp)
18989       MIB.addDisp(MI->getOperand(i), SPOffset);
18990     else
18991       MIB.addOperand(MI->getOperand(i));
18992   }
18993   MIB.setMemRefs(MMOBegin, MMOEnd);
18994   // Jump
18995   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
18996
18997   MI->eraseFromParent();
18998   return MBB;
18999 }
19000
19001 // Replace 213-type (isel default) FMA3 instructions with 231-type for
19002 // accumulator loops. Writing back to the accumulator allows the coalescer
19003 // to remove extra copies in the loop.
19004 MachineBasicBlock *
19005 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
19006                                  MachineBasicBlock *MBB) const {
19007   MachineOperand &AddendOp = MI->getOperand(3);
19008
19009   // Bail out early if the addend isn't a register - we can't switch these.
19010   if (!AddendOp.isReg())
19011     return MBB;
19012
19013   MachineFunction &MF = *MBB->getParent();
19014   MachineRegisterInfo &MRI = MF.getRegInfo();
19015
19016   // Check whether the addend is defined by a PHI:
19017   assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
19018   MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
19019   if (!AddendDef.isPHI())
19020     return MBB;
19021
19022   // Look for the following pattern:
19023   // loop:
19024   //   %addend = phi [%entry, 0], [%loop, %result]
19025   //   ...
19026   //   %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
19027
19028   // Replace with:
19029   //   loop:
19030   //   %addend = phi [%entry, 0], [%loop, %result]
19031   //   ...
19032   //   %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
19033
19034   for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
19035     assert(AddendDef.getOperand(i).isReg());
19036     MachineOperand PHISrcOp = AddendDef.getOperand(i);
19037     MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
19038     if (&PHISrcInst == MI) {
19039       // Found a matching instruction.
19040       unsigned NewFMAOpc = 0;
19041       switch (MI->getOpcode()) {
19042         case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
19043         case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
19044         case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
19045         case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
19046         case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
19047         case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
19048         case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
19049         case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
19050         case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
19051         case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
19052         case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
19053         case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
19054         case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
19055         case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
19056         case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
19057         case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
19058         case X86::VFMADDSUBPDr213r: NewFMAOpc = X86::VFMADDSUBPDr231r; break;
19059         case X86::VFMADDSUBPSr213r: NewFMAOpc = X86::VFMADDSUBPSr231r; break;
19060         case X86::VFMSUBADDPDr213r: NewFMAOpc = X86::VFMSUBADDPDr231r; break;
19061         case X86::VFMSUBADDPSr213r: NewFMAOpc = X86::VFMSUBADDPSr231r; break;
19062
19063         case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
19064         case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
19065         case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
19066         case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
19067         case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
19068         case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
19069         case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
19070         case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
19071         case X86::VFMADDSUBPDr213rY: NewFMAOpc = X86::VFMADDSUBPDr231rY; break;
19072         case X86::VFMADDSUBPSr213rY: NewFMAOpc = X86::VFMADDSUBPSr231rY; break;
19073         case X86::VFMSUBADDPDr213rY: NewFMAOpc = X86::VFMSUBADDPDr231rY; break;
19074         case X86::VFMSUBADDPSr213rY: NewFMAOpc = X86::VFMSUBADDPSr231rY; break;
19075         default: llvm_unreachable("Unrecognized FMA variant.");
19076       }
19077
19078       const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
19079       MachineInstrBuilder MIB =
19080         BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
19081         .addOperand(MI->getOperand(0))
19082         .addOperand(MI->getOperand(3))
19083         .addOperand(MI->getOperand(2))
19084         .addOperand(MI->getOperand(1));
19085       MBB->insert(MachineBasicBlock::iterator(MI), MIB);
19086       MI->eraseFromParent();
19087     }
19088   }
19089
19090   return MBB;
19091 }
19092
19093 MachineBasicBlock *
19094 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
19095                                                MachineBasicBlock *BB) const {
19096   switch (MI->getOpcode()) {
19097   default: llvm_unreachable("Unexpected instr type to insert");
19098   case X86::TAILJMPd64:
19099   case X86::TAILJMPr64:
19100   case X86::TAILJMPm64:
19101   case X86::TAILJMPd64_REX:
19102   case X86::TAILJMPr64_REX:
19103   case X86::TAILJMPm64_REX:
19104     llvm_unreachable("TAILJMP64 would not be touched here.");
19105   case X86::TCRETURNdi64:
19106   case X86::TCRETURNri64:
19107   case X86::TCRETURNmi64:
19108     return BB;
19109   case X86::WIN_ALLOCA:
19110     return EmitLoweredWinAlloca(MI, BB);
19111   case X86::SEG_ALLOCA_32:
19112   case X86::SEG_ALLOCA_64:
19113     return EmitLoweredSegAlloca(MI, BB);
19114   case X86::TLSCall_32:
19115   case X86::TLSCall_64:
19116     return EmitLoweredTLSCall(MI, BB);
19117   case X86::CMOV_GR8:
19118   case X86::CMOV_FR32:
19119   case X86::CMOV_FR64:
19120   case X86::CMOV_V4F32:
19121   case X86::CMOV_V2F64:
19122   case X86::CMOV_V2I64:
19123   case X86::CMOV_V8F32:
19124   case X86::CMOV_V4F64:
19125   case X86::CMOV_V4I64:
19126   case X86::CMOV_V16F32:
19127   case X86::CMOV_V8F64:
19128   case X86::CMOV_V8I64:
19129   case X86::CMOV_GR16:
19130   case X86::CMOV_GR32:
19131   case X86::CMOV_RFP32:
19132   case X86::CMOV_RFP64:
19133   case X86::CMOV_RFP80:
19134     return EmitLoweredSelect(MI, BB);
19135
19136   case X86::FP32_TO_INT16_IN_MEM:
19137   case X86::FP32_TO_INT32_IN_MEM:
19138   case X86::FP32_TO_INT64_IN_MEM:
19139   case X86::FP64_TO_INT16_IN_MEM:
19140   case X86::FP64_TO_INT32_IN_MEM:
19141   case X86::FP64_TO_INT64_IN_MEM:
19142   case X86::FP80_TO_INT16_IN_MEM:
19143   case X86::FP80_TO_INT32_IN_MEM:
19144   case X86::FP80_TO_INT64_IN_MEM: {
19145     MachineFunction *F = BB->getParent();
19146     const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19147     DebugLoc DL = MI->getDebugLoc();
19148
19149     // Change the floating point control register to use "round towards zero"
19150     // mode when truncating to an integer value.
19151     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
19152     addFrameReference(BuildMI(*BB, MI, DL,
19153                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
19154
19155     // Load the old value of the high byte of the control word...
19156     unsigned OldCW =
19157       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
19158     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
19159                       CWFrameIdx);
19160
19161     // Set the high part to be round to zero...
19162     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
19163       .addImm(0xC7F);
19164
19165     // Reload the modified control word now...
19166     addFrameReference(BuildMI(*BB, MI, DL,
19167                               TII->get(X86::FLDCW16m)), CWFrameIdx);
19168
19169     // Restore the memory image of control word to original value
19170     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
19171       .addReg(OldCW);
19172
19173     // Get the X86 opcode to use.
19174     unsigned Opc;
19175     switch (MI->getOpcode()) {
19176     default: llvm_unreachable("illegal opcode!");
19177     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
19178     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
19179     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
19180     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
19181     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
19182     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
19183     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
19184     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
19185     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
19186     }
19187
19188     X86AddressMode AM;
19189     MachineOperand &Op = MI->getOperand(0);
19190     if (Op.isReg()) {
19191       AM.BaseType = X86AddressMode::RegBase;
19192       AM.Base.Reg = Op.getReg();
19193     } else {
19194       AM.BaseType = X86AddressMode::FrameIndexBase;
19195       AM.Base.FrameIndex = Op.getIndex();
19196     }
19197     Op = MI->getOperand(1);
19198     if (Op.isImm())
19199       AM.Scale = Op.getImm();
19200     Op = MI->getOperand(2);
19201     if (Op.isImm())
19202       AM.IndexReg = Op.getImm();
19203     Op = MI->getOperand(3);
19204     if (Op.isGlobal()) {
19205       AM.GV = Op.getGlobal();
19206     } else {
19207       AM.Disp = Op.getImm();
19208     }
19209     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
19210                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
19211
19212     // Reload the original control word now.
19213     addFrameReference(BuildMI(*BB, MI, DL,
19214                               TII->get(X86::FLDCW16m)), CWFrameIdx);
19215
19216     MI->eraseFromParent();   // The pseudo instruction is gone now.
19217     return BB;
19218   }
19219     // String/text processing lowering.
19220   case X86::PCMPISTRM128REG:
19221   case X86::VPCMPISTRM128REG:
19222   case X86::PCMPISTRM128MEM:
19223   case X86::VPCMPISTRM128MEM:
19224   case X86::PCMPESTRM128REG:
19225   case X86::VPCMPESTRM128REG:
19226   case X86::PCMPESTRM128MEM:
19227   case X86::VPCMPESTRM128MEM:
19228     assert(Subtarget->hasSSE42() &&
19229            "Target must have SSE4.2 or AVX features enabled");
19230     return EmitPCMPSTRM(MI, BB, Subtarget->getInstrInfo());
19231
19232   // String/text processing lowering.
19233   case X86::PCMPISTRIREG:
19234   case X86::VPCMPISTRIREG:
19235   case X86::PCMPISTRIMEM:
19236   case X86::VPCMPISTRIMEM:
19237   case X86::PCMPESTRIREG:
19238   case X86::VPCMPESTRIREG:
19239   case X86::PCMPESTRIMEM:
19240   case X86::VPCMPESTRIMEM:
19241     assert(Subtarget->hasSSE42() &&
19242            "Target must have SSE4.2 or AVX features enabled");
19243     return EmitPCMPSTRI(MI, BB, Subtarget->getInstrInfo());
19244
19245   // Thread synchronization.
19246   case X86::MONITOR:
19247     return EmitMonitor(MI, BB, Subtarget);
19248
19249   // xbegin
19250   case X86::XBEGIN:
19251     return EmitXBegin(MI, BB, Subtarget->getInstrInfo());
19252
19253   case X86::VASTART_SAVE_XMM_REGS:
19254     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
19255
19256   case X86::VAARG_64:
19257     return EmitVAARG64WithCustomInserter(MI, BB);
19258
19259   case X86::EH_SjLj_SetJmp32:
19260   case X86::EH_SjLj_SetJmp64:
19261     return emitEHSjLjSetJmp(MI, BB);
19262
19263   case X86::EH_SjLj_LongJmp32:
19264   case X86::EH_SjLj_LongJmp64:
19265     return emitEHSjLjLongJmp(MI, BB);
19266
19267   case TargetOpcode::STATEPOINT:
19268     // As an implementation detail, STATEPOINT shares the STACKMAP format at
19269     // this point in the process.  We diverge later.
19270     return emitPatchPoint(MI, BB);
19271
19272   case TargetOpcode::STACKMAP:
19273   case TargetOpcode::PATCHPOINT:
19274     return emitPatchPoint(MI, BB);
19275
19276   case X86::VFMADDPDr213r:
19277   case X86::VFMADDPSr213r:
19278   case X86::VFMADDSDr213r:
19279   case X86::VFMADDSSr213r:
19280   case X86::VFMSUBPDr213r:
19281   case X86::VFMSUBPSr213r:
19282   case X86::VFMSUBSDr213r:
19283   case X86::VFMSUBSSr213r:
19284   case X86::VFNMADDPDr213r:
19285   case X86::VFNMADDPSr213r:
19286   case X86::VFNMADDSDr213r:
19287   case X86::VFNMADDSSr213r:
19288   case X86::VFNMSUBPDr213r:
19289   case X86::VFNMSUBPSr213r:
19290   case X86::VFNMSUBSDr213r:
19291   case X86::VFNMSUBSSr213r:
19292   case X86::VFMADDSUBPDr213r:
19293   case X86::VFMADDSUBPSr213r:
19294   case X86::VFMSUBADDPDr213r:
19295   case X86::VFMSUBADDPSr213r:
19296   case X86::VFMADDPDr213rY:
19297   case X86::VFMADDPSr213rY:
19298   case X86::VFMSUBPDr213rY:
19299   case X86::VFMSUBPSr213rY:
19300   case X86::VFNMADDPDr213rY:
19301   case X86::VFNMADDPSr213rY:
19302   case X86::VFNMSUBPDr213rY:
19303   case X86::VFNMSUBPSr213rY:
19304   case X86::VFMADDSUBPDr213rY:
19305   case X86::VFMADDSUBPSr213rY:
19306   case X86::VFMSUBADDPDr213rY:
19307   case X86::VFMSUBADDPSr213rY:
19308     return emitFMA3Instr(MI, BB);
19309   }
19310 }
19311
19312 //===----------------------------------------------------------------------===//
19313 //                           X86 Optimization Hooks
19314 //===----------------------------------------------------------------------===//
19315
19316 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
19317                                                       APInt &KnownZero,
19318                                                       APInt &KnownOne,
19319                                                       const SelectionDAG &DAG,
19320                                                       unsigned Depth) const {
19321   unsigned BitWidth = KnownZero.getBitWidth();
19322   unsigned Opc = Op.getOpcode();
19323   assert((Opc >= ISD::BUILTIN_OP_END ||
19324           Opc == ISD::INTRINSIC_WO_CHAIN ||
19325           Opc == ISD::INTRINSIC_W_CHAIN ||
19326           Opc == ISD::INTRINSIC_VOID) &&
19327          "Should use MaskedValueIsZero if you don't know whether Op"
19328          " is a target node!");
19329
19330   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
19331   switch (Opc) {
19332   default: break;
19333   case X86ISD::ADD:
19334   case X86ISD::SUB:
19335   case X86ISD::ADC:
19336   case X86ISD::SBB:
19337   case X86ISD::SMUL:
19338   case X86ISD::UMUL:
19339   case X86ISD::INC:
19340   case X86ISD::DEC:
19341   case X86ISD::OR:
19342   case X86ISD::XOR:
19343   case X86ISD::AND:
19344     // These nodes' second result is a boolean.
19345     if (Op.getResNo() == 0)
19346       break;
19347     // Fallthrough
19348   case X86ISD::SETCC:
19349     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
19350     break;
19351   case ISD::INTRINSIC_WO_CHAIN: {
19352     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
19353     unsigned NumLoBits = 0;
19354     switch (IntId) {
19355     default: break;
19356     case Intrinsic::x86_sse_movmsk_ps:
19357     case Intrinsic::x86_avx_movmsk_ps_256:
19358     case Intrinsic::x86_sse2_movmsk_pd:
19359     case Intrinsic::x86_avx_movmsk_pd_256:
19360     case Intrinsic::x86_mmx_pmovmskb:
19361     case Intrinsic::x86_sse2_pmovmskb_128:
19362     case Intrinsic::x86_avx2_pmovmskb: {
19363       // High bits of movmskp{s|d}, pmovmskb are known zero.
19364       switch (IntId) {
19365         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
19366         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
19367         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
19368         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
19369         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
19370         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
19371         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
19372         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
19373       }
19374       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
19375       break;
19376     }
19377     }
19378     break;
19379   }
19380   }
19381 }
19382
19383 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
19384   SDValue Op,
19385   const SelectionDAG &,
19386   unsigned Depth) const {
19387   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
19388   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
19389     return Op.getValueType().getScalarType().getSizeInBits();
19390
19391   // Fallback case.
19392   return 1;
19393 }
19394
19395 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
19396 /// node is a GlobalAddress + offset.
19397 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
19398                                        const GlobalValue* &GA,
19399                                        int64_t &Offset) const {
19400   if (N->getOpcode() == X86ISD::Wrapper) {
19401     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
19402       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
19403       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
19404       return true;
19405     }
19406   }
19407   return TargetLowering::isGAPlusOffset(N, GA, Offset);
19408 }
19409
19410 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
19411 /// same as extracting the high 128-bit part of 256-bit vector and then
19412 /// inserting the result into the low part of a new 256-bit vector
19413 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
19414   EVT VT = SVOp->getValueType(0);
19415   unsigned NumElems = VT.getVectorNumElements();
19416
19417   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
19418   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
19419     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
19420         SVOp->getMaskElt(j) >= 0)
19421       return false;
19422
19423   return true;
19424 }
19425
19426 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
19427 /// same as extracting the low 128-bit part of 256-bit vector and then
19428 /// inserting the result into the high part of a new 256-bit vector
19429 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
19430   EVT VT = SVOp->getValueType(0);
19431   unsigned NumElems = VT.getVectorNumElements();
19432
19433   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
19434   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
19435     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
19436         SVOp->getMaskElt(j) >= 0)
19437       return false;
19438
19439   return true;
19440 }
19441
19442 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
19443 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
19444                                         TargetLowering::DAGCombinerInfo &DCI,
19445                                         const X86Subtarget* Subtarget) {
19446   SDLoc dl(N);
19447   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
19448   SDValue V1 = SVOp->getOperand(0);
19449   SDValue V2 = SVOp->getOperand(1);
19450   EVT VT = SVOp->getValueType(0);
19451   unsigned NumElems = VT.getVectorNumElements();
19452
19453   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
19454       V2.getOpcode() == ISD::CONCAT_VECTORS) {
19455     //
19456     //                   0,0,0,...
19457     //                      |
19458     //    V      UNDEF    BUILD_VECTOR    UNDEF
19459     //     \      /           \           /
19460     //  CONCAT_VECTOR         CONCAT_VECTOR
19461     //         \                  /
19462     //          \                /
19463     //          RESULT: V + zero extended
19464     //
19465     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
19466         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
19467         V1.getOperand(1).getOpcode() != ISD::UNDEF)
19468       return SDValue();
19469
19470     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
19471       return SDValue();
19472
19473     // To match the shuffle mask, the first half of the mask should
19474     // be exactly the first vector, and all the rest a splat with the
19475     // first element of the second one.
19476     for (unsigned i = 0; i != NumElems/2; ++i)
19477       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
19478           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
19479         return SDValue();
19480
19481     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
19482     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
19483       if (Ld->hasNUsesOfValue(1, 0)) {
19484         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
19485         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
19486         SDValue ResNode =
19487           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
19488                                   Ld->getMemoryVT(),
19489                                   Ld->getPointerInfo(),
19490                                   Ld->getAlignment(),
19491                                   false/*isVolatile*/, true/*ReadMem*/,
19492                                   false/*WriteMem*/);
19493
19494         // Make sure the newly-created LOAD is in the same position as Ld in
19495         // terms of dependency. We create a TokenFactor for Ld and ResNode,
19496         // and update uses of Ld's output chain to use the TokenFactor.
19497         if (Ld->hasAnyUseOfValue(1)) {
19498           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
19499                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
19500           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
19501           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
19502                                  SDValue(ResNode.getNode(), 1));
19503         }
19504
19505         return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
19506       }
19507     }
19508
19509     // Emit a zeroed vector and insert the desired subvector on its
19510     // first half.
19511     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
19512     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
19513     return DCI.CombineTo(N, InsV);
19514   }
19515
19516   //===--------------------------------------------------------------------===//
19517   // Combine some shuffles into subvector extracts and inserts:
19518   //
19519
19520   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
19521   if (isShuffleHigh128VectorInsertLow(SVOp)) {
19522     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
19523     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
19524     return DCI.CombineTo(N, InsV);
19525   }
19526
19527   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
19528   if (isShuffleLow128VectorInsertHigh(SVOp)) {
19529     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
19530     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
19531     return DCI.CombineTo(N, InsV);
19532   }
19533
19534   return SDValue();
19535 }
19536
19537 /// \brief Combine an arbitrary chain of shuffles into a single instruction if
19538 /// possible.
19539 ///
19540 /// This is the leaf of the recursive combinine below. When we have found some
19541 /// chain of single-use x86 shuffle instructions and accumulated the combined
19542 /// shuffle mask represented by them, this will try to pattern match that mask
19543 /// into either a single instruction if there is a special purpose instruction
19544 /// for this operation, or into a PSHUFB instruction which is a fully general
19545 /// instruction but should only be used to replace chains over a certain depth.
19546 static bool combineX86ShuffleChain(SDValue Op, SDValue Root, ArrayRef<int> Mask,
19547                                    int Depth, bool HasPSHUFB, SelectionDAG &DAG,
19548                                    TargetLowering::DAGCombinerInfo &DCI,
19549                                    const X86Subtarget *Subtarget) {
19550   assert(!Mask.empty() && "Cannot combine an empty shuffle mask!");
19551
19552   // Find the operand that enters the chain. Note that multiple uses are OK
19553   // here, we're not going to remove the operand we find.
19554   SDValue Input = Op.getOperand(0);
19555   while (Input.getOpcode() == ISD::BITCAST)
19556     Input = Input.getOperand(0);
19557
19558   MVT VT = Input.getSimpleValueType();
19559   MVT RootVT = Root.getSimpleValueType();
19560   SDLoc DL(Root);
19561
19562   // Just remove no-op shuffle masks.
19563   if (Mask.size() == 1) {
19564     DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Input),
19565                   /*AddTo*/ true);
19566     return true;
19567   }
19568
19569   // Use the float domain if the operand type is a floating point type.
19570   bool FloatDomain = VT.isFloatingPoint();
19571
19572   // For floating point shuffles, we don't have free copies in the shuffle
19573   // instructions or the ability to load as part of the instruction, so
19574   // canonicalize their shuffles to UNPCK or MOV variants.
19575   //
19576   // Note that even with AVX we prefer the PSHUFD form of shuffle for integer
19577   // vectors because it can have a load folded into it that UNPCK cannot. This
19578   // doesn't preclude something switching to the shorter encoding post-RA.
19579   //
19580   // FIXME: Should teach these routines about AVX vector widths.
19581   if (FloatDomain && VT.getSizeInBits() == 128) {
19582     if (Mask.equals({0, 0}) || Mask.equals({1, 1})) {
19583       bool Lo = Mask.equals({0, 0});
19584       unsigned Shuffle;
19585       MVT ShuffleVT;
19586       // Check if we have SSE3 which will let us use MOVDDUP. That instruction
19587       // is no slower than UNPCKLPD but has the option to fold the input operand
19588       // into even an unaligned memory load.
19589       if (Lo && Subtarget->hasSSE3()) {
19590         Shuffle = X86ISD::MOVDDUP;
19591         ShuffleVT = MVT::v2f64;
19592       } else {
19593         // We have MOVLHPS and MOVHLPS throughout SSE and they encode smaller
19594         // than the UNPCK variants.
19595         Shuffle = Lo ? X86ISD::MOVLHPS : X86ISD::MOVHLPS;
19596         ShuffleVT = MVT::v4f32;
19597       }
19598       if (Depth == 1 && Root->getOpcode() == Shuffle)
19599         return false; // Nothing to do!
19600       Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
19601       DCI.AddToWorklist(Op.getNode());
19602       if (Shuffle == X86ISD::MOVDDUP)
19603         Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
19604       else
19605         Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
19606       DCI.AddToWorklist(Op.getNode());
19607       DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
19608                     /*AddTo*/ true);
19609       return true;
19610     }
19611     if (Subtarget->hasSSE3() &&
19612         (Mask.equals({0, 0, 2, 2}) || Mask.equals({1, 1, 3, 3}))) {
19613       bool Lo = Mask.equals({0, 0, 2, 2});
19614       unsigned Shuffle = Lo ? X86ISD::MOVSLDUP : X86ISD::MOVSHDUP;
19615       MVT ShuffleVT = MVT::v4f32;
19616       if (Depth == 1 && Root->getOpcode() == Shuffle)
19617         return false; // Nothing to do!
19618       Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
19619       DCI.AddToWorklist(Op.getNode());
19620       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
19621       DCI.AddToWorklist(Op.getNode());
19622       DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
19623                     /*AddTo*/ true);
19624       return true;
19625     }
19626     if (Mask.equals({0, 0, 1, 1}) || Mask.equals({2, 2, 3, 3})) {
19627       bool Lo = Mask.equals({0, 0, 1, 1});
19628       unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
19629       MVT ShuffleVT = MVT::v4f32;
19630       if (Depth == 1 && Root->getOpcode() == Shuffle)
19631         return false; // Nothing to do!
19632       Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
19633       DCI.AddToWorklist(Op.getNode());
19634       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
19635       DCI.AddToWorklist(Op.getNode());
19636       DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
19637                     /*AddTo*/ true);
19638       return true;
19639     }
19640   }
19641
19642   // We always canonicalize the 8 x i16 and 16 x i8 shuffles into their UNPCK
19643   // variants as none of these have single-instruction variants that are
19644   // superior to the UNPCK formulation.
19645   if (!FloatDomain && VT.getSizeInBits() == 128 &&
19646       (Mask.equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
19647        Mask.equals({4, 4, 5, 5, 6, 6, 7, 7}) ||
19648        Mask.equals({0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7}) ||
19649        Mask.equals(
19650            {8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15, 15}))) {
19651     bool Lo = Mask[0] == 0;
19652     unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
19653     if (Depth == 1 && Root->getOpcode() == Shuffle)
19654       return false; // Nothing to do!
19655     MVT ShuffleVT;
19656     switch (Mask.size()) {
19657     case 8:
19658       ShuffleVT = MVT::v8i16;
19659       break;
19660     case 16:
19661       ShuffleVT = MVT::v16i8;
19662       break;
19663     default:
19664       llvm_unreachable("Impossible mask size!");
19665     };
19666     Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
19667     DCI.AddToWorklist(Op.getNode());
19668     Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
19669     DCI.AddToWorklist(Op.getNode());
19670     DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
19671                   /*AddTo*/ true);
19672     return true;
19673   }
19674
19675   // Don't try to re-form single instruction chains under any circumstances now
19676   // that we've done encoding canonicalization for them.
19677   if (Depth < 2)
19678     return false;
19679
19680   // If we have 3 or more shuffle instructions or a chain involving PSHUFB, we
19681   // can replace them with a single PSHUFB instruction profitably. Intel's
19682   // manuals suggest only using PSHUFB if doing so replacing 5 instructions, but
19683   // in practice PSHUFB tends to be *very* fast so we're more aggressive.
19684   if ((Depth >= 3 || HasPSHUFB) && Subtarget->hasSSSE3()) {
19685     SmallVector<SDValue, 16> PSHUFBMask;
19686     int NumBytes = VT.getSizeInBits() / 8;
19687     int Ratio = NumBytes / Mask.size();
19688     for (int i = 0; i < NumBytes; ++i) {
19689       if (Mask[i / Ratio] == SM_SentinelUndef) {
19690         PSHUFBMask.push_back(DAG.getUNDEF(MVT::i8));
19691         continue;
19692       }
19693       int M = Mask[i / Ratio] != SM_SentinelZero
19694                   ? Ratio * Mask[i / Ratio] + i % Ratio
19695                   : 255;
19696       PSHUFBMask.push_back(DAG.getConstant(M, MVT::i8));
19697     }
19698     MVT ByteVT = MVT::getVectorVT(MVT::i8, NumBytes);
19699     Op = DAG.getNode(ISD::BITCAST, DL, ByteVT, Input);
19700     DCI.AddToWorklist(Op.getNode());
19701     SDValue PSHUFBMaskOp =
19702         DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVT, PSHUFBMask);
19703     DCI.AddToWorklist(PSHUFBMaskOp.getNode());
19704     Op = DAG.getNode(X86ISD::PSHUFB, DL, ByteVT, Op, PSHUFBMaskOp);
19705     DCI.AddToWorklist(Op.getNode());
19706     DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
19707                   /*AddTo*/ true);
19708     return true;
19709   }
19710
19711   // Failed to find any combines.
19712   return false;
19713 }
19714
19715 /// \brief Fully generic combining of x86 shuffle instructions.
19716 ///
19717 /// This should be the last combine run over the x86 shuffle instructions. Once
19718 /// they have been fully optimized, this will recursively consider all chains
19719 /// of single-use shuffle instructions, build a generic model of the cumulative
19720 /// shuffle operation, and check for simpler instructions which implement this
19721 /// operation. We use this primarily for two purposes:
19722 ///
19723 /// 1) Collapse generic shuffles to specialized single instructions when
19724 ///    equivalent. In most cases, this is just an encoding size win, but
19725 ///    sometimes we will collapse multiple generic shuffles into a single
19726 ///    special-purpose shuffle.
19727 /// 2) Look for sequences of shuffle instructions with 3 or more total
19728 ///    instructions, and replace them with the slightly more expensive SSSE3
19729 ///    PSHUFB instruction if available. We do this as the last combining step
19730 ///    to ensure we avoid using PSHUFB if we can implement the shuffle with
19731 ///    a suitable short sequence of other instructions. The PHUFB will either
19732 ///    use a register or have to read from memory and so is slightly (but only
19733 ///    slightly) more expensive than the other shuffle instructions.
19734 ///
19735 /// Because this is inherently a quadratic operation (for each shuffle in
19736 /// a chain, we recurse up the chain), the depth is limited to 8 instructions.
19737 /// This should never be an issue in practice as the shuffle lowering doesn't
19738 /// produce sequences of more than 8 instructions.
19739 ///
19740 /// FIXME: We will currently miss some cases where the redundant shuffling
19741 /// would simplify under the threshold for PSHUFB formation because of
19742 /// combine-ordering. To fix this, we should do the redundant instruction
19743 /// combining in this recursive walk.
19744 static bool combineX86ShufflesRecursively(SDValue Op, SDValue Root,
19745                                           ArrayRef<int> RootMask,
19746                                           int Depth, bool HasPSHUFB,
19747                                           SelectionDAG &DAG,
19748                                           TargetLowering::DAGCombinerInfo &DCI,
19749                                           const X86Subtarget *Subtarget) {
19750   // Bound the depth of our recursive combine because this is ultimately
19751   // quadratic in nature.
19752   if (Depth > 8)
19753     return false;
19754
19755   // Directly rip through bitcasts to find the underlying operand.
19756   while (Op.getOpcode() == ISD::BITCAST && Op.getOperand(0).hasOneUse())
19757     Op = Op.getOperand(0);
19758
19759   MVT VT = Op.getSimpleValueType();
19760   if (!VT.isVector())
19761     return false; // Bail if we hit a non-vector.
19762
19763   assert(Root.getSimpleValueType().isVector() &&
19764          "Shuffles operate on vector types!");
19765   assert(VT.getSizeInBits() == Root.getSimpleValueType().getSizeInBits() &&
19766          "Can only combine shuffles of the same vector register size.");
19767
19768   if (!isTargetShuffle(Op.getOpcode()))
19769     return false;
19770   SmallVector<int, 16> OpMask;
19771   bool IsUnary;
19772   bool HaveMask = getTargetShuffleMask(Op.getNode(), VT, OpMask, IsUnary);
19773   // We only can combine unary shuffles which we can decode the mask for.
19774   if (!HaveMask || !IsUnary)
19775     return false;
19776
19777   assert(VT.getVectorNumElements() == OpMask.size() &&
19778          "Different mask size from vector size!");
19779   assert(((RootMask.size() > OpMask.size() &&
19780            RootMask.size() % OpMask.size() == 0) ||
19781           (OpMask.size() > RootMask.size() &&
19782            OpMask.size() % RootMask.size() == 0) ||
19783           OpMask.size() == RootMask.size()) &&
19784          "The smaller number of elements must divide the larger.");
19785   int RootRatio = std::max<int>(1, OpMask.size() / RootMask.size());
19786   int OpRatio = std::max<int>(1, RootMask.size() / OpMask.size());
19787   assert(((RootRatio == 1 && OpRatio == 1) ||
19788           (RootRatio == 1) != (OpRatio == 1)) &&
19789          "Must not have a ratio for both incoming and op masks!");
19790
19791   SmallVector<int, 16> Mask;
19792   Mask.reserve(std::max(OpMask.size(), RootMask.size()));
19793
19794   // Merge this shuffle operation's mask into our accumulated mask. Note that
19795   // this shuffle's mask will be the first applied to the input, followed by the
19796   // root mask to get us all the way to the root value arrangement. The reason
19797   // for this order is that we are recursing up the operation chain.
19798   for (int i = 0, e = std::max(OpMask.size(), RootMask.size()); i < e; ++i) {
19799     int RootIdx = i / RootRatio;
19800     if (RootMask[RootIdx] < 0) {
19801       // This is a zero or undef lane, we're done.
19802       Mask.push_back(RootMask[RootIdx]);
19803       continue;
19804     }
19805
19806     int RootMaskedIdx = RootMask[RootIdx] * RootRatio + i % RootRatio;
19807     int OpIdx = RootMaskedIdx / OpRatio;
19808     if (OpMask[OpIdx] < 0) {
19809       // The incoming lanes are zero or undef, it doesn't matter which ones we
19810       // are using.
19811       Mask.push_back(OpMask[OpIdx]);
19812       continue;
19813     }
19814
19815     // Ok, we have non-zero lanes, map them through.
19816     Mask.push_back(OpMask[OpIdx] * OpRatio +
19817                    RootMaskedIdx % OpRatio);
19818   }
19819
19820   // See if we can recurse into the operand to combine more things.
19821   switch (Op.getOpcode()) {
19822     case X86ISD::PSHUFB:
19823       HasPSHUFB = true;
19824     case X86ISD::PSHUFD:
19825     case X86ISD::PSHUFHW:
19826     case X86ISD::PSHUFLW:
19827       if (Op.getOperand(0).hasOneUse() &&
19828           combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
19829                                         HasPSHUFB, DAG, DCI, Subtarget))
19830         return true;
19831       break;
19832
19833     case X86ISD::UNPCKL:
19834     case X86ISD::UNPCKH:
19835       assert(Op.getOperand(0) == Op.getOperand(1) && "We only combine unary shuffles!");
19836       // We can't check for single use, we have to check that this shuffle is the only user.
19837       if (Op->isOnlyUserOf(Op.getOperand(0).getNode()) &&
19838           combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
19839                                         HasPSHUFB, DAG, DCI, Subtarget))
19840           return true;
19841       break;
19842   }
19843
19844   // Minor canonicalization of the accumulated shuffle mask to make it easier
19845   // to match below. All this does is detect masks with squential pairs of
19846   // elements, and shrink them to the half-width mask. It does this in a loop
19847   // so it will reduce the size of the mask to the minimal width mask which
19848   // performs an equivalent shuffle.
19849   SmallVector<int, 16> WidenedMask;
19850   while (Mask.size() > 1 && canWidenShuffleElements(Mask, WidenedMask)) {
19851     Mask = std::move(WidenedMask);
19852     WidenedMask.clear();
19853   }
19854
19855   return combineX86ShuffleChain(Op, Root, Mask, Depth, HasPSHUFB, DAG, DCI,
19856                                 Subtarget);
19857 }
19858
19859 /// \brief Get the PSHUF-style mask from PSHUF node.
19860 ///
19861 /// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
19862 /// PSHUF-style masks that can be reused with such instructions.
19863 static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
19864   MVT VT = N.getSimpleValueType();
19865   SmallVector<int, 4> Mask;
19866   bool IsUnary;
19867   bool HaveMask = getTargetShuffleMask(N.getNode(), VT, Mask, IsUnary);
19868   (void)HaveMask;
19869   assert(HaveMask);
19870
19871   // If we have more than 128-bits, only the low 128-bits of shuffle mask
19872   // matter. Check that the upper masks are repeats and remove them.
19873   if (VT.getSizeInBits() > 128) {
19874     int LaneElts = 128 / VT.getScalarSizeInBits();
19875 #ifndef NDEBUG
19876     for (int i = 1, NumLanes = VT.getSizeInBits() / 128; i < NumLanes; ++i)
19877       for (int j = 0; j < LaneElts; ++j)
19878         assert(Mask[j] == Mask[i * LaneElts + j] - LaneElts &&
19879                "Mask doesn't repeat in high 128-bit lanes!");
19880 #endif
19881     Mask.resize(LaneElts);
19882   }
19883
19884   switch (N.getOpcode()) {
19885   case X86ISD::PSHUFD:
19886     return Mask;
19887   case X86ISD::PSHUFLW:
19888     Mask.resize(4);
19889     return Mask;
19890   case X86ISD::PSHUFHW:
19891     Mask.erase(Mask.begin(), Mask.begin() + 4);
19892     for (int &M : Mask)
19893       M -= 4;
19894     return Mask;
19895   default:
19896     llvm_unreachable("No valid shuffle instruction found!");
19897   }
19898 }
19899
19900 /// \brief Search for a combinable shuffle across a chain ending in pshufd.
19901 ///
19902 /// We walk up the chain and look for a combinable shuffle, skipping over
19903 /// shuffles that we could hoist this shuffle's transformation past without
19904 /// altering anything.
19905 static SDValue
19906 combineRedundantDWordShuffle(SDValue N, MutableArrayRef<int> Mask,
19907                              SelectionDAG &DAG,
19908                              TargetLowering::DAGCombinerInfo &DCI) {
19909   assert(N.getOpcode() == X86ISD::PSHUFD &&
19910          "Called with something other than an x86 128-bit half shuffle!");
19911   SDLoc DL(N);
19912
19913   // Walk up a single-use chain looking for a combinable shuffle. Keep a stack
19914   // of the shuffles in the chain so that we can form a fresh chain to replace
19915   // this one.
19916   SmallVector<SDValue, 8> Chain;
19917   SDValue V = N.getOperand(0);
19918   for (; V.hasOneUse(); V = V.getOperand(0)) {
19919     switch (V.getOpcode()) {
19920     default:
19921       return SDValue(); // Nothing combined!
19922
19923     case ISD::BITCAST:
19924       // Skip bitcasts as we always know the type for the target specific
19925       // instructions.
19926       continue;
19927
19928     case X86ISD::PSHUFD:
19929       // Found another dword shuffle.
19930       break;
19931
19932     case X86ISD::PSHUFLW:
19933       // Check that the low words (being shuffled) are the identity in the
19934       // dword shuffle, and the high words are self-contained.
19935       if (Mask[0] != 0 || Mask[1] != 1 ||
19936           !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
19937         return SDValue();
19938
19939       Chain.push_back(V);
19940       continue;
19941
19942     case X86ISD::PSHUFHW:
19943       // Check that the high words (being shuffled) are the identity in the
19944       // dword shuffle, and the low words are self-contained.
19945       if (Mask[2] != 2 || Mask[3] != 3 ||
19946           !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
19947         return SDValue();
19948
19949       Chain.push_back(V);
19950       continue;
19951
19952     case X86ISD::UNPCKL:
19953     case X86ISD::UNPCKH:
19954       // For either i8 -> i16 or i16 -> i32 unpacks, we can combine a dword
19955       // shuffle into a preceding word shuffle.
19956       if (V.getSimpleValueType().getScalarType() != MVT::i8 &&
19957           V.getSimpleValueType().getScalarType() != MVT::i16)
19958         return SDValue();
19959
19960       // Search for a half-shuffle which we can combine with.
19961       unsigned CombineOp =
19962           V.getOpcode() == X86ISD::UNPCKL ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
19963       if (V.getOperand(0) != V.getOperand(1) ||
19964           !V->isOnlyUserOf(V.getOperand(0).getNode()))
19965         return SDValue();
19966       Chain.push_back(V);
19967       V = V.getOperand(0);
19968       do {
19969         switch (V.getOpcode()) {
19970         default:
19971           return SDValue(); // Nothing to combine.
19972
19973         case X86ISD::PSHUFLW:
19974         case X86ISD::PSHUFHW:
19975           if (V.getOpcode() == CombineOp)
19976             break;
19977
19978           Chain.push_back(V);
19979
19980           // Fallthrough!
19981         case ISD::BITCAST:
19982           V = V.getOperand(0);
19983           continue;
19984         }
19985         break;
19986       } while (V.hasOneUse());
19987       break;
19988     }
19989     // Break out of the loop if we break out of the switch.
19990     break;
19991   }
19992
19993   if (!V.hasOneUse())
19994     // We fell out of the loop without finding a viable combining instruction.
19995     return SDValue();
19996
19997   // Merge this node's mask and our incoming mask.
19998   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
19999   for (int &M : Mask)
20000     M = VMask[M];
20001   V = DAG.getNode(V.getOpcode(), DL, V.getValueType(), V.getOperand(0),
20002                   getV4X86ShuffleImm8ForMask(Mask, DAG));
20003
20004   // Rebuild the chain around this new shuffle.
20005   while (!Chain.empty()) {
20006     SDValue W = Chain.pop_back_val();
20007
20008     if (V.getValueType() != W.getOperand(0).getValueType())
20009       V = DAG.getNode(ISD::BITCAST, DL, W.getOperand(0).getValueType(), V);
20010
20011     switch (W.getOpcode()) {
20012     default:
20013       llvm_unreachable("Only PSHUF and UNPCK instructions get here!");
20014
20015     case X86ISD::UNPCKL:
20016     case X86ISD::UNPCKH:
20017       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, V);
20018       break;
20019
20020     case X86ISD::PSHUFD:
20021     case X86ISD::PSHUFLW:
20022     case X86ISD::PSHUFHW:
20023       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, W.getOperand(1));
20024       break;
20025     }
20026   }
20027   if (V.getValueType() != N.getValueType())
20028     V = DAG.getNode(ISD::BITCAST, DL, N.getValueType(), V);
20029
20030   // Return the new chain to replace N.
20031   return V;
20032 }
20033
20034 /// \brief Search for a combinable shuffle across a chain ending in pshuflw or pshufhw.
20035 ///
20036 /// We walk up the chain, skipping shuffles of the other half and looking
20037 /// through shuffles which switch halves trying to find a shuffle of the same
20038 /// pair of dwords.
20039 static bool combineRedundantHalfShuffle(SDValue N, MutableArrayRef<int> Mask,
20040                                         SelectionDAG &DAG,
20041                                         TargetLowering::DAGCombinerInfo &DCI) {
20042   assert(
20043       (N.getOpcode() == X86ISD::PSHUFLW || N.getOpcode() == X86ISD::PSHUFHW) &&
20044       "Called with something other than an x86 128-bit half shuffle!");
20045   SDLoc DL(N);
20046   unsigned CombineOpcode = N.getOpcode();
20047
20048   // Walk up a single-use chain looking for a combinable shuffle.
20049   SDValue V = N.getOperand(0);
20050   for (; V.hasOneUse(); V = V.getOperand(0)) {
20051     switch (V.getOpcode()) {
20052     default:
20053       return false; // Nothing combined!
20054
20055     case ISD::BITCAST:
20056       // Skip bitcasts as we always know the type for the target specific
20057       // instructions.
20058       continue;
20059
20060     case X86ISD::PSHUFLW:
20061     case X86ISD::PSHUFHW:
20062       if (V.getOpcode() == CombineOpcode)
20063         break;
20064
20065       // Other-half shuffles are no-ops.
20066       continue;
20067     }
20068     // Break out of the loop if we break out of the switch.
20069     break;
20070   }
20071
20072   if (!V.hasOneUse())
20073     // We fell out of the loop without finding a viable combining instruction.
20074     return false;
20075
20076   // Combine away the bottom node as its shuffle will be accumulated into
20077   // a preceding shuffle.
20078   DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
20079
20080   // Record the old value.
20081   SDValue Old = V;
20082
20083   // Merge this node's mask and our incoming mask (adjusted to account for all
20084   // the pshufd instructions encountered).
20085   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
20086   for (int &M : Mask)
20087     M = VMask[M];
20088   V = DAG.getNode(V.getOpcode(), DL, MVT::v8i16, V.getOperand(0),
20089                   getV4X86ShuffleImm8ForMask(Mask, DAG));
20090
20091   // Check that the shuffles didn't cancel each other out. If not, we need to
20092   // combine to the new one.
20093   if (Old != V)
20094     // Replace the combinable shuffle with the combined one, updating all users
20095     // so that we re-evaluate the chain here.
20096     DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
20097
20098   return true;
20099 }
20100
20101 /// \brief Try to combine x86 target specific shuffles.
20102 static SDValue PerformTargetShuffleCombine(SDValue N, SelectionDAG &DAG,
20103                                            TargetLowering::DAGCombinerInfo &DCI,
20104                                            const X86Subtarget *Subtarget) {
20105   SDLoc DL(N);
20106   MVT VT = N.getSimpleValueType();
20107   SmallVector<int, 4> Mask;
20108
20109   switch (N.getOpcode()) {
20110   case X86ISD::PSHUFD:
20111   case X86ISD::PSHUFLW:
20112   case X86ISD::PSHUFHW:
20113     Mask = getPSHUFShuffleMask(N);
20114     assert(Mask.size() == 4);
20115     break;
20116   default:
20117     return SDValue();
20118   }
20119
20120   // Nuke no-op shuffles that show up after combining.
20121   if (isNoopShuffleMask(Mask))
20122     return DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
20123
20124   // Look for simplifications involving one or two shuffle instructions.
20125   SDValue V = N.getOperand(0);
20126   switch (N.getOpcode()) {
20127   default:
20128     break;
20129   case X86ISD::PSHUFLW:
20130   case X86ISD::PSHUFHW:
20131     assert(VT.getScalarType() == MVT::i16 && "Bad word shuffle type!");
20132
20133     if (combineRedundantHalfShuffle(N, Mask, DAG, DCI))
20134       return SDValue(); // We combined away this shuffle, so we're done.
20135
20136     // See if this reduces to a PSHUFD which is no more expensive and can
20137     // combine with more operations. Note that it has to at least flip the
20138     // dwords as otherwise it would have been removed as a no-op.
20139     if (makeArrayRef(Mask).equals({2, 3, 0, 1})) {
20140       int DMask[] = {0, 1, 2, 3};
20141       int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
20142       DMask[DOffset + 0] = DOffset + 1;
20143       DMask[DOffset + 1] = DOffset + 0;
20144       MVT DVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
20145       V = DAG.getNode(ISD::BITCAST, DL, DVT, V);
20146       DCI.AddToWorklist(V.getNode());
20147       V = DAG.getNode(X86ISD::PSHUFD, DL, DVT, V,
20148                       getV4X86ShuffleImm8ForMask(DMask, DAG));
20149       DCI.AddToWorklist(V.getNode());
20150       return DAG.getNode(ISD::BITCAST, DL, VT, V);
20151     }
20152
20153     // Look for shuffle patterns which can be implemented as a single unpack.
20154     // FIXME: This doesn't handle the location of the PSHUFD generically, and
20155     // only works when we have a PSHUFD followed by two half-shuffles.
20156     if (Mask[0] == Mask[1] && Mask[2] == Mask[3] &&
20157         (V.getOpcode() == X86ISD::PSHUFLW ||
20158          V.getOpcode() == X86ISD::PSHUFHW) &&
20159         V.getOpcode() != N.getOpcode() &&
20160         V.hasOneUse()) {
20161       SDValue D = V.getOperand(0);
20162       while (D.getOpcode() == ISD::BITCAST && D.hasOneUse())
20163         D = D.getOperand(0);
20164       if (D.getOpcode() == X86ISD::PSHUFD && D.hasOneUse()) {
20165         SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
20166         SmallVector<int, 4> DMask = getPSHUFShuffleMask(D);
20167         int NOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
20168         int VOffset = V.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
20169         int WordMask[8];
20170         for (int i = 0; i < 4; ++i) {
20171           WordMask[i + NOffset] = Mask[i] + NOffset;
20172           WordMask[i + VOffset] = VMask[i] + VOffset;
20173         }
20174         // Map the word mask through the DWord mask.
20175         int MappedMask[8];
20176         for (int i = 0; i < 8; ++i)
20177           MappedMask[i] = 2 * DMask[WordMask[i] / 2] + WordMask[i] % 2;
20178         if (makeArrayRef(MappedMask).equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
20179             makeArrayRef(MappedMask).equals({4, 4, 5, 5, 6, 6, 7, 7})) {
20180           // We can replace all three shuffles with an unpack.
20181           V = DAG.getNode(ISD::BITCAST, DL, VT, D.getOperand(0));
20182           DCI.AddToWorklist(V.getNode());
20183           return DAG.getNode(MappedMask[0] == 0 ? X86ISD::UNPCKL
20184                                                 : X86ISD::UNPCKH,
20185                              DL, VT, V, V);
20186         }
20187       }
20188     }
20189
20190     break;
20191
20192   case X86ISD::PSHUFD:
20193     if (SDValue NewN = combineRedundantDWordShuffle(N, Mask, DAG, DCI))
20194       return NewN;
20195
20196     break;
20197   }
20198
20199   return SDValue();
20200 }
20201
20202 /// \brief Try to combine a shuffle into a target-specific add-sub node.
20203 ///
20204 /// We combine this directly on the abstract vector shuffle nodes so it is
20205 /// easier to generically match. We also insert dummy vector shuffle nodes for
20206 /// the operands which explicitly discard the lanes which are unused by this
20207 /// operation to try to flow through the rest of the combiner the fact that
20208 /// they're unused.
20209 static SDValue combineShuffleToAddSub(SDNode *N, SelectionDAG &DAG) {
20210   SDLoc DL(N);
20211   EVT VT = N->getValueType(0);
20212
20213   // We only handle target-independent shuffles.
20214   // FIXME: It would be easy and harmless to use the target shuffle mask
20215   // extraction tool to support more.
20216   if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
20217     return SDValue();
20218
20219   auto *SVN = cast<ShuffleVectorSDNode>(N);
20220   ArrayRef<int> Mask = SVN->getMask();
20221   SDValue V1 = N->getOperand(0);
20222   SDValue V2 = N->getOperand(1);
20223
20224   // We require the first shuffle operand to be the SUB node, and the second to
20225   // be the ADD node.
20226   // FIXME: We should support the commuted patterns.
20227   if (V1->getOpcode() != ISD::FSUB || V2->getOpcode() != ISD::FADD)
20228     return SDValue();
20229
20230   // If there are other uses of these operations we can't fold them.
20231   if (!V1->hasOneUse() || !V2->hasOneUse())
20232     return SDValue();
20233
20234   // Ensure that both operations have the same operands. Note that we can
20235   // commute the FADD operands.
20236   SDValue LHS = V1->getOperand(0), RHS = V1->getOperand(1);
20237   if ((V2->getOperand(0) != LHS || V2->getOperand(1) != RHS) &&
20238       (V2->getOperand(0) != RHS || V2->getOperand(1) != LHS))
20239     return SDValue();
20240
20241   // We're looking for blends between FADD and FSUB nodes. We insist on these
20242   // nodes being lined up in a specific expected pattern.
20243   if (!(isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
20244         isShuffleEquivalent(V1, V2, Mask, {0, 5, 2, 7}) ||
20245         isShuffleEquivalent(V1, V2, Mask, {0, 9, 2, 11, 4, 13, 6, 15})))
20246     return SDValue();
20247
20248   // Only specific types are legal at this point, assert so we notice if and
20249   // when these change.
20250   assert((VT == MVT::v4f32 || VT == MVT::v2f64 || VT == MVT::v8f32 ||
20251           VT == MVT::v4f64) &&
20252          "Unknown vector type encountered!");
20253
20254   return DAG.getNode(X86ISD::ADDSUB, DL, VT, LHS, RHS);
20255 }
20256
20257 /// PerformShuffleCombine - Performs several different shuffle combines.
20258 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
20259                                      TargetLowering::DAGCombinerInfo &DCI,
20260                                      const X86Subtarget *Subtarget) {
20261   SDLoc dl(N);
20262   SDValue N0 = N->getOperand(0);
20263   SDValue N1 = N->getOperand(1);
20264   EVT VT = N->getValueType(0);
20265
20266   // Don't create instructions with illegal types after legalize types has run.
20267   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20268   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
20269     return SDValue();
20270
20271   // If we have legalized the vector types, look for blends of FADD and FSUB
20272   // nodes that we can fuse into an ADDSUB node.
20273   if (TLI.isTypeLegal(VT) && Subtarget->hasSSE3())
20274     if (SDValue AddSub = combineShuffleToAddSub(N, DAG))
20275       return AddSub;
20276
20277   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
20278   if (Subtarget->hasFp256() && VT.is256BitVector() &&
20279       N->getOpcode() == ISD::VECTOR_SHUFFLE)
20280     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
20281
20282   // During Type Legalization, when promoting illegal vector types,
20283   // the backend might introduce new shuffle dag nodes and bitcasts.
20284   //
20285   // This code performs the following transformation:
20286   // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
20287   //       (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
20288   //
20289   // We do this only if both the bitcast and the BINOP dag nodes have
20290   // one use. Also, perform this transformation only if the new binary
20291   // operation is legal. This is to avoid introducing dag nodes that
20292   // potentially need to be further expanded (or custom lowered) into a
20293   // less optimal sequence of dag nodes.
20294   if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
20295       N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
20296       N0.getOpcode() == ISD::BITCAST) {
20297     SDValue BC0 = N0.getOperand(0);
20298     EVT SVT = BC0.getValueType();
20299     unsigned Opcode = BC0.getOpcode();
20300     unsigned NumElts = VT.getVectorNumElements();
20301
20302     if (BC0.hasOneUse() && SVT.isVector() &&
20303         SVT.getVectorNumElements() * 2 == NumElts &&
20304         TLI.isOperationLegal(Opcode, VT)) {
20305       bool CanFold = false;
20306       switch (Opcode) {
20307       default : break;
20308       case ISD::ADD :
20309       case ISD::FADD :
20310       case ISD::SUB :
20311       case ISD::FSUB :
20312       case ISD::MUL :
20313       case ISD::FMUL :
20314         CanFold = true;
20315       }
20316
20317       unsigned SVTNumElts = SVT.getVectorNumElements();
20318       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
20319       for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
20320         CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
20321       for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
20322         CanFold = SVOp->getMaskElt(i) < 0;
20323
20324       if (CanFold) {
20325         SDValue BC00 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(0));
20326         SDValue BC01 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(1));
20327         SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
20328         return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
20329       }
20330     }
20331   }
20332
20333   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
20334   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
20335   // consecutive, non-overlapping, and in the right order.
20336   SmallVector<SDValue, 16> Elts;
20337   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
20338     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
20339
20340   SDValue LD = EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true);
20341   if (LD.getNode())
20342     return LD;
20343
20344   if (isTargetShuffle(N->getOpcode())) {
20345     SDValue Shuffle =
20346         PerformTargetShuffleCombine(SDValue(N, 0), DAG, DCI, Subtarget);
20347     if (Shuffle.getNode())
20348       return Shuffle;
20349
20350     // Try recursively combining arbitrary sequences of x86 shuffle
20351     // instructions into higher-order shuffles. We do this after combining
20352     // specific PSHUF instruction sequences into their minimal form so that we
20353     // can evaluate how many specialized shuffle instructions are involved in
20354     // a particular chain.
20355     SmallVector<int, 1> NonceMask; // Just a placeholder.
20356     NonceMask.push_back(0);
20357     if (combineX86ShufflesRecursively(SDValue(N, 0), SDValue(N, 0), NonceMask,
20358                                       /*Depth*/ 1, /*HasPSHUFB*/ false, DAG,
20359                                       DCI, Subtarget))
20360       return SDValue(); // This routine will use CombineTo to replace N.
20361   }
20362
20363   return SDValue();
20364 }
20365
20366 /// PerformTruncateCombine - Converts truncate operation to
20367 /// a sequence of vector shuffle operations.
20368 /// It is possible when we truncate 256-bit vector to 128-bit vector
20369 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
20370                                       TargetLowering::DAGCombinerInfo &DCI,
20371                                       const X86Subtarget *Subtarget)  {
20372   return SDValue();
20373 }
20374
20375 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
20376 /// specific shuffle of a load can be folded into a single element load.
20377 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
20378 /// shuffles have been custom lowered so we need to handle those here.
20379 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
20380                                          TargetLowering::DAGCombinerInfo &DCI) {
20381   if (DCI.isBeforeLegalizeOps())
20382     return SDValue();
20383
20384   SDValue InVec = N->getOperand(0);
20385   SDValue EltNo = N->getOperand(1);
20386
20387   if (!isa<ConstantSDNode>(EltNo))
20388     return SDValue();
20389
20390   EVT OriginalVT = InVec.getValueType();
20391
20392   if (InVec.getOpcode() == ISD::BITCAST) {
20393     // Don't duplicate a load with other uses.
20394     if (!InVec.hasOneUse())
20395       return SDValue();
20396     EVT BCVT = InVec.getOperand(0).getValueType();
20397     if (BCVT.getVectorNumElements() != OriginalVT.getVectorNumElements())
20398       return SDValue();
20399     InVec = InVec.getOperand(0);
20400   }
20401
20402   EVT CurrentVT = InVec.getValueType();
20403
20404   if (!isTargetShuffle(InVec.getOpcode()))
20405     return SDValue();
20406
20407   // Don't duplicate a load with other uses.
20408   if (!InVec.hasOneUse())
20409     return SDValue();
20410
20411   SmallVector<int, 16> ShuffleMask;
20412   bool UnaryShuffle;
20413   if (!getTargetShuffleMask(InVec.getNode(), CurrentVT.getSimpleVT(),
20414                             ShuffleMask, UnaryShuffle))
20415     return SDValue();
20416
20417   // Select the input vector, guarding against out of range extract vector.
20418   unsigned NumElems = CurrentVT.getVectorNumElements();
20419   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
20420   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
20421   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
20422                                          : InVec.getOperand(1);
20423
20424   // If inputs to shuffle are the same for both ops, then allow 2 uses
20425   unsigned AllowedUses = InVec.getNumOperands() > 1 &&
20426                          InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
20427
20428   if (LdNode.getOpcode() == ISD::BITCAST) {
20429     // Don't duplicate a load with other uses.
20430     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
20431       return SDValue();
20432
20433     AllowedUses = 1; // only allow 1 load use if we have a bitcast
20434     LdNode = LdNode.getOperand(0);
20435   }
20436
20437   if (!ISD::isNormalLoad(LdNode.getNode()))
20438     return SDValue();
20439
20440   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
20441
20442   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
20443     return SDValue();
20444
20445   EVT EltVT = N->getValueType(0);
20446   // If there's a bitcast before the shuffle, check if the load type and
20447   // alignment is valid.
20448   unsigned Align = LN0->getAlignment();
20449   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20450   unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment(
20451       EltVT.getTypeForEVT(*DAG.getContext()));
20452
20453   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, EltVT))
20454     return SDValue();
20455
20456   // All checks match so transform back to vector_shuffle so that DAG combiner
20457   // can finish the job
20458   SDLoc dl(N);
20459
20460   // Create shuffle node taking into account the case that its a unary shuffle
20461   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(CurrentVT)
20462                                    : InVec.getOperand(1);
20463   Shuffle = DAG.getVectorShuffle(CurrentVT, dl,
20464                                  InVec.getOperand(0), Shuffle,
20465                                  &ShuffleMask[0]);
20466   Shuffle = DAG.getNode(ISD::BITCAST, dl, OriginalVT, Shuffle);
20467   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
20468                      EltNo);
20469 }
20470
20471 /// \brief Detect bitcasts between i32 to x86mmx low word. Since MMX types are
20472 /// special and don't usually play with other vector types, it's better to
20473 /// handle them early to be sure we emit efficient code by avoiding
20474 /// store-load conversions.
20475 static SDValue PerformBITCASTCombine(SDNode *N, SelectionDAG &DAG) {
20476   if (N->getValueType(0) != MVT::x86mmx ||
20477       N->getOperand(0)->getOpcode() != ISD::BUILD_VECTOR ||
20478       N->getOperand(0)->getValueType(0) != MVT::v2i32)
20479     return SDValue();
20480
20481   SDValue V = N->getOperand(0);
20482   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V.getOperand(1));
20483   if (C && C->getZExtValue() == 0 && V.getOperand(0).getValueType() == MVT::i32)
20484     return DAG.getNode(X86ISD::MMX_MOVW2D, SDLoc(V.getOperand(0)),
20485                        N->getValueType(0), V.getOperand(0));
20486
20487   return SDValue();
20488 }
20489
20490 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
20491 /// generation and convert it from being a bunch of shuffles and extracts
20492 /// into a somewhat faster sequence. For i686, the best sequence is apparently
20493 /// storing the value and loading scalars back, while for x64 we should
20494 /// use 64-bit extracts and shifts.
20495 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
20496                                          TargetLowering::DAGCombinerInfo &DCI) {
20497   SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
20498   if (NewOp.getNode())
20499     return NewOp;
20500
20501   SDValue InputVector = N->getOperand(0);
20502
20503   // Detect mmx to i32 conversion through a v2i32 elt extract.
20504   if (InputVector.getOpcode() == ISD::BITCAST && InputVector.hasOneUse() &&
20505       N->getValueType(0) == MVT::i32 &&
20506       InputVector.getValueType() == MVT::v2i32) {
20507
20508     // The bitcast source is a direct mmx result.
20509     SDValue MMXSrc = InputVector.getNode()->getOperand(0);
20510     if (MMXSrc.getValueType() == MVT::x86mmx)
20511       return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
20512                          N->getValueType(0),
20513                          InputVector.getNode()->getOperand(0));
20514
20515     // The mmx is indirect: (i64 extract_elt (v1i64 bitcast (x86mmx ...))).
20516     SDValue MMXSrcOp = MMXSrc.getOperand(0);
20517     if (MMXSrc.getOpcode() == ISD::EXTRACT_VECTOR_ELT && MMXSrc.hasOneUse() &&
20518         MMXSrc.getValueType() == MVT::i64 && MMXSrcOp.hasOneUse() &&
20519         MMXSrcOp.getOpcode() == ISD::BITCAST &&
20520         MMXSrcOp.getValueType() == MVT::v1i64 &&
20521         MMXSrcOp.getOperand(0).getValueType() == MVT::x86mmx)
20522       return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
20523                          N->getValueType(0),
20524                          MMXSrcOp.getOperand(0));
20525   }
20526
20527   // Only operate on vectors of 4 elements, where the alternative shuffling
20528   // gets to be more expensive.
20529   if (InputVector.getValueType() != MVT::v4i32)
20530     return SDValue();
20531
20532   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
20533   // single use which is a sign-extend or zero-extend, and all elements are
20534   // used.
20535   SmallVector<SDNode *, 4> Uses;
20536   unsigned ExtractedElements = 0;
20537   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
20538        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
20539     if (UI.getUse().getResNo() != InputVector.getResNo())
20540       return SDValue();
20541
20542     SDNode *Extract = *UI;
20543     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
20544       return SDValue();
20545
20546     if (Extract->getValueType(0) != MVT::i32)
20547       return SDValue();
20548     if (!Extract->hasOneUse())
20549       return SDValue();
20550     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
20551         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
20552       return SDValue();
20553     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
20554       return SDValue();
20555
20556     // Record which element was extracted.
20557     ExtractedElements |=
20558       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
20559
20560     Uses.push_back(Extract);
20561   }
20562
20563   // If not all the elements were used, this may not be worthwhile.
20564   if (ExtractedElements != 15)
20565     return SDValue();
20566
20567   // Ok, we've now decided to do the transformation.
20568   // If 64-bit shifts are legal, use the extract-shift sequence,
20569   // otherwise bounce the vector off the cache.
20570   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20571   SDValue Vals[4];
20572   SDLoc dl(InputVector);
20573
20574   if (TLI.isOperationLegal(ISD::SRA, MVT::i64)) {
20575     SDValue Cst = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, InputVector);
20576     EVT VecIdxTy = DAG.getTargetLoweringInfo().getVectorIdxTy();
20577     SDValue BottomHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
20578       DAG.getConstant(0, VecIdxTy));
20579     SDValue TopHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
20580       DAG.getConstant(1, VecIdxTy));
20581
20582     SDValue ShAmt = DAG.getConstant(32,
20583       DAG.getTargetLoweringInfo().getShiftAmountTy(MVT::i64));
20584     Vals[0] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BottomHalf);
20585     Vals[1] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
20586       DAG.getNode(ISD::SRA, dl, MVT::i64, BottomHalf, ShAmt));
20587     Vals[2] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, TopHalf);
20588     Vals[3] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
20589       DAG.getNode(ISD::SRA, dl, MVT::i64, TopHalf, ShAmt));
20590   } else {
20591     // Store the value to a temporary stack slot.
20592     SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
20593     SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
20594       MachinePointerInfo(), false, false, 0);
20595
20596     EVT ElementType = InputVector.getValueType().getVectorElementType();
20597     unsigned EltSize = ElementType.getSizeInBits() / 8;
20598
20599     // Replace each use (extract) with a load of the appropriate element.
20600     for (unsigned i = 0; i < 4; ++i) {
20601       uint64_t Offset = EltSize * i;
20602       SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
20603
20604       SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
20605                                        StackPtr, OffsetVal);
20606
20607       // Load the scalar.
20608       Vals[i] = DAG.getLoad(ElementType, dl, Ch,
20609                             ScalarAddr, MachinePointerInfo(),
20610                             false, false, false, 0);
20611
20612     }
20613   }
20614
20615   // Replace the extracts
20616   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
20617     UE = Uses.end(); UI != UE; ++UI) {
20618     SDNode *Extract = *UI;
20619
20620     SDValue Idx = Extract->getOperand(1);
20621     uint64_t IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
20622     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), Vals[IdxVal]);
20623   }
20624
20625   // The replacement was made in place; don't return anything.
20626   return SDValue();
20627 }
20628
20629 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
20630 static std::pair<unsigned, bool>
20631 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
20632                    SelectionDAG &DAG, const X86Subtarget *Subtarget) {
20633   if (!VT.isVector())
20634     return std::make_pair(0, false);
20635
20636   bool NeedSplit = false;
20637   switch (VT.getSimpleVT().SimpleTy) {
20638   default: return std::make_pair(0, false);
20639   case MVT::v4i64:
20640   case MVT::v2i64:
20641     if (!Subtarget->hasVLX())
20642       return std::make_pair(0, false);
20643     break;
20644   case MVT::v64i8:
20645   case MVT::v32i16:
20646     if (!Subtarget->hasBWI())
20647       return std::make_pair(0, false);
20648     break;
20649   case MVT::v16i32:
20650   case MVT::v8i64:
20651     if (!Subtarget->hasAVX512())
20652       return std::make_pair(0, false);
20653     break;
20654   case MVT::v32i8:
20655   case MVT::v16i16:
20656   case MVT::v8i32:
20657     if (!Subtarget->hasAVX2())
20658       NeedSplit = true;
20659     if (!Subtarget->hasAVX())
20660       return std::make_pair(0, false);
20661     break;
20662   case MVT::v16i8:
20663   case MVT::v8i16:
20664   case MVT::v4i32:
20665     if (!Subtarget->hasSSE2())
20666       return std::make_pair(0, false);
20667   }
20668
20669   // SSE2 has only a small subset of the operations.
20670   bool hasUnsigned = Subtarget->hasSSE41() ||
20671                      (Subtarget->hasSSE2() && VT == MVT::v16i8);
20672   bool hasSigned = Subtarget->hasSSE41() ||
20673                    (Subtarget->hasSSE2() && VT == MVT::v8i16);
20674
20675   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
20676
20677   unsigned Opc = 0;
20678   // Check for x CC y ? x : y.
20679   if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
20680       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
20681     switch (CC) {
20682     default: break;
20683     case ISD::SETULT:
20684     case ISD::SETULE:
20685       Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
20686     case ISD::SETUGT:
20687     case ISD::SETUGE:
20688       Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
20689     case ISD::SETLT:
20690     case ISD::SETLE:
20691       Opc = hasSigned ? X86ISD::SMIN : 0; break;
20692     case ISD::SETGT:
20693     case ISD::SETGE:
20694       Opc = hasSigned ? X86ISD::SMAX : 0; break;
20695     }
20696   // Check for x CC y ? y : x -- a min/max with reversed arms.
20697   } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
20698              DAG.isEqualTo(RHS, Cond.getOperand(0))) {
20699     switch (CC) {
20700     default: break;
20701     case ISD::SETULT:
20702     case ISD::SETULE:
20703       Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
20704     case ISD::SETUGT:
20705     case ISD::SETUGE:
20706       Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
20707     case ISD::SETLT:
20708     case ISD::SETLE:
20709       Opc = hasSigned ? X86ISD::SMAX : 0; break;
20710     case ISD::SETGT:
20711     case ISD::SETGE:
20712       Opc = hasSigned ? X86ISD::SMIN : 0; break;
20713     }
20714   }
20715
20716   return std::make_pair(Opc, NeedSplit);
20717 }
20718
20719 static SDValue
20720 transformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
20721                                       const X86Subtarget *Subtarget) {
20722   SDLoc dl(N);
20723   SDValue Cond = N->getOperand(0);
20724   SDValue LHS = N->getOperand(1);
20725   SDValue RHS = N->getOperand(2);
20726
20727   if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
20728     SDValue CondSrc = Cond->getOperand(0);
20729     if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
20730       Cond = CondSrc->getOperand(0);
20731   }
20732
20733   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
20734     return SDValue();
20735
20736   // A vselect where all conditions and data are constants can be optimized into
20737   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
20738   if (ISD::isBuildVectorOfConstantSDNodes(LHS.getNode()) &&
20739       ISD::isBuildVectorOfConstantSDNodes(RHS.getNode()))
20740     return SDValue();
20741
20742   unsigned MaskValue = 0;
20743   if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
20744     return SDValue();
20745
20746   MVT VT = N->getSimpleValueType(0);
20747   unsigned NumElems = VT.getVectorNumElements();
20748   SmallVector<int, 8> ShuffleMask(NumElems, -1);
20749   for (unsigned i = 0; i < NumElems; ++i) {
20750     // Be sure we emit undef where we can.
20751     if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
20752       ShuffleMask[i] = -1;
20753     else
20754       ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
20755   }
20756
20757   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20758   if (!TLI.isShuffleMaskLegal(ShuffleMask, VT))
20759     return SDValue();
20760   return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
20761 }
20762
20763 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
20764 /// nodes.
20765 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
20766                                     TargetLowering::DAGCombinerInfo &DCI,
20767                                     const X86Subtarget *Subtarget) {
20768   SDLoc DL(N);
20769   SDValue Cond = N->getOperand(0);
20770   // Get the LHS/RHS of the select.
20771   SDValue LHS = N->getOperand(1);
20772   SDValue RHS = N->getOperand(2);
20773   EVT VT = LHS.getValueType();
20774   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20775
20776   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
20777   // instructions match the semantics of the common C idiom x<y?x:y but not
20778   // x<=y?x:y, because of how they handle negative zero (which can be
20779   // ignored in unsafe-math mode).
20780   // We also try to create v2f32 min/max nodes, which we later widen to v4f32.
20781   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
20782       VT != MVT::f80 && (TLI.isTypeLegal(VT) || VT == MVT::v2f32) &&
20783       (Subtarget->hasSSE2() ||
20784        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
20785     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
20786
20787     unsigned Opcode = 0;
20788     // Check for x CC y ? x : y.
20789     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
20790         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
20791       switch (CC) {
20792       default: break;
20793       case ISD::SETULT:
20794         // Converting this to a min would handle NaNs incorrectly, and swapping
20795         // the operands would cause it to handle comparisons between positive
20796         // and negative zero incorrectly.
20797         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
20798           if (!DAG.getTarget().Options.UnsafeFPMath &&
20799               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
20800             break;
20801           std::swap(LHS, RHS);
20802         }
20803         Opcode = X86ISD::FMIN;
20804         break;
20805       case ISD::SETOLE:
20806         // Converting this to a min would handle comparisons between positive
20807         // and negative zero incorrectly.
20808         if (!DAG.getTarget().Options.UnsafeFPMath &&
20809             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
20810           break;
20811         Opcode = X86ISD::FMIN;
20812         break;
20813       case ISD::SETULE:
20814         // Converting this to a min would handle both negative zeros and NaNs
20815         // incorrectly, but we can swap the operands to fix both.
20816         std::swap(LHS, RHS);
20817       case ISD::SETOLT:
20818       case ISD::SETLT:
20819       case ISD::SETLE:
20820         Opcode = X86ISD::FMIN;
20821         break;
20822
20823       case ISD::SETOGE:
20824         // Converting this to a max would handle comparisons between positive
20825         // and negative zero incorrectly.
20826         if (!DAG.getTarget().Options.UnsafeFPMath &&
20827             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
20828           break;
20829         Opcode = X86ISD::FMAX;
20830         break;
20831       case ISD::SETUGT:
20832         // Converting this to a max would handle NaNs incorrectly, and swapping
20833         // the operands would cause it to handle comparisons between positive
20834         // and negative zero incorrectly.
20835         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
20836           if (!DAG.getTarget().Options.UnsafeFPMath &&
20837               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
20838             break;
20839           std::swap(LHS, RHS);
20840         }
20841         Opcode = X86ISD::FMAX;
20842         break;
20843       case ISD::SETUGE:
20844         // Converting this to a max would handle both negative zeros and NaNs
20845         // incorrectly, but we can swap the operands to fix both.
20846         std::swap(LHS, RHS);
20847       case ISD::SETOGT:
20848       case ISD::SETGT:
20849       case ISD::SETGE:
20850         Opcode = X86ISD::FMAX;
20851         break;
20852       }
20853     // Check for x CC y ? y : x -- a min/max with reversed arms.
20854     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
20855                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
20856       switch (CC) {
20857       default: break;
20858       case ISD::SETOGE:
20859         // Converting this to a min would handle comparisons between positive
20860         // and negative zero incorrectly, and swapping the operands would
20861         // cause it to handle NaNs incorrectly.
20862         if (!DAG.getTarget().Options.UnsafeFPMath &&
20863             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
20864           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
20865             break;
20866           std::swap(LHS, RHS);
20867         }
20868         Opcode = X86ISD::FMIN;
20869         break;
20870       case ISD::SETUGT:
20871         // Converting this to a min would handle NaNs incorrectly.
20872         if (!DAG.getTarget().Options.UnsafeFPMath &&
20873             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
20874           break;
20875         Opcode = X86ISD::FMIN;
20876         break;
20877       case ISD::SETUGE:
20878         // Converting this to a min would handle both negative zeros and NaNs
20879         // incorrectly, but we can swap the operands to fix both.
20880         std::swap(LHS, RHS);
20881       case ISD::SETOGT:
20882       case ISD::SETGT:
20883       case ISD::SETGE:
20884         Opcode = X86ISD::FMIN;
20885         break;
20886
20887       case ISD::SETULT:
20888         // Converting this to a max would handle NaNs incorrectly.
20889         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
20890           break;
20891         Opcode = X86ISD::FMAX;
20892         break;
20893       case ISD::SETOLE:
20894         // Converting this to a max would handle comparisons between positive
20895         // and negative zero incorrectly, and swapping the operands would
20896         // cause it to handle NaNs incorrectly.
20897         if (!DAG.getTarget().Options.UnsafeFPMath &&
20898             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
20899           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
20900             break;
20901           std::swap(LHS, RHS);
20902         }
20903         Opcode = X86ISD::FMAX;
20904         break;
20905       case ISD::SETULE:
20906         // Converting this to a max would handle both negative zeros and NaNs
20907         // incorrectly, but we can swap the operands to fix both.
20908         std::swap(LHS, RHS);
20909       case ISD::SETOLT:
20910       case ISD::SETLT:
20911       case ISD::SETLE:
20912         Opcode = X86ISD::FMAX;
20913         break;
20914       }
20915     }
20916
20917     if (Opcode)
20918       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
20919   }
20920
20921   EVT CondVT = Cond.getValueType();
20922   if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
20923       CondVT.getVectorElementType() == MVT::i1) {
20924     // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
20925     // lowering on KNL. In this case we convert it to
20926     // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
20927     // The same situation for all 128 and 256-bit vectors of i8 and i16.
20928     // Since SKX these selects have a proper lowering.
20929     EVT OpVT = LHS.getValueType();
20930     if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
20931         (OpVT.getVectorElementType() == MVT::i8 ||
20932          OpVT.getVectorElementType() == MVT::i16) &&
20933         !(Subtarget->hasBWI() && Subtarget->hasVLX())) {
20934       Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
20935       DCI.AddToWorklist(Cond.getNode());
20936       return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
20937     }
20938   }
20939   // If this is a select between two integer constants, try to do some
20940   // optimizations.
20941   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
20942     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
20943       // Don't do this for crazy integer types.
20944       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
20945         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
20946         // so that TrueC (the true value) is larger than FalseC.
20947         bool NeedsCondInvert = false;
20948
20949         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
20950             // Efficiently invertible.
20951             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
20952              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
20953               isa<ConstantSDNode>(Cond.getOperand(1))))) {
20954           NeedsCondInvert = true;
20955           std::swap(TrueC, FalseC);
20956         }
20957
20958         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
20959         if (FalseC->getAPIntValue() == 0 &&
20960             TrueC->getAPIntValue().isPowerOf2()) {
20961           if (NeedsCondInvert) // Invert the condition if needed.
20962             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
20963                                DAG.getConstant(1, Cond.getValueType()));
20964
20965           // Zero extend the condition if needed.
20966           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
20967
20968           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
20969           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
20970                              DAG.getConstant(ShAmt, MVT::i8));
20971         }
20972
20973         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
20974         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
20975           if (NeedsCondInvert) // Invert the condition if needed.
20976             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
20977                                DAG.getConstant(1, Cond.getValueType()));
20978
20979           // Zero extend the condition if needed.
20980           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
20981                              FalseC->getValueType(0), Cond);
20982           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
20983                              SDValue(FalseC, 0));
20984         }
20985
20986         // Optimize cases that will turn into an LEA instruction.  This requires
20987         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
20988         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
20989           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
20990           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
20991
20992           bool isFastMultiplier = false;
20993           if (Diff < 10) {
20994             switch ((unsigned char)Diff) {
20995               default: break;
20996               case 1:  // result = add base, cond
20997               case 2:  // result = lea base(    , cond*2)
20998               case 3:  // result = lea base(cond, cond*2)
20999               case 4:  // result = lea base(    , cond*4)
21000               case 5:  // result = lea base(cond, cond*4)
21001               case 8:  // result = lea base(    , cond*8)
21002               case 9:  // result = lea base(cond, cond*8)
21003                 isFastMultiplier = true;
21004                 break;
21005             }
21006           }
21007
21008           if (isFastMultiplier) {
21009             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
21010             if (NeedsCondInvert) // Invert the condition if needed.
21011               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
21012                                  DAG.getConstant(1, Cond.getValueType()));
21013
21014             // Zero extend the condition if needed.
21015             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
21016                                Cond);
21017             // Scale the condition by the difference.
21018             if (Diff != 1)
21019               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
21020                                  DAG.getConstant(Diff, Cond.getValueType()));
21021
21022             // Add the base if non-zero.
21023             if (FalseC->getAPIntValue() != 0)
21024               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
21025                                  SDValue(FalseC, 0));
21026             return Cond;
21027           }
21028         }
21029       }
21030   }
21031
21032   // Canonicalize max and min:
21033   // (x > y) ? x : y -> (x >= y) ? x : y
21034   // (x < y) ? x : y -> (x <= y) ? x : y
21035   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
21036   // the need for an extra compare
21037   // against zero. e.g.
21038   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
21039   // subl   %esi, %edi
21040   // testl  %edi, %edi
21041   // movl   $0, %eax
21042   // cmovgl %edi, %eax
21043   // =>
21044   // xorl   %eax, %eax
21045   // subl   %esi, $edi
21046   // cmovsl %eax, %edi
21047   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
21048       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
21049       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
21050     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
21051     switch (CC) {
21052     default: break;
21053     case ISD::SETLT:
21054     case ISD::SETGT: {
21055       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
21056       Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
21057                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
21058       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
21059     }
21060     }
21061   }
21062
21063   // Early exit check
21064   if (!TLI.isTypeLegal(VT))
21065     return SDValue();
21066
21067   // Match VSELECTs into subs with unsigned saturation.
21068   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
21069       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
21070       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
21071        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
21072     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
21073
21074     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
21075     // left side invert the predicate to simplify logic below.
21076     SDValue Other;
21077     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
21078       Other = RHS;
21079       CC = ISD::getSetCCInverse(CC, true);
21080     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
21081       Other = LHS;
21082     }
21083
21084     if (Other.getNode() && Other->getNumOperands() == 2 &&
21085         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
21086       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
21087       SDValue CondRHS = Cond->getOperand(1);
21088
21089       // Look for a general sub with unsigned saturation first.
21090       // x >= y ? x-y : 0 --> subus x, y
21091       // x >  y ? x-y : 0 --> subus x, y
21092       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
21093           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
21094         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
21095
21096       if (auto *OpRHSBV = dyn_cast<BuildVectorSDNode>(OpRHS))
21097         if (auto *OpRHSConst = OpRHSBV->getConstantSplatNode()) {
21098           if (auto *CondRHSBV = dyn_cast<BuildVectorSDNode>(CondRHS))
21099             if (auto *CondRHSConst = CondRHSBV->getConstantSplatNode())
21100               // If the RHS is a constant we have to reverse the const
21101               // canonicalization.
21102               // x > C-1 ? x+-C : 0 --> subus x, C
21103               if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
21104                   CondRHSConst->getAPIntValue() ==
21105                       (-OpRHSConst->getAPIntValue() - 1))
21106                 return DAG.getNode(
21107                     X86ISD::SUBUS, DL, VT, OpLHS,
21108                     DAG.getConstant(-OpRHSConst->getAPIntValue(), VT));
21109
21110           // Another special case: If C was a sign bit, the sub has been
21111           // canonicalized into a xor.
21112           // FIXME: Would it be better to use computeKnownBits to determine
21113           //        whether it's safe to decanonicalize the xor?
21114           // x s< 0 ? x^C : 0 --> subus x, C
21115           if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
21116               ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
21117               OpRHSConst->getAPIntValue().isSignBit())
21118             // Note that we have to rebuild the RHS constant here to ensure we
21119             // don't rely on particular values of undef lanes.
21120             return DAG.getNode(
21121                 X86ISD::SUBUS, DL, VT, OpLHS,
21122                 DAG.getConstant(OpRHSConst->getAPIntValue(), VT));
21123         }
21124     }
21125   }
21126
21127   // Try to match a min/max vector operation.
21128   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
21129     std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
21130     unsigned Opc = ret.first;
21131     bool NeedSplit = ret.second;
21132
21133     if (Opc && NeedSplit) {
21134       unsigned NumElems = VT.getVectorNumElements();
21135       // Extract the LHS vectors
21136       SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
21137       SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
21138
21139       // Extract the RHS vectors
21140       SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
21141       SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
21142
21143       // Create min/max for each subvector
21144       LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
21145       RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
21146
21147       // Merge the result
21148       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
21149     } else if (Opc)
21150       return DAG.getNode(Opc, DL, VT, LHS, RHS);
21151   }
21152
21153   // Simplify vector selection if condition value type matches vselect
21154   // operand type
21155   if (N->getOpcode() == ISD::VSELECT && CondVT == VT) {
21156     assert(Cond.getValueType().isVector() &&
21157            "vector select expects a vector selector!");
21158
21159     bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
21160     bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
21161
21162     // Try invert the condition if true value is not all 1s and false value
21163     // is not all 0s.
21164     if (!TValIsAllOnes && !FValIsAllZeros &&
21165         // Check if the selector will be produced by CMPP*/PCMP*
21166         Cond.getOpcode() == ISD::SETCC &&
21167         // Check if SETCC has already been promoted
21168         TLI.getSetCCResultType(*DAG.getContext(), VT) == CondVT) {
21169       bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
21170       bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
21171
21172       if (TValIsAllZeros || FValIsAllOnes) {
21173         SDValue CC = Cond.getOperand(2);
21174         ISD::CondCode NewCC =
21175           ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
21176                                Cond.getOperand(0).getValueType().isInteger());
21177         Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
21178         std::swap(LHS, RHS);
21179         TValIsAllOnes = FValIsAllOnes;
21180         FValIsAllZeros = TValIsAllZeros;
21181       }
21182     }
21183
21184     if (TValIsAllOnes || FValIsAllZeros) {
21185       SDValue Ret;
21186
21187       if (TValIsAllOnes && FValIsAllZeros)
21188         Ret = Cond;
21189       else if (TValIsAllOnes)
21190         Ret = DAG.getNode(ISD::OR, DL, CondVT, Cond,
21191                           DAG.getNode(ISD::BITCAST, DL, CondVT, RHS));
21192       else if (FValIsAllZeros)
21193         Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
21194                           DAG.getNode(ISD::BITCAST, DL, CondVT, LHS));
21195
21196       return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
21197     }
21198   }
21199
21200   // We should generate an X86ISD::BLENDI from a vselect if its argument
21201   // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
21202   // constants. This specific pattern gets generated when we split a
21203   // selector for a 512 bit vector in a machine without AVX512 (but with
21204   // 256-bit vectors), during legalization:
21205   //
21206   // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
21207   //
21208   // Iff we find this pattern and the build_vectors are built from
21209   // constants, we translate the vselect into a shuffle_vector that we
21210   // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
21211   if ((N->getOpcode() == ISD::VSELECT ||
21212        N->getOpcode() == X86ISD::SHRUNKBLEND) &&
21213       !DCI.isBeforeLegalize()) {
21214     SDValue Shuffle = transformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
21215     if (Shuffle.getNode())
21216       return Shuffle;
21217   }
21218
21219   // If this is a *dynamic* select (non-constant condition) and we can match
21220   // this node with one of the variable blend instructions, restructure the
21221   // condition so that the blends can use the high bit of each element and use
21222   // SimplifyDemandedBits to simplify the condition operand.
21223   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
21224       !DCI.isBeforeLegalize() &&
21225       !ISD::isBuildVectorOfConstantSDNodes(Cond.getNode())) {
21226     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
21227
21228     // Don't optimize vector selects that map to mask-registers.
21229     if (BitWidth == 1)
21230       return SDValue();
21231
21232     // We can only handle the cases where VSELECT is directly legal on the
21233     // subtarget. We custom lower VSELECT nodes with constant conditions and
21234     // this makes it hard to see whether a dynamic VSELECT will correctly
21235     // lower, so we both check the operation's status and explicitly handle the
21236     // cases where a *dynamic* blend will fail even though a constant-condition
21237     // blend could be custom lowered.
21238     // FIXME: We should find a better way to handle this class of problems.
21239     // Potentially, we should combine constant-condition vselect nodes
21240     // pre-legalization into shuffles and not mark as many types as custom
21241     // lowered.
21242     if (!TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
21243       return SDValue();
21244     // FIXME: We don't support i16-element blends currently. We could and
21245     // should support them by making *all* the bits in the condition be set
21246     // rather than just the high bit and using an i8-element blend.
21247     if (VT.getScalarType() == MVT::i16)
21248       return SDValue();
21249     // Dynamic blending was only available from SSE4.1 onward.
21250     if (VT.getSizeInBits() == 128 && !Subtarget->hasSSE41())
21251       return SDValue();
21252     // Byte blends are only available in AVX2
21253     if (VT.getSizeInBits() == 256 && VT.getScalarType() == MVT::i8 &&
21254         !Subtarget->hasAVX2())
21255       return SDValue();
21256
21257     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
21258     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
21259
21260     APInt KnownZero, KnownOne;
21261     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
21262                                           DCI.isBeforeLegalizeOps());
21263     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
21264         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne,
21265                                  TLO)) {
21266       // If we changed the computation somewhere in the DAG, this change
21267       // will affect all users of Cond.
21268       // Make sure it is fine and update all the nodes so that we do not
21269       // use the generic VSELECT anymore. Otherwise, we may perform
21270       // wrong optimizations as we messed up with the actual expectation
21271       // for the vector boolean values.
21272       if (Cond != TLO.Old) {
21273         // Check all uses of that condition operand to check whether it will be
21274         // consumed by non-BLEND instructions, which may depend on all bits are
21275         // set properly.
21276         for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
21277              I != E; ++I)
21278           if (I->getOpcode() != ISD::VSELECT)
21279             // TODO: Add other opcodes eventually lowered into BLEND.
21280             return SDValue();
21281
21282         // Update all the users of the condition, before committing the change,
21283         // so that the VSELECT optimizations that expect the correct vector
21284         // boolean value will not be triggered.
21285         for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
21286              I != E; ++I)
21287           DAG.ReplaceAllUsesOfValueWith(
21288               SDValue(*I, 0),
21289               DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(*I), I->getValueType(0),
21290                           Cond, I->getOperand(1), I->getOperand(2)));
21291         DCI.CommitTargetLoweringOpt(TLO);
21292         return SDValue();
21293       }
21294       // At this point, only Cond is changed. Change the condition
21295       // just for N to keep the opportunity to optimize all other
21296       // users their own way.
21297       DAG.ReplaceAllUsesOfValueWith(
21298           SDValue(N, 0),
21299           DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(N), N->getValueType(0),
21300                       TLO.New, N->getOperand(1), N->getOperand(2)));
21301       return SDValue();
21302     }
21303   }
21304
21305   return SDValue();
21306 }
21307
21308 // Check whether a boolean test is testing a boolean value generated by
21309 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
21310 // code.
21311 //
21312 // Simplify the following patterns:
21313 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
21314 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
21315 // to (Op EFLAGS Cond)
21316 //
21317 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
21318 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
21319 // to (Op EFLAGS !Cond)
21320 //
21321 // where Op could be BRCOND or CMOV.
21322 //
21323 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
21324   // Quit if not CMP and SUB with its value result used.
21325   if (Cmp.getOpcode() != X86ISD::CMP &&
21326       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
21327       return SDValue();
21328
21329   // Quit if not used as a boolean value.
21330   if (CC != X86::COND_E && CC != X86::COND_NE)
21331     return SDValue();
21332
21333   // Check CMP operands. One of them should be 0 or 1 and the other should be
21334   // an SetCC or extended from it.
21335   SDValue Op1 = Cmp.getOperand(0);
21336   SDValue Op2 = Cmp.getOperand(1);
21337
21338   SDValue SetCC;
21339   const ConstantSDNode* C = nullptr;
21340   bool needOppositeCond = (CC == X86::COND_E);
21341   bool checkAgainstTrue = false; // Is it a comparison against 1?
21342
21343   if ((C = dyn_cast<ConstantSDNode>(Op1)))
21344     SetCC = Op2;
21345   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
21346     SetCC = Op1;
21347   else // Quit if all operands are not constants.
21348     return SDValue();
21349
21350   if (C->getZExtValue() == 1) {
21351     needOppositeCond = !needOppositeCond;
21352     checkAgainstTrue = true;
21353   } else if (C->getZExtValue() != 0)
21354     // Quit if the constant is neither 0 or 1.
21355     return SDValue();
21356
21357   bool truncatedToBoolWithAnd = false;
21358   // Skip (zext $x), (trunc $x), or (and $x, 1) node.
21359   while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
21360          SetCC.getOpcode() == ISD::TRUNCATE ||
21361          SetCC.getOpcode() == ISD::AND) {
21362     if (SetCC.getOpcode() == ISD::AND) {
21363       int OpIdx = -1;
21364       ConstantSDNode *CS;
21365       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
21366           CS->getZExtValue() == 1)
21367         OpIdx = 1;
21368       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
21369           CS->getZExtValue() == 1)
21370         OpIdx = 0;
21371       if (OpIdx == -1)
21372         break;
21373       SetCC = SetCC.getOperand(OpIdx);
21374       truncatedToBoolWithAnd = true;
21375     } else
21376       SetCC = SetCC.getOperand(0);
21377   }
21378
21379   switch (SetCC.getOpcode()) {
21380   case X86ISD::SETCC_CARRY:
21381     // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
21382     // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
21383     // i.e. it's a comparison against true but the result of SETCC_CARRY is not
21384     // truncated to i1 using 'and'.
21385     if (checkAgainstTrue && !truncatedToBoolWithAnd)
21386       break;
21387     assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
21388            "Invalid use of SETCC_CARRY!");
21389     // FALL THROUGH
21390   case X86ISD::SETCC:
21391     // Set the condition code or opposite one if necessary.
21392     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
21393     if (needOppositeCond)
21394       CC = X86::GetOppositeBranchCondition(CC);
21395     return SetCC.getOperand(1);
21396   case X86ISD::CMOV: {
21397     // Check whether false/true value has canonical one, i.e. 0 or 1.
21398     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
21399     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
21400     // Quit if true value is not a constant.
21401     if (!TVal)
21402       return SDValue();
21403     // Quit if false value is not a constant.
21404     if (!FVal) {
21405       SDValue Op = SetCC.getOperand(0);
21406       // Skip 'zext' or 'trunc' node.
21407       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
21408           Op.getOpcode() == ISD::TRUNCATE)
21409         Op = Op.getOperand(0);
21410       // A special case for rdrand/rdseed, where 0 is set if false cond is
21411       // found.
21412       if ((Op.getOpcode() != X86ISD::RDRAND &&
21413            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
21414         return SDValue();
21415     }
21416     // Quit if false value is not the constant 0 or 1.
21417     bool FValIsFalse = true;
21418     if (FVal && FVal->getZExtValue() != 0) {
21419       if (FVal->getZExtValue() != 1)
21420         return SDValue();
21421       // If FVal is 1, opposite cond is needed.
21422       needOppositeCond = !needOppositeCond;
21423       FValIsFalse = false;
21424     }
21425     // Quit if TVal is not the constant opposite of FVal.
21426     if (FValIsFalse && TVal->getZExtValue() != 1)
21427       return SDValue();
21428     if (!FValIsFalse && TVal->getZExtValue() != 0)
21429       return SDValue();
21430     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
21431     if (needOppositeCond)
21432       CC = X86::GetOppositeBranchCondition(CC);
21433     return SetCC.getOperand(3);
21434   }
21435   }
21436
21437   return SDValue();
21438 }
21439
21440 /// Check whether Cond is an AND/OR of SETCCs off of the same EFLAGS.
21441 /// Match:
21442 ///   (X86or (X86setcc) (X86setcc))
21443 ///   (X86cmp (and (X86setcc) (X86setcc)), 0)
21444 static bool checkBoolTestAndOrSetCCCombine(SDValue Cond, X86::CondCode &CC0,
21445                                            X86::CondCode &CC1, SDValue &Flags,
21446                                            bool &isAnd) {
21447   if (Cond->getOpcode() == X86ISD::CMP) {
21448     ConstantSDNode *CondOp1C = dyn_cast<ConstantSDNode>(Cond->getOperand(1));
21449     if (!CondOp1C || !CondOp1C->isNullValue())
21450       return false;
21451
21452     Cond = Cond->getOperand(0);
21453   }
21454
21455   isAnd = false;
21456
21457   SDValue SetCC0, SetCC1;
21458   switch (Cond->getOpcode()) {
21459   default: return false;
21460   case ISD::AND:
21461   case X86ISD::AND:
21462     isAnd = true;
21463     // fallthru
21464   case ISD::OR:
21465   case X86ISD::OR:
21466     SetCC0 = Cond->getOperand(0);
21467     SetCC1 = Cond->getOperand(1);
21468     break;
21469   };
21470
21471   // Make sure we have SETCC nodes, using the same flags value.
21472   if (SetCC0.getOpcode() != X86ISD::SETCC ||
21473       SetCC1.getOpcode() != X86ISD::SETCC ||
21474       SetCC0->getOperand(1) != SetCC1->getOperand(1))
21475     return false;
21476
21477   CC0 = (X86::CondCode)SetCC0->getConstantOperandVal(0);
21478   CC1 = (X86::CondCode)SetCC1->getConstantOperandVal(0);
21479   Flags = SetCC0->getOperand(1);
21480   return true;
21481 }
21482
21483 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
21484 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
21485                                   TargetLowering::DAGCombinerInfo &DCI,
21486                                   const X86Subtarget *Subtarget) {
21487   SDLoc DL(N);
21488
21489   // If the flag operand isn't dead, don't touch this CMOV.
21490   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
21491     return SDValue();
21492
21493   SDValue FalseOp = N->getOperand(0);
21494   SDValue TrueOp = N->getOperand(1);
21495   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
21496   SDValue Cond = N->getOperand(3);
21497
21498   if (CC == X86::COND_E || CC == X86::COND_NE) {
21499     switch (Cond.getOpcode()) {
21500     default: break;
21501     case X86ISD::BSR:
21502     case X86ISD::BSF:
21503       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
21504       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
21505         return (CC == X86::COND_E) ? FalseOp : TrueOp;
21506     }
21507   }
21508
21509   SDValue Flags;
21510
21511   Flags = checkBoolTestSetCCCombine(Cond, CC);
21512   if (Flags.getNode() &&
21513       // Extra check as FCMOV only supports a subset of X86 cond.
21514       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
21515     SDValue Ops[] = { FalseOp, TrueOp,
21516                       DAG.getConstant(CC, MVT::i8), Flags };
21517     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
21518   }
21519
21520   // If this is a select between two integer constants, try to do some
21521   // optimizations.  Note that the operands are ordered the opposite of SELECT
21522   // operands.
21523   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
21524     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
21525       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
21526       // larger than FalseC (the false value).
21527       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
21528         CC = X86::GetOppositeBranchCondition(CC);
21529         std::swap(TrueC, FalseC);
21530         std::swap(TrueOp, FalseOp);
21531       }
21532
21533       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
21534       // This is efficient for any integer data type (including i8/i16) and
21535       // shift amount.
21536       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
21537         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
21538                            DAG.getConstant(CC, MVT::i8), Cond);
21539
21540         // Zero extend the condition if needed.
21541         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
21542
21543         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
21544         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
21545                            DAG.getConstant(ShAmt, MVT::i8));
21546         if (N->getNumValues() == 2)  // Dead flag value?
21547           return DCI.CombineTo(N, Cond, SDValue());
21548         return Cond;
21549       }
21550
21551       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
21552       // for any integer data type, including i8/i16.
21553       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
21554         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
21555                            DAG.getConstant(CC, MVT::i8), Cond);
21556
21557         // Zero extend the condition if needed.
21558         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
21559                            FalseC->getValueType(0), Cond);
21560         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
21561                            SDValue(FalseC, 0));
21562
21563         if (N->getNumValues() == 2)  // Dead flag value?
21564           return DCI.CombineTo(N, Cond, SDValue());
21565         return Cond;
21566       }
21567
21568       // Optimize cases that will turn into an LEA instruction.  This requires
21569       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
21570       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
21571         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
21572         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
21573
21574         bool isFastMultiplier = false;
21575         if (Diff < 10) {
21576           switch ((unsigned char)Diff) {
21577           default: break;
21578           case 1:  // result = add base, cond
21579           case 2:  // result = lea base(    , cond*2)
21580           case 3:  // result = lea base(cond, cond*2)
21581           case 4:  // result = lea base(    , cond*4)
21582           case 5:  // result = lea base(cond, cond*4)
21583           case 8:  // result = lea base(    , cond*8)
21584           case 9:  // result = lea base(cond, cond*8)
21585             isFastMultiplier = true;
21586             break;
21587           }
21588         }
21589
21590         if (isFastMultiplier) {
21591           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
21592           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
21593                              DAG.getConstant(CC, MVT::i8), Cond);
21594           // Zero extend the condition if needed.
21595           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
21596                              Cond);
21597           // Scale the condition by the difference.
21598           if (Diff != 1)
21599             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
21600                                DAG.getConstant(Diff, Cond.getValueType()));
21601
21602           // Add the base if non-zero.
21603           if (FalseC->getAPIntValue() != 0)
21604             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
21605                                SDValue(FalseC, 0));
21606           if (N->getNumValues() == 2)  // Dead flag value?
21607             return DCI.CombineTo(N, Cond, SDValue());
21608           return Cond;
21609         }
21610       }
21611     }
21612   }
21613
21614   // Handle these cases:
21615   //   (select (x != c), e, c) -> select (x != c), e, x),
21616   //   (select (x == c), c, e) -> select (x == c), x, e)
21617   // where the c is an integer constant, and the "select" is the combination
21618   // of CMOV and CMP.
21619   //
21620   // The rationale for this change is that the conditional-move from a constant
21621   // needs two instructions, however, conditional-move from a register needs
21622   // only one instruction.
21623   //
21624   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
21625   //  some instruction-combining opportunities. This opt needs to be
21626   //  postponed as late as possible.
21627   //
21628   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
21629     // the DCI.xxxx conditions are provided to postpone the optimization as
21630     // late as possible.
21631
21632     ConstantSDNode *CmpAgainst = nullptr;
21633     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
21634         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
21635         !isa<ConstantSDNode>(Cond.getOperand(0))) {
21636
21637       if (CC == X86::COND_NE &&
21638           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
21639         CC = X86::GetOppositeBranchCondition(CC);
21640         std::swap(TrueOp, FalseOp);
21641       }
21642
21643       if (CC == X86::COND_E &&
21644           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
21645         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
21646                           DAG.getConstant(CC, MVT::i8), Cond };
21647         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
21648       }
21649     }
21650   }
21651
21652   // Fold and/or of setcc's to double CMOV:
21653   //   (CMOV F, T, ((cc1 | cc2) != 0)) -> (CMOV (CMOV F, T, cc1), T, cc2)
21654   //   (CMOV F, T, ((cc1 & cc2) != 0)) -> (CMOV (CMOV T, F, !cc1), F, !cc2)
21655   //
21656   // This combine lets us generate:
21657   //   cmovcc1 (jcc1 if we don't have CMOV)
21658   //   cmovcc2 (same)
21659   // instead of:
21660   //   setcc1
21661   //   setcc2
21662   //   and/or
21663   //   cmovne (jne if we don't have CMOV)
21664   // When we can't use the CMOV instruction, it might increase branch
21665   // mispredicts.
21666   // When we can use CMOV, or when there is no mispredict, this improves
21667   // throughput and reduces register pressure.
21668   //
21669   if (CC == X86::COND_NE) {
21670     SDValue Flags;
21671     X86::CondCode CC0, CC1;
21672     bool isAndSetCC;
21673     if (checkBoolTestAndOrSetCCCombine(Cond, CC0, CC1, Flags, isAndSetCC)) {
21674       if (isAndSetCC) {
21675         std::swap(FalseOp, TrueOp);
21676         CC0 = X86::GetOppositeBranchCondition(CC0);
21677         CC1 = X86::GetOppositeBranchCondition(CC1);
21678       }
21679
21680       SDValue LOps[] = {FalseOp, TrueOp, DAG.getConstant(CC0, MVT::i8),
21681         Flags};
21682       SDValue LCMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), LOps);
21683       SDValue Ops[] = {LCMOV, TrueOp, DAG.getConstant(CC1, MVT::i8), Flags};
21684       SDValue CMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
21685       DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SDValue(CMOV.getNode(), 1));
21686       return CMOV;
21687     }
21688   }
21689
21690   return SDValue();
21691 }
21692
21693 static SDValue PerformINTRINSIC_WO_CHAINCombine(SDNode *N, SelectionDAG &DAG,
21694                                                 const X86Subtarget *Subtarget) {
21695   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
21696   switch (IntNo) {
21697   default: return SDValue();
21698   // SSE/AVX/AVX2 blend intrinsics.
21699   case Intrinsic::x86_avx2_pblendvb:
21700     // Don't try to simplify this intrinsic if we don't have AVX2.
21701     if (!Subtarget->hasAVX2())
21702       return SDValue();
21703     // FALL-THROUGH
21704   case Intrinsic::x86_avx_blendv_pd_256:
21705   case Intrinsic::x86_avx_blendv_ps_256:
21706     // Don't try to simplify this intrinsic if we don't have AVX.
21707     if (!Subtarget->hasAVX())
21708       return SDValue();
21709     // FALL-THROUGH
21710   case Intrinsic::x86_sse41_blendvps:
21711   case Intrinsic::x86_sse41_blendvpd:
21712   case Intrinsic::x86_sse41_pblendvb: {
21713     SDValue Op0 = N->getOperand(1);
21714     SDValue Op1 = N->getOperand(2);
21715     SDValue Mask = N->getOperand(3);
21716
21717     // Don't try to simplify this intrinsic if we don't have SSE4.1.
21718     if (!Subtarget->hasSSE41())
21719       return SDValue();
21720
21721     // fold (blend A, A, Mask) -> A
21722     if (Op0 == Op1)
21723       return Op0;
21724     // fold (blend A, B, allZeros) -> A
21725     if (ISD::isBuildVectorAllZeros(Mask.getNode()))
21726       return Op0;
21727     // fold (blend A, B, allOnes) -> B
21728     if (ISD::isBuildVectorAllOnes(Mask.getNode()))
21729       return Op1;
21730
21731     // Simplify the case where the mask is a constant i32 value.
21732     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Mask)) {
21733       if (C->isNullValue())
21734         return Op0;
21735       if (C->isAllOnesValue())
21736         return Op1;
21737     }
21738
21739     return SDValue();
21740   }
21741
21742   // Packed SSE2/AVX2 arithmetic shift immediate intrinsics.
21743   case Intrinsic::x86_sse2_psrai_w:
21744   case Intrinsic::x86_sse2_psrai_d:
21745   case Intrinsic::x86_avx2_psrai_w:
21746   case Intrinsic::x86_avx2_psrai_d:
21747   case Intrinsic::x86_sse2_psra_w:
21748   case Intrinsic::x86_sse2_psra_d:
21749   case Intrinsic::x86_avx2_psra_w:
21750   case Intrinsic::x86_avx2_psra_d: {
21751     SDValue Op0 = N->getOperand(1);
21752     SDValue Op1 = N->getOperand(2);
21753     EVT VT = Op0.getValueType();
21754     assert(VT.isVector() && "Expected a vector type!");
21755
21756     if (isa<BuildVectorSDNode>(Op1))
21757       Op1 = Op1.getOperand(0);
21758
21759     if (!isa<ConstantSDNode>(Op1))
21760       return SDValue();
21761
21762     EVT SVT = VT.getVectorElementType();
21763     unsigned SVTBits = SVT.getSizeInBits();
21764
21765     ConstantSDNode *CND = cast<ConstantSDNode>(Op1);
21766     const APInt &C = APInt(SVTBits, CND->getAPIntValue().getZExtValue());
21767     uint64_t ShAmt = C.getZExtValue();
21768
21769     // Don't try to convert this shift into a ISD::SRA if the shift
21770     // count is bigger than or equal to the element size.
21771     if (ShAmt >= SVTBits)
21772       return SDValue();
21773
21774     // Trivial case: if the shift count is zero, then fold this
21775     // into the first operand.
21776     if (ShAmt == 0)
21777       return Op0;
21778
21779     // Replace this packed shift intrinsic with a target independent
21780     // shift dag node.
21781     SDValue Splat = DAG.getConstant(C, VT);
21782     return DAG.getNode(ISD::SRA, SDLoc(N), VT, Op0, Splat);
21783   }
21784   }
21785 }
21786
21787 /// PerformMulCombine - Optimize a single multiply with constant into two
21788 /// in order to implement it with two cheaper instructions, e.g.
21789 /// LEA + SHL, LEA + LEA.
21790 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
21791                                  TargetLowering::DAGCombinerInfo &DCI) {
21792   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
21793     return SDValue();
21794
21795   EVT VT = N->getValueType(0);
21796   if (VT != MVT::i64 && VT != MVT::i32)
21797     return SDValue();
21798
21799   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
21800   if (!C)
21801     return SDValue();
21802   uint64_t MulAmt = C->getZExtValue();
21803   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
21804     return SDValue();
21805
21806   uint64_t MulAmt1 = 0;
21807   uint64_t MulAmt2 = 0;
21808   if ((MulAmt % 9) == 0) {
21809     MulAmt1 = 9;
21810     MulAmt2 = MulAmt / 9;
21811   } else if ((MulAmt % 5) == 0) {
21812     MulAmt1 = 5;
21813     MulAmt2 = MulAmt / 5;
21814   } else if ((MulAmt % 3) == 0) {
21815     MulAmt1 = 3;
21816     MulAmt2 = MulAmt / 3;
21817   }
21818   if (MulAmt2 &&
21819       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
21820     SDLoc DL(N);
21821
21822     if (isPowerOf2_64(MulAmt2) &&
21823         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
21824       // If second multiplifer is pow2, issue it first. We want the multiply by
21825       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
21826       // is an add.
21827       std::swap(MulAmt1, MulAmt2);
21828
21829     SDValue NewMul;
21830     if (isPowerOf2_64(MulAmt1))
21831       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
21832                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
21833     else
21834       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
21835                            DAG.getConstant(MulAmt1, VT));
21836
21837     if (isPowerOf2_64(MulAmt2))
21838       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
21839                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
21840     else
21841       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
21842                            DAG.getConstant(MulAmt2, VT));
21843
21844     // Do not add new nodes to DAG combiner worklist.
21845     DCI.CombineTo(N, NewMul, false);
21846   }
21847   return SDValue();
21848 }
21849
21850 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
21851   SDValue N0 = N->getOperand(0);
21852   SDValue N1 = N->getOperand(1);
21853   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
21854   EVT VT = N0.getValueType();
21855
21856   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
21857   // since the result of setcc_c is all zero's or all ones.
21858   if (VT.isInteger() && !VT.isVector() &&
21859       N1C && N0.getOpcode() == ISD::AND &&
21860       N0.getOperand(1).getOpcode() == ISD::Constant) {
21861     SDValue N00 = N0.getOperand(0);
21862     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
21863         ((N00.getOpcode() == ISD::ANY_EXTEND ||
21864           N00.getOpcode() == ISD::ZERO_EXTEND) &&
21865          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
21866       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
21867       APInt ShAmt = N1C->getAPIntValue();
21868       Mask = Mask.shl(ShAmt);
21869       if (Mask != 0)
21870         return DAG.getNode(ISD::AND, SDLoc(N), VT,
21871                            N00, DAG.getConstant(Mask, VT));
21872     }
21873   }
21874
21875   // Hardware support for vector shifts is sparse which makes us scalarize the
21876   // vector operations in many cases. Also, on sandybridge ADD is faster than
21877   // shl.
21878   // (shl V, 1) -> add V,V
21879   if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
21880     if (auto *N1SplatC = N1BV->getConstantSplatNode()) {
21881       assert(N0.getValueType().isVector() && "Invalid vector shift type");
21882       // We shift all of the values by one. In many cases we do not have
21883       // hardware support for this operation. This is better expressed as an ADD
21884       // of two values.
21885       if (N1SplatC->getZExtValue() == 1)
21886         return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
21887     }
21888
21889   return SDValue();
21890 }
21891
21892 /// \brief Returns a vector of 0s if the node in input is a vector logical
21893 /// shift by a constant amount which is known to be bigger than or equal
21894 /// to the vector element size in bits.
21895 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
21896                                       const X86Subtarget *Subtarget) {
21897   EVT VT = N->getValueType(0);
21898
21899   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
21900       (!Subtarget->hasInt256() ||
21901        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
21902     return SDValue();
21903
21904   SDValue Amt = N->getOperand(1);
21905   SDLoc DL(N);
21906   if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Amt))
21907     if (auto *AmtSplat = AmtBV->getConstantSplatNode()) {
21908       APInt ShiftAmt = AmtSplat->getAPIntValue();
21909       unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
21910
21911       // SSE2/AVX2 logical shifts always return a vector of 0s
21912       // if the shift amount is bigger than or equal to
21913       // the element size. The constant shift amount will be
21914       // encoded as a 8-bit immediate.
21915       if (ShiftAmt.trunc(8).uge(MaxAmount))
21916         return getZeroVector(VT, Subtarget, DAG, DL);
21917     }
21918
21919   return SDValue();
21920 }
21921
21922 /// PerformShiftCombine - Combine shifts.
21923 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
21924                                    TargetLowering::DAGCombinerInfo &DCI,
21925                                    const X86Subtarget *Subtarget) {
21926   if (N->getOpcode() == ISD::SHL) {
21927     SDValue V = PerformSHLCombine(N, DAG);
21928     if (V.getNode()) return V;
21929   }
21930
21931   if (N->getOpcode() != ISD::SRA) {
21932     // Try to fold this logical shift into a zero vector.
21933     SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
21934     if (V.getNode()) return V;
21935   }
21936
21937   return SDValue();
21938 }
21939
21940 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
21941 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
21942 // and friends.  Likewise for OR -> CMPNEQSS.
21943 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
21944                             TargetLowering::DAGCombinerInfo &DCI,
21945                             const X86Subtarget *Subtarget) {
21946   unsigned opcode;
21947
21948   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
21949   // we're requiring SSE2 for both.
21950   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
21951     SDValue N0 = N->getOperand(0);
21952     SDValue N1 = N->getOperand(1);
21953     SDValue CMP0 = N0->getOperand(1);
21954     SDValue CMP1 = N1->getOperand(1);
21955     SDLoc DL(N);
21956
21957     // The SETCCs should both refer to the same CMP.
21958     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
21959       return SDValue();
21960
21961     SDValue CMP00 = CMP0->getOperand(0);
21962     SDValue CMP01 = CMP0->getOperand(1);
21963     EVT     VT    = CMP00.getValueType();
21964
21965     if (VT == MVT::f32 || VT == MVT::f64) {
21966       bool ExpectingFlags = false;
21967       // Check for any users that want flags:
21968       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
21969            !ExpectingFlags && UI != UE; ++UI)
21970         switch (UI->getOpcode()) {
21971         default:
21972         case ISD::BR_CC:
21973         case ISD::BRCOND:
21974         case ISD::SELECT:
21975           ExpectingFlags = true;
21976           break;
21977         case ISD::CopyToReg:
21978         case ISD::SIGN_EXTEND:
21979         case ISD::ZERO_EXTEND:
21980         case ISD::ANY_EXTEND:
21981           break;
21982         }
21983
21984       if (!ExpectingFlags) {
21985         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
21986         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
21987
21988         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
21989           X86::CondCode tmp = cc0;
21990           cc0 = cc1;
21991           cc1 = tmp;
21992         }
21993
21994         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
21995             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
21996           // FIXME: need symbolic constants for these magic numbers.
21997           // See X86ATTInstPrinter.cpp:printSSECC().
21998           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
21999           if (Subtarget->hasAVX512()) {
22000             SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
22001                                          CMP01, DAG.getConstant(x86cc, MVT::i8));
22002             if (N->getValueType(0) != MVT::i1)
22003               return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
22004                                  FSetCC);
22005             return FSetCC;
22006           }
22007           SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
22008                                               CMP00.getValueType(), CMP00, CMP01,
22009                                               DAG.getConstant(x86cc, MVT::i8));
22010
22011           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
22012           MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
22013
22014           if (is64BitFP && !Subtarget->is64Bit()) {
22015             // On a 32-bit target, we cannot bitcast the 64-bit float to a
22016             // 64-bit integer, since that's not a legal type. Since
22017             // OnesOrZeroesF is all ones of all zeroes, we don't need all the
22018             // bits, but can do this little dance to extract the lowest 32 bits
22019             // and work with those going forward.
22020             SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
22021                                            OnesOrZeroesF);
22022             SDValue Vector32 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f32,
22023                                            Vector64);
22024             OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
22025                                         Vector32, DAG.getIntPtrConstant(0));
22026             IntVT = MVT::i32;
22027           }
22028
22029           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, IntVT, OnesOrZeroesF);
22030           SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
22031                                       DAG.getConstant(1, IntVT));
22032           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
22033           return OneBitOfTruth;
22034         }
22035       }
22036     }
22037   }
22038   return SDValue();
22039 }
22040
22041 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
22042 /// so it can be folded inside ANDNP.
22043 static bool CanFoldXORWithAllOnes(const SDNode *N) {
22044   EVT VT = N->getValueType(0);
22045
22046   // Match direct AllOnes for 128 and 256-bit vectors
22047   if (ISD::isBuildVectorAllOnes(N))
22048     return true;
22049
22050   // Look through a bit convert.
22051   if (N->getOpcode() == ISD::BITCAST)
22052     N = N->getOperand(0).getNode();
22053
22054   // Sometimes the operand may come from a insert_subvector building a 256-bit
22055   // allones vector
22056   if (VT.is256BitVector() &&
22057       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
22058     SDValue V1 = N->getOperand(0);
22059     SDValue V2 = N->getOperand(1);
22060
22061     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
22062         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
22063         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
22064         ISD::isBuildVectorAllOnes(V2.getNode()))
22065       return true;
22066   }
22067
22068   return false;
22069 }
22070
22071 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
22072 // register. In most cases we actually compare or select YMM-sized registers
22073 // and mixing the two types creates horrible code. This method optimizes
22074 // some of the transition sequences.
22075 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
22076                                  TargetLowering::DAGCombinerInfo &DCI,
22077                                  const X86Subtarget *Subtarget) {
22078   EVT VT = N->getValueType(0);
22079   if (!VT.is256BitVector())
22080     return SDValue();
22081
22082   assert((N->getOpcode() == ISD::ANY_EXTEND ||
22083           N->getOpcode() == ISD::ZERO_EXTEND ||
22084           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
22085
22086   SDValue Narrow = N->getOperand(0);
22087   EVT NarrowVT = Narrow->getValueType(0);
22088   if (!NarrowVT.is128BitVector())
22089     return SDValue();
22090
22091   if (Narrow->getOpcode() != ISD::XOR &&
22092       Narrow->getOpcode() != ISD::AND &&
22093       Narrow->getOpcode() != ISD::OR)
22094     return SDValue();
22095
22096   SDValue N0  = Narrow->getOperand(0);
22097   SDValue N1  = Narrow->getOperand(1);
22098   SDLoc DL(Narrow);
22099
22100   // The Left side has to be a trunc.
22101   if (N0.getOpcode() != ISD::TRUNCATE)
22102     return SDValue();
22103
22104   // The type of the truncated inputs.
22105   EVT WideVT = N0->getOperand(0)->getValueType(0);
22106   if (WideVT != VT)
22107     return SDValue();
22108
22109   // The right side has to be a 'trunc' or a constant vector.
22110   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
22111   ConstantSDNode *RHSConstSplat = nullptr;
22112   if (auto *RHSBV = dyn_cast<BuildVectorSDNode>(N1))
22113     RHSConstSplat = RHSBV->getConstantSplatNode();
22114   if (!RHSTrunc && !RHSConstSplat)
22115     return SDValue();
22116
22117   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22118
22119   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
22120     return SDValue();
22121
22122   // Set N0 and N1 to hold the inputs to the new wide operation.
22123   N0 = N0->getOperand(0);
22124   if (RHSConstSplat) {
22125     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
22126                      SDValue(RHSConstSplat, 0));
22127     SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
22128     N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
22129   } else if (RHSTrunc) {
22130     N1 = N1->getOperand(0);
22131   }
22132
22133   // Generate the wide operation.
22134   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
22135   unsigned Opcode = N->getOpcode();
22136   switch (Opcode) {
22137   case ISD::ANY_EXTEND:
22138     return Op;
22139   case ISD::ZERO_EXTEND: {
22140     unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
22141     APInt Mask = APInt::getAllOnesValue(InBits);
22142     Mask = Mask.zext(VT.getScalarType().getSizeInBits());
22143     return DAG.getNode(ISD::AND, DL, VT,
22144                        Op, DAG.getConstant(Mask, VT));
22145   }
22146   case ISD::SIGN_EXTEND:
22147     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
22148                        Op, DAG.getValueType(NarrowVT));
22149   default:
22150     llvm_unreachable("Unexpected opcode");
22151   }
22152 }
22153
22154 static SDValue VectorZextCombine(SDNode *N, SelectionDAG &DAG,
22155                                  TargetLowering::DAGCombinerInfo &DCI,
22156                                  const X86Subtarget *Subtarget) {
22157   SDValue N0 = N->getOperand(0);
22158   SDValue N1 = N->getOperand(1);
22159   SDLoc DL(N);
22160
22161   // A vector zext_in_reg may be represented as a shuffle,
22162   // feeding into a bitcast (this represents anyext) feeding into
22163   // an and with a mask.
22164   // We'd like to try to combine that into a shuffle with zero
22165   // plus a bitcast, removing the and.
22166   if (N0.getOpcode() != ISD::BITCAST ||
22167       N0.getOperand(0).getOpcode() != ISD::VECTOR_SHUFFLE)
22168     return SDValue();
22169
22170   // The other side of the AND should be a splat of 2^C, where C
22171   // is the number of bits in the source type.
22172   if (N1.getOpcode() == ISD::BITCAST)
22173     N1 = N1.getOperand(0);
22174   if (N1.getOpcode() != ISD::BUILD_VECTOR)
22175     return SDValue();
22176   BuildVectorSDNode *Vector = cast<BuildVectorSDNode>(N1);
22177
22178   ShuffleVectorSDNode *Shuffle = cast<ShuffleVectorSDNode>(N0.getOperand(0));
22179   EVT SrcType = Shuffle->getValueType(0);
22180
22181   // We expect a single-source shuffle
22182   if (Shuffle->getOperand(1)->getOpcode() != ISD::UNDEF)
22183     return SDValue();
22184
22185   unsigned SrcSize = SrcType.getScalarSizeInBits();
22186
22187   APInt SplatValue, SplatUndef;
22188   unsigned SplatBitSize;
22189   bool HasAnyUndefs;
22190   if (!Vector->isConstantSplat(SplatValue, SplatUndef,
22191                                 SplatBitSize, HasAnyUndefs))
22192     return SDValue();
22193
22194   unsigned ResSize = N1.getValueType().getScalarSizeInBits();
22195   // Make sure the splat matches the mask we expect
22196   if (SplatBitSize > ResSize ||
22197       (SplatValue + 1).exactLogBase2() != (int)SrcSize)
22198     return SDValue();
22199
22200   // Make sure the input and output size make sense
22201   if (SrcSize >= ResSize || ResSize % SrcSize)
22202     return SDValue();
22203
22204   // We expect a shuffle of the form <0, u, u, u, 1, u, u, u...>
22205   // The number of u's between each two values depends on the ratio between
22206   // the source and dest type.
22207   unsigned ZextRatio = ResSize / SrcSize;
22208   bool IsZext = true;
22209   for (unsigned i = 0; i < SrcType.getVectorNumElements(); ++i) {
22210     if (i % ZextRatio) {
22211       if (Shuffle->getMaskElt(i) > 0) {
22212         // Expected undef
22213         IsZext = false;
22214         break;
22215       }
22216     } else {
22217       if (Shuffle->getMaskElt(i) != (int)(i / ZextRatio)) {
22218         // Expected element number
22219         IsZext = false;
22220         break;
22221       }
22222     }
22223   }
22224
22225   if (!IsZext)
22226     return SDValue();
22227
22228   // Ok, perform the transformation - replace the shuffle with
22229   // a shuffle of the form <0, k, k, k, 1, k, k, k> with zero
22230   // (instead of undef) where the k elements come from the zero vector.
22231   SmallVector<int, 8> Mask;
22232   unsigned NumElems = SrcType.getVectorNumElements();
22233   for (unsigned i = 0; i < NumElems; ++i)
22234     if (i % ZextRatio)
22235       Mask.push_back(NumElems);
22236     else
22237       Mask.push_back(i / ZextRatio);
22238
22239   SDValue NewShuffle = DAG.getVectorShuffle(Shuffle->getValueType(0), DL,
22240     Shuffle->getOperand(0), DAG.getConstant(0, SrcType), Mask);
22241   return DAG.getNode(ISD::BITCAST, DL,  N0.getValueType(), NewShuffle);
22242 }
22243
22244 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
22245                                  TargetLowering::DAGCombinerInfo &DCI,
22246                                  const X86Subtarget *Subtarget) {
22247   if (DCI.isBeforeLegalizeOps())
22248     return SDValue();
22249
22250   if (SDValue Zext = VectorZextCombine(N, DAG, DCI, Subtarget))
22251     return Zext;
22252
22253   if (SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget))
22254     return R;
22255
22256   EVT VT = N->getValueType(0);
22257   SDValue N0 = N->getOperand(0);
22258   SDValue N1 = N->getOperand(1);
22259   SDLoc DL(N);
22260
22261   // Create BEXTR instructions
22262   // BEXTR is ((X >> imm) & (2**size-1))
22263   if (VT == MVT::i32 || VT == MVT::i64) {
22264     // Check for BEXTR.
22265     if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
22266         (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
22267       ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
22268       ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
22269       if (MaskNode && ShiftNode) {
22270         uint64_t Mask = MaskNode->getZExtValue();
22271         uint64_t Shift = ShiftNode->getZExtValue();
22272         if (isMask_64(Mask)) {
22273           uint64_t MaskSize = countPopulation(Mask);
22274           if (Shift + MaskSize <= VT.getSizeInBits())
22275             return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
22276                                DAG.getConstant(Shift | (MaskSize << 8), VT));
22277         }
22278       }
22279     } // BEXTR
22280
22281     return SDValue();
22282   }
22283
22284   // Want to form ANDNP nodes:
22285   // 1) In the hopes of then easily combining them with OR and AND nodes
22286   //    to form PBLEND/PSIGN.
22287   // 2) To match ANDN packed intrinsics
22288   if (VT != MVT::v2i64 && VT != MVT::v4i64)
22289     return SDValue();
22290
22291   // Check LHS for vnot
22292   if (N0.getOpcode() == ISD::XOR &&
22293       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
22294       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
22295     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
22296
22297   // Check RHS for vnot
22298   if (N1.getOpcode() == ISD::XOR &&
22299       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
22300       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
22301     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
22302
22303   return SDValue();
22304 }
22305
22306 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
22307                                 TargetLowering::DAGCombinerInfo &DCI,
22308                                 const X86Subtarget *Subtarget) {
22309   if (DCI.isBeforeLegalizeOps())
22310     return SDValue();
22311
22312   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
22313   if (R.getNode())
22314     return R;
22315
22316   SDValue N0 = N->getOperand(0);
22317   SDValue N1 = N->getOperand(1);
22318   EVT VT = N->getValueType(0);
22319
22320   // look for psign/blend
22321   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
22322     if (!Subtarget->hasSSSE3() ||
22323         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
22324       return SDValue();
22325
22326     // Canonicalize pandn to RHS
22327     if (N0.getOpcode() == X86ISD::ANDNP)
22328       std::swap(N0, N1);
22329     // or (and (m, y), (pandn m, x))
22330     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
22331       SDValue Mask = N1.getOperand(0);
22332       SDValue X    = N1.getOperand(1);
22333       SDValue Y;
22334       if (N0.getOperand(0) == Mask)
22335         Y = N0.getOperand(1);
22336       if (N0.getOperand(1) == Mask)
22337         Y = N0.getOperand(0);
22338
22339       // Check to see if the mask appeared in both the AND and ANDNP and
22340       if (!Y.getNode())
22341         return SDValue();
22342
22343       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
22344       // Look through mask bitcast.
22345       if (Mask.getOpcode() == ISD::BITCAST)
22346         Mask = Mask.getOperand(0);
22347       if (X.getOpcode() == ISD::BITCAST)
22348         X = X.getOperand(0);
22349       if (Y.getOpcode() == ISD::BITCAST)
22350         Y = Y.getOperand(0);
22351
22352       EVT MaskVT = Mask.getValueType();
22353
22354       // Validate that the Mask operand is a vector sra node.
22355       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
22356       // there is no psrai.b
22357       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
22358       unsigned SraAmt = ~0;
22359       if (Mask.getOpcode() == ISD::SRA) {
22360         if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Mask.getOperand(1)))
22361           if (auto *AmtConst = AmtBV->getConstantSplatNode())
22362             SraAmt = AmtConst->getZExtValue();
22363       } else if (Mask.getOpcode() == X86ISD::VSRAI) {
22364         SDValue SraC = Mask.getOperand(1);
22365         SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
22366       }
22367       if ((SraAmt + 1) != EltBits)
22368         return SDValue();
22369
22370       SDLoc DL(N);
22371
22372       // Now we know we at least have a plendvb with the mask val.  See if
22373       // we can form a psignb/w/d.
22374       // psign = x.type == y.type == mask.type && y = sub(0, x);
22375       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
22376           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
22377           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
22378         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
22379                "Unsupported VT for PSIGN");
22380         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
22381         return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
22382       }
22383       // PBLENDVB only available on SSE 4.1
22384       if (!Subtarget->hasSSE41())
22385         return SDValue();
22386
22387       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
22388
22389       X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
22390       Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
22391       Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
22392       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
22393       return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
22394     }
22395   }
22396
22397   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
22398     return SDValue();
22399
22400   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
22401   MachineFunction &MF = DAG.getMachineFunction();
22402   bool OptForSize =
22403       MF.getFunction()->hasFnAttribute(Attribute::OptimizeForSize);
22404
22405   // SHLD/SHRD instructions have lower register pressure, but on some
22406   // platforms they have higher latency than the equivalent
22407   // series of shifts/or that would otherwise be generated.
22408   // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
22409   // have higher latencies and we are not optimizing for size.
22410   if (!OptForSize && Subtarget->isSHLDSlow())
22411     return SDValue();
22412
22413   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
22414     std::swap(N0, N1);
22415   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
22416     return SDValue();
22417   if (!N0.hasOneUse() || !N1.hasOneUse())
22418     return SDValue();
22419
22420   SDValue ShAmt0 = N0.getOperand(1);
22421   if (ShAmt0.getValueType() != MVT::i8)
22422     return SDValue();
22423   SDValue ShAmt1 = N1.getOperand(1);
22424   if (ShAmt1.getValueType() != MVT::i8)
22425     return SDValue();
22426   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
22427     ShAmt0 = ShAmt0.getOperand(0);
22428   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
22429     ShAmt1 = ShAmt1.getOperand(0);
22430
22431   SDLoc DL(N);
22432   unsigned Opc = X86ISD::SHLD;
22433   SDValue Op0 = N0.getOperand(0);
22434   SDValue Op1 = N1.getOperand(0);
22435   if (ShAmt0.getOpcode() == ISD::SUB) {
22436     Opc = X86ISD::SHRD;
22437     std::swap(Op0, Op1);
22438     std::swap(ShAmt0, ShAmt1);
22439   }
22440
22441   unsigned Bits = VT.getSizeInBits();
22442   if (ShAmt1.getOpcode() == ISD::SUB) {
22443     SDValue Sum = ShAmt1.getOperand(0);
22444     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
22445       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
22446       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
22447         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
22448       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
22449         return DAG.getNode(Opc, DL, VT,
22450                            Op0, Op1,
22451                            DAG.getNode(ISD::TRUNCATE, DL,
22452                                        MVT::i8, ShAmt0));
22453     }
22454   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
22455     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
22456     if (ShAmt0C &&
22457         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
22458       return DAG.getNode(Opc, DL, VT,
22459                          N0.getOperand(0), N1.getOperand(0),
22460                          DAG.getNode(ISD::TRUNCATE, DL,
22461                                        MVT::i8, ShAmt0));
22462   }
22463
22464   return SDValue();
22465 }
22466
22467 // Generate NEG and CMOV for integer abs.
22468 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
22469   EVT VT = N->getValueType(0);
22470
22471   // Since X86 does not have CMOV for 8-bit integer, we don't convert
22472   // 8-bit integer abs to NEG and CMOV.
22473   if (VT.isInteger() && VT.getSizeInBits() == 8)
22474     return SDValue();
22475
22476   SDValue N0 = N->getOperand(0);
22477   SDValue N1 = N->getOperand(1);
22478   SDLoc DL(N);
22479
22480   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
22481   // and change it to SUB and CMOV.
22482   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
22483       N0.getOpcode() == ISD::ADD &&
22484       N0.getOperand(1) == N1 &&
22485       N1.getOpcode() == ISD::SRA &&
22486       N1.getOperand(0) == N0.getOperand(0))
22487     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
22488       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
22489         // Generate SUB & CMOV.
22490         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
22491                                   DAG.getConstant(0, VT), N0.getOperand(0));
22492
22493         SDValue Ops[] = { N0.getOperand(0), Neg,
22494                           DAG.getConstant(X86::COND_GE, MVT::i8),
22495                           SDValue(Neg.getNode(), 1) };
22496         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
22497       }
22498   return SDValue();
22499 }
22500
22501 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
22502 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
22503                                  TargetLowering::DAGCombinerInfo &DCI,
22504                                  const X86Subtarget *Subtarget) {
22505   if (DCI.isBeforeLegalizeOps())
22506     return SDValue();
22507
22508   if (Subtarget->hasCMov()) {
22509     SDValue RV = performIntegerAbsCombine(N, DAG);
22510     if (RV.getNode())
22511       return RV;
22512   }
22513
22514   return SDValue();
22515 }
22516
22517 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
22518 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
22519                                   TargetLowering::DAGCombinerInfo &DCI,
22520                                   const X86Subtarget *Subtarget) {
22521   LoadSDNode *Ld = cast<LoadSDNode>(N);
22522   EVT RegVT = Ld->getValueType(0);
22523   EVT MemVT = Ld->getMemoryVT();
22524   SDLoc dl(Ld);
22525   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22526
22527   // For chips with slow 32-byte unaligned loads, break the 32-byte operation
22528   // into two 16-byte operations.
22529   ISD::LoadExtType Ext = Ld->getExtensionType();
22530   unsigned Alignment = Ld->getAlignment();
22531   bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
22532   if (RegVT.is256BitVector() && Subtarget->isUnalignedMem32Slow() &&
22533       !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
22534     unsigned NumElems = RegVT.getVectorNumElements();
22535     if (NumElems < 2)
22536       return SDValue();
22537
22538     SDValue Ptr = Ld->getBasePtr();
22539     SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
22540
22541     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
22542                                   NumElems/2);
22543     SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
22544                                 Ld->getPointerInfo(), Ld->isVolatile(),
22545                                 Ld->isNonTemporal(), Ld->isInvariant(),
22546                                 Alignment);
22547     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
22548     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
22549                                 Ld->getPointerInfo(), Ld->isVolatile(),
22550                                 Ld->isNonTemporal(), Ld->isInvariant(),
22551                                 std::min(16U, Alignment));
22552     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
22553                              Load1.getValue(1),
22554                              Load2.getValue(1));
22555
22556     SDValue NewVec = DAG.getUNDEF(RegVT);
22557     NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
22558     NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
22559     return DCI.CombineTo(N, NewVec, TF, true);
22560   }
22561
22562   return SDValue();
22563 }
22564
22565 /// PerformMLOADCombine - Resolve extending loads
22566 static SDValue PerformMLOADCombine(SDNode *N, SelectionDAG &DAG,
22567                                    TargetLowering::DAGCombinerInfo &DCI,
22568                                    const X86Subtarget *Subtarget) {
22569   MaskedLoadSDNode *Mld = cast<MaskedLoadSDNode>(N);
22570   if (Mld->getExtensionType() != ISD::SEXTLOAD)
22571     return SDValue();
22572
22573   EVT VT = Mld->getValueType(0);
22574   unsigned NumElems = VT.getVectorNumElements();
22575   EVT LdVT = Mld->getMemoryVT();
22576   SDLoc dl(Mld);
22577
22578   assert(LdVT != VT && "Cannot extend to the same type");
22579   unsigned ToSz = VT.getVectorElementType().getSizeInBits();
22580   unsigned FromSz = LdVT.getVectorElementType().getSizeInBits();
22581   // From, To sizes and ElemCount must be pow of two
22582   assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
22583     "Unexpected size for extending masked load");
22584
22585   unsigned SizeRatio  = ToSz / FromSz;
22586   assert(SizeRatio * NumElems * FromSz == VT.getSizeInBits());
22587
22588   // Create a type on which we perform the shuffle
22589   EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
22590           LdVT.getScalarType(), NumElems*SizeRatio);
22591   assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
22592
22593   // Convert Src0 value
22594   SDValue WideSrc0 = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Mld->getSrc0());
22595   if (Mld->getSrc0().getOpcode() != ISD::UNDEF) {
22596     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
22597     for (unsigned i = 0; i != NumElems; ++i)
22598       ShuffleVec[i] = i * SizeRatio;
22599
22600     // Can't shuffle using an illegal type.
22601     assert (DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT)
22602             && "WideVecVT should be legal");
22603     WideSrc0 = DAG.getVectorShuffle(WideVecVT, dl, WideSrc0,
22604                                     DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
22605   }
22606   // Prepare the new mask
22607   SDValue NewMask;
22608   SDValue Mask = Mld->getMask();
22609   if (Mask.getValueType() == VT) {
22610     // Mask and original value have the same type
22611     NewMask = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Mask);
22612     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
22613     for (unsigned i = 0; i != NumElems; ++i)
22614       ShuffleVec[i] = i * SizeRatio;
22615     for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
22616       ShuffleVec[i] = NumElems*SizeRatio;
22617     NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
22618                                    DAG.getConstant(0, WideVecVT),
22619                                    &ShuffleVec[0]);
22620   }
22621   else {
22622     assert(Mask.getValueType().getVectorElementType() == MVT::i1);
22623     unsigned WidenNumElts = NumElems*SizeRatio;
22624     unsigned MaskNumElts = VT.getVectorNumElements();
22625     EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(),  MVT::i1,
22626                                      WidenNumElts);
22627
22628     unsigned NumConcat = WidenNumElts / MaskNumElts;
22629     SmallVector<SDValue, 16> Ops(NumConcat);
22630     SDValue ZeroVal = DAG.getConstant(0, Mask.getValueType());
22631     Ops[0] = Mask;
22632     for (unsigned i = 1; i != NumConcat; ++i)
22633       Ops[i] = ZeroVal;
22634
22635     NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
22636   }
22637
22638   SDValue WideLd = DAG.getMaskedLoad(WideVecVT, dl, Mld->getChain(),
22639                                      Mld->getBasePtr(), NewMask, WideSrc0,
22640                                      Mld->getMemoryVT(), Mld->getMemOperand(),
22641                                      ISD::NON_EXTLOAD);
22642   SDValue NewVec = DAG.getNode(X86ISD::VSEXT, dl, VT, WideLd);
22643   return DCI.CombineTo(N, NewVec, WideLd.getValue(1), true);
22644
22645 }
22646 /// PerformMSTORECombine - Resolve truncating stores
22647 static SDValue PerformMSTORECombine(SDNode *N, SelectionDAG &DAG,
22648                                     const X86Subtarget *Subtarget) {
22649   MaskedStoreSDNode *Mst = cast<MaskedStoreSDNode>(N);
22650   if (!Mst->isTruncatingStore())
22651     return SDValue();
22652
22653   EVT VT = Mst->getValue().getValueType();
22654   unsigned NumElems = VT.getVectorNumElements();
22655   EVT StVT = Mst->getMemoryVT();
22656   SDLoc dl(Mst);
22657
22658   assert(StVT != VT && "Cannot truncate to the same type");
22659   unsigned FromSz = VT.getVectorElementType().getSizeInBits();
22660   unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
22661
22662   // From, To sizes and ElemCount must be pow of two
22663   assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
22664     "Unexpected size for truncating masked store");
22665   // We are going to use the original vector elt for storing.
22666   // Accumulated smaller vector elements must be a multiple of the store size.
22667   assert (((NumElems * FromSz) % ToSz) == 0 &&
22668           "Unexpected ratio for truncating masked store");
22669
22670   unsigned SizeRatio  = FromSz / ToSz;
22671   assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
22672
22673   // Create a type on which we perform the shuffle
22674   EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
22675           StVT.getScalarType(), NumElems*SizeRatio);
22676
22677   assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
22678
22679   SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Mst->getValue());
22680   SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
22681   for (unsigned i = 0; i != NumElems; ++i)
22682     ShuffleVec[i] = i * SizeRatio;
22683
22684   // Can't shuffle using an illegal type.
22685   assert (DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT)
22686           && "WideVecVT should be legal");
22687
22688   SDValue TruncatedVal = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
22689                                         DAG.getUNDEF(WideVecVT),
22690                                         &ShuffleVec[0]);
22691
22692   SDValue NewMask;
22693   SDValue Mask = Mst->getMask();
22694   if (Mask.getValueType() == VT) {
22695     // Mask and original value have the same type
22696     NewMask = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Mask);
22697     for (unsigned i = 0; i != NumElems; ++i)
22698       ShuffleVec[i] = i * SizeRatio;
22699     for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
22700       ShuffleVec[i] = NumElems*SizeRatio;
22701     NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
22702                                    DAG.getConstant(0, WideVecVT),
22703                                    &ShuffleVec[0]);
22704   }
22705   else {
22706     assert(Mask.getValueType().getVectorElementType() == MVT::i1);
22707     unsigned WidenNumElts = NumElems*SizeRatio;
22708     unsigned MaskNumElts = VT.getVectorNumElements();
22709     EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(),  MVT::i1,
22710                                      WidenNumElts);
22711
22712     unsigned NumConcat = WidenNumElts / MaskNumElts;
22713     SmallVector<SDValue, 16> Ops(NumConcat);
22714     SDValue ZeroVal = DAG.getConstant(0, Mask.getValueType());
22715     Ops[0] = Mask;
22716     for (unsigned i = 1; i != NumConcat; ++i)
22717       Ops[i] = ZeroVal;
22718
22719     NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
22720   }
22721
22722   return DAG.getMaskedStore(Mst->getChain(), dl, TruncatedVal, Mst->getBasePtr(),
22723                             NewMask, StVT, Mst->getMemOperand(), false);
22724 }
22725 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
22726 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
22727                                    const X86Subtarget *Subtarget) {
22728   StoreSDNode *St = cast<StoreSDNode>(N);
22729   EVT VT = St->getValue().getValueType();
22730   EVT StVT = St->getMemoryVT();
22731   SDLoc dl(St);
22732   SDValue StoredVal = St->getOperand(1);
22733   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22734
22735   // If we are saving a concatenation of two XMM registers and 32-byte stores
22736   // are slow, such as on Sandy Bridge, perform two 16-byte stores.
22737   unsigned Alignment = St->getAlignment();
22738   bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
22739   if (VT.is256BitVector() && Subtarget->isUnalignedMem32Slow() &&
22740       StVT == VT && !IsAligned) {
22741     unsigned NumElems = VT.getVectorNumElements();
22742     if (NumElems < 2)
22743       return SDValue();
22744
22745     SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
22746     SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
22747
22748     SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
22749     SDValue Ptr0 = St->getBasePtr();
22750     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
22751
22752     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
22753                                 St->getPointerInfo(), St->isVolatile(),
22754                                 St->isNonTemporal(), Alignment);
22755     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
22756                                 St->getPointerInfo(), St->isVolatile(),
22757                                 St->isNonTemporal(),
22758                                 std::min(16U, Alignment));
22759     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
22760   }
22761
22762   // Optimize trunc store (of multiple scalars) to shuffle and store.
22763   // First, pack all of the elements in one place. Next, store to memory
22764   // in fewer chunks.
22765   if (St->isTruncatingStore() && VT.isVector()) {
22766     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22767     unsigned NumElems = VT.getVectorNumElements();
22768     assert(StVT != VT && "Cannot truncate to the same type");
22769     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
22770     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
22771
22772     // From, To sizes and ElemCount must be pow of two
22773     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
22774     // We are going to use the original vector elt for storing.
22775     // Accumulated smaller vector elements must be a multiple of the store size.
22776     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
22777
22778     unsigned SizeRatio  = FromSz / ToSz;
22779
22780     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
22781
22782     // Create a type on which we perform the shuffle
22783     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
22784             StVT.getScalarType(), NumElems*SizeRatio);
22785
22786     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
22787
22788     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
22789     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
22790     for (unsigned i = 0; i != NumElems; ++i)
22791       ShuffleVec[i] = i * SizeRatio;
22792
22793     // Can't shuffle using an illegal type.
22794     if (!TLI.isTypeLegal(WideVecVT))
22795       return SDValue();
22796
22797     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
22798                                          DAG.getUNDEF(WideVecVT),
22799                                          &ShuffleVec[0]);
22800     // At this point all of the data is stored at the bottom of the
22801     // register. We now need to save it to mem.
22802
22803     // Find the largest store unit
22804     MVT StoreType = MVT::i8;
22805     for (MVT Tp : MVT::integer_valuetypes()) {
22806       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
22807         StoreType = Tp;
22808     }
22809
22810     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
22811     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
22812         (64 <= NumElems * ToSz))
22813       StoreType = MVT::f64;
22814
22815     // Bitcast the original vector into a vector of store-size units
22816     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
22817             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
22818     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
22819     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
22820     SmallVector<SDValue, 8> Chains;
22821     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
22822                                         TLI.getPointerTy());
22823     SDValue Ptr = St->getBasePtr();
22824
22825     // Perform one or more big stores into memory.
22826     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
22827       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
22828                                    StoreType, ShuffWide,
22829                                    DAG.getIntPtrConstant(i));
22830       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
22831                                 St->getPointerInfo(), St->isVolatile(),
22832                                 St->isNonTemporal(), St->getAlignment());
22833       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
22834       Chains.push_back(Ch);
22835     }
22836
22837     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
22838   }
22839
22840   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
22841   // the FP state in cases where an emms may be missing.
22842   // A preferable solution to the general problem is to figure out the right
22843   // places to insert EMMS.  This qualifies as a quick hack.
22844
22845   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
22846   if (VT.getSizeInBits() != 64)
22847     return SDValue();
22848
22849   const Function *F = DAG.getMachineFunction().getFunction();
22850   bool NoImplicitFloatOps = F->hasFnAttribute(Attribute::NoImplicitFloat);
22851   bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
22852                      && Subtarget->hasSSE2();
22853   if ((VT.isVector() ||
22854        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
22855       isa<LoadSDNode>(St->getValue()) &&
22856       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
22857       St->getChain().hasOneUse() && !St->isVolatile()) {
22858     SDNode* LdVal = St->getValue().getNode();
22859     LoadSDNode *Ld = nullptr;
22860     int TokenFactorIndex = -1;
22861     SmallVector<SDValue, 8> Ops;
22862     SDNode* ChainVal = St->getChain().getNode();
22863     // Must be a store of a load.  We currently handle two cases:  the load
22864     // is a direct child, and it's under an intervening TokenFactor.  It is
22865     // possible to dig deeper under nested TokenFactors.
22866     if (ChainVal == LdVal)
22867       Ld = cast<LoadSDNode>(St->getChain());
22868     else if (St->getValue().hasOneUse() &&
22869              ChainVal->getOpcode() == ISD::TokenFactor) {
22870       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
22871         if (ChainVal->getOperand(i).getNode() == LdVal) {
22872           TokenFactorIndex = i;
22873           Ld = cast<LoadSDNode>(St->getValue());
22874         } else
22875           Ops.push_back(ChainVal->getOperand(i));
22876       }
22877     }
22878
22879     if (!Ld || !ISD::isNormalLoad(Ld))
22880       return SDValue();
22881
22882     // If this is not the MMX case, i.e. we are just turning i64 load/store
22883     // into f64 load/store, avoid the transformation if there are multiple
22884     // uses of the loaded value.
22885     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
22886       return SDValue();
22887
22888     SDLoc LdDL(Ld);
22889     SDLoc StDL(N);
22890     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
22891     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
22892     // pair instead.
22893     if (Subtarget->is64Bit() || F64IsLegal) {
22894       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
22895       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
22896                                   Ld->getPointerInfo(), Ld->isVolatile(),
22897                                   Ld->isNonTemporal(), Ld->isInvariant(),
22898                                   Ld->getAlignment());
22899       SDValue NewChain = NewLd.getValue(1);
22900       if (TokenFactorIndex != -1) {
22901         Ops.push_back(NewChain);
22902         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
22903       }
22904       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
22905                           St->getPointerInfo(),
22906                           St->isVolatile(), St->isNonTemporal(),
22907                           St->getAlignment());
22908     }
22909
22910     // Otherwise, lower to two pairs of 32-bit loads / stores.
22911     SDValue LoAddr = Ld->getBasePtr();
22912     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
22913                                  DAG.getConstant(4, MVT::i32));
22914
22915     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
22916                                Ld->getPointerInfo(),
22917                                Ld->isVolatile(), Ld->isNonTemporal(),
22918                                Ld->isInvariant(), Ld->getAlignment());
22919     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
22920                                Ld->getPointerInfo().getWithOffset(4),
22921                                Ld->isVolatile(), Ld->isNonTemporal(),
22922                                Ld->isInvariant(),
22923                                MinAlign(Ld->getAlignment(), 4));
22924
22925     SDValue NewChain = LoLd.getValue(1);
22926     if (TokenFactorIndex != -1) {
22927       Ops.push_back(LoLd);
22928       Ops.push_back(HiLd);
22929       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
22930     }
22931
22932     LoAddr = St->getBasePtr();
22933     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
22934                          DAG.getConstant(4, MVT::i32));
22935
22936     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
22937                                 St->getPointerInfo(),
22938                                 St->isVolatile(), St->isNonTemporal(),
22939                                 St->getAlignment());
22940     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
22941                                 St->getPointerInfo().getWithOffset(4),
22942                                 St->isVolatile(),
22943                                 St->isNonTemporal(),
22944                                 MinAlign(St->getAlignment(), 4));
22945     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
22946   }
22947   return SDValue();
22948 }
22949
22950 /// Return 'true' if this vector operation is "horizontal"
22951 /// and return the operands for the horizontal operation in LHS and RHS.  A
22952 /// horizontal operation performs the binary operation on successive elements
22953 /// of its first operand, then on successive elements of its second operand,
22954 /// returning the resulting values in a vector.  For example, if
22955 ///   A = < float a0, float a1, float a2, float a3 >
22956 /// and
22957 ///   B = < float b0, float b1, float b2, float b3 >
22958 /// then the result of doing a horizontal operation on A and B is
22959 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
22960 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
22961 /// A horizontal-op B, for some already available A and B, and if so then LHS is
22962 /// set to A, RHS to B, and the routine returns 'true'.
22963 /// Note that the binary operation should have the property that if one of the
22964 /// operands is UNDEF then the result is UNDEF.
22965 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
22966   // Look for the following pattern: if
22967   //   A = < float a0, float a1, float a2, float a3 >
22968   //   B = < float b0, float b1, float b2, float b3 >
22969   // and
22970   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
22971   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
22972   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
22973   // which is A horizontal-op B.
22974
22975   // At least one of the operands should be a vector shuffle.
22976   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
22977       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
22978     return false;
22979
22980   MVT VT = LHS.getSimpleValueType();
22981
22982   assert((VT.is128BitVector() || VT.is256BitVector()) &&
22983          "Unsupported vector type for horizontal add/sub");
22984
22985   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
22986   // operate independently on 128-bit lanes.
22987   unsigned NumElts = VT.getVectorNumElements();
22988   unsigned NumLanes = VT.getSizeInBits()/128;
22989   unsigned NumLaneElts = NumElts / NumLanes;
22990   assert((NumLaneElts % 2 == 0) &&
22991          "Vector type should have an even number of elements in each lane");
22992   unsigned HalfLaneElts = NumLaneElts/2;
22993
22994   // View LHS in the form
22995   //   LHS = VECTOR_SHUFFLE A, B, LMask
22996   // If LHS is not a shuffle then pretend it is the shuffle
22997   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
22998   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
22999   // type VT.
23000   SDValue A, B;
23001   SmallVector<int, 16> LMask(NumElts);
23002   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
23003     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
23004       A = LHS.getOperand(0);
23005     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
23006       B = LHS.getOperand(1);
23007     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
23008     std::copy(Mask.begin(), Mask.end(), LMask.begin());
23009   } else {
23010     if (LHS.getOpcode() != ISD::UNDEF)
23011       A = LHS;
23012     for (unsigned i = 0; i != NumElts; ++i)
23013       LMask[i] = i;
23014   }
23015
23016   // Likewise, view RHS in the form
23017   //   RHS = VECTOR_SHUFFLE C, D, RMask
23018   SDValue C, D;
23019   SmallVector<int, 16> RMask(NumElts);
23020   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
23021     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
23022       C = RHS.getOperand(0);
23023     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
23024       D = RHS.getOperand(1);
23025     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
23026     std::copy(Mask.begin(), Mask.end(), RMask.begin());
23027   } else {
23028     if (RHS.getOpcode() != ISD::UNDEF)
23029       C = RHS;
23030     for (unsigned i = 0; i != NumElts; ++i)
23031       RMask[i] = i;
23032   }
23033
23034   // Check that the shuffles are both shuffling the same vectors.
23035   if (!(A == C && B == D) && !(A == D && B == C))
23036     return false;
23037
23038   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
23039   if (!A.getNode() && !B.getNode())
23040     return false;
23041
23042   // If A and B occur in reverse order in RHS, then "swap" them (which means
23043   // rewriting the mask).
23044   if (A != C)
23045     ShuffleVectorSDNode::commuteMask(RMask);
23046
23047   // At this point LHS and RHS are equivalent to
23048   //   LHS = VECTOR_SHUFFLE A, B, LMask
23049   //   RHS = VECTOR_SHUFFLE A, B, RMask
23050   // Check that the masks correspond to performing a horizontal operation.
23051   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
23052     for (unsigned i = 0; i != NumLaneElts; ++i) {
23053       int LIdx = LMask[i+l], RIdx = RMask[i+l];
23054
23055       // Ignore any UNDEF components.
23056       if (LIdx < 0 || RIdx < 0 ||
23057           (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
23058           (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
23059         continue;
23060
23061       // Check that successive elements are being operated on.  If not, this is
23062       // not a horizontal operation.
23063       unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
23064       int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
23065       if (!(LIdx == Index && RIdx == Index + 1) &&
23066           !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
23067         return false;
23068     }
23069   }
23070
23071   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
23072   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
23073   return true;
23074 }
23075
23076 /// Do target-specific dag combines on floating point adds.
23077 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
23078                                   const X86Subtarget *Subtarget) {
23079   EVT VT = N->getValueType(0);
23080   SDValue LHS = N->getOperand(0);
23081   SDValue RHS = N->getOperand(1);
23082
23083   // Try to synthesize horizontal adds from adds of shuffles.
23084   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
23085        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
23086       isHorizontalBinOp(LHS, RHS, true))
23087     return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
23088   return SDValue();
23089 }
23090
23091 /// Do target-specific dag combines on floating point subs.
23092 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
23093                                   const X86Subtarget *Subtarget) {
23094   EVT VT = N->getValueType(0);
23095   SDValue LHS = N->getOperand(0);
23096   SDValue RHS = N->getOperand(1);
23097
23098   // Try to synthesize horizontal subs from subs of shuffles.
23099   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
23100        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
23101       isHorizontalBinOp(LHS, RHS, false))
23102     return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
23103   return SDValue();
23104 }
23105
23106 /// Do target-specific dag combines on X86ISD::FOR and X86ISD::FXOR nodes.
23107 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
23108   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
23109
23110   // F[X]OR(0.0, x) -> x
23111   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
23112     if (C->getValueAPF().isPosZero())
23113       return N->getOperand(1);
23114
23115   // F[X]OR(x, 0.0) -> x
23116   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
23117     if (C->getValueAPF().isPosZero())
23118       return N->getOperand(0);
23119   return SDValue();
23120 }
23121
23122 /// Do target-specific dag combines on X86ISD::FMIN and X86ISD::FMAX nodes.
23123 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
23124   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
23125
23126   // Only perform optimizations if UnsafeMath is used.
23127   if (!DAG.getTarget().Options.UnsafeFPMath)
23128     return SDValue();
23129
23130   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
23131   // into FMINC and FMAXC, which are Commutative operations.
23132   unsigned NewOp = 0;
23133   switch (N->getOpcode()) {
23134     default: llvm_unreachable("unknown opcode");
23135     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
23136     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
23137   }
23138
23139   return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
23140                      N->getOperand(0), N->getOperand(1));
23141 }
23142
23143 /// Do target-specific dag combines on X86ISD::FAND nodes.
23144 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
23145   // FAND(0.0, x) -> 0.0
23146   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
23147     if (C->getValueAPF().isPosZero())
23148       return N->getOperand(0);
23149
23150   // FAND(x, 0.0) -> 0.0
23151   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
23152     if (C->getValueAPF().isPosZero())
23153       return N->getOperand(1);
23154
23155   return SDValue();
23156 }
23157
23158 /// Do target-specific dag combines on X86ISD::FANDN nodes
23159 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
23160   // FANDN(0.0, x) -> x
23161   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
23162     if (C->getValueAPF().isPosZero())
23163       return N->getOperand(1);
23164
23165   // FANDN(x, 0.0) -> 0.0
23166   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
23167     if (C->getValueAPF().isPosZero())
23168       return N->getOperand(1);
23169
23170   return SDValue();
23171 }
23172
23173 static SDValue PerformBTCombine(SDNode *N,
23174                                 SelectionDAG &DAG,
23175                                 TargetLowering::DAGCombinerInfo &DCI) {
23176   // BT ignores high bits in the bit index operand.
23177   SDValue Op1 = N->getOperand(1);
23178   if (Op1.hasOneUse()) {
23179     unsigned BitWidth = Op1.getValueSizeInBits();
23180     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
23181     APInt KnownZero, KnownOne;
23182     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
23183                                           !DCI.isBeforeLegalizeOps());
23184     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23185     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
23186         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
23187       DCI.CommitTargetLoweringOpt(TLO);
23188   }
23189   return SDValue();
23190 }
23191
23192 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
23193   SDValue Op = N->getOperand(0);
23194   if (Op.getOpcode() == ISD::BITCAST)
23195     Op = Op.getOperand(0);
23196   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
23197   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
23198       VT.getVectorElementType().getSizeInBits() ==
23199       OpVT.getVectorElementType().getSizeInBits()) {
23200     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
23201   }
23202   return SDValue();
23203 }
23204
23205 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
23206                                                const X86Subtarget *Subtarget) {
23207   EVT VT = N->getValueType(0);
23208   if (!VT.isVector())
23209     return SDValue();
23210
23211   SDValue N0 = N->getOperand(0);
23212   SDValue N1 = N->getOperand(1);
23213   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
23214   SDLoc dl(N);
23215
23216   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
23217   // both SSE and AVX2 since there is no sign-extended shift right
23218   // operation on a vector with 64-bit elements.
23219   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
23220   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
23221   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
23222       N0.getOpcode() == ISD::SIGN_EXTEND)) {
23223     SDValue N00 = N0.getOperand(0);
23224
23225     // EXTLOAD has a better solution on AVX2,
23226     // it may be replaced with X86ISD::VSEXT node.
23227     if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
23228       if (!ISD::isNormalLoad(N00.getNode()))
23229         return SDValue();
23230
23231     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
23232         SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
23233                                   N00, N1);
23234       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
23235     }
23236   }
23237   return SDValue();
23238 }
23239
23240 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
23241                                   TargetLowering::DAGCombinerInfo &DCI,
23242                                   const X86Subtarget *Subtarget) {
23243   SDValue N0 = N->getOperand(0);
23244   EVT VT = N->getValueType(0);
23245
23246   // (i8,i32 sext (sdivrem (i8 x, i8 y)) ->
23247   // (i8,i32 (sdivrem_sext_hreg (i8 x, i8 y)
23248   // This exposes the sext to the sdivrem lowering, so that it directly extends
23249   // from AH (which we otherwise need to do contortions to access).
23250   if (N0.getOpcode() == ISD::SDIVREM && N0.getResNo() == 1 &&
23251       N0.getValueType() == MVT::i8 && VT == MVT::i32) {
23252     SDLoc dl(N);
23253     SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
23254     SDValue R = DAG.getNode(X86ISD::SDIVREM8_SEXT_HREG, dl, NodeTys,
23255                             N0.getOperand(0), N0.getOperand(1));
23256     DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
23257     return R.getValue(1);
23258   }
23259
23260   if (!DCI.isBeforeLegalizeOps())
23261     return SDValue();
23262
23263   if (!Subtarget->hasFp256())
23264     return SDValue();
23265
23266   if (VT.isVector() && VT.getSizeInBits() == 256) {
23267     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
23268     if (R.getNode())
23269       return R;
23270   }
23271
23272   return SDValue();
23273 }
23274
23275 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
23276                                  const X86Subtarget* Subtarget) {
23277   SDLoc dl(N);
23278   EVT VT = N->getValueType(0);
23279
23280   // Let legalize expand this if it isn't a legal type yet.
23281   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
23282     return SDValue();
23283
23284   EVT ScalarVT = VT.getScalarType();
23285   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
23286       (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
23287     return SDValue();
23288
23289   SDValue A = N->getOperand(0);
23290   SDValue B = N->getOperand(1);
23291   SDValue C = N->getOperand(2);
23292
23293   bool NegA = (A.getOpcode() == ISD::FNEG);
23294   bool NegB = (B.getOpcode() == ISD::FNEG);
23295   bool NegC = (C.getOpcode() == ISD::FNEG);
23296
23297   // Negative multiplication when NegA xor NegB
23298   bool NegMul = (NegA != NegB);
23299   if (NegA)
23300     A = A.getOperand(0);
23301   if (NegB)
23302     B = B.getOperand(0);
23303   if (NegC)
23304     C = C.getOperand(0);
23305
23306   unsigned Opcode;
23307   if (!NegMul)
23308     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
23309   else
23310     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
23311
23312   return DAG.getNode(Opcode, dl, VT, A, B, C);
23313 }
23314
23315 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
23316                                   TargetLowering::DAGCombinerInfo &DCI,
23317                                   const X86Subtarget *Subtarget) {
23318   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
23319   //           (and (i32 x86isd::setcc_carry), 1)
23320   // This eliminates the zext. This transformation is necessary because
23321   // ISD::SETCC is always legalized to i8.
23322   SDLoc dl(N);
23323   SDValue N0 = N->getOperand(0);
23324   EVT VT = N->getValueType(0);
23325
23326   if (N0.getOpcode() == ISD::AND &&
23327       N0.hasOneUse() &&
23328       N0.getOperand(0).hasOneUse()) {
23329     SDValue N00 = N0.getOperand(0);
23330     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
23331       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
23332       if (!C || C->getZExtValue() != 1)
23333         return SDValue();
23334       return DAG.getNode(ISD::AND, dl, VT,
23335                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
23336                                      N00.getOperand(0), N00.getOperand(1)),
23337                          DAG.getConstant(1, VT));
23338     }
23339   }
23340
23341   if (N0.getOpcode() == ISD::TRUNCATE &&
23342       N0.hasOneUse() &&
23343       N0.getOperand(0).hasOneUse()) {
23344     SDValue N00 = N0.getOperand(0);
23345     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
23346       return DAG.getNode(ISD::AND, dl, VT,
23347                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
23348                                      N00.getOperand(0), N00.getOperand(1)),
23349                          DAG.getConstant(1, VT));
23350     }
23351   }
23352   if (VT.is256BitVector()) {
23353     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
23354     if (R.getNode())
23355       return R;
23356   }
23357
23358   // (i8,i32 zext (udivrem (i8 x, i8 y)) ->
23359   // (i8,i32 (udivrem_zext_hreg (i8 x, i8 y)
23360   // This exposes the zext to the udivrem lowering, so that it directly extends
23361   // from AH (which we otherwise need to do contortions to access).
23362   if (N0.getOpcode() == ISD::UDIVREM &&
23363       N0.getResNo() == 1 && N0.getValueType() == MVT::i8 &&
23364       (VT == MVT::i32 || VT == MVT::i64)) {
23365     SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
23366     SDValue R = DAG.getNode(X86ISD::UDIVREM8_ZEXT_HREG, dl, NodeTys,
23367                             N0.getOperand(0), N0.getOperand(1));
23368     DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
23369     return R.getValue(1);
23370   }
23371
23372   return SDValue();
23373 }
23374
23375 // Optimize x == -y --> x+y == 0
23376 //          x != -y --> x+y != 0
23377 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
23378                                       const X86Subtarget* Subtarget) {
23379   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
23380   SDValue LHS = N->getOperand(0);
23381   SDValue RHS = N->getOperand(1);
23382   EVT VT = N->getValueType(0);
23383   SDLoc DL(N);
23384
23385   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
23386     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
23387       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
23388         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N), LHS.getValueType(), RHS,
23389                                    LHS.getOperand(1));
23390         return DAG.getSetCC(SDLoc(N), N->getValueType(0), addV,
23391                             DAG.getConstant(0, addV.getValueType()), CC);
23392       }
23393   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
23394     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
23395       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
23396         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N), RHS.getValueType(), LHS,
23397                                    RHS.getOperand(1));
23398         return DAG.getSetCC(SDLoc(N), N->getValueType(0), addV,
23399                             DAG.getConstant(0, addV.getValueType()), CC);
23400       }
23401
23402   if (VT.getScalarType() == MVT::i1 &&
23403       (CC == ISD::SETNE || CC == ISD::SETEQ || ISD::isSignedIntSetCC(CC))) {
23404     bool IsSEXT0 =
23405         (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
23406         (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
23407     bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
23408
23409     if (!IsSEXT0 || !IsVZero1) {
23410       // Swap the operands and update the condition code.
23411       std::swap(LHS, RHS);
23412       CC = ISD::getSetCCSwappedOperands(CC);
23413
23414       IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
23415                 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
23416       IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
23417     }
23418
23419     if (IsSEXT0 && IsVZero1) {
23420       assert(VT == LHS.getOperand(0).getValueType() &&
23421              "Uexpected operand type");
23422       if (CC == ISD::SETGT)
23423         return DAG.getConstant(0, VT);
23424       if (CC == ISD::SETLE)
23425         return DAG.getConstant(1, VT);
23426       if (CC == ISD::SETEQ || CC == ISD::SETGE)
23427         return DAG.getNOT(DL, LHS.getOperand(0), VT);
23428
23429       assert((CC == ISD::SETNE || CC == ISD::SETLT) &&
23430              "Unexpected condition code!");
23431       return LHS.getOperand(0);
23432     }
23433   }
23434
23435   return SDValue();
23436 }
23437
23438 static SDValue NarrowVectorLoadToElement(LoadSDNode *Load, unsigned Index,
23439                                          SelectionDAG &DAG) {
23440   SDLoc dl(Load);
23441   MVT VT = Load->getSimpleValueType(0);
23442   MVT EVT = VT.getVectorElementType();
23443   SDValue Addr = Load->getOperand(1);
23444   SDValue NewAddr = DAG.getNode(
23445       ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
23446       DAG.getConstant(Index * EVT.getStoreSize(), Addr.getSimpleValueType()));
23447
23448   SDValue NewLoad =
23449       DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
23450                   DAG.getMachineFunction().getMachineMemOperand(
23451                       Load->getMemOperand(), 0, EVT.getStoreSize()));
23452   return NewLoad;
23453 }
23454
23455 static SDValue PerformINSERTPSCombine(SDNode *N, SelectionDAG &DAG,
23456                                       const X86Subtarget *Subtarget) {
23457   SDLoc dl(N);
23458   MVT VT = N->getOperand(1)->getSimpleValueType(0);
23459   assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
23460          "X86insertps is only defined for v4x32");
23461
23462   SDValue Ld = N->getOperand(1);
23463   if (MayFoldLoad(Ld)) {
23464     // Extract the countS bits from the immediate so we can get the proper
23465     // address when narrowing the vector load to a specific element.
23466     // When the second source op is a memory address, insertps doesn't use
23467     // countS and just gets an f32 from that address.
23468     unsigned DestIndex =
23469         cast<ConstantSDNode>(N->getOperand(2))->getZExtValue() >> 6;
23470
23471     Ld = NarrowVectorLoadToElement(cast<LoadSDNode>(Ld), DestIndex, DAG);
23472
23473     // Create this as a scalar to vector to match the instruction pattern.
23474     SDValue LoadScalarToVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Ld);
23475     // countS bits are ignored when loading from memory on insertps, which
23476     // means we don't need to explicitly set them to 0.
23477     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N->getOperand(0),
23478                        LoadScalarToVector, N->getOperand(2));
23479   }
23480   return SDValue();
23481 }
23482
23483 static SDValue PerformBLENDICombine(SDNode *N, SelectionDAG &DAG) {
23484   SDValue V0 = N->getOperand(0);
23485   SDValue V1 = N->getOperand(1);
23486   SDLoc DL(N);
23487   EVT VT = N->getValueType(0);
23488
23489   // Canonicalize a v2f64 blend with a mask of 2 by swapping the vector
23490   // operands and changing the mask to 1. This saves us a bunch of
23491   // pattern-matching possibilities related to scalar math ops in SSE/AVX.
23492   // x86InstrInfo knows how to commute this back after instruction selection
23493   // if it would help register allocation.
23494
23495   // TODO: If optimizing for size or a processor that doesn't suffer from
23496   // partial register update stalls, this should be transformed into a MOVSD
23497   // instruction because a MOVSD is 1-2 bytes smaller than a BLENDPD.
23498
23499   if (VT == MVT::v2f64)
23500     if (auto *Mask = dyn_cast<ConstantSDNode>(N->getOperand(2)))
23501       if (Mask->getZExtValue() == 2 && !isShuffleFoldableLoad(V0)) {
23502         SDValue NewMask = DAG.getConstant(1, MVT::i8);
23503         return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V0, NewMask);
23504       }
23505
23506   return SDValue();
23507 }
23508
23509 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
23510 // as "sbb reg,reg", since it can be extended without zext and produces
23511 // an all-ones bit which is more useful than 0/1 in some cases.
23512 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
23513                                MVT VT) {
23514   if (VT == MVT::i8)
23515     return DAG.getNode(ISD::AND, DL, VT,
23516                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
23517                                    DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
23518                        DAG.getConstant(1, VT));
23519   assert (VT == MVT::i1 && "Unexpected type for SECCC node");
23520   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
23521                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
23522                                  DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS));
23523 }
23524
23525 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
23526 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
23527                                    TargetLowering::DAGCombinerInfo &DCI,
23528                                    const X86Subtarget *Subtarget) {
23529   SDLoc DL(N);
23530   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
23531   SDValue EFLAGS = N->getOperand(1);
23532
23533   if (CC == X86::COND_A) {
23534     // Try to convert COND_A into COND_B in an attempt to facilitate
23535     // materializing "setb reg".
23536     //
23537     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
23538     // cannot take an immediate as its first operand.
23539     //
23540     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
23541         EFLAGS.getValueType().isInteger() &&
23542         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
23543       SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
23544                                    EFLAGS.getNode()->getVTList(),
23545                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
23546       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
23547       return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
23548     }
23549   }
23550
23551   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
23552   // a zext and produces an all-ones bit which is more useful than 0/1 in some
23553   // cases.
23554   if (CC == X86::COND_B)
23555     return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
23556
23557   SDValue Flags;
23558
23559   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
23560   if (Flags.getNode()) {
23561     SDValue Cond = DAG.getConstant(CC, MVT::i8);
23562     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
23563   }
23564
23565   return SDValue();
23566 }
23567
23568 // Optimize branch condition evaluation.
23569 //
23570 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
23571                                     TargetLowering::DAGCombinerInfo &DCI,
23572                                     const X86Subtarget *Subtarget) {
23573   SDLoc DL(N);
23574   SDValue Chain = N->getOperand(0);
23575   SDValue Dest = N->getOperand(1);
23576   SDValue EFLAGS = N->getOperand(3);
23577   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
23578
23579   SDValue Flags;
23580
23581   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
23582   if (Flags.getNode()) {
23583     SDValue Cond = DAG.getConstant(CC, MVT::i8);
23584     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
23585                        Flags);
23586   }
23587
23588   return SDValue();
23589 }
23590
23591 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
23592                                                          SelectionDAG &DAG) {
23593   // Take advantage of vector comparisons producing 0 or -1 in each lane to
23594   // optimize away operation when it's from a constant.
23595   //
23596   // The general transformation is:
23597   //    UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
23598   //       AND(VECTOR_CMP(x,y), constant2)
23599   //    constant2 = UNARYOP(constant)
23600
23601   // Early exit if this isn't a vector operation, the operand of the
23602   // unary operation isn't a bitwise AND, or if the sizes of the operations
23603   // aren't the same.
23604   EVT VT = N->getValueType(0);
23605   if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
23606       N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
23607       VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
23608     return SDValue();
23609
23610   // Now check that the other operand of the AND is a constant. We could
23611   // make the transformation for non-constant splats as well, but it's unclear
23612   // that would be a benefit as it would not eliminate any operations, just
23613   // perform one more step in scalar code before moving to the vector unit.
23614   if (BuildVectorSDNode *BV =
23615           dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
23616     // Bail out if the vector isn't a constant.
23617     if (!BV->isConstant())
23618       return SDValue();
23619
23620     // Everything checks out. Build up the new and improved node.
23621     SDLoc DL(N);
23622     EVT IntVT = BV->getValueType(0);
23623     // Create a new constant of the appropriate type for the transformed
23624     // DAG.
23625     SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
23626     // The AND node needs bitcasts to/from an integer vector type around it.
23627     SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
23628     SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
23629                                  N->getOperand(0)->getOperand(0), MaskConst);
23630     SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
23631     return Res;
23632   }
23633
23634   return SDValue();
23635 }
23636
23637 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
23638                                         const X86Subtarget *Subtarget) {
23639   // First try to optimize away the conversion entirely when it's
23640   // conditionally from a constant. Vectors only.
23641   SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG);
23642   if (Res != SDValue())
23643     return Res;
23644
23645   // Now move on to more general possibilities.
23646   SDValue Op0 = N->getOperand(0);
23647   EVT InVT = Op0->getValueType(0);
23648
23649   // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
23650   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
23651     SDLoc dl(N);
23652     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
23653     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
23654     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
23655   }
23656
23657   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
23658   // a 32-bit target where SSE doesn't support i64->FP operations.
23659   if (Op0.getOpcode() == ISD::LOAD) {
23660     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
23661     EVT VT = Ld->getValueType(0);
23662     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
23663         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
23664         !Subtarget->is64Bit() && VT == MVT::i64) {
23665       SDValue FILDChain = Subtarget->getTargetLowering()->BuildFILD(
23666           SDValue(N, 0), Ld->getValueType(0), Ld->getChain(), Op0, DAG);
23667       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
23668       return FILDChain;
23669     }
23670   }
23671   return SDValue();
23672 }
23673
23674 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
23675 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
23676                                  X86TargetLowering::DAGCombinerInfo &DCI) {
23677   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
23678   // the result is either zero or one (depending on the input carry bit).
23679   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
23680   if (X86::isZeroNode(N->getOperand(0)) &&
23681       X86::isZeroNode(N->getOperand(1)) &&
23682       // We don't have a good way to replace an EFLAGS use, so only do this when
23683       // dead right now.
23684       SDValue(N, 1).use_empty()) {
23685     SDLoc DL(N);
23686     EVT VT = N->getValueType(0);
23687     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
23688     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
23689                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
23690                                            DAG.getConstant(X86::COND_B,MVT::i8),
23691                                            N->getOperand(2)),
23692                                DAG.getConstant(1, VT));
23693     return DCI.CombineTo(N, Res1, CarryOut);
23694   }
23695
23696   return SDValue();
23697 }
23698
23699 // fold (add Y, (sete  X, 0)) -> adc  0, Y
23700 //      (add Y, (setne X, 0)) -> sbb -1, Y
23701 //      (sub (sete  X, 0), Y) -> sbb  0, Y
23702 //      (sub (setne X, 0), Y) -> adc -1, Y
23703 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
23704   SDLoc DL(N);
23705
23706   // Look through ZExts.
23707   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
23708   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
23709     return SDValue();
23710
23711   SDValue SetCC = Ext.getOperand(0);
23712   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
23713     return SDValue();
23714
23715   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
23716   if (CC != X86::COND_E && CC != X86::COND_NE)
23717     return SDValue();
23718
23719   SDValue Cmp = SetCC.getOperand(1);
23720   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
23721       !X86::isZeroNode(Cmp.getOperand(1)) ||
23722       !Cmp.getOperand(0).getValueType().isInteger())
23723     return SDValue();
23724
23725   SDValue CmpOp0 = Cmp.getOperand(0);
23726   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
23727                                DAG.getConstant(1, CmpOp0.getValueType()));
23728
23729   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
23730   if (CC == X86::COND_NE)
23731     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
23732                        DL, OtherVal.getValueType(), OtherVal,
23733                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
23734   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
23735                      DL, OtherVal.getValueType(), OtherVal,
23736                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
23737 }
23738
23739 /// PerformADDCombine - Do target-specific dag combines on integer adds.
23740 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
23741                                  const X86Subtarget *Subtarget) {
23742   EVT VT = N->getValueType(0);
23743   SDValue Op0 = N->getOperand(0);
23744   SDValue Op1 = N->getOperand(1);
23745
23746   // Try to synthesize horizontal adds from adds of shuffles.
23747   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
23748        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
23749       isHorizontalBinOp(Op0, Op1, true))
23750     return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
23751
23752   return OptimizeConditionalInDecrement(N, DAG);
23753 }
23754
23755 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
23756                                  const X86Subtarget *Subtarget) {
23757   SDValue Op0 = N->getOperand(0);
23758   SDValue Op1 = N->getOperand(1);
23759
23760   // X86 can't encode an immediate LHS of a sub. See if we can push the
23761   // negation into a preceding instruction.
23762   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
23763     // If the RHS of the sub is a XOR with one use and a constant, invert the
23764     // immediate. Then add one to the LHS of the sub so we can turn
23765     // X-Y -> X+~Y+1, saving one register.
23766     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
23767         isa<ConstantSDNode>(Op1.getOperand(1))) {
23768       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
23769       EVT VT = Op0.getValueType();
23770       SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
23771                                    Op1.getOperand(0),
23772                                    DAG.getConstant(~XorC, VT));
23773       return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
23774                          DAG.getConstant(C->getAPIntValue()+1, VT));
23775     }
23776   }
23777
23778   // Try to synthesize horizontal adds from adds of shuffles.
23779   EVT VT = N->getValueType(0);
23780   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
23781        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
23782       isHorizontalBinOp(Op0, Op1, true))
23783     return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
23784
23785   return OptimizeConditionalInDecrement(N, DAG);
23786 }
23787
23788 /// performVZEXTCombine - Performs build vector combines
23789 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
23790                                    TargetLowering::DAGCombinerInfo &DCI,
23791                                    const X86Subtarget *Subtarget) {
23792   SDLoc DL(N);
23793   MVT VT = N->getSimpleValueType(0);
23794   SDValue Op = N->getOperand(0);
23795   MVT OpVT = Op.getSimpleValueType();
23796   MVT OpEltVT = OpVT.getVectorElementType();
23797   unsigned InputBits = OpEltVT.getSizeInBits() * VT.getVectorNumElements();
23798
23799   // (vzext (bitcast (vzext (x)) -> (vzext x)
23800   SDValue V = Op;
23801   while (V.getOpcode() == ISD::BITCAST)
23802     V = V.getOperand(0);
23803
23804   if (V != Op && V.getOpcode() == X86ISD::VZEXT) {
23805     MVT InnerVT = V.getSimpleValueType();
23806     MVT InnerEltVT = InnerVT.getVectorElementType();
23807
23808     // If the element sizes match exactly, we can just do one larger vzext. This
23809     // is always an exact type match as vzext operates on integer types.
23810     if (OpEltVT == InnerEltVT) {
23811       assert(OpVT == InnerVT && "Types must match for vzext!");
23812       return DAG.getNode(X86ISD::VZEXT, DL, VT, V.getOperand(0));
23813     }
23814
23815     // The only other way we can combine them is if only a single element of the
23816     // inner vzext is used in the input to the outer vzext.
23817     if (InnerEltVT.getSizeInBits() < InputBits)
23818       return SDValue();
23819
23820     // In this case, the inner vzext is completely dead because we're going to
23821     // only look at bits inside of the low element. Just do the outer vzext on
23822     // a bitcast of the input to the inner.
23823     return DAG.getNode(X86ISD::VZEXT, DL, VT,
23824                        DAG.getNode(ISD::BITCAST, DL, OpVT, V));
23825   }
23826
23827   // Check if we can bypass extracting and re-inserting an element of an input
23828   // vector. Essentialy:
23829   // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
23830   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR &&
23831       V.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
23832       V.getOperand(0).getSimpleValueType().getSizeInBits() == InputBits) {
23833     SDValue ExtractedV = V.getOperand(0);
23834     SDValue OrigV = ExtractedV.getOperand(0);
23835     if (auto *ExtractIdx = dyn_cast<ConstantSDNode>(ExtractedV.getOperand(1)))
23836       if (ExtractIdx->getZExtValue() == 0) {
23837         MVT OrigVT = OrigV.getSimpleValueType();
23838         // Extract a subvector if necessary...
23839         if (OrigVT.getSizeInBits() > OpVT.getSizeInBits()) {
23840           int Ratio = OrigVT.getSizeInBits() / OpVT.getSizeInBits();
23841           OrigVT = MVT::getVectorVT(OrigVT.getVectorElementType(),
23842                                     OrigVT.getVectorNumElements() / Ratio);
23843           OrigV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigVT, OrigV,
23844                               DAG.getIntPtrConstant(0));
23845         }
23846         Op = DAG.getNode(ISD::BITCAST, DL, OpVT, OrigV);
23847         return DAG.getNode(X86ISD::VZEXT, DL, VT, Op);
23848       }
23849   }
23850
23851   return SDValue();
23852 }
23853
23854 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
23855                                              DAGCombinerInfo &DCI) const {
23856   SelectionDAG &DAG = DCI.DAG;
23857   switch (N->getOpcode()) {
23858   default: break;
23859   case ISD::EXTRACT_VECTOR_ELT:
23860     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
23861   case ISD::VSELECT:
23862   case ISD::SELECT:
23863   case X86ISD::SHRUNKBLEND:
23864     return PerformSELECTCombine(N, DAG, DCI, Subtarget);
23865   case ISD::BITCAST:        return PerformBITCASTCombine(N, DAG);
23866   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
23867   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
23868   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
23869   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
23870   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
23871   case ISD::SHL:
23872   case ISD::SRA:
23873   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
23874   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
23875   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
23876   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
23877   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
23878   case ISD::MLOAD:          return PerformMLOADCombine(N, DAG, DCI, Subtarget);
23879   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
23880   case ISD::MSTORE:         return PerformMSTORECombine(N, DAG, Subtarget);
23881   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, Subtarget);
23882   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
23883   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
23884   case X86ISD::FXOR:
23885   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
23886   case X86ISD::FMIN:
23887   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
23888   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
23889   case X86ISD::FANDN:       return PerformFANDNCombine(N, DAG);
23890   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
23891   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
23892   case ISD::ANY_EXTEND:
23893   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
23894   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
23895   case ISD::SIGN_EXTEND_INREG:
23896     return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
23897   case ISD::TRUNCATE:       return PerformTruncateCombine(N, DAG,DCI,Subtarget);
23898   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG, Subtarget);
23899   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
23900   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
23901   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
23902   case X86ISD::SHUFP:       // Handle all target specific shuffles
23903   case X86ISD::PALIGNR:
23904   case X86ISD::UNPCKH:
23905   case X86ISD::UNPCKL:
23906   case X86ISD::MOVHLPS:
23907   case X86ISD::MOVLHPS:
23908   case X86ISD::PSHUFB:
23909   case X86ISD::PSHUFD:
23910   case X86ISD::PSHUFHW:
23911   case X86ISD::PSHUFLW:
23912   case X86ISD::MOVSS:
23913   case X86ISD::MOVSD:
23914   case X86ISD::VPERMILPI:
23915   case X86ISD::VPERM2X128:
23916   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
23917   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
23918   case ISD::INTRINSIC_WO_CHAIN:
23919     return PerformINTRINSIC_WO_CHAINCombine(N, DAG, Subtarget);
23920   case X86ISD::INSERTPS: {
23921     if (getTargetMachine().getOptLevel() > CodeGenOpt::None)
23922       return PerformINSERTPSCombine(N, DAG, Subtarget);
23923     break;
23924   }
23925   case X86ISD::BLENDI:    return PerformBLENDICombine(N, DAG);
23926   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DAG, Subtarget);
23927   }
23928
23929   return SDValue();
23930 }
23931
23932 /// isTypeDesirableForOp - Return true if the target has native support for
23933 /// the specified value type and it is 'desirable' to use the type for the
23934 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
23935 /// instruction encodings are longer and some i16 instructions are slow.
23936 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
23937   if (!isTypeLegal(VT))
23938     return false;
23939   if (VT != MVT::i16)
23940     return true;
23941
23942   switch (Opc) {
23943   default:
23944     return true;
23945   case ISD::LOAD:
23946   case ISD::SIGN_EXTEND:
23947   case ISD::ZERO_EXTEND:
23948   case ISD::ANY_EXTEND:
23949   case ISD::SHL:
23950   case ISD::SRL:
23951   case ISD::SUB:
23952   case ISD::ADD:
23953   case ISD::MUL:
23954   case ISD::AND:
23955   case ISD::OR:
23956   case ISD::XOR:
23957     return false;
23958   }
23959 }
23960
23961 /// IsDesirableToPromoteOp - This method query the target whether it is
23962 /// beneficial for dag combiner to promote the specified node. If true, it
23963 /// should return the desired promotion type by reference.
23964 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
23965   EVT VT = Op.getValueType();
23966   if (VT != MVT::i16)
23967     return false;
23968
23969   bool Promote = false;
23970   bool Commute = false;
23971   switch (Op.getOpcode()) {
23972   default: break;
23973   case ISD::LOAD: {
23974     LoadSDNode *LD = cast<LoadSDNode>(Op);
23975     // If the non-extending load has a single use and it's not live out, then it
23976     // might be folded.
23977     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
23978                                                      Op.hasOneUse()*/) {
23979       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
23980              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
23981         // The only case where we'd want to promote LOAD (rather then it being
23982         // promoted as an operand is when it's only use is liveout.
23983         if (UI->getOpcode() != ISD::CopyToReg)
23984           return false;
23985       }
23986     }
23987     Promote = true;
23988     break;
23989   }
23990   case ISD::SIGN_EXTEND:
23991   case ISD::ZERO_EXTEND:
23992   case ISD::ANY_EXTEND:
23993     Promote = true;
23994     break;
23995   case ISD::SHL:
23996   case ISD::SRL: {
23997     SDValue N0 = Op.getOperand(0);
23998     // Look out for (store (shl (load), x)).
23999     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
24000       return false;
24001     Promote = true;
24002     break;
24003   }
24004   case ISD::ADD:
24005   case ISD::MUL:
24006   case ISD::AND:
24007   case ISD::OR:
24008   case ISD::XOR:
24009     Commute = true;
24010     // fallthrough
24011   case ISD::SUB: {
24012     SDValue N0 = Op.getOperand(0);
24013     SDValue N1 = Op.getOperand(1);
24014     if (!Commute && MayFoldLoad(N1))
24015       return false;
24016     // Avoid disabling potential load folding opportunities.
24017     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
24018       return false;
24019     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
24020       return false;
24021     Promote = true;
24022   }
24023   }
24024
24025   PVT = MVT::i32;
24026   return Promote;
24027 }
24028
24029 //===----------------------------------------------------------------------===//
24030 //                           X86 Inline Assembly Support
24031 //===----------------------------------------------------------------------===//
24032
24033 // Helper to match a string separated by whitespace.
24034 static bool matchAsm(StringRef S, ArrayRef<const char *> Pieces) {
24035   S = S.substr(S.find_first_not_of(" \t")); // Skip leading whitespace.
24036
24037   for (StringRef Piece : Pieces) {
24038     if (!S.startswith(Piece)) // Check if the piece matches.
24039       return false;
24040
24041     S = S.substr(Piece.size());
24042     StringRef::size_type Pos = S.find_first_not_of(" \t");
24043     if (Pos == 0) // We matched a prefix.
24044       return false;
24045
24046     S = S.substr(Pos);
24047   }
24048
24049   return S.empty();
24050 }
24051
24052 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
24053
24054   if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
24055     if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
24056         std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
24057         std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
24058
24059       if (AsmPieces.size() == 3)
24060         return true;
24061       else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
24062         return true;
24063     }
24064   }
24065   return false;
24066 }
24067
24068 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
24069   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
24070
24071   std::string AsmStr = IA->getAsmString();
24072
24073   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
24074   if (!Ty || Ty->getBitWidth() % 16 != 0)
24075     return false;
24076
24077   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
24078   SmallVector<StringRef, 4> AsmPieces;
24079   SplitString(AsmStr, AsmPieces, ";\n");
24080
24081   switch (AsmPieces.size()) {
24082   default: return false;
24083   case 1:
24084     // FIXME: this should verify that we are targeting a 486 or better.  If not,
24085     // we will turn this bswap into something that will be lowered to logical
24086     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
24087     // lower so don't worry about this.
24088     // bswap $0
24089     if (matchAsm(AsmPieces[0], {"bswap", "$0"}) ||
24090         matchAsm(AsmPieces[0], {"bswapl", "$0"}) ||
24091         matchAsm(AsmPieces[0], {"bswapq", "$0"}) ||
24092         matchAsm(AsmPieces[0], {"bswap", "${0:q}"}) ||
24093         matchAsm(AsmPieces[0], {"bswapl", "${0:q}"}) ||
24094         matchAsm(AsmPieces[0], {"bswapq", "${0:q}"})) {
24095       // No need to check constraints, nothing other than the equivalent of
24096       // "=r,0" would be valid here.
24097       return IntrinsicLowering::LowerToByteSwap(CI);
24098     }
24099
24100     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
24101     if (CI->getType()->isIntegerTy(16) &&
24102         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
24103         (matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) ||
24104          matchAsm(AsmPieces[0], {"rolw", "$$8,", "${0:w}"}))) {
24105       AsmPieces.clear();
24106       const std::string &ConstraintsStr = IA->getConstraintString();
24107       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
24108       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
24109       if (clobbersFlagRegisters(AsmPieces))
24110         return IntrinsicLowering::LowerToByteSwap(CI);
24111     }
24112     break;
24113   case 3:
24114     if (CI->getType()->isIntegerTy(32) &&
24115         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
24116         matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) &&
24117         matchAsm(AsmPieces[1], {"rorl", "$$16,", "$0"}) &&
24118         matchAsm(AsmPieces[2], {"rorw", "$$8,", "${0:w}"})) {
24119       AsmPieces.clear();
24120       const std::string &ConstraintsStr = IA->getConstraintString();
24121       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
24122       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
24123       if (clobbersFlagRegisters(AsmPieces))
24124         return IntrinsicLowering::LowerToByteSwap(CI);
24125     }
24126
24127     if (CI->getType()->isIntegerTy(64)) {
24128       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
24129       if (Constraints.size() >= 2 &&
24130           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
24131           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
24132         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
24133         if (matchAsm(AsmPieces[0], {"bswap", "%eax"}) &&
24134             matchAsm(AsmPieces[1], {"bswap", "%edx"}) &&
24135             matchAsm(AsmPieces[2], {"xchgl", "%eax,", "%edx"}))
24136           return IntrinsicLowering::LowerToByteSwap(CI);
24137       }
24138     }
24139     break;
24140   }
24141   return false;
24142 }
24143
24144 /// getConstraintType - Given a constraint letter, return the type of
24145 /// constraint it is for this target.
24146 X86TargetLowering::ConstraintType
24147 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
24148   if (Constraint.size() == 1) {
24149     switch (Constraint[0]) {
24150     case 'R':
24151     case 'q':
24152     case 'Q':
24153     case 'f':
24154     case 't':
24155     case 'u':
24156     case 'y':
24157     case 'x':
24158     case 'Y':
24159     case 'l':
24160       return C_RegisterClass;
24161     case 'a':
24162     case 'b':
24163     case 'c':
24164     case 'd':
24165     case 'S':
24166     case 'D':
24167     case 'A':
24168       return C_Register;
24169     case 'I':
24170     case 'J':
24171     case 'K':
24172     case 'L':
24173     case 'M':
24174     case 'N':
24175     case 'G':
24176     case 'C':
24177     case 'e':
24178     case 'Z':
24179       return C_Other;
24180     default:
24181       break;
24182     }
24183   }
24184   return TargetLowering::getConstraintType(Constraint);
24185 }
24186
24187 /// Examine constraint type and operand type and determine a weight value.
24188 /// This object must already have been set up with the operand type
24189 /// and the current alternative constraint selected.
24190 TargetLowering::ConstraintWeight
24191   X86TargetLowering::getSingleConstraintMatchWeight(
24192     AsmOperandInfo &info, const char *constraint) const {
24193   ConstraintWeight weight = CW_Invalid;
24194   Value *CallOperandVal = info.CallOperandVal;
24195     // If we don't have a value, we can't do a match,
24196     // but allow it at the lowest weight.
24197   if (!CallOperandVal)
24198     return CW_Default;
24199   Type *type = CallOperandVal->getType();
24200   // Look at the constraint type.
24201   switch (*constraint) {
24202   default:
24203     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
24204   case 'R':
24205   case 'q':
24206   case 'Q':
24207   case 'a':
24208   case 'b':
24209   case 'c':
24210   case 'd':
24211   case 'S':
24212   case 'D':
24213   case 'A':
24214     if (CallOperandVal->getType()->isIntegerTy())
24215       weight = CW_SpecificReg;
24216     break;
24217   case 'f':
24218   case 't':
24219   case 'u':
24220     if (type->isFloatingPointTy())
24221       weight = CW_SpecificReg;
24222     break;
24223   case 'y':
24224     if (type->isX86_MMXTy() && Subtarget->hasMMX())
24225       weight = CW_SpecificReg;
24226     break;
24227   case 'x':
24228   case 'Y':
24229     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
24230         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
24231       weight = CW_Register;
24232     break;
24233   case 'I':
24234     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
24235       if (C->getZExtValue() <= 31)
24236         weight = CW_Constant;
24237     }
24238     break;
24239   case 'J':
24240     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24241       if (C->getZExtValue() <= 63)
24242         weight = CW_Constant;
24243     }
24244     break;
24245   case 'K':
24246     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24247       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
24248         weight = CW_Constant;
24249     }
24250     break;
24251   case 'L':
24252     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24253       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
24254         weight = CW_Constant;
24255     }
24256     break;
24257   case 'M':
24258     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24259       if (C->getZExtValue() <= 3)
24260         weight = CW_Constant;
24261     }
24262     break;
24263   case 'N':
24264     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24265       if (C->getZExtValue() <= 0xff)
24266         weight = CW_Constant;
24267     }
24268     break;
24269   case 'G':
24270   case 'C':
24271     if (isa<ConstantFP>(CallOperandVal)) {
24272       weight = CW_Constant;
24273     }
24274     break;
24275   case 'e':
24276     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24277       if ((C->getSExtValue() >= -0x80000000LL) &&
24278           (C->getSExtValue() <= 0x7fffffffLL))
24279         weight = CW_Constant;
24280     }
24281     break;
24282   case 'Z':
24283     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24284       if (C->getZExtValue() <= 0xffffffff)
24285         weight = CW_Constant;
24286     }
24287     break;
24288   }
24289   return weight;
24290 }
24291
24292 /// LowerXConstraint - try to replace an X constraint, which matches anything,
24293 /// with another that has more specific requirements based on the type of the
24294 /// corresponding operand.
24295 const char *X86TargetLowering::
24296 LowerXConstraint(EVT ConstraintVT) const {
24297   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
24298   // 'f' like normal targets.
24299   if (ConstraintVT.isFloatingPoint()) {
24300     if (Subtarget->hasSSE2())
24301       return "Y";
24302     if (Subtarget->hasSSE1())
24303       return "x";
24304   }
24305
24306   return TargetLowering::LowerXConstraint(ConstraintVT);
24307 }
24308
24309 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
24310 /// vector.  If it is invalid, don't add anything to Ops.
24311 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
24312                                                      std::string &Constraint,
24313                                                      std::vector<SDValue>&Ops,
24314                                                      SelectionDAG &DAG) const {
24315   SDValue Result;
24316
24317   // Only support length 1 constraints for now.
24318   if (Constraint.length() > 1) return;
24319
24320   char ConstraintLetter = Constraint[0];
24321   switch (ConstraintLetter) {
24322   default: break;
24323   case 'I':
24324     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24325       if (C->getZExtValue() <= 31) {
24326         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
24327         break;
24328       }
24329     }
24330     return;
24331   case 'J':
24332     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24333       if (C->getZExtValue() <= 63) {
24334         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
24335         break;
24336       }
24337     }
24338     return;
24339   case 'K':
24340     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24341       if (isInt<8>(C->getSExtValue())) {
24342         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
24343         break;
24344       }
24345     }
24346     return;
24347   case 'L':
24348     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24349       if (C->getZExtValue() == 0xff || C->getZExtValue() == 0xffff ||
24350           (Subtarget->is64Bit() && C->getZExtValue() == 0xffffffff)) {
24351         Result = DAG.getTargetConstant(C->getSExtValue(), Op.getValueType());
24352         break;
24353       }
24354     }
24355     return;
24356   case 'M':
24357     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24358       if (C->getZExtValue() <= 3) {
24359         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
24360         break;
24361       }
24362     }
24363     return;
24364   case 'N':
24365     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24366       if (C->getZExtValue() <= 255) {
24367         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
24368         break;
24369       }
24370     }
24371     return;
24372   case 'O':
24373     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24374       if (C->getZExtValue() <= 127) {
24375         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
24376         break;
24377       }
24378     }
24379     return;
24380   case 'e': {
24381     // 32-bit signed value
24382     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24383       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
24384                                            C->getSExtValue())) {
24385         // Widen to 64 bits here to get it sign extended.
24386         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
24387         break;
24388       }
24389     // FIXME gcc accepts some relocatable values here too, but only in certain
24390     // memory models; it's complicated.
24391     }
24392     return;
24393   }
24394   case 'Z': {
24395     // 32-bit unsigned value
24396     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24397       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
24398                                            C->getZExtValue())) {
24399         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
24400         break;
24401       }
24402     }
24403     // FIXME gcc accepts some relocatable values here too, but only in certain
24404     // memory models; it's complicated.
24405     return;
24406   }
24407   case 'i': {
24408     // Literal immediates are always ok.
24409     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
24410       // Widen to 64 bits here to get it sign extended.
24411       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
24412       break;
24413     }
24414
24415     // In any sort of PIC mode addresses need to be computed at runtime by
24416     // adding in a register or some sort of table lookup.  These can't
24417     // be used as immediates.
24418     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
24419       return;
24420
24421     // If we are in non-pic codegen mode, we allow the address of a global (with
24422     // an optional displacement) to be used with 'i'.
24423     GlobalAddressSDNode *GA = nullptr;
24424     int64_t Offset = 0;
24425
24426     // Match either (GA), (GA+C), (GA+C1+C2), etc.
24427     while (1) {
24428       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
24429         Offset += GA->getOffset();
24430         break;
24431       } else if (Op.getOpcode() == ISD::ADD) {
24432         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
24433           Offset += C->getZExtValue();
24434           Op = Op.getOperand(0);
24435           continue;
24436         }
24437       } else if (Op.getOpcode() == ISD::SUB) {
24438         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
24439           Offset += -C->getZExtValue();
24440           Op = Op.getOperand(0);
24441           continue;
24442         }
24443       }
24444
24445       // Otherwise, this isn't something we can handle, reject it.
24446       return;
24447     }
24448
24449     const GlobalValue *GV = GA->getGlobal();
24450     // If we require an extra load to get this address, as in PIC mode, we
24451     // can't accept it.
24452     if (isGlobalStubReference(
24453             Subtarget->ClassifyGlobalReference(GV, DAG.getTarget())))
24454       return;
24455
24456     Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
24457                                         GA->getValueType(0), Offset);
24458     break;
24459   }
24460   }
24461
24462   if (Result.getNode()) {
24463     Ops.push_back(Result);
24464     return;
24465   }
24466   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
24467 }
24468
24469 std::pair<unsigned, const TargetRegisterClass *>
24470 X86TargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
24471                                                 const std::string &Constraint,
24472                                                 MVT VT) const {
24473   // First, see if this is a constraint that directly corresponds to an LLVM
24474   // register class.
24475   if (Constraint.size() == 1) {
24476     // GCC Constraint Letters
24477     switch (Constraint[0]) {
24478     default: break;
24479       // TODO: Slight differences here in allocation order and leaving
24480       // RIP in the class. Do they matter any more here than they do
24481       // in the normal allocation?
24482     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
24483       if (Subtarget->is64Bit()) {
24484         if (VT == MVT::i32 || VT == MVT::f32)
24485           return std::make_pair(0U, &X86::GR32RegClass);
24486         if (VT == MVT::i16)
24487           return std::make_pair(0U, &X86::GR16RegClass);
24488         if (VT == MVT::i8 || VT == MVT::i1)
24489           return std::make_pair(0U, &X86::GR8RegClass);
24490         if (VT == MVT::i64 || VT == MVT::f64)
24491           return std::make_pair(0U, &X86::GR64RegClass);
24492         break;
24493       }
24494       // 32-bit fallthrough
24495     case 'Q':   // Q_REGS
24496       if (VT == MVT::i32 || VT == MVT::f32)
24497         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
24498       if (VT == MVT::i16)
24499         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
24500       if (VT == MVT::i8 || VT == MVT::i1)
24501         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
24502       if (VT == MVT::i64)
24503         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
24504       break;
24505     case 'r':   // GENERAL_REGS
24506     case 'l':   // INDEX_REGS
24507       if (VT == MVT::i8 || VT == MVT::i1)
24508         return std::make_pair(0U, &X86::GR8RegClass);
24509       if (VT == MVT::i16)
24510         return std::make_pair(0U, &X86::GR16RegClass);
24511       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
24512         return std::make_pair(0U, &X86::GR32RegClass);
24513       return std::make_pair(0U, &X86::GR64RegClass);
24514     case 'R':   // LEGACY_REGS
24515       if (VT == MVT::i8 || VT == MVT::i1)
24516         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
24517       if (VT == MVT::i16)
24518         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
24519       if (VT == MVT::i32 || !Subtarget->is64Bit())
24520         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
24521       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
24522     case 'f':  // FP Stack registers.
24523       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
24524       // value to the correct fpstack register class.
24525       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
24526         return std::make_pair(0U, &X86::RFP32RegClass);
24527       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
24528         return std::make_pair(0U, &X86::RFP64RegClass);
24529       return std::make_pair(0U, &X86::RFP80RegClass);
24530     case 'y':   // MMX_REGS if MMX allowed.
24531       if (!Subtarget->hasMMX()) break;
24532       return std::make_pair(0U, &X86::VR64RegClass);
24533     case 'Y':   // SSE_REGS if SSE2 allowed
24534       if (!Subtarget->hasSSE2()) break;
24535       // FALL THROUGH.
24536     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
24537       if (!Subtarget->hasSSE1()) break;
24538
24539       switch (VT.SimpleTy) {
24540       default: break;
24541       // Scalar SSE types.
24542       case MVT::f32:
24543       case MVT::i32:
24544         return std::make_pair(0U, &X86::FR32RegClass);
24545       case MVT::f64:
24546       case MVT::i64:
24547         return std::make_pair(0U, &X86::FR64RegClass);
24548       // Vector types.
24549       case MVT::v16i8:
24550       case MVT::v8i16:
24551       case MVT::v4i32:
24552       case MVT::v2i64:
24553       case MVT::v4f32:
24554       case MVT::v2f64:
24555         return std::make_pair(0U, &X86::VR128RegClass);
24556       // AVX types.
24557       case MVT::v32i8:
24558       case MVT::v16i16:
24559       case MVT::v8i32:
24560       case MVT::v4i64:
24561       case MVT::v8f32:
24562       case MVT::v4f64:
24563         return std::make_pair(0U, &X86::VR256RegClass);
24564       case MVT::v8f64:
24565       case MVT::v16f32:
24566       case MVT::v16i32:
24567       case MVT::v8i64:
24568         return std::make_pair(0U, &X86::VR512RegClass);
24569       }
24570       break;
24571     }
24572   }
24573
24574   // Use the default implementation in TargetLowering to convert the register
24575   // constraint into a member of a register class.
24576   std::pair<unsigned, const TargetRegisterClass*> Res;
24577   Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
24578
24579   // Not found as a standard register?
24580   if (!Res.second) {
24581     // Map st(0) -> st(7) -> ST0
24582     if (Constraint.size() == 7 && Constraint[0] == '{' &&
24583         tolower(Constraint[1]) == 's' &&
24584         tolower(Constraint[2]) == 't' &&
24585         Constraint[3] == '(' &&
24586         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
24587         Constraint[5] == ')' &&
24588         Constraint[6] == '}') {
24589
24590       Res.first = X86::FP0+Constraint[4]-'0';
24591       Res.second = &X86::RFP80RegClass;
24592       return Res;
24593     }
24594
24595     // GCC allows "st(0)" to be called just plain "st".
24596     if (StringRef("{st}").equals_lower(Constraint)) {
24597       Res.first = X86::FP0;
24598       Res.second = &X86::RFP80RegClass;
24599       return Res;
24600     }
24601
24602     // flags -> EFLAGS
24603     if (StringRef("{flags}").equals_lower(Constraint)) {
24604       Res.first = X86::EFLAGS;
24605       Res.second = &X86::CCRRegClass;
24606       return Res;
24607     }
24608
24609     // 'A' means EAX + EDX.
24610     if (Constraint == "A") {
24611       Res.first = X86::EAX;
24612       Res.second = &X86::GR32_ADRegClass;
24613       return Res;
24614     }
24615     return Res;
24616   }
24617
24618   // Otherwise, check to see if this is a register class of the wrong value
24619   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
24620   // turn into {ax},{dx}.
24621   if (Res.second->hasType(VT))
24622     return Res;   // Correct type already, nothing to do.
24623
24624   // All of the single-register GCC register classes map their values onto
24625   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
24626   // really want an 8-bit or 32-bit register, map to the appropriate register
24627   // class and return the appropriate register.
24628   if (Res.second == &X86::GR16RegClass) {
24629     if (VT == MVT::i8 || VT == MVT::i1) {
24630       unsigned DestReg = 0;
24631       switch (Res.first) {
24632       default: break;
24633       case X86::AX: DestReg = X86::AL; break;
24634       case X86::DX: DestReg = X86::DL; break;
24635       case X86::CX: DestReg = X86::CL; break;
24636       case X86::BX: DestReg = X86::BL; break;
24637       }
24638       if (DestReg) {
24639         Res.first = DestReg;
24640         Res.second = &X86::GR8RegClass;
24641       }
24642     } else if (VT == MVT::i32 || VT == MVT::f32) {
24643       unsigned DestReg = 0;
24644       switch (Res.first) {
24645       default: break;
24646       case X86::AX: DestReg = X86::EAX; break;
24647       case X86::DX: DestReg = X86::EDX; break;
24648       case X86::CX: DestReg = X86::ECX; break;
24649       case X86::BX: DestReg = X86::EBX; break;
24650       case X86::SI: DestReg = X86::ESI; break;
24651       case X86::DI: DestReg = X86::EDI; break;
24652       case X86::BP: DestReg = X86::EBP; break;
24653       case X86::SP: DestReg = X86::ESP; break;
24654       }
24655       if (DestReg) {
24656         Res.first = DestReg;
24657         Res.second = &X86::GR32RegClass;
24658       }
24659     } else if (VT == MVT::i64 || VT == MVT::f64) {
24660       unsigned DestReg = 0;
24661       switch (Res.first) {
24662       default: break;
24663       case X86::AX: DestReg = X86::RAX; break;
24664       case X86::DX: DestReg = X86::RDX; break;
24665       case X86::CX: DestReg = X86::RCX; break;
24666       case X86::BX: DestReg = X86::RBX; break;
24667       case X86::SI: DestReg = X86::RSI; break;
24668       case X86::DI: DestReg = X86::RDI; break;
24669       case X86::BP: DestReg = X86::RBP; break;
24670       case X86::SP: DestReg = X86::RSP; break;
24671       }
24672       if (DestReg) {
24673         Res.first = DestReg;
24674         Res.second = &X86::GR64RegClass;
24675       }
24676     }
24677   } else if (Res.second == &X86::FR32RegClass ||
24678              Res.second == &X86::FR64RegClass ||
24679              Res.second == &X86::VR128RegClass ||
24680              Res.second == &X86::VR256RegClass ||
24681              Res.second == &X86::FR32XRegClass ||
24682              Res.second == &X86::FR64XRegClass ||
24683              Res.second == &X86::VR128XRegClass ||
24684              Res.second == &X86::VR256XRegClass ||
24685              Res.second == &X86::VR512RegClass) {
24686     // Handle references to XMM physical registers that got mapped into the
24687     // wrong class.  This can happen with constraints like {xmm0} where the
24688     // target independent register mapper will just pick the first match it can
24689     // find, ignoring the required type.
24690
24691     if (VT == MVT::f32 || VT == MVT::i32)
24692       Res.second = &X86::FR32RegClass;
24693     else if (VT == MVT::f64 || VT == MVT::i64)
24694       Res.second = &X86::FR64RegClass;
24695     else if (X86::VR128RegClass.hasType(VT))
24696       Res.second = &X86::VR128RegClass;
24697     else if (X86::VR256RegClass.hasType(VT))
24698       Res.second = &X86::VR256RegClass;
24699     else if (X86::VR512RegClass.hasType(VT))
24700       Res.second = &X86::VR512RegClass;
24701   }
24702
24703   return Res;
24704 }
24705
24706 int X86TargetLowering::getScalingFactorCost(const AddrMode &AM,
24707                                             Type *Ty) const {
24708   // Scaling factors are not free at all.
24709   // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
24710   // will take 2 allocations in the out of order engine instead of 1
24711   // for plain addressing mode, i.e. inst (reg1).
24712   // E.g.,
24713   // vaddps (%rsi,%drx), %ymm0, %ymm1
24714   // Requires two allocations (one for the load, one for the computation)
24715   // whereas:
24716   // vaddps (%rsi), %ymm0, %ymm1
24717   // Requires just 1 allocation, i.e., freeing allocations for other operations
24718   // and having less micro operations to execute.
24719   //
24720   // For some X86 architectures, this is even worse because for instance for
24721   // stores, the complex addressing mode forces the instruction to use the
24722   // "load" ports instead of the dedicated "store" port.
24723   // E.g., on Haswell:
24724   // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
24725   // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.
24726   if (isLegalAddressingMode(AM, Ty))
24727     // Scale represents reg2 * scale, thus account for 1
24728     // as soon as we use a second register.
24729     return AM.Scale != 0;
24730   return -1;
24731 }
24732
24733 bool X86TargetLowering::isTargetFTOL() const {
24734   return Subtarget->isTargetKnownWindowsMSVC() && !Subtarget->is64Bit();
24735 }