[WinEH] Sink UnwindHelp completely out of IR
[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                        MachinePointerInfo(), MachinePointerInfo());
2147 }
2148
2149 /// Return true if the calling convention is one that
2150 /// supports tail call optimization.
2151 static bool IsTailCallConvention(CallingConv::ID CC) {
2152   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2153           CC == CallingConv::HiPE);
2154 }
2155
2156 /// \brief Return true if the calling convention is a C calling convention.
2157 static bool IsCCallConvention(CallingConv::ID CC) {
2158   return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2159           CC == CallingConv::X86_64_SysV);
2160 }
2161
2162 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2163   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2164     return false;
2165
2166   CallSite CS(CI);
2167   CallingConv::ID CalleeCC = CS.getCallingConv();
2168   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2169     return false;
2170
2171   return true;
2172 }
2173
2174 /// Return true if the function is being made into
2175 /// a tailcall target by changing its ABI.
2176 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2177                                    bool GuaranteedTailCallOpt) {
2178   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2179 }
2180
2181 SDValue
2182 X86TargetLowering::LowerMemArgument(SDValue Chain,
2183                                     CallingConv::ID CallConv,
2184                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2185                                     SDLoc dl, SelectionDAG &DAG,
2186                                     const CCValAssign &VA,
2187                                     MachineFrameInfo *MFI,
2188                                     unsigned i) const {
2189   // Create the nodes corresponding to a load from this parameter slot.
2190   ISD::ArgFlagsTy Flags = Ins[i].Flags;
2191   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(
2192       CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2193   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2194   EVT ValVT;
2195
2196   // If value is passed by pointer we have address passed instead of the value
2197   // itself.
2198   if (VA.getLocInfo() == CCValAssign::Indirect)
2199     ValVT = VA.getLocVT();
2200   else
2201     ValVT = VA.getValVT();
2202
2203   // FIXME: For now, all byval parameter objects are marked mutable. This can be
2204   // changed with more analysis.
2205   // In case of tail call optimization mark all arguments mutable. Since they
2206   // could be overwritten by lowering of arguments in case of a tail call.
2207   if (Flags.isByVal()) {
2208     unsigned Bytes = Flags.getByValSize();
2209     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2210     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2211     return DAG.getFrameIndex(FI, getPointerTy());
2212   } else {
2213     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2214                                     VA.getLocMemOffset(), isImmutable);
2215     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2216     return DAG.getLoad(ValVT, dl, Chain, FIN,
2217                        MachinePointerInfo::getFixedStack(FI),
2218                        false, false, false, 0);
2219   }
2220 }
2221
2222 // FIXME: Get this from tablegen.
2223 static ArrayRef<MCPhysReg> get64BitArgumentGPRs(CallingConv::ID CallConv,
2224                                                 const X86Subtarget *Subtarget) {
2225   assert(Subtarget->is64Bit());
2226
2227   if (Subtarget->isCallingConvWin64(CallConv)) {
2228     static const MCPhysReg GPR64ArgRegsWin64[] = {
2229       X86::RCX, X86::RDX, X86::R8,  X86::R9
2230     };
2231     return makeArrayRef(std::begin(GPR64ArgRegsWin64), std::end(GPR64ArgRegsWin64));
2232   }
2233
2234   static const MCPhysReg GPR64ArgRegs64Bit[] = {
2235     X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2236   };
2237   return makeArrayRef(std::begin(GPR64ArgRegs64Bit), std::end(GPR64ArgRegs64Bit));
2238 }
2239
2240 // FIXME: Get this from tablegen.
2241 static ArrayRef<MCPhysReg> get64BitArgumentXMMs(MachineFunction &MF,
2242                                                 CallingConv::ID CallConv,
2243                                                 const X86Subtarget *Subtarget) {
2244   assert(Subtarget->is64Bit());
2245   if (Subtarget->isCallingConvWin64(CallConv)) {
2246     // The XMM registers which might contain var arg parameters are shadowed
2247     // in their paired GPR.  So we only need to save the GPR to their home
2248     // slots.
2249     // TODO: __vectorcall will change this.
2250     return None;
2251   }
2252
2253   const Function *Fn = MF.getFunction();
2254   bool NoImplicitFloatOps = Fn->hasFnAttribute(Attribute::NoImplicitFloat);
2255   assert(!(MF.getTarget().Options.UseSoftFloat && NoImplicitFloatOps) &&
2256          "SSE register cannot be used when SSE is disabled!");
2257   if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2258       !Subtarget->hasSSE1())
2259     // Kernel mode asks for SSE to be disabled, so there are no XMM argument
2260     // registers.
2261     return None;
2262
2263   static const MCPhysReg XMMArgRegs64Bit[] = {
2264     X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2265     X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2266   };
2267   return makeArrayRef(std::begin(XMMArgRegs64Bit), std::end(XMMArgRegs64Bit));
2268 }
2269
2270 SDValue
2271 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2272                                         CallingConv::ID CallConv,
2273                                         bool isVarArg,
2274                                       const SmallVectorImpl<ISD::InputArg> &Ins,
2275                                         SDLoc dl,
2276                                         SelectionDAG &DAG,
2277                                         SmallVectorImpl<SDValue> &InVals)
2278                                           const {
2279   MachineFunction &MF = DAG.getMachineFunction();
2280   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2281   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
2282
2283   const Function* Fn = MF.getFunction();
2284   if (Fn->hasExternalLinkage() &&
2285       Subtarget->isTargetCygMing() &&
2286       Fn->getName() == "main")
2287     FuncInfo->setForceFramePointer(true);
2288
2289   MachineFrameInfo *MFI = MF.getFrameInfo();
2290   bool Is64Bit = Subtarget->is64Bit();
2291   bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2292
2293   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2294          "Var args not supported with calling convention fastcc, ghc or hipe");
2295
2296   // Assign locations to all of the incoming arguments.
2297   SmallVector<CCValAssign, 16> ArgLocs;
2298   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2299
2300   // Allocate shadow area for Win64
2301   if (IsWin64)
2302     CCInfo.AllocateStack(32, 8);
2303
2304   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2305
2306   unsigned LastVal = ~0U;
2307   SDValue ArgValue;
2308   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2309     CCValAssign &VA = ArgLocs[i];
2310     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2311     // places.
2312     assert(VA.getValNo() != LastVal &&
2313            "Don't support value assigned to multiple locs yet");
2314     (void)LastVal;
2315     LastVal = VA.getValNo();
2316
2317     if (VA.isRegLoc()) {
2318       EVT RegVT = VA.getLocVT();
2319       const TargetRegisterClass *RC;
2320       if (RegVT == MVT::i32)
2321         RC = &X86::GR32RegClass;
2322       else if (Is64Bit && RegVT == MVT::i64)
2323         RC = &X86::GR64RegClass;
2324       else if (RegVT == MVT::f32)
2325         RC = &X86::FR32RegClass;
2326       else if (RegVT == MVT::f64)
2327         RC = &X86::FR64RegClass;
2328       else if (RegVT.is512BitVector())
2329         RC = &X86::VR512RegClass;
2330       else if (RegVT.is256BitVector())
2331         RC = &X86::VR256RegClass;
2332       else if (RegVT.is128BitVector())
2333         RC = &X86::VR128RegClass;
2334       else if (RegVT == MVT::x86mmx)
2335         RC = &X86::VR64RegClass;
2336       else if (RegVT == MVT::i1)
2337         RC = &X86::VK1RegClass;
2338       else if (RegVT == MVT::v8i1)
2339         RC = &X86::VK8RegClass;
2340       else if (RegVT == MVT::v16i1)
2341         RC = &X86::VK16RegClass;
2342       else if (RegVT == MVT::v32i1)
2343         RC = &X86::VK32RegClass;
2344       else if (RegVT == MVT::v64i1)
2345         RC = &X86::VK64RegClass;
2346       else
2347         llvm_unreachable("Unknown argument type!");
2348
2349       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2350       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2351
2352       // If this is an 8 or 16-bit value, it is really passed promoted to 32
2353       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
2354       // right size.
2355       if (VA.getLocInfo() == CCValAssign::SExt)
2356         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2357                                DAG.getValueType(VA.getValVT()));
2358       else if (VA.getLocInfo() == CCValAssign::ZExt)
2359         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2360                                DAG.getValueType(VA.getValVT()));
2361       else if (VA.getLocInfo() == CCValAssign::BCvt)
2362         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2363
2364       if (VA.isExtInLoc()) {
2365         // Handle MMX values passed in XMM regs.
2366         if (RegVT.isVector())
2367           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2368         else
2369           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2370       }
2371     } else {
2372       assert(VA.isMemLoc());
2373       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2374     }
2375
2376     // If value is passed via pointer - do a load.
2377     if (VA.getLocInfo() == CCValAssign::Indirect)
2378       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2379                              MachinePointerInfo(), false, false, false, 0);
2380
2381     InVals.push_back(ArgValue);
2382   }
2383
2384   if (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC()) {
2385     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2386       // The x86-64 ABIs require that for returning structs by value we copy
2387       // the sret argument into %rax/%eax (depending on ABI) for the return.
2388       // Win32 requires us to put the sret argument to %eax as well.
2389       // Save the argument into a virtual register so that we can access it
2390       // from the return points.
2391       if (Ins[i].Flags.isSRet()) {
2392         unsigned Reg = FuncInfo->getSRetReturnReg();
2393         if (!Reg) {
2394           MVT PtrTy = getPointerTy();
2395           Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2396           FuncInfo->setSRetReturnReg(Reg);
2397         }
2398         SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2399         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2400         break;
2401       }
2402     }
2403   }
2404
2405   unsigned StackSize = CCInfo.getNextStackOffset();
2406   // Align stack specially for tail calls.
2407   if (FuncIsMadeTailCallSafe(CallConv,
2408                              MF.getTarget().Options.GuaranteedTailCallOpt))
2409     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2410
2411   // If the function takes variable number of arguments, make a frame index for
2412   // the start of the first vararg value... for expansion of llvm.va_start. We
2413   // can skip this if there are no va_start calls.
2414   if (MFI->hasVAStart() &&
2415       (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2416                    CallConv != CallingConv::X86_ThisCall))) {
2417     FuncInfo->setVarArgsFrameIndex(
2418         MFI->CreateFixedObject(1, StackSize, true));
2419   }
2420
2421   MachineModuleInfo &MMI = MF.getMMI();
2422   const Function *WinEHParent = nullptr;
2423   if (IsWin64 && MMI.hasWinEHFuncInfo(Fn))
2424     WinEHParent = MMI.getWinEHParent(Fn);
2425   bool IsWinEHOutlined = WinEHParent && WinEHParent != Fn;
2426   bool IsWinEHParent = WinEHParent && WinEHParent == Fn;
2427
2428   // Figure out if XMM registers are in use.
2429   assert(!(MF.getTarget().Options.UseSoftFloat &&
2430            Fn->hasFnAttribute(Attribute::NoImplicitFloat)) &&
2431          "SSE register cannot be used when SSE is disabled!");
2432
2433   // 64-bit calling conventions support varargs and register parameters, so we
2434   // have to do extra work to spill them in the prologue.
2435   if (Is64Bit && isVarArg && MFI->hasVAStart()) {
2436     // Find the first unallocated argument registers.
2437     ArrayRef<MCPhysReg> ArgGPRs = get64BitArgumentGPRs(CallConv, Subtarget);
2438     ArrayRef<MCPhysReg> ArgXMMs = get64BitArgumentXMMs(MF, CallConv, Subtarget);
2439     unsigned NumIntRegs = CCInfo.getFirstUnallocated(ArgGPRs);
2440     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(ArgXMMs);
2441     assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2442            "SSE register cannot be used when SSE is disabled!");
2443
2444     // Gather all the live in physical registers.
2445     SmallVector<SDValue, 6> LiveGPRs;
2446     SmallVector<SDValue, 8> LiveXMMRegs;
2447     SDValue ALVal;
2448     for (MCPhysReg Reg : ArgGPRs.slice(NumIntRegs)) {
2449       unsigned GPR = MF.addLiveIn(Reg, &X86::GR64RegClass);
2450       LiveGPRs.push_back(
2451           DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64));
2452     }
2453     if (!ArgXMMs.empty()) {
2454       unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2455       ALVal = DAG.getCopyFromReg(Chain, dl, AL, MVT::i8);
2456       for (MCPhysReg Reg : ArgXMMs.slice(NumXMMRegs)) {
2457         unsigned XMMReg = MF.addLiveIn(Reg, &X86::VR128RegClass);
2458         LiveXMMRegs.push_back(
2459             DAG.getCopyFromReg(Chain, dl, XMMReg, MVT::v4f32));
2460       }
2461     }
2462
2463     if (IsWin64) {
2464       // Get to the caller-allocated home save location.  Add 8 to account
2465       // for the return address.
2466       int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2467       FuncInfo->setRegSaveFrameIndex(
2468           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2469       // Fixup to set vararg frame on shadow area (4 x i64).
2470       if (NumIntRegs < 4)
2471         FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2472     } else {
2473       // For X86-64, if there are vararg parameters that are passed via
2474       // registers, then we must store them to their spots on the stack so
2475       // they may be loaded by deferencing the result of va_next.
2476       FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2477       FuncInfo->setVarArgsFPOffset(ArgGPRs.size() * 8 + NumXMMRegs * 16);
2478       FuncInfo->setRegSaveFrameIndex(MFI->CreateStackObject(
2479           ArgGPRs.size() * 8 + ArgXMMs.size() * 16, 16, false));
2480     }
2481
2482     // Store the integer parameter registers.
2483     SmallVector<SDValue, 8> MemOps;
2484     SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2485                                       getPointerTy());
2486     unsigned Offset = FuncInfo->getVarArgsGPOffset();
2487     for (SDValue Val : LiveGPRs) {
2488       SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2489                                 DAG.getIntPtrConstant(Offset));
2490       SDValue Store =
2491         DAG.getStore(Val.getValue(1), dl, Val, FIN,
2492                      MachinePointerInfo::getFixedStack(
2493                        FuncInfo->getRegSaveFrameIndex(), Offset),
2494                      false, false, 0);
2495       MemOps.push_back(Store);
2496       Offset += 8;
2497     }
2498
2499     if (!ArgXMMs.empty() && NumXMMRegs != ArgXMMs.size()) {
2500       // Now store the XMM (fp + vector) parameter registers.
2501       SmallVector<SDValue, 12> SaveXMMOps;
2502       SaveXMMOps.push_back(Chain);
2503       SaveXMMOps.push_back(ALVal);
2504       SaveXMMOps.push_back(DAG.getIntPtrConstant(
2505                              FuncInfo->getRegSaveFrameIndex()));
2506       SaveXMMOps.push_back(DAG.getIntPtrConstant(
2507                              FuncInfo->getVarArgsFPOffset()));
2508       SaveXMMOps.insert(SaveXMMOps.end(), LiveXMMRegs.begin(),
2509                         LiveXMMRegs.end());
2510       MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2511                                    MVT::Other, SaveXMMOps));
2512     }
2513
2514     if (!MemOps.empty())
2515       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2516   } else if (IsWinEHOutlined) {
2517     // Get to the caller-allocated home save location.  Add 8 to account
2518     // for the return address.
2519     int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2520     FuncInfo->setRegSaveFrameIndex(MFI->CreateFixedObject(
2521         /*Size=*/1, /*SPOffset=*/HomeOffset + 8, /*Immutable=*/false));
2522
2523     MMI.getWinEHFuncInfo(Fn)
2524         .CatchHandlerParentFrameObjIdx[const_cast<Function *>(Fn)] =
2525         FuncInfo->getRegSaveFrameIndex();
2526
2527     // Store the second integer parameter (rdx) into rsp+16 relative to the
2528     // stack pointer at the entry of the function.
2529     SDValue RSFIN =
2530         DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(), getPointerTy());
2531     unsigned GPR = MF.addLiveIn(X86::RDX, &X86::GR64RegClass);
2532     SDValue Val = DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64);
2533     Chain = DAG.getStore(
2534         Val.getValue(1), dl, Val, RSFIN,
2535         MachinePointerInfo::getFixedStack(FuncInfo->getRegSaveFrameIndex()),
2536         /*isVolatile=*/true, /*isNonTemporal=*/false, /*Alignment=*/0);
2537   }
2538
2539   if (isVarArg && MFI->hasMustTailInVarArgFunc()) {
2540     // Find the largest legal vector type.
2541     MVT VecVT = MVT::Other;
2542     // FIXME: Only some x86_32 calling conventions support AVX512.
2543     if (Subtarget->hasAVX512() &&
2544         (Is64Bit || (CallConv == CallingConv::X86_VectorCall ||
2545                      CallConv == CallingConv::Intel_OCL_BI)))
2546       VecVT = MVT::v16f32;
2547     else if (Subtarget->hasAVX())
2548       VecVT = MVT::v8f32;
2549     else if (Subtarget->hasSSE2())
2550       VecVT = MVT::v4f32;
2551
2552     // We forward some GPRs and some vector types.
2553     SmallVector<MVT, 2> RegParmTypes;
2554     MVT IntVT = Is64Bit ? MVT::i64 : MVT::i32;
2555     RegParmTypes.push_back(IntVT);
2556     if (VecVT != MVT::Other)
2557       RegParmTypes.push_back(VecVT);
2558
2559     // Compute the set of forwarded registers. The rest are scratch.
2560     SmallVectorImpl<ForwardedRegister> &Forwards =
2561         FuncInfo->getForwardedMustTailRegParms();
2562     CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes, CC_X86);
2563
2564     // Conservatively forward AL on x86_64, since it might be used for varargs.
2565     if (Is64Bit && !CCInfo.isAllocated(X86::AL)) {
2566       unsigned ALVReg = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2567       Forwards.push_back(ForwardedRegister(ALVReg, X86::AL, MVT::i8));
2568     }
2569
2570     // Copy all forwards from physical to virtual registers.
2571     for (ForwardedRegister &F : Forwards) {
2572       // FIXME: Can we use a less constrained schedule?
2573       SDValue RegVal = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
2574       F.VReg = MF.getRegInfo().createVirtualRegister(getRegClassFor(F.VT));
2575       Chain = DAG.getCopyToReg(Chain, dl, F.VReg, RegVal);
2576     }
2577   }
2578
2579   // Some CCs need callee pop.
2580   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2581                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2582     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2583   } else {
2584     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2585     // If this is an sret function, the return should pop the hidden pointer.
2586     if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2587         !Subtarget->getTargetTriple().isOSMSVCRT() &&
2588         argsAreStructReturn(Ins) == StackStructReturn)
2589       FuncInfo->setBytesToPopOnReturn(4);
2590   }
2591
2592   if (!Is64Bit) {
2593     // RegSaveFrameIndex is X86-64 only.
2594     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2595     if (CallConv == CallingConv::X86_FastCall ||
2596         CallConv == CallingConv::X86_ThisCall)
2597       // fastcc functions can't have varargs.
2598       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2599   }
2600
2601   FuncInfo->setArgumentStackSize(StackSize);
2602
2603   if (IsWinEHParent) {
2604     int UnwindHelpFI = MFI->CreateStackObject(8, 8, /*isSS=*/false);
2605     SDValue StackSlot = DAG.getFrameIndex(UnwindHelpFI, MVT::i64);
2606     MMI.getWinEHFuncInfo(MF.getFunction()).UnwindHelpFrameIdx = UnwindHelpFI;
2607     SDValue Neg2 = DAG.getConstant(-2, MVT::i64);
2608     Chain = DAG.getStore(Chain, dl, Neg2, StackSlot,
2609                          MachinePointerInfo::getFixedStack(UnwindHelpFI),
2610                          /*isVolatile=*/true,
2611                          /*isNonTemporal=*/false, /*Alignment=*/0);
2612   }
2613
2614   return Chain;
2615 }
2616
2617 SDValue
2618 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2619                                     SDValue StackPtr, SDValue Arg,
2620                                     SDLoc dl, SelectionDAG &DAG,
2621                                     const CCValAssign &VA,
2622                                     ISD::ArgFlagsTy Flags) const {
2623   unsigned LocMemOffset = VA.getLocMemOffset();
2624   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2625   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2626   if (Flags.isByVal())
2627     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2628
2629   return DAG.getStore(Chain, dl, Arg, PtrOff,
2630                       MachinePointerInfo::getStack(LocMemOffset),
2631                       false, false, 0);
2632 }
2633
2634 /// Emit a load of return address if tail call
2635 /// optimization is performed and it is required.
2636 SDValue
2637 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2638                                            SDValue &OutRetAddr, SDValue Chain,
2639                                            bool IsTailCall, bool Is64Bit,
2640                                            int FPDiff, SDLoc dl) const {
2641   // Adjust the Return address stack slot.
2642   EVT VT = getPointerTy();
2643   OutRetAddr = getReturnAddressFrameIndex(DAG);
2644
2645   // Load the "old" Return address.
2646   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2647                            false, false, false, 0);
2648   return SDValue(OutRetAddr.getNode(), 1);
2649 }
2650
2651 /// Emit a store of the return address if tail call
2652 /// optimization is performed and it is required (FPDiff!=0).
2653 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2654                                         SDValue Chain, SDValue RetAddrFrIdx,
2655                                         EVT PtrVT, unsigned SlotSize,
2656                                         int FPDiff, SDLoc dl) {
2657   // Store the return address to the appropriate stack slot.
2658   if (!FPDiff) return Chain;
2659   // Calculate the new stack slot for the return address.
2660   int NewReturnAddrFI =
2661     MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2662                                          false);
2663   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2664   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2665                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2666                        false, false, 0);
2667   return Chain;
2668 }
2669
2670 SDValue
2671 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2672                              SmallVectorImpl<SDValue> &InVals) const {
2673   SelectionDAG &DAG                     = CLI.DAG;
2674   SDLoc &dl                             = CLI.DL;
2675   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2676   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
2677   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
2678   SDValue Chain                         = CLI.Chain;
2679   SDValue Callee                        = CLI.Callee;
2680   CallingConv::ID CallConv              = CLI.CallConv;
2681   bool &isTailCall                      = CLI.IsTailCall;
2682   bool isVarArg                         = CLI.IsVarArg;
2683
2684   MachineFunction &MF = DAG.getMachineFunction();
2685   bool Is64Bit        = Subtarget->is64Bit();
2686   bool IsWin64        = Subtarget->isCallingConvWin64(CallConv);
2687   StructReturnType SR = callIsStructReturn(Outs);
2688   bool IsSibcall      = false;
2689   X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2690
2691   if (MF.getTarget().Options.DisableTailCalls)
2692     isTailCall = false;
2693
2694   bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
2695   if (IsMustTail) {
2696     // Force this to be a tail call.  The verifier rules are enough to ensure
2697     // that we can lower this successfully without moving the return address
2698     // around.
2699     isTailCall = true;
2700   } else if (isTailCall) {
2701     // Check if it's really possible to do a tail call.
2702     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2703                     isVarArg, SR != NotStructReturn,
2704                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2705                     Outs, OutVals, Ins, DAG);
2706
2707     // Sibcalls are automatically detected tailcalls which do not require
2708     // ABI changes.
2709     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2710       IsSibcall = true;
2711
2712     if (isTailCall)
2713       ++NumTailCalls;
2714   }
2715
2716   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2717          "Var args not supported with calling convention fastcc, ghc or hipe");
2718
2719   // Analyze operands of the call, assigning locations to each operand.
2720   SmallVector<CCValAssign, 16> ArgLocs;
2721   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2722
2723   // Allocate shadow area for Win64
2724   if (IsWin64)
2725     CCInfo.AllocateStack(32, 8);
2726
2727   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2728
2729   // Get a count of how many bytes are to be pushed on the stack.
2730   unsigned NumBytes = CCInfo.getNextStackOffset();
2731   if (IsSibcall)
2732     // This is a sibcall. The memory operands are available in caller's
2733     // own caller's stack.
2734     NumBytes = 0;
2735   else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
2736            IsTailCallConvention(CallConv))
2737     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2738
2739   int FPDiff = 0;
2740   if (isTailCall && !IsSibcall && !IsMustTail) {
2741     // Lower arguments at fp - stackoffset + fpdiff.
2742     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2743
2744     FPDiff = NumBytesCallerPushed - NumBytes;
2745
2746     // Set the delta of movement of the returnaddr stackslot.
2747     // But only set if delta is greater than previous delta.
2748     if (FPDiff < X86Info->getTCReturnAddrDelta())
2749       X86Info->setTCReturnAddrDelta(FPDiff);
2750   }
2751
2752   unsigned NumBytesToPush = NumBytes;
2753   unsigned NumBytesToPop = NumBytes;
2754
2755   // If we have an inalloca argument, all stack space has already been allocated
2756   // for us and be right at the top of the stack.  We don't support multiple
2757   // arguments passed in memory when using inalloca.
2758   if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
2759     NumBytesToPush = 0;
2760     if (!ArgLocs.back().isMemLoc())
2761       report_fatal_error("cannot use inalloca attribute on a register "
2762                          "parameter");
2763     if (ArgLocs.back().getLocMemOffset() != 0)
2764       report_fatal_error("any parameter with the inalloca attribute must be "
2765                          "the only memory argument");
2766   }
2767
2768   if (!IsSibcall)
2769     Chain = DAG.getCALLSEQ_START(
2770         Chain, DAG.getIntPtrConstant(NumBytesToPush, true), dl);
2771
2772   SDValue RetAddrFrIdx;
2773   // Load return address for tail calls.
2774   if (isTailCall && FPDiff)
2775     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2776                                     Is64Bit, FPDiff, dl);
2777
2778   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2779   SmallVector<SDValue, 8> MemOpChains;
2780   SDValue StackPtr;
2781
2782   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2783   // of tail call optimization arguments are handle later.
2784   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
2785   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2786     // Skip inalloca arguments, they have already been written.
2787     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2788     if (Flags.isInAlloca())
2789       continue;
2790
2791     CCValAssign &VA = ArgLocs[i];
2792     EVT RegVT = VA.getLocVT();
2793     SDValue Arg = OutVals[i];
2794     bool isByVal = Flags.isByVal();
2795
2796     // Promote the value if needed.
2797     switch (VA.getLocInfo()) {
2798     default: llvm_unreachable("Unknown loc info!");
2799     case CCValAssign::Full: break;
2800     case CCValAssign::SExt:
2801       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2802       break;
2803     case CCValAssign::ZExt:
2804       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2805       break;
2806     case CCValAssign::AExt:
2807       if (RegVT.is128BitVector()) {
2808         // Special case: passing MMX values in XMM registers.
2809         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2810         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2811         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2812       } else
2813         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2814       break;
2815     case CCValAssign::BCvt:
2816       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2817       break;
2818     case CCValAssign::Indirect: {
2819       // Store the argument.
2820       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2821       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2822       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2823                            MachinePointerInfo::getFixedStack(FI),
2824                            false, false, 0);
2825       Arg = SpillSlot;
2826       break;
2827     }
2828     }
2829
2830     if (VA.isRegLoc()) {
2831       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2832       if (isVarArg && IsWin64) {
2833         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2834         // shadow reg if callee is a varargs function.
2835         unsigned ShadowReg = 0;
2836         switch (VA.getLocReg()) {
2837         case X86::XMM0: ShadowReg = X86::RCX; break;
2838         case X86::XMM1: ShadowReg = X86::RDX; break;
2839         case X86::XMM2: ShadowReg = X86::R8; break;
2840         case X86::XMM3: ShadowReg = X86::R9; break;
2841         }
2842         if (ShadowReg)
2843           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2844       }
2845     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2846       assert(VA.isMemLoc());
2847       if (!StackPtr.getNode())
2848         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2849                                       getPointerTy());
2850       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2851                                              dl, DAG, VA, Flags));
2852     }
2853   }
2854
2855   if (!MemOpChains.empty())
2856     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
2857
2858   if (Subtarget->isPICStyleGOT()) {
2859     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2860     // GOT pointer.
2861     if (!isTailCall) {
2862       RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2863                DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
2864     } else {
2865       // If we are tail calling and generating PIC/GOT style code load the
2866       // address of the callee into ECX. The value in ecx is used as target of
2867       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2868       // for tail calls on PIC/GOT architectures. Normally we would just put the
2869       // address of GOT into ebx and then call target@PLT. But for tail calls
2870       // ebx would be restored (since ebx is callee saved) before jumping to the
2871       // target@PLT.
2872
2873       // Note: The actual moving to ECX is done further down.
2874       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2875       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2876           !G->getGlobal()->hasProtectedVisibility())
2877         Callee = LowerGlobalAddress(Callee, DAG);
2878       else if (isa<ExternalSymbolSDNode>(Callee))
2879         Callee = LowerExternalSymbol(Callee, DAG);
2880     }
2881   }
2882
2883   if (Is64Bit && isVarArg && !IsWin64 && !IsMustTail) {
2884     // From AMD64 ABI document:
2885     // For calls that may call functions that use varargs or stdargs
2886     // (prototype-less calls or calls to functions containing ellipsis (...) in
2887     // the declaration) %al is used as hidden argument to specify the number
2888     // of SSE registers used. The contents of %al do not need to match exactly
2889     // the number of registers, but must be an ubound on the number of SSE
2890     // registers used and is in the range 0 - 8 inclusive.
2891
2892     // Count the number of XMM registers allocated.
2893     static const MCPhysReg XMMArgRegs[] = {
2894       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2895       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2896     };
2897     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs);
2898     assert((Subtarget->hasSSE1() || !NumXMMRegs)
2899            && "SSE registers cannot be used when SSE is disabled");
2900
2901     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2902                                         DAG.getConstant(NumXMMRegs, MVT::i8)));
2903   }
2904
2905   if (isVarArg && IsMustTail) {
2906     const auto &Forwards = X86Info->getForwardedMustTailRegParms();
2907     for (const auto &F : Forwards) {
2908       SDValue Val = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
2909       RegsToPass.push_back(std::make_pair(unsigned(F.PReg), Val));
2910     }
2911   }
2912
2913   // For tail calls lower the arguments to the 'real' stack slots.  Sibcalls
2914   // don't need this because the eligibility check rejects calls that require
2915   // shuffling arguments passed in memory.
2916   if (!IsSibcall && isTailCall) {
2917     // Force all the incoming stack arguments to be loaded from the stack
2918     // before any new outgoing arguments are stored to the stack, because the
2919     // outgoing stack slots may alias the incoming argument stack slots, and
2920     // the alias isn't otherwise explicit. This is slightly more conservative
2921     // than necessary, because it means that each store effectively depends
2922     // on every argument instead of just those arguments it would clobber.
2923     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2924
2925     SmallVector<SDValue, 8> MemOpChains2;
2926     SDValue FIN;
2927     int FI = 0;
2928     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2929       CCValAssign &VA = ArgLocs[i];
2930       if (VA.isRegLoc())
2931         continue;
2932       assert(VA.isMemLoc());
2933       SDValue Arg = OutVals[i];
2934       ISD::ArgFlagsTy Flags = Outs[i].Flags;
2935       // Skip inalloca arguments.  They don't require any work.
2936       if (Flags.isInAlloca())
2937         continue;
2938       // Create frame index.
2939       int32_t Offset = VA.getLocMemOffset()+FPDiff;
2940       uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2941       FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2942       FIN = DAG.getFrameIndex(FI, getPointerTy());
2943
2944       if (Flags.isByVal()) {
2945         // Copy relative to framepointer.
2946         SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2947         if (!StackPtr.getNode())
2948           StackPtr = DAG.getCopyFromReg(Chain, dl,
2949                                         RegInfo->getStackRegister(),
2950                                         getPointerTy());
2951         Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2952
2953         MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2954                                                          ArgChain,
2955                                                          Flags, DAG, dl));
2956       } else {
2957         // Store relative to framepointer.
2958         MemOpChains2.push_back(
2959           DAG.getStore(ArgChain, dl, Arg, FIN,
2960                        MachinePointerInfo::getFixedStack(FI),
2961                        false, false, 0));
2962       }
2963     }
2964
2965     if (!MemOpChains2.empty())
2966       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
2967
2968     // Store the return address to the appropriate stack slot.
2969     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
2970                                      getPointerTy(), RegInfo->getSlotSize(),
2971                                      FPDiff, dl);
2972   }
2973
2974   // Build a sequence of copy-to-reg nodes chained together with token chain
2975   // and flag operands which copy the outgoing args into registers.
2976   SDValue InFlag;
2977   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2978     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2979                              RegsToPass[i].second, InFlag);
2980     InFlag = Chain.getValue(1);
2981   }
2982
2983   if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
2984     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2985     // In the 64-bit large code model, we have to make all calls
2986     // through a register, since the call instruction's 32-bit
2987     // pc-relative offset may not be large enough to hold the whole
2988     // address.
2989   } else if (Callee->getOpcode() == ISD::GlobalAddress) {
2990     // If the callee is a GlobalAddress node (quite common, every direct call
2991     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2992     // it.
2993     GlobalAddressSDNode* G = cast<GlobalAddressSDNode>(Callee);
2994
2995     // We should use extra load for direct calls to dllimported functions in
2996     // non-JIT mode.
2997     const GlobalValue *GV = G->getGlobal();
2998     if (!GV->hasDLLImportStorageClass()) {
2999       unsigned char OpFlags = 0;
3000       bool ExtraLoad = false;
3001       unsigned WrapperKind = ISD::DELETED_NODE;
3002
3003       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
3004       // external symbols most go through the PLT in PIC mode.  If the symbol
3005       // has hidden or protected visibility, or if it is static or local, then
3006       // we don't need to use the PLT - we can directly call it.
3007       if (Subtarget->isTargetELF() &&
3008           DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
3009           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
3010         OpFlags = X86II::MO_PLT;
3011       } else if (Subtarget->isPICStyleStubAny() &&
3012                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
3013                  (!Subtarget->getTargetTriple().isMacOSX() ||
3014                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3015         // PC-relative references to external symbols should go through $stub,
3016         // unless we're building with the leopard linker or later, which
3017         // automatically synthesizes these stubs.
3018         OpFlags = X86II::MO_DARWIN_STUB;
3019       } else if (Subtarget->isPICStyleRIPRel() && isa<Function>(GV) &&
3020                  cast<Function>(GV)->hasFnAttribute(Attribute::NonLazyBind)) {
3021         // If the function is marked as non-lazy, generate an indirect call
3022         // which loads from the GOT directly. This avoids runtime overhead
3023         // at the cost of eager binding (and one extra byte of encoding).
3024         OpFlags = X86II::MO_GOTPCREL;
3025         WrapperKind = X86ISD::WrapperRIP;
3026         ExtraLoad = true;
3027       }
3028
3029       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
3030                                           G->getOffset(), OpFlags);
3031
3032       // Add a wrapper if needed.
3033       if (WrapperKind != ISD::DELETED_NODE)
3034         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
3035       // Add extra indirection if needed.
3036       if (ExtraLoad)
3037         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
3038                              MachinePointerInfo::getGOT(),
3039                              false, false, false, 0);
3040     }
3041   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3042     unsigned char OpFlags = 0;
3043
3044     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
3045     // external symbols should go through the PLT.
3046     if (Subtarget->isTargetELF() &&
3047         DAG.getTarget().getRelocationModel() == Reloc::PIC_) {
3048       OpFlags = X86II::MO_PLT;
3049     } else if (Subtarget->isPICStyleStubAny() &&
3050                (!Subtarget->getTargetTriple().isMacOSX() ||
3051                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3052       // PC-relative references to external symbols should go through $stub,
3053       // unless we're building with the leopard linker or later, which
3054       // automatically synthesizes these stubs.
3055       OpFlags = X86II::MO_DARWIN_STUB;
3056     }
3057
3058     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
3059                                          OpFlags);
3060   } else if (Subtarget->isTarget64BitILP32() &&
3061              Callee->getValueType(0) == MVT::i32) {
3062     // Zero-extend the 32-bit Callee address into a 64-bit according to x32 ABI
3063     Callee = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, Callee);
3064   }
3065
3066   // Returns a chain & a flag for retval copy to use.
3067   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3068   SmallVector<SDValue, 8> Ops;
3069
3070   if (!IsSibcall && isTailCall) {
3071     Chain = DAG.getCALLSEQ_END(Chain,
3072                                DAG.getIntPtrConstant(NumBytesToPop, true),
3073                                DAG.getIntPtrConstant(0, true), InFlag, dl);
3074     InFlag = Chain.getValue(1);
3075   }
3076
3077   Ops.push_back(Chain);
3078   Ops.push_back(Callee);
3079
3080   if (isTailCall)
3081     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
3082
3083   // Add argument registers to the end of the list so that they are known live
3084   // into the call.
3085   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3086     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3087                                   RegsToPass[i].second.getValueType()));
3088
3089   // Add a register mask operand representing the call-preserved registers.
3090   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
3091   const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
3092   assert(Mask && "Missing call preserved mask for calling convention");
3093   Ops.push_back(DAG.getRegisterMask(Mask));
3094
3095   if (InFlag.getNode())
3096     Ops.push_back(InFlag);
3097
3098   if (isTailCall) {
3099     // We used to do:
3100     //// If this is the first return lowered for this function, add the regs
3101     //// to the liveout set for the function.
3102     // This isn't right, although it's probably harmless on x86; liveouts
3103     // should be computed from returns not tail calls.  Consider a void
3104     // function making a tail call to a function returning int.
3105     return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
3106   }
3107
3108   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
3109   InFlag = Chain.getValue(1);
3110
3111   // Create the CALLSEQ_END node.
3112   unsigned NumBytesForCalleeToPop;
3113   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
3114                        DAG.getTarget().Options.GuaranteedTailCallOpt))
3115     NumBytesForCalleeToPop = NumBytes;    // Callee pops everything
3116   else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
3117            !Subtarget->getTargetTriple().isOSMSVCRT() &&
3118            SR == StackStructReturn)
3119     // If this is a call to a struct-return function, the callee
3120     // pops the hidden struct pointer, so we have to push it back.
3121     // This is common for Darwin/X86, Linux & Mingw32 targets.
3122     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
3123     NumBytesForCalleeToPop = 4;
3124   else
3125     NumBytesForCalleeToPop = 0;  // Callee pops nothing.
3126
3127   // Returns a flag for retval copy to use.
3128   if (!IsSibcall) {
3129     Chain = DAG.getCALLSEQ_END(Chain,
3130                                DAG.getIntPtrConstant(NumBytesToPop, true),
3131                                DAG.getIntPtrConstant(NumBytesForCalleeToPop,
3132                                                      true),
3133                                InFlag, dl);
3134     InFlag = Chain.getValue(1);
3135   }
3136
3137   // Handle result values, copying them out of physregs into vregs that we
3138   // return.
3139   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3140                          Ins, dl, DAG, InVals);
3141 }
3142
3143 //===----------------------------------------------------------------------===//
3144 //                Fast Calling Convention (tail call) implementation
3145 //===----------------------------------------------------------------------===//
3146
3147 //  Like std call, callee cleans arguments, convention except that ECX is
3148 //  reserved for storing the tail called function address. Only 2 registers are
3149 //  free for argument passing (inreg). Tail call optimization is performed
3150 //  provided:
3151 //                * tailcallopt is enabled
3152 //                * caller/callee are fastcc
3153 //  On X86_64 architecture with GOT-style position independent code only local
3154 //  (within module) calls are supported at the moment.
3155 //  To keep the stack aligned according to platform abi the function
3156 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
3157 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3158 //  If a tail called function callee has more arguments than the caller the
3159 //  caller needs to make sure that there is room to move the RETADDR to. This is
3160 //  achieved by reserving an area the size of the argument delta right after the
3161 //  original RETADDR, but before the saved framepointer or the spilled registers
3162 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3163 //  stack layout:
3164 //    arg1
3165 //    arg2
3166 //    RETADDR
3167 //    [ new RETADDR
3168 //      move area ]
3169 //    (possible EBP)
3170 //    ESI
3171 //    EDI
3172 //    local1 ..
3173
3174 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
3175 /// for a 16 byte align requirement.
3176 unsigned
3177 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3178                                                SelectionDAG& DAG) const {
3179   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3180   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
3181   unsigned StackAlignment = TFI.getStackAlignment();
3182   uint64_t AlignMask = StackAlignment - 1;
3183   int64_t Offset = StackSize;
3184   unsigned SlotSize = RegInfo->getSlotSize();
3185   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3186     // Number smaller than 12 so just add the difference.
3187     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3188   } else {
3189     // Mask out lower bits, add stackalignment once plus the 12 bytes.
3190     Offset = ((~AlignMask) & Offset) + StackAlignment +
3191       (StackAlignment-SlotSize);
3192   }
3193   return Offset;
3194 }
3195
3196 /// MatchingStackOffset - Return true if the given stack call argument is
3197 /// already available in the same position (relatively) of the caller's
3198 /// incoming argument stack.
3199 static
3200 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3201                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3202                          const X86InstrInfo *TII) {
3203   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3204   int FI = INT_MAX;
3205   if (Arg.getOpcode() == ISD::CopyFromReg) {
3206     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3207     if (!TargetRegisterInfo::isVirtualRegister(VR))
3208       return false;
3209     MachineInstr *Def = MRI->getVRegDef(VR);
3210     if (!Def)
3211       return false;
3212     if (!Flags.isByVal()) {
3213       if (!TII->isLoadFromStackSlot(Def, FI))
3214         return false;
3215     } else {
3216       unsigned Opcode = Def->getOpcode();
3217       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r ||
3218            Opcode == X86::LEA64_32r) &&
3219           Def->getOperand(1).isFI()) {
3220         FI = Def->getOperand(1).getIndex();
3221         Bytes = Flags.getByValSize();
3222       } else
3223         return false;
3224     }
3225   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3226     if (Flags.isByVal())
3227       // ByVal argument is passed in as a pointer but it's now being
3228       // dereferenced. e.g.
3229       // define @foo(%struct.X* %A) {
3230       //   tail call @bar(%struct.X* byval %A)
3231       // }
3232       return false;
3233     SDValue Ptr = Ld->getBasePtr();
3234     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3235     if (!FINode)
3236       return false;
3237     FI = FINode->getIndex();
3238   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3239     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3240     FI = FINode->getIndex();
3241     Bytes = Flags.getByValSize();
3242   } else
3243     return false;
3244
3245   assert(FI != INT_MAX);
3246   if (!MFI->isFixedObjectIndex(FI))
3247     return false;
3248   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3249 }
3250
3251 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3252 /// for tail call optimization. Targets which want to do tail call
3253 /// optimization should implement this function.
3254 bool
3255 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3256                                                      CallingConv::ID CalleeCC,
3257                                                      bool isVarArg,
3258                                                      bool isCalleeStructRet,
3259                                                      bool isCallerStructRet,
3260                                                      Type *RetTy,
3261                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
3262                                     const SmallVectorImpl<SDValue> &OutVals,
3263                                     const SmallVectorImpl<ISD::InputArg> &Ins,
3264                                                      SelectionDAG &DAG) const {
3265   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3266     return false;
3267
3268   // If -tailcallopt is specified, make fastcc functions tail-callable.
3269   const MachineFunction &MF = DAG.getMachineFunction();
3270   const Function *CallerF = MF.getFunction();
3271
3272   // If the function return type is x86_fp80 and the callee return type is not,
3273   // then the FP_EXTEND of the call result is not a nop. It's not safe to
3274   // perform a tailcall optimization here.
3275   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3276     return false;
3277
3278   CallingConv::ID CallerCC = CallerF->getCallingConv();
3279   bool CCMatch = CallerCC == CalleeCC;
3280   bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3281   bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3282
3283   // Win64 functions have extra shadow space for argument homing. Don't do the
3284   // sibcall if the caller and callee have mismatched expectations for this
3285   // space.
3286   if (IsCalleeWin64 != IsCallerWin64)
3287     return false;
3288
3289   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3290     if (IsTailCallConvention(CalleeCC) && CCMatch)
3291       return true;
3292     return false;
3293   }
3294
3295   // Look for obvious safe cases to perform tail call optimization that do not
3296   // require ABI changes. This is what gcc calls sibcall.
3297
3298   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3299   // emit a special epilogue.
3300   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3301   if (RegInfo->needsStackRealignment(MF))
3302     return false;
3303
3304   // Also avoid sibcall optimization if either caller or callee uses struct
3305   // return semantics.
3306   if (isCalleeStructRet || isCallerStructRet)
3307     return false;
3308
3309   // An stdcall/thiscall caller is expected to clean up its arguments; the
3310   // callee isn't going to do that.
3311   // FIXME: this is more restrictive than needed. We could produce a tailcall
3312   // when the stack adjustment matches. For example, with a thiscall that takes
3313   // only one argument.
3314   if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3315                    CallerCC == CallingConv::X86_ThisCall))
3316     return false;
3317
3318   // Do not sibcall optimize vararg calls unless all arguments are passed via
3319   // registers.
3320   if (isVarArg && !Outs.empty()) {
3321
3322     // Optimizing for varargs on Win64 is unlikely to be safe without
3323     // additional testing.
3324     if (IsCalleeWin64 || IsCallerWin64)
3325       return false;
3326
3327     SmallVector<CCValAssign, 16> ArgLocs;
3328     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3329                    *DAG.getContext());
3330
3331     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3332     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3333       if (!ArgLocs[i].isRegLoc())
3334         return false;
3335   }
3336
3337   // If the call result is in ST0 / ST1, it needs to be popped off the x87
3338   // stack.  Therefore, if it's not used by the call it is not safe to optimize
3339   // this into a sibcall.
3340   bool Unused = false;
3341   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3342     if (!Ins[i].Used) {
3343       Unused = true;
3344       break;
3345     }
3346   }
3347   if (Unused) {
3348     SmallVector<CCValAssign, 16> RVLocs;
3349     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(), RVLocs,
3350                    *DAG.getContext());
3351     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3352     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3353       CCValAssign &VA = RVLocs[i];
3354       if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
3355         return false;
3356     }
3357   }
3358
3359   // If the calling conventions do not match, then we'd better make sure the
3360   // results are returned in the same way as what the caller expects.
3361   if (!CCMatch) {
3362     SmallVector<CCValAssign, 16> RVLocs1;
3363     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
3364                     *DAG.getContext());
3365     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3366
3367     SmallVector<CCValAssign, 16> RVLocs2;
3368     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
3369                     *DAG.getContext());
3370     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3371
3372     if (RVLocs1.size() != RVLocs2.size())
3373       return false;
3374     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3375       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3376         return false;
3377       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3378         return false;
3379       if (RVLocs1[i].isRegLoc()) {
3380         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3381           return false;
3382       } else {
3383         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3384           return false;
3385       }
3386     }
3387   }
3388
3389   // If the callee takes no arguments then go on to check the results of the
3390   // call.
3391   if (!Outs.empty()) {
3392     // Check if stack adjustment is needed. For now, do not do this if any
3393     // argument is passed on the stack.
3394     SmallVector<CCValAssign, 16> ArgLocs;
3395     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3396                    *DAG.getContext());
3397
3398     // Allocate shadow area for Win64
3399     if (IsCalleeWin64)
3400       CCInfo.AllocateStack(32, 8);
3401
3402     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3403     if (CCInfo.getNextStackOffset()) {
3404       MachineFunction &MF = DAG.getMachineFunction();
3405       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3406         return false;
3407
3408       // Check if the arguments are already laid out in the right way as
3409       // the caller's fixed stack objects.
3410       MachineFrameInfo *MFI = MF.getFrameInfo();
3411       const MachineRegisterInfo *MRI = &MF.getRegInfo();
3412       const X86InstrInfo *TII = Subtarget->getInstrInfo();
3413       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3414         CCValAssign &VA = ArgLocs[i];
3415         SDValue Arg = OutVals[i];
3416         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3417         if (VA.getLocInfo() == CCValAssign::Indirect)
3418           return false;
3419         if (!VA.isRegLoc()) {
3420           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3421                                    MFI, MRI, TII))
3422             return false;
3423         }
3424       }
3425     }
3426
3427     // If the tailcall address may be in a register, then make sure it's
3428     // possible to register allocate for it. In 32-bit, the call address can
3429     // only target EAX, EDX, or ECX since the tail call must be scheduled after
3430     // callee-saved registers are restored. These happen to be the same
3431     // registers used to pass 'inreg' arguments so watch out for those.
3432     if (!Subtarget->is64Bit() &&
3433         ((!isa<GlobalAddressSDNode>(Callee) &&
3434           !isa<ExternalSymbolSDNode>(Callee)) ||
3435          DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3436       unsigned NumInRegs = 0;
3437       // In PIC we need an extra register to formulate the address computation
3438       // for the callee.
3439       unsigned MaxInRegs =
3440         (DAG.getTarget().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3441
3442       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3443         CCValAssign &VA = ArgLocs[i];
3444         if (!VA.isRegLoc())
3445           continue;
3446         unsigned Reg = VA.getLocReg();
3447         switch (Reg) {
3448         default: break;
3449         case X86::EAX: case X86::EDX: case X86::ECX:
3450           if (++NumInRegs == MaxInRegs)
3451             return false;
3452           break;
3453         }
3454       }
3455     }
3456   }
3457
3458   return true;
3459 }
3460
3461 FastISel *
3462 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3463                                   const TargetLibraryInfo *libInfo) const {
3464   return X86::createFastISel(funcInfo, libInfo);
3465 }
3466
3467 //===----------------------------------------------------------------------===//
3468 //                           Other Lowering Hooks
3469 //===----------------------------------------------------------------------===//
3470
3471 static bool MayFoldLoad(SDValue Op) {
3472   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3473 }
3474
3475 static bool MayFoldIntoStore(SDValue Op) {
3476   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3477 }
3478
3479 static bool isTargetShuffle(unsigned Opcode) {
3480   switch(Opcode) {
3481   default: return false;
3482   case X86ISD::BLENDI:
3483   case X86ISD::PSHUFB:
3484   case X86ISD::PSHUFD:
3485   case X86ISD::PSHUFHW:
3486   case X86ISD::PSHUFLW:
3487   case X86ISD::SHUFP:
3488   case X86ISD::PALIGNR:
3489   case X86ISD::MOVLHPS:
3490   case X86ISD::MOVLHPD:
3491   case X86ISD::MOVHLPS:
3492   case X86ISD::MOVLPS:
3493   case X86ISD::MOVLPD:
3494   case X86ISD::MOVSHDUP:
3495   case X86ISD::MOVSLDUP:
3496   case X86ISD::MOVDDUP:
3497   case X86ISD::MOVSS:
3498   case X86ISD::MOVSD:
3499   case X86ISD::UNPCKL:
3500   case X86ISD::UNPCKH:
3501   case X86ISD::VPERMILPI:
3502   case X86ISD::VPERM2X128:
3503   case X86ISD::VPERMI:
3504     return true;
3505   }
3506 }
3507
3508 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3509                                     SDValue V1, unsigned TargetMask,
3510                                     SelectionDAG &DAG) {
3511   switch(Opc) {
3512   default: llvm_unreachable("Unknown x86 shuffle node");
3513   case X86ISD::PSHUFD:
3514   case X86ISD::PSHUFHW:
3515   case X86ISD::PSHUFLW:
3516   case X86ISD::VPERMILPI:
3517   case X86ISD::VPERMI:
3518     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3519   }
3520 }
3521
3522 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3523                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
3524   switch(Opc) {
3525   default: llvm_unreachable("Unknown x86 shuffle node");
3526   case X86ISD::MOVLHPS:
3527   case X86ISD::MOVLHPD:
3528   case X86ISD::MOVHLPS:
3529   case X86ISD::MOVLPS:
3530   case X86ISD::MOVLPD:
3531   case X86ISD::MOVSS:
3532   case X86ISD::MOVSD:
3533   case X86ISD::UNPCKL:
3534   case X86ISD::UNPCKH:
3535     return DAG.getNode(Opc, dl, VT, V1, V2);
3536   }
3537 }
3538
3539 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3540   MachineFunction &MF = DAG.getMachineFunction();
3541   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3542   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3543   int ReturnAddrIndex = FuncInfo->getRAIndex();
3544
3545   if (ReturnAddrIndex == 0) {
3546     // Set up a frame object for the return address.
3547     unsigned SlotSize = RegInfo->getSlotSize();
3548     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3549                                                            -(int64_t)SlotSize,
3550                                                            false);
3551     FuncInfo->setRAIndex(ReturnAddrIndex);
3552   }
3553
3554   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3555 }
3556
3557 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3558                                        bool hasSymbolicDisplacement) {
3559   // Offset should fit into 32 bit immediate field.
3560   if (!isInt<32>(Offset))
3561     return false;
3562
3563   // If we don't have a symbolic displacement - we don't have any extra
3564   // restrictions.
3565   if (!hasSymbolicDisplacement)
3566     return true;
3567
3568   // FIXME: Some tweaks might be needed for medium code model.
3569   if (M != CodeModel::Small && M != CodeModel::Kernel)
3570     return false;
3571
3572   // For small code model we assume that latest object is 16MB before end of 31
3573   // bits boundary. We may also accept pretty large negative constants knowing
3574   // that all objects are in the positive half of address space.
3575   if (M == CodeModel::Small && Offset < 16*1024*1024)
3576     return true;
3577
3578   // For kernel code model we know that all object resist in the negative half
3579   // of 32bits address space. We may not accept negative offsets, since they may
3580   // be just off and we may accept pretty large positive ones.
3581   if (M == CodeModel::Kernel && Offset >= 0)
3582     return true;
3583
3584   return false;
3585 }
3586
3587 /// isCalleePop - Determines whether the callee is required to pop its
3588 /// own arguments. Callee pop is necessary to support tail calls.
3589 bool X86::isCalleePop(CallingConv::ID CallingConv,
3590                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3591   switch (CallingConv) {
3592   default:
3593     return false;
3594   case CallingConv::X86_StdCall:
3595   case CallingConv::X86_FastCall:
3596   case CallingConv::X86_ThisCall:
3597     return !is64Bit;
3598   case CallingConv::Fast:
3599   case CallingConv::GHC:
3600   case CallingConv::HiPE:
3601     if (IsVarArg)
3602       return false;
3603     return TailCallOpt;
3604   }
3605 }
3606
3607 /// \brief Return true if the condition is an unsigned comparison operation.
3608 static bool isX86CCUnsigned(unsigned X86CC) {
3609   switch (X86CC) {
3610   default: llvm_unreachable("Invalid integer condition!");
3611   case X86::COND_E:     return true;
3612   case X86::COND_G:     return false;
3613   case X86::COND_GE:    return false;
3614   case X86::COND_L:     return false;
3615   case X86::COND_LE:    return false;
3616   case X86::COND_NE:    return true;
3617   case X86::COND_B:     return true;
3618   case X86::COND_A:     return true;
3619   case X86::COND_BE:    return true;
3620   case X86::COND_AE:    return true;
3621   }
3622   llvm_unreachable("covered switch fell through?!");
3623 }
3624
3625 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3626 /// specific condition code, returning the condition code and the LHS/RHS of the
3627 /// comparison to make.
3628 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3629                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3630   if (!isFP) {
3631     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3632       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3633         // X > -1   -> X == 0, jump !sign.
3634         RHS = DAG.getConstant(0, RHS.getValueType());
3635         return X86::COND_NS;
3636       }
3637       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3638         // X < 0   -> X == 0, jump on sign.
3639         return X86::COND_S;
3640       }
3641       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3642         // X < 1   -> X <= 0
3643         RHS = DAG.getConstant(0, RHS.getValueType());
3644         return X86::COND_LE;
3645       }
3646     }
3647
3648     switch (SetCCOpcode) {
3649     default: llvm_unreachable("Invalid integer condition!");
3650     case ISD::SETEQ:  return X86::COND_E;
3651     case ISD::SETGT:  return X86::COND_G;
3652     case ISD::SETGE:  return X86::COND_GE;
3653     case ISD::SETLT:  return X86::COND_L;
3654     case ISD::SETLE:  return X86::COND_LE;
3655     case ISD::SETNE:  return X86::COND_NE;
3656     case ISD::SETULT: return X86::COND_B;
3657     case ISD::SETUGT: return X86::COND_A;
3658     case ISD::SETULE: return X86::COND_BE;
3659     case ISD::SETUGE: return X86::COND_AE;
3660     }
3661   }
3662
3663   // First determine if it is required or is profitable to flip the operands.
3664
3665   // If LHS is a foldable load, but RHS is not, flip the condition.
3666   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3667       !ISD::isNON_EXTLoad(RHS.getNode())) {
3668     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3669     std::swap(LHS, RHS);
3670   }
3671
3672   switch (SetCCOpcode) {
3673   default: break;
3674   case ISD::SETOLT:
3675   case ISD::SETOLE:
3676   case ISD::SETUGT:
3677   case ISD::SETUGE:
3678     std::swap(LHS, RHS);
3679     break;
3680   }
3681
3682   // On a floating point condition, the flags are set as follows:
3683   // ZF  PF  CF   op
3684   //  0 | 0 | 0 | X > Y
3685   //  0 | 0 | 1 | X < Y
3686   //  1 | 0 | 0 | X == Y
3687   //  1 | 1 | 1 | unordered
3688   switch (SetCCOpcode) {
3689   default: llvm_unreachable("Condcode should be pre-legalized away");
3690   case ISD::SETUEQ:
3691   case ISD::SETEQ:   return X86::COND_E;
3692   case ISD::SETOLT:              // flipped
3693   case ISD::SETOGT:
3694   case ISD::SETGT:   return X86::COND_A;
3695   case ISD::SETOLE:              // flipped
3696   case ISD::SETOGE:
3697   case ISD::SETGE:   return X86::COND_AE;
3698   case ISD::SETUGT:              // flipped
3699   case ISD::SETULT:
3700   case ISD::SETLT:   return X86::COND_B;
3701   case ISD::SETUGE:              // flipped
3702   case ISD::SETULE:
3703   case ISD::SETLE:   return X86::COND_BE;
3704   case ISD::SETONE:
3705   case ISD::SETNE:   return X86::COND_NE;
3706   case ISD::SETUO:   return X86::COND_P;
3707   case ISD::SETO:    return X86::COND_NP;
3708   case ISD::SETOEQ:
3709   case ISD::SETUNE:  return X86::COND_INVALID;
3710   }
3711 }
3712
3713 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3714 /// code. Current x86 isa includes the following FP cmov instructions:
3715 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3716 static bool hasFPCMov(unsigned X86CC) {
3717   switch (X86CC) {
3718   default:
3719     return false;
3720   case X86::COND_B:
3721   case X86::COND_BE:
3722   case X86::COND_E:
3723   case X86::COND_P:
3724   case X86::COND_A:
3725   case X86::COND_AE:
3726   case X86::COND_NE:
3727   case X86::COND_NP:
3728     return true;
3729   }
3730 }
3731
3732 /// isFPImmLegal - Returns true if the target can instruction select the
3733 /// specified FP immediate natively. If false, the legalizer will
3734 /// materialize the FP immediate as a load from a constant pool.
3735 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3736   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3737     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3738       return true;
3739   }
3740   return false;
3741 }
3742
3743 bool X86TargetLowering::shouldReduceLoadWidth(SDNode *Load,
3744                                               ISD::LoadExtType ExtTy,
3745                                               EVT NewVT) const {
3746   // "ELF Handling for Thread-Local Storage" specifies that R_X86_64_GOTTPOFF
3747   // relocation target a movq or addq instruction: don't let the load shrink.
3748   SDValue BasePtr = cast<LoadSDNode>(Load)->getBasePtr();
3749   if (BasePtr.getOpcode() == X86ISD::WrapperRIP)
3750     if (const auto *GA = dyn_cast<GlobalAddressSDNode>(BasePtr.getOperand(0)))
3751       return GA->getTargetFlags() != X86II::MO_GOTTPOFF;
3752   return true;
3753 }
3754
3755 /// \brief Returns true if it is beneficial to convert a load of a constant
3756 /// to just the constant itself.
3757 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
3758                                                           Type *Ty) const {
3759   assert(Ty->isIntegerTy());
3760
3761   unsigned BitSize = Ty->getPrimitiveSizeInBits();
3762   if (BitSize == 0 || BitSize > 64)
3763     return false;
3764   return true;
3765 }
3766
3767 bool X86TargetLowering::isExtractSubvectorCheap(EVT ResVT,
3768                                                 unsigned Index) const {
3769   if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
3770     return false;
3771
3772   return (Index == 0 || Index == ResVT.getVectorNumElements());
3773 }
3774
3775 bool X86TargetLowering::isCheapToSpeculateCttz() const {
3776   // Speculate cttz only if we can directly use TZCNT.
3777   return Subtarget->hasBMI();
3778 }
3779
3780 bool X86TargetLowering::isCheapToSpeculateCtlz() const {
3781   // Speculate ctlz only if we can directly use LZCNT.
3782   return Subtarget->hasLZCNT();
3783 }
3784
3785 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3786 /// the specified range (L, H].
3787 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3788   return (Val < 0) || (Val >= Low && Val < Hi);
3789 }
3790
3791 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3792 /// specified value.
3793 static bool isUndefOrEqual(int Val, int CmpVal) {
3794   return (Val < 0 || Val == CmpVal);
3795 }
3796
3797 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3798 /// from position Pos and ending in Pos+Size, falls within the specified
3799 /// sequential range (Low, Low+Size]. or is undef.
3800 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3801                                        unsigned Pos, unsigned Size, int Low) {
3802   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3803     if (!isUndefOrEqual(Mask[i], Low))
3804       return false;
3805   return true;
3806 }
3807
3808 /// isVEXTRACTIndex - Return true if the specified
3809 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
3810 /// suitable for instruction that extract 128 or 256 bit vectors
3811 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
3812   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
3813   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3814     return false;
3815
3816   // The index should be aligned on a vecWidth-bit boundary.
3817   uint64_t Index =
3818     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3819
3820   MVT VT = N->getSimpleValueType(0);
3821   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
3822   bool Result = (Index * ElSize) % vecWidth == 0;
3823
3824   return Result;
3825 }
3826
3827 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
3828 /// operand specifies a subvector insert that is suitable for input to
3829 /// insertion of 128 or 256-bit subvectors
3830 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
3831   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
3832   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3833     return false;
3834   // The index should be aligned on a vecWidth-bit boundary.
3835   uint64_t Index =
3836     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3837
3838   MVT VT = N->getSimpleValueType(0);
3839   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
3840   bool Result = (Index * ElSize) % vecWidth == 0;
3841
3842   return Result;
3843 }
3844
3845 bool X86::isVINSERT128Index(SDNode *N) {
3846   return isVINSERTIndex(N, 128);
3847 }
3848
3849 bool X86::isVINSERT256Index(SDNode *N) {
3850   return isVINSERTIndex(N, 256);
3851 }
3852
3853 bool X86::isVEXTRACT128Index(SDNode *N) {
3854   return isVEXTRACTIndex(N, 128);
3855 }
3856
3857 bool X86::isVEXTRACT256Index(SDNode *N) {
3858   return isVEXTRACTIndex(N, 256);
3859 }
3860
3861 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
3862   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
3863   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3864     llvm_unreachable("Illegal extract subvector for VEXTRACT");
3865
3866   uint64_t Index =
3867     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3868
3869   MVT VecVT = N->getOperand(0).getSimpleValueType();
3870   MVT ElVT = VecVT.getVectorElementType();
3871
3872   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
3873   return Index / NumElemsPerChunk;
3874 }
3875
3876 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
3877   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
3878   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3879     llvm_unreachable("Illegal insert subvector for VINSERT");
3880
3881   uint64_t Index =
3882     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3883
3884   MVT VecVT = N->getSimpleValueType(0);
3885   MVT ElVT = VecVT.getVectorElementType();
3886
3887   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
3888   return Index / NumElemsPerChunk;
3889 }
3890
3891 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
3892 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
3893 /// and VINSERTI128 instructions.
3894 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
3895   return getExtractVEXTRACTImmediate(N, 128);
3896 }
3897
3898 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
3899 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
3900 /// and VINSERTI64x4 instructions.
3901 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
3902   return getExtractVEXTRACTImmediate(N, 256);
3903 }
3904
3905 /// getInsertVINSERT128Immediate - Return the appropriate immediate
3906 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
3907 /// and VINSERTI128 instructions.
3908 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
3909   return getInsertVINSERTImmediate(N, 128);
3910 }
3911
3912 /// getInsertVINSERT256Immediate - Return the appropriate immediate
3913 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
3914 /// and VINSERTI64x4 instructions.
3915 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
3916   return getInsertVINSERTImmediate(N, 256);
3917 }
3918
3919 /// isZero - Returns true if Elt is a constant integer zero
3920 static bool isZero(SDValue V) {
3921   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
3922   return C && C->isNullValue();
3923 }
3924
3925 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
3926 /// constant +0.0.
3927 bool X86::isZeroNode(SDValue Elt) {
3928   if (isZero(Elt))
3929     return true;
3930   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
3931     return CFP->getValueAPF().isPosZero();
3932   return false;
3933 }
3934
3935 /// getZeroVector - Returns a vector of specified type with all zero elements.
3936 ///
3937 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
3938                              SelectionDAG &DAG, SDLoc dl) {
3939   assert(VT.isVector() && "Expected a vector type");
3940
3941   // Always build SSE zero vectors as <4 x i32> bitcasted
3942   // to their dest type. This ensures they get CSE'd.
3943   SDValue Vec;
3944   if (VT.is128BitVector()) {  // SSE
3945     if (Subtarget->hasSSE2()) {  // SSE2
3946       SDValue Cst = DAG.getConstant(0, MVT::i32);
3947       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3948     } else { // SSE1
3949       SDValue Cst = DAG.getConstantFP(+0.0, MVT::f32);
3950       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
3951     }
3952   } else if (VT.is256BitVector()) { // AVX
3953     if (Subtarget->hasInt256()) { // AVX2
3954       SDValue Cst = DAG.getConstant(0, MVT::i32);
3955       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
3956       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
3957     } else {
3958       // 256-bit logic and arithmetic instructions in AVX are all
3959       // floating-point, no support for integer ops. Emit fp zeroed vectors.
3960       SDValue Cst = DAG.getConstantFP(+0.0, MVT::f32);
3961       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
3962       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
3963     }
3964   } else if (VT.is512BitVector()) { // AVX-512
3965       SDValue Cst = DAG.getConstant(0, MVT::i32);
3966       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
3967                         Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
3968       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
3969   } else if (VT.getScalarType() == MVT::i1) {
3970
3971     assert((Subtarget->hasBWI() || VT.getVectorNumElements() <= 16)
3972             && "Unexpected vector type");
3973     assert((Subtarget->hasVLX() || VT.getVectorNumElements() >= 8)
3974             && "Unexpected vector type");
3975     SDValue Cst = DAG.getConstant(0, MVT::i1);
3976     SmallVector<SDValue, 64> Ops(VT.getVectorNumElements(), Cst);
3977     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
3978   } else
3979     llvm_unreachable("Unexpected vector type");
3980
3981   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
3982 }
3983
3984 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
3985                                 SelectionDAG &DAG, SDLoc dl,
3986                                 unsigned vectorWidth) {
3987   assert((vectorWidth == 128 || vectorWidth == 256) &&
3988          "Unsupported vector width");
3989   EVT VT = Vec.getValueType();
3990   EVT ElVT = VT.getVectorElementType();
3991   unsigned Factor = VT.getSizeInBits()/vectorWidth;
3992   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
3993                                   VT.getVectorNumElements()/Factor);
3994
3995   // Extract from UNDEF is UNDEF.
3996   if (Vec.getOpcode() == ISD::UNDEF)
3997     return DAG.getUNDEF(ResultVT);
3998
3999   // Extract the relevant vectorWidth bits.  Generate an EXTRACT_SUBVECTOR
4000   unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
4001
4002   // This is the index of the first element of the vectorWidth-bit chunk
4003   // we want.
4004   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / vectorWidth)
4005                                * ElemsPerChunk);
4006
4007   // If the input is a buildvector just emit a smaller one.
4008   if (Vec.getOpcode() == ISD::BUILD_VECTOR)
4009     return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
4010                        makeArrayRef(Vec->op_begin() + NormalizedIdxVal,
4011                                     ElemsPerChunk));
4012
4013   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
4014   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec, VecIdx);
4015 }
4016
4017 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
4018 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
4019 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
4020 /// instructions or a simple subregister reference. Idx is an index in the
4021 /// 128 bits we want.  It need not be aligned to a 128-bit boundary.  That makes
4022 /// lowering EXTRACT_VECTOR_ELT operations easier.
4023 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
4024                                    SelectionDAG &DAG, SDLoc dl) {
4025   assert((Vec.getValueType().is256BitVector() ||
4026           Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
4027   return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
4028 }
4029
4030 /// Generate a DAG to grab 256-bits from a 512-bit vector.
4031 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
4032                                    SelectionDAG &DAG, SDLoc dl) {
4033   assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
4034   return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
4035 }
4036
4037 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
4038                                unsigned IdxVal, SelectionDAG &DAG,
4039                                SDLoc dl, unsigned vectorWidth) {
4040   assert((vectorWidth == 128 || vectorWidth == 256) &&
4041          "Unsupported vector width");
4042   // Inserting UNDEF is Result
4043   if (Vec.getOpcode() == ISD::UNDEF)
4044     return Result;
4045   EVT VT = Vec.getValueType();
4046   EVT ElVT = VT.getVectorElementType();
4047   EVT ResultVT = Result.getValueType();
4048
4049   // Insert the relevant vectorWidth bits.
4050   unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
4051
4052   // This is the index of the first element of the vectorWidth-bit chunk
4053   // we want.
4054   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/vectorWidth)
4055                                * ElemsPerChunk);
4056
4057   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
4058   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec, VecIdx);
4059 }
4060
4061 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
4062 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
4063 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
4064 /// simple superregister reference.  Idx is an index in the 128 bits
4065 /// we want.  It need not be aligned to a 128-bit boundary.  That makes
4066 /// lowering INSERT_VECTOR_ELT operations easier.
4067 static SDValue Insert128BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4068                                   SelectionDAG &DAG, SDLoc dl) {
4069   assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
4070
4071   // For insertion into the zero index (low half) of a 256-bit vector, it is
4072   // more efficient to generate a blend with immediate instead of an insert*128.
4073   // We are still creating an INSERT_SUBVECTOR below with an undef node to
4074   // extend the subvector to the size of the result vector. Make sure that
4075   // we are not recursing on that node by checking for undef here.
4076   if (IdxVal == 0 && Result.getValueType().is256BitVector() &&
4077       Result.getOpcode() != ISD::UNDEF) {
4078     EVT ResultVT = Result.getValueType();
4079     SDValue ZeroIndex = DAG.getIntPtrConstant(0);
4080     SDValue Undef = DAG.getUNDEF(ResultVT);
4081     SDValue Vec256 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Undef,
4082                                  Vec, ZeroIndex);
4083
4084     // The blend instruction, and therefore its mask, depend on the data type.
4085     MVT ScalarType = ResultVT.getScalarType().getSimpleVT();
4086     if (ScalarType.isFloatingPoint()) {
4087       // Choose either vblendps (float) or vblendpd (double).
4088       unsigned ScalarSize = ScalarType.getSizeInBits();
4089       assert((ScalarSize == 64 || ScalarSize == 32) && "Unknown float type");
4090       unsigned MaskVal = (ScalarSize == 64) ? 0x03 : 0x0f;
4091       SDValue Mask = DAG.getConstant(MaskVal, MVT::i8);
4092       return DAG.getNode(X86ISD::BLENDI, dl, ResultVT, Result, Vec256, Mask);
4093     }
4094
4095     const X86Subtarget &Subtarget =
4096     static_cast<const X86Subtarget &>(DAG.getSubtarget());
4097
4098     // AVX2 is needed for 256-bit integer blend support.
4099     // Integers must be cast to 32-bit because there is only vpblendd;
4100     // vpblendw can't be used for this because it has a handicapped mask.
4101
4102     // If we don't have AVX2, then cast to float. Using a wrong domain blend
4103     // is still more efficient than using the wrong domain vinsertf128 that
4104     // will be created by InsertSubVector().
4105     MVT CastVT = Subtarget.hasAVX2() ? MVT::v8i32 : MVT::v8f32;
4106
4107     SDValue Mask = DAG.getConstant(0x0f, MVT::i8);
4108     Vec256 = DAG.getNode(ISD::BITCAST, dl, CastVT, Vec256);
4109     Vec256 = DAG.getNode(X86ISD::BLENDI, dl, CastVT, Result, Vec256, Mask);
4110     return DAG.getNode(ISD::BITCAST, dl, ResultVT, Vec256);
4111   }
4112
4113   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
4114 }
4115
4116 static SDValue Insert256BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4117                                   SelectionDAG &DAG, SDLoc dl) {
4118   assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
4119   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
4120 }
4121
4122 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
4123 /// instructions. This is used because creating CONCAT_VECTOR nodes of
4124 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
4125 /// large BUILD_VECTORS.
4126 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
4127                                    unsigned NumElems, SelectionDAG &DAG,
4128                                    SDLoc dl) {
4129   SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4130   return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
4131 }
4132
4133 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
4134                                    unsigned NumElems, SelectionDAG &DAG,
4135                                    SDLoc dl) {
4136   SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4137   return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
4138 }
4139
4140 /// getOnesVector - Returns a vector of specified type with all bits set.
4141 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4142 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4143 /// Then bitcast to their original type, ensuring they get CSE'd.
4144 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4145                              SDLoc dl) {
4146   assert(VT.isVector() && "Expected a vector type");
4147
4148   SDValue Cst = DAG.getConstant(~0U, MVT::i32);
4149   SDValue Vec;
4150   if (VT.is256BitVector()) {
4151     if (HasInt256) { // AVX2
4152       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4153       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4154     } else { // AVX
4155       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4156       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4157     }
4158   } else if (VT.is128BitVector()) {
4159     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4160   } else
4161     llvm_unreachable("Unexpected vector type");
4162
4163   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4164 }
4165
4166 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4167 /// operation of specified width.
4168 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4169                        SDValue V2) {
4170   unsigned NumElems = VT.getVectorNumElements();
4171   SmallVector<int, 8> Mask;
4172   Mask.push_back(NumElems);
4173   for (unsigned i = 1; i != NumElems; ++i)
4174     Mask.push_back(i);
4175   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4176 }
4177
4178 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4179 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4180                           SDValue V2) {
4181   unsigned NumElems = VT.getVectorNumElements();
4182   SmallVector<int, 8> Mask;
4183   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4184     Mask.push_back(i);
4185     Mask.push_back(i + NumElems);
4186   }
4187   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4188 }
4189
4190 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4191 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4192                           SDValue V2) {
4193   unsigned NumElems = VT.getVectorNumElements();
4194   SmallVector<int, 8> Mask;
4195   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4196     Mask.push_back(i + Half);
4197     Mask.push_back(i + NumElems + Half);
4198   }
4199   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4200 }
4201
4202 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4203 /// vector of zero or undef vector.  This produces a shuffle where the low
4204 /// element of V2 is swizzled into the zero/undef vector, landing at element
4205 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
4206 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4207                                            bool IsZero,
4208                                            const X86Subtarget *Subtarget,
4209                                            SelectionDAG &DAG) {
4210   MVT VT = V2.getSimpleValueType();
4211   SDValue V1 = IsZero
4212     ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
4213   unsigned NumElems = VT.getVectorNumElements();
4214   SmallVector<int, 16> MaskVec;
4215   for (unsigned i = 0; i != NumElems; ++i)
4216     // If this is the insertion idx, put the low elt of V2 here.
4217     MaskVec.push_back(i == Idx ? NumElems : i);
4218   return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
4219 }
4220
4221 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
4222 /// target specific opcode. Returns true if the Mask could be calculated. Sets
4223 /// IsUnary to true if only uses one source. Note that this will set IsUnary for
4224 /// shuffles which use a single input multiple times, and in those cases it will
4225 /// adjust the mask to only have indices within that single input.
4226 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4227                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
4228   unsigned NumElems = VT.getVectorNumElements();
4229   SDValue ImmN;
4230
4231   IsUnary = false;
4232   bool IsFakeUnary = false;
4233   switch(N->getOpcode()) {
4234   case X86ISD::BLENDI:
4235     ImmN = N->getOperand(N->getNumOperands()-1);
4236     DecodeBLENDMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4237     break;
4238   case X86ISD::SHUFP:
4239     ImmN = N->getOperand(N->getNumOperands()-1);
4240     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4241     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4242     break;
4243   case X86ISD::UNPCKH:
4244     DecodeUNPCKHMask(VT, Mask);
4245     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4246     break;
4247   case X86ISD::UNPCKL:
4248     DecodeUNPCKLMask(VT, Mask);
4249     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4250     break;
4251   case X86ISD::MOVHLPS:
4252     DecodeMOVHLPSMask(NumElems, Mask);
4253     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4254     break;
4255   case X86ISD::MOVLHPS:
4256     DecodeMOVLHPSMask(NumElems, Mask);
4257     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4258     break;
4259   case X86ISD::PALIGNR:
4260     ImmN = N->getOperand(N->getNumOperands()-1);
4261     DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4262     break;
4263   case X86ISD::PSHUFD:
4264   case X86ISD::VPERMILPI:
4265     ImmN = N->getOperand(N->getNumOperands()-1);
4266     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4267     IsUnary = true;
4268     break;
4269   case X86ISD::PSHUFHW:
4270     ImmN = N->getOperand(N->getNumOperands()-1);
4271     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4272     IsUnary = true;
4273     break;
4274   case X86ISD::PSHUFLW:
4275     ImmN = N->getOperand(N->getNumOperands()-1);
4276     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4277     IsUnary = true;
4278     break;
4279   case X86ISD::PSHUFB: {
4280     IsUnary = true;
4281     SDValue MaskNode = N->getOperand(1);
4282     while (MaskNode->getOpcode() == ISD::BITCAST)
4283       MaskNode = MaskNode->getOperand(0);
4284
4285     if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
4286       // If we have a build-vector, then things are easy.
4287       EVT VT = MaskNode.getValueType();
4288       assert(VT.isVector() &&
4289              "Can't produce a non-vector with a build_vector!");
4290       if (!VT.isInteger())
4291         return false;
4292
4293       int NumBytesPerElement = VT.getVectorElementType().getSizeInBits() / 8;
4294
4295       SmallVector<uint64_t, 32> RawMask;
4296       for (int i = 0, e = MaskNode->getNumOperands(); i < e; ++i) {
4297         SDValue Op = MaskNode->getOperand(i);
4298         if (Op->getOpcode() == ISD::UNDEF) {
4299           RawMask.push_back((uint64_t)SM_SentinelUndef);
4300           continue;
4301         }
4302         auto *CN = dyn_cast<ConstantSDNode>(Op.getNode());
4303         if (!CN)
4304           return false;
4305         APInt MaskElement = CN->getAPIntValue();
4306
4307         // We now have to decode the element which could be any integer size and
4308         // extract each byte of it.
4309         for (int j = 0; j < NumBytesPerElement; ++j) {
4310           // Note that this is x86 and so always little endian: the low byte is
4311           // the first byte of the mask.
4312           RawMask.push_back(MaskElement.getLoBits(8).getZExtValue());
4313           MaskElement = MaskElement.lshr(8);
4314         }
4315       }
4316       DecodePSHUFBMask(RawMask, Mask);
4317       break;
4318     }
4319
4320     auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
4321     if (!MaskLoad)
4322       return false;
4323
4324     SDValue Ptr = MaskLoad->getBasePtr();
4325     if (Ptr->getOpcode() == X86ISD::Wrapper)
4326       Ptr = Ptr->getOperand(0);
4327
4328     auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
4329     if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
4330       return false;
4331
4332     if (auto *C = dyn_cast<Constant>(MaskCP->getConstVal())) {
4333       DecodePSHUFBMask(C, Mask);
4334       if (Mask.empty())
4335         return false;
4336       break;
4337     }
4338
4339     return false;
4340   }
4341   case X86ISD::VPERMI:
4342     ImmN = N->getOperand(N->getNumOperands()-1);
4343     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4344     IsUnary = true;
4345     break;
4346   case X86ISD::MOVSS:
4347   case X86ISD::MOVSD:
4348     DecodeScalarMoveMask(VT, /* IsLoad */ false, Mask);
4349     break;
4350   case X86ISD::VPERM2X128:
4351     ImmN = N->getOperand(N->getNumOperands()-1);
4352     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4353     if (Mask.empty()) return false;
4354     break;
4355   case X86ISD::MOVSLDUP:
4356     DecodeMOVSLDUPMask(VT, Mask);
4357     IsUnary = true;
4358     break;
4359   case X86ISD::MOVSHDUP:
4360     DecodeMOVSHDUPMask(VT, Mask);
4361     IsUnary = true;
4362     break;
4363   case X86ISD::MOVDDUP:
4364     DecodeMOVDDUPMask(VT, Mask);
4365     IsUnary = true;
4366     break;
4367   case X86ISD::MOVLHPD:
4368   case X86ISD::MOVLPD:
4369   case X86ISD::MOVLPS:
4370     // Not yet implemented
4371     return false;
4372   default: llvm_unreachable("unknown target shuffle node");
4373   }
4374
4375   // If we have a fake unary shuffle, the shuffle mask is spread across two
4376   // inputs that are actually the same node. Re-map the mask to always point
4377   // into the first input.
4378   if (IsFakeUnary)
4379     for (int &M : Mask)
4380       if (M >= (int)Mask.size())
4381         M -= Mask.size();
4382
4383   return true;
4384 }
4385
4386 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4387 /// element of the result of the vector shuffle.
4388 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4389                                    unsigned Depth) {
4390   if (Depth == 6)
4391     return SDValue();  // Limit search depth.
4392
4393   SDValue V = SDValue(N, 0);
4394   EVT VT = V.getValueType();
4395   unsigned Opcode = V.getOpcode();
4396
4397   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4398   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4399     int Elt = SV->getMaskElt(Index);
4400
4401     if (Elt < 0)
4402       return DAG.getUNDEF(VT.getVectorElementType());
4403
4404     unsigned NumElems = VT.getVectorNumElements();
4405     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4406                                          : SV->getOperand(1);
4407     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4408   }
4409
4410   // Recurse into target specific vector shuffles to find scalars.
4411   if (isTargetShuffle(Opcode)) {
4412     MVT ShufVT = V.getSimpleValueType();
4413     unsigned NumElems = ShufVT.getVectorNumElements();
4414     SmallVector<int, 16> ShuffleMask;
4415     bool IsUnary;
4416
4417     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4418       return SDValue();
4419
4420     int Elt = ShuffleMask[Index];
4421     if (Elt < 0)
4422       return DAG.getUNDEF(ShufVT.getVectorElementType());
4423
4424     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4425                                          : N->getOperand(1);
4426     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4427                                Depth+1);
4428   }
4429
4430   // Actual nodes that may contain scalar elements
4431   if (Opcode == ISD::BITCAST) {
4432     V = V.getOperand(0);
4433     EVT SrcVT = V.getValueType();
4434     unsigned NumElems = VT.getVectorNumElements();
4435
4436     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4437       return SDValue();
4438   }
4439
4440   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4441     return (Index == 0) ? V.getOperand(0)
4442                         : DAG.getUNDEF(VT.getVectorElementType());
4443
4444   if (V.getOpcode() == ISD::BUILD_VECTOR)
4445     return V.getOperand(Index);
4446
4447   return SDValue();
4448 }
4449
4450 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4451 ///
4452 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4453                                        unsigned NumNonZero, unsigned NumZero,
4454                                        SelectionDAG &DAG,
4455                                        const X86Subtarget* Subtarget,
4456                                        const TargetLowering &TLI) {
4457   if (NumNonZero > 8)
4458     return SDValue();
4459
4460   SDLoc dl(Op);
4461   SDValue V;
4462   bool First = true;
4463   for (unsigned i = 0; i < 16; ++i) {
4464     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4465     if (ThisIsNonZero && First) {
4466       if (NumZero)
4467         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4468       else
4469         V = DAG.getUNDEF(MVT::v8i16);
4470       First = false;
4471     }
4472
4473     if ((i & 1) != 0) {
4474       SDValue ThisElt, LastElt;
4475       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4476       if (LastIsNonZero) {
4477         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4478                               MVT::i16, Op.getOperand(i-1));
4479       }
4480       if (ThisIsNonZero) {
4481         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4482         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4483                               ThisElt, DAG.getConstant(8, MVT::i8));
4484         if (LastIsNonZero)
4485           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4486       } else
4487         ThisElt = LastElt;
4488
4489       if (ThisElt.getNode())
4490         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4491                         DAG.getIntPtrConstant(i/2));
4492     }
4493   }
4494
4495   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4496 }
4497
4498 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4499 ///
4500 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4501                                      unsigned NumNonZero, unsigned NumZero,
4502                                      SelectionDAG &DAG,
4503                                      const X86Subtarget* Subtarget,
4504                                      const TargetLowering &TLI) {
4505   if (NumNonZero > 4)
4506     return SDValue();
4507
4508   SDLoc dl(Op);
4509   SDValue V;
4510   bool First = true;
4511   for (unsigned i = 0; i < 8; ++i) {
4512     bool isNonZero = (NonZeros & (1 << i)) != 0;
4513     if (isNonZero) {
4514       if (First) {
4515         if (NumZero)
4516           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4517         else
4518           V = DAG.getUNDEF(MVT::v8i16);
4519         First = false;
4520       }
4521       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4522                       MVT::v8i16, V, Op.getOperand(i),
4523                       DAG.getIntPtrConstant(i));
4524     }
4525   }
4526
4527   return V;
4528 }
4529
4530 /// LowerBuildVectorv4x32 - Custom lower build_vector of v4i32 or v4f32.
4531 static SDValue LowerBuildVectorv4x32(SDValue Op, SelectionDAG &DAG,
4532                                      const X86Subtarget *Subtarget,
4533                                      const TargetLowering &TLI) {
4534   // Find all zeroable elements.
4535   std::bitset<4> Zeroable;
4536   for (int i=0; i < 4; ++i) {
4537     SDValue Elt = Op->getOperand(i);
4538     Zeroable[i] = (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt));
4539   }
4540   assert(Zeroable.size() - Zeroable.count() > 1 &&
4541          "We expect at least two non-zero elements!");
4542
4543   // We only know how to deal with build_vector nodes where elements are either
4544   // zeroable or extract_vector_elt with constant index.
4545   SDValue FirstNonZero;
4546   unsigned FirstNonZeroIdx;
4547   for (unsigned i=0; i < 4; ++i) {
4548     if (Zeroable[i])
4549       continue;
4550     SDValue Elt = Op->getOperand(i);
4551     if (Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4552         !isa<ConstantSDNode>(Elt.getOperand(1)))
4553       return SDValue();
4554     // Make sure that this node is extracting from a 128-bit vector.
4555     MVT VT = Elt.getOperand(0).getSimpleValueType();
4556     if (!VT.is128BitVector())
4557       return SDValue();
4558     if (!FirstNonZero.getNode()) {
4559       FirstNonZero = Elt;
4560       FirstNonZeroIdx = i;
4561     }
4562   }
4563
4564   assert(FirstNonZero.getNode() && "Unexpected build vector of all zeros!");
4565   SDValue V1 = FirstNonZero.getOperand(0);
4566   MVT VT = V1.getSimpleValueType();
4567
4568   // See if this build_vector can be lowered as a blend with zero.
4569   SDValue Elt;
4570   unsigned EltMaskIdx, EltIdx;
4571   int Mask[4];
4572   for (EltIdx = 0; EltIdx < 4; ++EltIdx) {
4573     if (Zeroable[EltIdx]) {
4574       // The zero vector will be on the right hand side.
4575       Mask[EltIdx] = EltIdx+4;
4576       continue;
4577     }
4578
4579     Elt = Op->getOperand(EltIdx);
4580     // By construction, Elt is a EXTRACT_VECTOR_ELT with constant index.
4581     EltMaskIdx = cast<ConstantSDNode>(Elt.getOperand(1))->getZExtValue();
4582     if (Elt.getOperand(0) != V1 || EltMaskIdx != EltIdx)
4583       break;
4584     Mask[EltIdx] = EltIdx;
4585   }
4586
4587   if (EltIdx == 4) {
4588     // Let the shuffle legalizer deal with blend operations.
4589     SDValue VZero = getZeroVector(VT, Subtarget, DAG, SDLoc(Op));
4590     if (V1.getSimpleValueType() != VT)
4591       V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), VT, V1);
4592     return DAG.getVectorShuffle(VT, SDLoc(V1), V1, VZero, &Mask[0]);
4593   }
4594
4595   // See if we can lower this build_vector to a INSERTPS.
4596   if (!Subtarget->hasSSE41())
4597     return SDValue();
4598
4599   SDValue V2 = Elt.getOperand(0);
4600   if (Elt == FirstNonZero && EltIdx == FirstNonZeroIdx)
4601     V1 = SDValue();
4602
4603   bool CanFold = true;
4604   for (unsigned i = EltIdx + 1; i < 4 && CanFold; ++i) {
4605     if (Zeroable[i])
4606       continue;
4607
4608     SDValue Current = Op->getOperand(i);
4609     SDValue SrcVector = Current->getOperand(0);
4610     if (!V1.getNode())
4611       V1 = SrcVector;
4612     CanFold = SrcVector == V1 &&
4613       cast<ConstantSDNode>(Current.getOperand(1))->getZExtValue() == i;
4614   }
4615
4616   if (!CanFold)
4617     return SDValue();
4618
4619   assert(V1.getNode() && "Expected at least two non-zero elements!");
4620   if (V1.getSimpleValueType() != MVT::v4f32)
4621     V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), MVT::v4f32, V1);
4622   if (V2.getSimpleValueType() != MVT::v4f32)
4623     V2 = DAG.getNode(ISD::BITCAST, SDLoc(V2), MVT::v4f32, V2);
4624
4625   // Ok, we can emit an INSERTPS instruction.
4626   unsigned ZMask = Zeroable.to_ulong();
4627
4628   unsigned InsertPSMask = EltMaskIdx << 6 | EltIdx << 4 | ZMask;
4629   assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
4630   SDValue Result = DAG.getNode(X86ISD::INSERTPS, SDLoc(Op), MVT::v4f32, V1, V2,
4631                                DAG.getIntPtrConstant(InsertPSMask));
4632   return DAG.getNode(ISD::BITCAST, SDLoc(Op), VT, Result);
4633 }
4634
4635 /// Return a vector logical shift node.
4636 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4637                          unsigned NumBits, SelectionDAG &DAG,
4638                          const TargetLowering &TLI, SDLoc dl) {
4639   assert(VT.is128BitVector() && "Unknown type for VShift");
4640   MVT ShVT = MVT::v2i64;
4641   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
4642   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4643   MVT ScalarShiftTy = TLI.getScalarShiftAmountTy(SrcOp.getValueType());
4644   assert(NumBits % 8 == 0 && "Only support byte sized shifts");
4645   SDValue ShiftVal = DAG.getConstant(NumBits/8, ScalarShiftTy);
4646   return DAG.getNode(ISD::BITCAST, dl, VT,
4647                      DAG.getNode(Opc, dl, ShVT, SrcOp, ShiftVal));
4648 }
4649
4650 static SDValue
4651 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
4652
4653   // Check if the scalar load can be widened into a vector load. And if
4654   // the address is "base + cst" see if the cst can be "absorbed" into
4655   // the shuffle mask.
4656   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4657     SDValue Ptr = LD->getBasePtr();
4658     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4659       return SDValue();
4660     EVT PVT = LD->getValueType(0);
4661     if (PVT != MVT::i32 && PVT != MVT::f32)
4662       return SDValue();
4663
4664     int FI = -1;
4665     int64_t Offset = 0;
4666     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4667       FI = FINode->getIndex();
4668       Offset = 0;
4669     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4670                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4671       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4672       Offset = Ptr.getConstantOperandVal(1);
4673       Ptr = Ptr.getOperand(0);
4674     } else {
4675       return SDValue();
4676     }
4677
4678     // FIXME: 256-bit vector instructions don't require a strict alignment,
4679     // improve this code to support it better.
4680     unsigned RequiredAlign = VT.getSizeInBits()/8;
4681     SDValue Chain = LD->getChain();
4682     // Make sure the stack object alignment is at least 16 or 32.
4683     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4684     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
4685       if (MFI->isFixedObjectIndex(FI)) {
4686         // Can't change the alignment. FIXME: It's possible to compute
4687         // the exact stack offset and reference FI + adjust offset instead.
4688         // If someone *really* cares about this. That's the way to implement it.
4689         return SDValue();
4690       } else {
4691         MFI->setObjectAlignment(FI, RequiredAlign);
4692       }
4693     }
4694
4695     // (Offset % 16 or 32) must be multiple of 4. Then address is then
4696     // Ptr + (Offset & ~15).
4697     if (Offset < 0)
4698       return SDValue();
4699     if ((Offset % RequiredAlign) & 3)
4700       return SDValue();
4701     int64_t StartOffset = Offset & ~(RequiredAlign-1);
4702     if (StartOffset)
4703       Ptr = DAG.getNode(ISD::ADD, SDLoc(Ptr), Ptr.getValueType(),
4704                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
4705
4706     int EltNo = (Offset - StartOffset) >> 2;
4707     unsigned NumElems = VT.getVectorNumElements();
4708
4709     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
4710     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
4711                              LD->getPointerInfo().getWithOffset(StartOffset),
4712                              false, false, false, 0);
4713
4714     SmallVector<int, 8> Mask(NumElems, EltNo);
4715
4716     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
4717   }
4718
4719   return SDValue();
4720 }
4721
4722 /// Given the initializing elements 'Elts' of a vector of type 'VT', see if the
4723 /// elements can be replaced by a single large load which has the same value as
4724 /// a build_vector or insert_subvector whose loaded operands are 'Elts'.
4725 ///
4726 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4727 ///
4728 /// FIXME: we'd also like to handle the case where the last elements are zero
4729 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4730 /// There's even a handy isZeroNode for that purpose.
4731 static SDValue EltsFromConsecutiveLoads(EVT VT, ArrayRef<SDValue> Elts,
4732                                         SDLoc &DL, SelectionDAG &DAG,
4733                                         bool isAfterLegalize) {
4734   unsigned NumElems = Elts.size();
4735
4736   LoadSDNode *LDBase = nullptr;
4737   unsigned LastLoadedElt = -1U;
4738
4739   // For each element in the initializer, see if we've found a load or an undef.
4740   // If we don't find an initial load element, or later load elements are
4741   // non-consecutive, bail out.
4742   for (unsigned i = 0; i < NumElems; ++i) {
4743     SDValue Elt = Elts[i];
4744     // Look through a bitcast.
4745     if (Elt.getNode() && Elt.getOpcode() == ISD::BITCAST)
4746       Elt = Elt.getOperand(0);
4747     if (!Elt.getNode() ||
4748         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
4749       return SDValue();
4750     if (!LDBase) {
4751       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
4752         return SDValue();
4753       LDBase = cast<LoadSDNode>(Elt.getNode());
4754       LastLoadedElt = i;
4755       continue;
4756     }
4757     if (Elt.getOpcode() == ISD::UNDEF)
4758       continue;
4759
4760     LoadSDNode *LD = cast<LoadSDNode>(Elt);
4761     EVT LdVT = Elt.getValueType();
4762     // Each loaded element must be the correct fractional portion of the
4763     // requested vector load.
4764     if (LdVT.getSizeInBits() != VT.getSizeInBits() / NumElems)
4765       return SDValue();
4766     if (!DAG.isConsecutiveLoad(LD, LDBase, LdVT.getSizeInBits() / 8, i))
4767       return SDValue();
4768     LastLoadedElt = i;
4769   }
4770
4771   // If we have found an entire vector of loads and undefs, then return a large
4772   // load of the entire vector width starting at the base pointer.  If we found
4773   // consecutive loads for the low half, generate a vzext_load node.
4774   if (LastLoadedElt == NumElems - 1) {
4775     assert(LDBase && "Did not find base load for merging consecutive loads");
4776     EVT EltVT = LDBase->getValueType(0);
4777     // Ensure that the input vector size for the merged loads matches the
4778     // cumulative size of the input elements.
4779     if (VT.getSizeInBits() != EltVT.getSizeInBits() * NumElems)
4780       return SDValue();
4781
4782     if (isAfterLegalize &&
4783         !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
4784       return SDValue();
4785
4786     SDValue NewLd = SDValue();
4787
4788     NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4789                         LDBase->getPointerInfo(), LDBase->isVolatile(),
4790                         LDBase->isNonTemporal(), LDBase->isInvariant(),
4791                         LDBase->getAlignment());
4792
4793     if (LDBase->hasAnyUseOfValue(1)) {
4794       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
4795                                      SDValue(LDBase, 1),
4796                                      SDValue(NewLd.getNode(), 1));
4797       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
4798       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
4799                              SDValue(NewLd.getNode(), 1));
4800     }
4801
4802     return NewLd;
4803   }
4804
4805   //TODO: The code below fires only for for loading the low v2i32 / v2f32
4806   //of a v4i32 / v4f32. It's probably worth generalizing.
4807   EVT EltVT = VT.getVectorElementType();
4808   if (NumElems == 4 && LastLoadedElt == 1 && (EltVT.getSizeInBits() == 32) &&
4809       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
4810     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
4811     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
4812     SDValue ResNode =
4813         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
4814                                 LDBase->getPointerInfo(),
4815                                 LDBase->getAlignment(),
4816                                 false/*isVolatile*/, true/*ReadMem*/,
4817                                 false/*WriteMem*/);
4818
4819     // Make sure the newly-created LOAD is in the same position as LDBase in
4820     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
4821     // update uses of LDBase's output chain to use the TokenFactor.
4822     if (LDBase->hasAnyUseOfValue(1)) {
4823       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
4824                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
4825       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
4826       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
4827                              SDValue(ResNode.getNode(), 1));
4828     }
4829
4830     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
4831   }
4832   return SDValue();
4833 }
4834
4835 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
4836 /// to generate a splat value for the following cases:
4837 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
4838 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
4839 /// a scalar load, or a constant.
4840 /// The VBROADCAST node is returned when a pattern is found,
4841 /// or SDValue() otherwise.
4842 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
4843                                     SelectionDAG &DAG) {
4844   // VBROADCAST requires AVX.
4845   // TODO: Splats could be generated for non-AVX CPUs using SSE
4846   // instructions, but there's less potential gain for only 128-bit vectors.
4847   if (!Subtarget->hasAVX())
4848     return SDValue();
4849
4850   MVT VT = Op.getSimpleValueType();
4851   SDLoc dl(Op);
4852
4853   assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
4854          "Unsupported vector type for broadcast.");
4855
4856   SDValue Ld;
4857   bool ConstSplatVal;
4858
4859   switch (Op.getOpcode()) {
4860     default:
4861       // Unknown pattern found.
4862       return SDValue();
4863
4864     case ISD::BUILD_VECTOR: {
4865       auto *BVOp = cast<BuildVectorSDNode>(Op.getNode());
4866       BitVector UndefElements;
4867       SDValue Splat = BVOp->getSplatValue(&UndefElements);
4868
4869       // We need a splat of a single value to use broadcast, and it doesn't
4870       // make any sense if the value is only in one element of the vector.
4871       if (!Splat || (VT.getVectorNumElements() - UndefElements.count()) <= 1)
4872         return SDValue();
4873
4874       Ld = Splat;
4875       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
4876                        Ld.getOpcode() == ISD::ConstantFP);
4877
4878       // Make sure that all of the users of a non-constant load are from the
4879       // BUILD_VECTOR node.
4880       if (!ConstSplatVal && !BVOp->isOnlyUserOf(Ld.getNode()))
4881         return SDValue();
4882       break;
4883     }
4884
4885     case ISD::VECTOR_SHUFFLE: {
4886       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
4887
4888       // Shuffles must have a splat mask where the first element is
4889       // broadcasted.
4890       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
4891         return SDValue();
4892
4893       SDValue Sc = Op.getOperand(0);
4894       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
4895           Sc.getOpcode() != ISD::BUILD_VECTOR) {
4896
4897         if (!Subtarget->hasInt256())
4898           return SDValue();
4899
4900         // Use the register form of the broadcast instruction available on AVX2.
4901         if (VT.getSizeInBits() >= 256)
4902           Sc = Extract128BitVector(Sc, 0, DAG, dl);
4903         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
4904       }
4905
4906       Ld = Sc.getOperand(0);
4907       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
4908                        Ld.getOpcode() == ISD::ConstantFP);
4909
4910       // The scalar_to_vector node and the suspected
4911       // load node must have exactly one user.
4912       // Constants may have multiple users.
4913
4914       // AVX-512 has register version of the broadcast
4915       bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
4916         Ld.getValueType().getSizeInBits() >= 32;
4917       if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
4918           !hasRegVer))
4919         return SDValue();
4920       break;
4921     }
4922   }
4923
4924   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
4925   bool IsGE256 = (VT.getSizeInBits() >= 256);
4926
4927   // When optimizing for size, generate up to 5 extra bytes for a broadcast
4928   // instruction to save 8 or more bytes of constant pool data.
4929   // TODO: If multiple splats are generated to load the same constant,
4930   // it may be detrimental to overall size. There needs to be a way to detect
4931   // that condition to know if this is truly a size win.
4932   const Function *F = DAG.getMachineFunction().getFunction();
4933   bool OptForSize = F->hasFnAttribute(Attribute::OptimizeForSize);
4934
4935   // Handle broadcasting a single constant scalar from the constant pool
4936   // into a vector.
4937   // On Sandybridge (no AVX2), it is still better to load a constant vector
4938   // from the constant pool and not to broadcast it from a scalar.
4939   // But override that restriction when optimizing for size.
4940   // TODO: Check if splatting is recommended for other AVX-capable CPUs.
4941   if (ConstSplatVal && (Subtarget->hasAVX2() || OptForSize)) {
4942     EVT CVT = Ld.getValueType();
4943     assert(!CVT.isVector() && "Must not broadcast a vector type");
4944
4945     // Splat f32, i32, v4f64, v4i64 in all cases with AVX2.
4946     // For size optimization, also splat v2f64 and v2i64, and for size opt
4947     // with AVX2, also splat i8 and i16.
4948     // With pattern matching, the VBROADCAST node may become a VMOVDDUP.
4949     if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
4950         (OptForSize && (ScalarSize == 64 || Subtarget->hasAVX2()))) {
4951       const Constant *C = nullptr;
4952       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
4953         C = CI->getConstantIntValue();
4954       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
4955         C = CF->getConstantFPValue();
4956
4957       assert(C && "Invalid constant type");
4958
4959       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4960       SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
4961       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
4962       Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
4963                        MachinePointerInfo::getConstantPool(),
4964                        false, false, false, Alignment);
4965
4966       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
4967     }
4968   }
4969
4970   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
4971
4972   // Handle AVX2 in-register broadcasts.
4973   if (!IsLoad && Subtarget->hasInt256() &&
4974       (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
4975     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
4976
4977   // The scalar source must be a normal load.
4978   if (!IsLoad)
4979     return SDValue();
4980
4981   if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
4982       (Subtarget->hasVLX() && ScalarSize == 64))
4983     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
4984
4985   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
4986   // double since there is no vbroadcastsd xmm
4987   if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
4988     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
4989       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
4990   }
4991
4992   // Unsupported broadcast.
4993   return SDValue();
4994 }
4995
4996 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
4997 /// underlying vector and index.
4998 ///
4999 /// Modifies \p ExtractedFromVec to the real vector and returns the real
5000 /// index.
5001 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
5002                                          SDValue ExtIdx) {
5003   int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5004   if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
5005     return Idx;
5006
5007   // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
5008   // lowered this:
5009   //   (extract_vector_elt (v8f32 %vreg1), Constant<6>)
5010   // to:
5011   //   (extract_vector_elt (vector_shuffle<2,u,u,u>
5012   //                           (extract_subvector (v8f32 %vreg0), Constant<4>),
5013   //                           undef)
5014   //                       Constant<0>)
5015   // In this case the vector is the extract_subvector expression and the index
5016   // is 2, as specified by the shuffle.
5017   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
5018   SDValue ShuffleVec = SVOp->getOperand(0);
5019   MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
5020   assert(ShuffleVecVT.getVectorElementType() ==
5021          ExtractedFromVec.getSimpleValueType().getVectorElementType());
5022
5023   int ShuffleIdx = SVOp->getMaskElt(Idx);
5024   if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
5025     ExtractedFromVec = ShuffleVec;
5026     return ShuffleIdx;
5027   }
5028   return Idx;
5029 }
5030
5031 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5032   MVT VT = Op.getSimpleValueType();
5033
5034   // Skip if insert_vec_elt is not supported.
5035   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5036   if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5037     return SDValue();
5038
5039   SDLoc DL(Op);
5040   unsigned NumElems = Op.getNumOperands();
5041
5042   SDValue VecIn1;
5043   SDValue VecIn2;
5044   SmallVector<unsigned, 4> InsertIndices;
5045   SmallVector<int, 8> Mask(NumElems, -1);
5046
5047   for (unsigned i = 0; i != NumElems; ++i) {
5048     unsigned Opc = Op.getOperand(i).getOpcode();
5049
5050     if (Opc == ISD::UNDEF)
5051       continue;
5052
5053     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5054       // Quit if more than 1 elements need inserting.
5055       if (InsertIndices.size() > 1)
5056         return SDValue();
5057
5058       InsertIndices.push_back(i);
5059       continue;
5060     }
5061
5062     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5063     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5064     // Quit if non-constant index.
5065     if (!isa<ConstantSDNode>(ExtIdx))
5066       return SDValue();
5067     int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5068
5069     // Quit if extracted from vector of different type.
5070     if (ExtractedFromVec.getValueType() != VT)
5071       return SDValue();
5072
5073     if (!VecIn1.getNode())
5074       VecIn1 = ExtractedFromVec;
5075     else if (VecIn1 != ExtractedFromVec) {
5076       if (!VecIn2.getNode())
5077         VecIn2 = ExtractedFromVec;
5078       else if (VecIn2 != ExtractedFromVec)
5079         // Quit if more than 2 vectors to shuffle
5080         return SDValue();
5081     }
5082
5083     if (ExtractedFromVec == VecIn1)
5084       Mask[i] = Idx;
5085     else if (ExtractedFromVec == VecIn2)
5086       Mask[i] = Idx + NumElems;
5087   }
5088
5089   if (!VecIn1.getNode())
5090     return SDValue();
5091
5092   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5093   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5094   for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5095     unsigned Idx = InsertIndices[i];
5096     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5097                      DAG.getIntPtrConstant(Idx));
5098   }
5099
5100   return NV;
5101 }
5102
5103 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5104 SDValue
5105 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5106
5107   MVT VT = Op.getSimpleValueType();
5108   assert((VT.getVectorElementType() == MVT::i1) && (VT.getSizeInBits() <= 16) &&
5109          "Unexpected type in LowerBUILD_VECTORvXi1!");
5110
5111   SDLoc dl(Op);
5112   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5113     SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
5114     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5115     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5116   }
5117
5118   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5119     SDValue Cst = DAG.getTargetConstant(1, MVT::i1);
5120     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5121     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5122   }
5123
5124   bool AllContants = true;
5125   uint64_t Immediate = 0;
5126   int NonConstIdx = -1;
5127   bool IsSplat = true;
5128   unsigned NumNonConsts = 0;
5129   unsigned NumConsts = 0;
5130   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5131     SDValue In = Op.getOperand(idx);
5132     if (In.getOpcode() == ISD::UNDEF)
5133       continue;
5134     if (!isa<ConstantSDNode>(In)) {
5135       AllContants = false;
5136       NonConstIdx = idx;
5137       NumNonConsts++;
5138     } else {
5139       NumConsts++;
5140       if (cast<ConstantSDNode>(In)->getZExtValue())
5141       Immediate |= (1ULL << idx);
5142     }
5143     if (In != Op.getOperand(0))
5144       IsSplat = false;
5145   }
5146
5147   if (AllContants) {
5148     SDValue FullMask = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1,
5149       DAG.getConstant(Immediate, MVT::i16));
5150     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, FullMask,
5151                        DAG.getIntPtrConstant(0));
5152   }
5153
5154   if (NumNonConsts == 1 && NonConstIdx != 0) {
5155     SDValue DstVec;
5156     if (NumConsts) {
5157       SDValue VecAsImm = DAG.getConstant(Immediate,
5158                                          MVT::getIntegerVT(VT.getSizeInBits()));
5159       DstVec = DAG.getNode(ISD::BITCAST, dl, VT, VecAsImm);
5160     }
5161     else
5162       DstVec = DAG.getUNDEF(VT);
5163     return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5164                        Op.getOperand(NonConstIdx),
5165                        DAG.getIntPtrConstant(NonConstIdx));
5166   }
5167   if (!IsSplat && (NonConstIdx != 0))
5168     llvm_unreachable("Unsupported BUILD_VECTOR operation");
5169   MVT SelectVT = (VT == MVT::v16i1)? MVT::i16 : MVT::i8;
5170   SDValue Select;
5171   if (IsSplat)
5172     Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
5173                           DAG.getConstant(-1, SelectVT),
5174                           DAG.getConstant(0, SelectVT));
5175   else
5176     Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
5177                          DAG.getConstant((Immediate | 1), SelectVT),
5178                          DAG.getConstant(Immediate, SelectVT));
5179   return DAG.getNode(ISD::BITCAST, dl, VT, Select);
5180 }
5181
5182 /// \brief Return true if \p N implements a horizontal binop and return the
5183 /// operands for the horizontal binop into V0 and V1.
5184 ///
5185 /// This is a helper function of PerformBUILD_VECTORCombine.
5186 /// This function checks that the build_vector \p N in input implements a
5187 /// horizontal operation. Parameter \p Opcode defines the kind of horizontal
5188 /// operation to match.
5189 /// For example, if \p Opcode is equal to ISD::ADD, then this function
5190 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
5191 /// is equal to ISD::SUB, then this function checks if this is a horizontal
5192 /// arithmetic sub.
5193 ///
5194 /// This function only analyzes elements of \p N whose indices are
5195 /// in range [BaseIdx, LastIdx).
5196 static bool isHorizontalBinOp(const BuildVectorSDNode *N, unsigned Opcode,
5197                               SelectionDAG &DAG,
5198                               unsigned BaseIdx, unsigned LastIdx,
5199                               SDValue &V0, SDValue &V1) {
5200   EVT VT = N->getValueType(0);
5201
5202   assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
5203   assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
5204          "Invalid Vector in input!");
5205
5206   bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
5207   bool CanFold = true;
5208   unsigned ExpectedVExtractIdx = BaseIdx;
5209   unsigned NumElts = LastIdx - BaseIdx;
5210   V0 = DAG.getUNDEF(VT);
5211   V1 = DAG.getUNDEF(VT);
5212
5213   // Check if N implements a horizontal binop.
5214   for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
5215     SDValue Op = N->getOperand(i + BaseIdx);
5216
5217     // Skip UNDEFs.
5218     if (Op->getOpcode() == ISD::UNDEF) {
5219       // Update the expected vector extract index.
5220       if (i * 2 == NumElts)
5221         ExpectedVExtractIdx = BaseIdx;
5222       ExpectedVExtractIdx += 2;
5223       continue;
5224     }
5225
5226     CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
5227
5228     if (!CanFold)
5229       break;
5230
5231     SDValue Op0 = Op.getOperand(0);
5232     SDValue Op1 = Op.getOperand(1);
5233
5234     // Try to match the following pattern:
5235     // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
5236     CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5237         Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5238         Op0.getOperand(0) == Op1.getOperand(0) &&
5239         isa<ConstantSDNode>(Op0.getOperand(1)) &&
5240         isa<ConstantSDNode>(Op1.getOperand(1)));
5241     if (!CanFold)
5242       break;
5243
5244     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5245     unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
5246
5247     if (i * 2 < NumElts) {
5248       if (V0.getOpcode() == ISD::UNDEF)
5249         V0 = Op0.getOperand(0);
5250     } else {
5251       if (V1.getOpcode() == ISD::UNDEF)
5252         V1 = Op0.getOperand(0);
5253       if (i * 2 == NumElts)
5254         ExpectedVExtractIdx = BaseIdx;
5255     }
5256
5257     SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
5258     if (I0 == ExpectedVExtractIdx)
5259       CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
5260     else if (IsCommutable && I1 == ExpectedVExtractIdx) {
5261       // Try to match the following dag sequence:
5262       // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
5263       CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
5264     } else
5265       CanFold = false;
5266
5267     ExpectedVExtractIdx += 2;
5268   }
5269
5270   return CanFold;
5271 }
5272
5273 /// \brief Emit a sequence of two 128-bit horizontal add/sub followed by
5274 /// a concat_vector.
5275 ///
5276 /// This is a helper function of PerformBUILD_VECTORCombine.
5277 /// This function expects two 256-bit vectors called V0 and V1.
5278 /// At first, each vector is split into two separate 128-bit vectors.
5279 /// Then, the resulting 128-bit vectors are used to implement two
5280 /// horizontal binary operations.
5281 ///
5282 /// The kind of horizontal binary operation is defined by \p X86Opcode.
5283 ///
5284 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
5285 /// the two new horizontal binop.
5286 /// When Mode is set, the first horizontal binop dag node would take as input
5287 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
5288 /// horizontal binop dag node would take as input the lower 128-bit of V1
5289 /// and the upper 128-bit of V1.
5290 ///   Example:
5291 ///     HADD V0_LO, V0_HI
5292 ///     HADD V1_LO, V1_HI
5293 ///
5294 /// Otherwise, the first horizontal binop dag node takes as input the lower
5295 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
5296 /// dag node takes the the upper 128-bit of V0 and the upper 128-bit of V1.
5297 ///   Example:
5298 ///     HADD V0_LO, V1_LO
5299 ///     HADD V0_HI, V1_HI
5300 ///
5301 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
5302 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
5303 /// the upper 128-bits of the result.
5304 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
5305                                      SDLoc DL, SelectionDAG &DAG,
5306                                      unsigned X86Opcode, bool Mode,
5307                                      bool isUndefLO, bool isUndefHI) {
5308   EVT VT = V0.getValueType();
5309   assert(VT.is256BitVector() && VT == V1.getValueType() &&
5310          "Invalid nodes in input!");
5311
5312   unsigned NumElts = VT.getVectorNumElements();
5313   SDValue V0_LO = Extract128BitVector(V0, 0, DAG, DL);
5314   SDValue V0_HI = Extract128BitVector(V0, NumElts/2, DAG, DL);
5315   SDValue V1_LO = Extract128BitVector(V1, 0, DAG, DL);
5316   SDValue V1_HI = Extract128BitVector(V1, NumElts/2, DAG, DL);
5317   EVT NewVT = V0_LO.getValueType();
5318
5319   SDValue LO = DAG.getUNDEF(NewVT);
5320   SDValue HI = DAG.getUNDEF(NewVT);
5321
5322   if (Mode) {
5323     // Don't emit a horizontal binop if the result is expected to be UNDEF.
5324     if (!isUndefLO && V0->getOpcode() != ISD::UNDEF)
5325       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
5326     if (!isUndefHI && V1->getOpcode() != ISD::UNDEF)
5327       HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
5328   } else {
5329     // Don't emit a horizontal binop if the result is expected to be UNDEF.
5330     if (!isUndefLO && (V0_LO->getOpcode() != ISD::UNDEF ||
5331                        V1_LO->getOpcode() != ISD::UNDEF))
5332       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
5333
5334     if (!isUndefHI && (V0_HI->getOpcode() != ISD::UNDEF ||
5335                        V1_HI->getOpcode() != ISD::UNDEF))
5336       HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
5337   }
5338
5339   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
5340 }
5341
5342 /// \brief Try to fold a build_vector that performs an 'addsub' into the
5343 /// sequence of 'vadd + vsub + blendi'.
5344 static SDValue matchAddSub(const BuildVectorSDNode *BV, SelectionDAG &DAG,
5345                            const X86Subtarget *Subtarget) {
5346   SDLoc DL(BV);
5347   EVT VT = BV->getValueType(0);
5348   unsigned NumElts = VT.getVectorNumElements();
5349   SDValue InVec0 = DAG.getUNDEF(VT);
5350   SDValue InVec1 = DAG.getUNDEF(VT);
5351
5352   assert((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v4f32 ||
5353           VT == MVT::v2f64) && "build_vector with an invalid type found!");
5354
5355   // Odd-numbered elements in the input build vector are obtained from
5356   // adding two integer/float elements.
5357   // Even-numbered elements in the input build vector are obtained from
5358   // subtracting two integer/float elements.
5359   unsigned ExpectedOpcode = ISD::FSUB;
5360   unsigned NextExpectedOpcode = ISD::FADD;
5361   bool AddFound = false;
5362   bool SubFound = false;
5363
5364   for (unsigned i = 0, e = NumElts; i != e; ++i) {
5365     SDValue Op = BV->getOperand(i);
5366
5367     // Skip 'undef' values.
5368     unsigned Opcode = Op.getOpcode();
5369     if (Opcode == ISD::UNDEF) {
5370       std::swap(ExpectedOpcode, NextExpectedOpcode);
5371       continue;
5372     }
5373
5374     // Early exit if we found an unexpected opcode.
5375     if (Opcode != ExpectedOpcode)
5376       return SDValue();
5377
5378     SDValue Op0 = Op.getOperand(0);
5379     SDValue Op1 = Op.getOperand(1);
5380
5381     // Try to match the following pattern:
5382     // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
5383     // Early exit if we cannot match that sequence.
5384     if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5385         Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5386         !isa<ConstantSDNode>(Op0.getOperand(1)) ||
5387         !isa<ConstantSDNode>(Op1.getOperand(1)) ||
5388         Op0.getOperand(1) != Op1.getOperand(1))
5389       return SDValue();
5390
5391     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5392     if (I0 != i)
5393       return SDValue();
5394
5395     // We found a valid add/sub node. Update the information accordingly.
5396     if (i & 1)
5397       AddFound = true;
5398     else
5399       SubFound = true;
5400
5401     // Update InVec0 and InVec1.
5402     if (InVec0.getOpcode() == ISD::UNDEF)
5403       InVec0 = Op0.getOperand(0);
5404     if (InVec1.getOpcode() == ISD::UNDEF)
5405       InVec1 = Op1.getOperand(0);
5406
5407     // Make sure that operands in input to each add/sub node always
5408     // come from a same pair of vectors.
5409     if (InVec0 != Op0.getOperand(0)) {
5410       if (ExpectedOpcode == ISD::FSUB)
5411         return SDValue();
5412
5413       // FADD is commutable. Try to commute the operands
5414       // and then test again.
5415       std::swap(Op0, Op1);
5416       if (InVec0 != Op0.getOperand(0))
5417         return SDValue();
5418     }
5419
5420     if (InVec1 != Op1.getOperand(0))
5421       return SDValue();
5422
5423     // Update the pair of expected opcodes.
5424     std::swap(ExpectedOpcode, NextExpectedOpcode);
5425   }
5426
5427   // Don't try to fold this build_vector into an ADDSUB if the inputs are undef.
5428   if (AddFound && SubFound && InVec0.getOpcode() != ISD::UNDEF &&
5429       InVec1.getOpcode() != ISD::UNDEF)
5430     return DAG.getNode(X86ISD::ADDSUB, DL, VT, InVec0, InVec1);
5431
5432   return SDValue();
5433 }
5434
5435 static SDValue PerformBUILD_VECTORCombine(SDNode *N, SelectionDAG &DAG,
5436                                           const X86Subtarget *Subtarget) {
5437   SDLoc DL(N);
5438   EVT VT = N->getValueType(0);
5439   unsigned NumElts = VT.getVectorNumElements();
5440   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(N);
5441   SDValue InVec0, InVec1;
5442
5443   // Try to match an ADDSUB.
5444   if ((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
5445       (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) {
5446     SDValue Value = matchAddSub(BV, DAG, Subtarget);
5447     if (Value.getNode())
5448       return Value;
5449   }
5450
5451   // Try to match horizontal ADD/SUB.
5452   unsigned NumUndefsLO = 0;
5453   unsigned NumUndefsHI = 0;
5454   unsigned Half = NumElts/2;
5455
5456   // Count the number of UNDEF operands in the build_vector in input.
5457   for (unsigned i = 0, e = Half; i != e; ++i)
5458     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
5459       NumUndefsLO++;
5460
5461   for (unsigned i = Half, e = NumElts; i != e; ++i)
5462     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
5463       NumUndefsHI++;
5464
5465   // Early exit if this is either a build_vector of all UNDEFs or all the
5466   // operands but one are UNDEF.
5467   if (NumUndefsLO + NumUndefsHI + 1 >= NumElts)
5468     return SDValue();
5469
5470   if ((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) {
5471     // Try to match an SSE3 float HADD/HSUB.
5472     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
5473       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
5474
5475     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
5476       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
5477   } else if ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) {
5478     // Try to match an SSSE3 integer HADD/HSUB.
5479     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
5480       return DAG.getNode(X86ISD::HADD, DL, VT, InVec0, InVec1);
5481
5482     if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
5483       return DAG.getNode(X86ISD::HSUB, DL, VT, InVec0, InVec1);
5484   }
5485
5486   if (!Subtarget->hasAVX())
5487     return SDValue();
5488
5489   if ((VT == MVT::v8f32 || VT == MVT::v4f64)) {
5490     // Try to match an AVX horizontal add/sub of packed single/double
5491     // precision floating point values from 256-bit vectors.
5492     SDValue InVec2, InVec3;
5493     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, Half, InVec0, InVec1) &&
5494         isHorizontalBinOp(BV, ISD::FADD, DAG, Half, NumElts, InVec2, InVec3) &&
5495         ((InVec0.getOpcode() == ISD::UNDEF ||
5496           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5497         ((InVec1.getOpcode() == ISD::UNDEF ||
5498           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5499       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
5500
5501     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, Half, InVec0, InVec1) &&
5502         isHorizontalBinOp(BV, ISD::FSUB, DAG, Half, NumElts, InVec2, InVec3) &&
5503         ((InVec0.getOpcode() == ISD::UNDEF ||
5504           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5505         ((InVec1.getOpcode() == ISD::UNDEF ||
5506           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5507       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
5508   } else if (VT == MVT::v8i32 || VT == MVT::v16i16) {
5509     // Try to match an AVX2 horizontal add/sub of signed integers.
5510     SDValue InVec2, InVec3;
5511     unsigned X86Opcode;
5512     bool CanFold = true;
5513
5514     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
5515         isHorizontalBinOp(BV, ISD::ADD, DAG, Half, NumElts, InVec2, InVec3) &&
5516         ((InVec0.getOpcode() == ISD::UNDEF ||
5517           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5518         ((InVec1.getOpcode() == ISD::UNDEF ||
5519           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5520       X86Opcode = X86ISD::HADD;
5521     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, Half, InVec0, InVec1) &&
5522         isHorizontalBinOp(BV, ISD::SUB, DAG, Half, NumElts, InVec2, InVec3) &&
5523         ((InVec0.getOpcode() == ISD::UNDEF ||
5524           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5525         ((InVec1.getOpcode() == ISD::UNDEF ||
5526           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5527       X86Opcode = X86ISD::HSUB;
5528     else
5529       CanFold = false;
5530
5531     if (CanFold) {
5532       // Fold this build_vector into a single horizontal add/sub.
5533       // Do this only if the target has AVX2.
5534       if (Subtarget->hasAVX2())
5535         return DAG.getNode(X86Opcode, DL, VT, InVec0, InVec1);
5536
5537       // Do not try to expand this build_vector into a pair of horizontal
5538       // add/sub if we can emit a pair of scalar add/sub.
5539       if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
5540         return SDValue();
5541
5542       // Convert this build_vector into a pair of horizontal binop followed by
5543       // a concat vector.
5544       bool isUndefLO = NumUndefsLO == Half;
5545       bool isUndefHI = NumUndefsHI == Half;
5546       return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, false,
5547                                    isUndefLO, isUndefHI);
5548     }
5549   }
5550
5551   if ((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
5552        VT == MVT::v16i16) && Subtarget->hasAVX()) {
5553     unsigned X86Opcode;
5554     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
5555       X86Opcode = X86ISD::HADD;
5556     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
5557       X86Opcode = X86ISD::HSUB;
5558     else if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
5559       X86Opcode = X86ISD::FHADD;
5560     else if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
5561       X86Opcode = X86ISD::FHSUB;
5562     else
5563       return SDValue();
5564
5565     // Don't try to expand this build_vector into a pair of horizontal add/sub
5566     // if we can simply emit a pair of scalar add/sub.
5567     if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
5568       return SDValue();
5569
5570     // Convert this build_vector into two horizontal add/sub followed by
5571     // a concat vector.
5572     bool isUndefLO = NumUndefsLO == Half;
5573     bool isUndefHI = NumUndefsHI == Half;
5574     return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
5575                                  isUndefLO, isUndefHI);
5576   }
5577
5578   return SDValue();
5579 }
5580
5581 SDValue
5582 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5583   SDLoc dl(Op);
5584
5585   MVT VT = Op.getSimpleValueType();
5586   MVT ExtVT = VT.getVectorElementType();
5587   unsigned NumElems = Op.getNumOperands();
5588
5589   // Generate vectors for predicate vectors.
5590   if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
5591     return LowerBUILD_VECTORvXi1(Op, DAG);
5592
5593   // Vectors containing all zeros can be matched by pxor and xorps later
5594   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5595     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5596     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5597     if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
5598       return Op;
5599
5600     return getZeroVector(VT, Subtarget, DAG, dl);
5601   }
5602
5603   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5604   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5605   // vpcmpeqd on 256-bit vectors.
5606   if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
5607     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
5608       return Op;
5609
5610     if (!VT.is512BitVector())
5611       return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
5612   }
5613
5614   if (SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG))
5615     return Broadcast;
5616
5617   unsigned EVTBits = ExtVT.getSizeInBits();
5618
5619   unsigned NumZero  = 0;
5620   unsigned NumNonZero = 0;
5621   unsigned NonZeros = 0;
5622   bool IsAllConstants = true;
5623   SmallSet<SDValue, 8> Values;
5624   for (unsigned i = 0; i < NumElems; ++i) {
5625     SDValue Elt = Op.getOperand(i);
5626     if (Elt.getOpcode() == ISD::UNDEF)
5627       continue;
5628     Values.insert(Elt);
5629     if (Elt.getOpcode() != ISD::Constant &&
5630         Elt.getOpcode() != ISD::ConstantFP)
5631       IsAllConstants = false;
5632     if (X86::isZeroNode(Elt))
5633       NumZero++;
5634     else {
5635       NonZeros |= (1 << i);
5636       NumNonZero++;
5637     }
5638   }
5639
5640   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
5641   if (NumNonZero == 0)
5642     return DAG.getUNDEF(VT);
5643
5644   // Special case for single non-zero, non-undef, element.
5645   if (NumNonZero == 1) {
5646     unsigned Idx = countTrailingZeros(NonZeros);
5647     SDValue Item = Op.getOperand(Idx);
5648
5649     // If this is an insertion of an i64 value on x86-32, and if the top bits of
5650     // the value are obviously zero, truncate the value to i32 and do the
5651     // insertion that way.  Only do this if the value is non-constant or if the
5652     // value is a constant being inserted into element 0.  It is cheaper to do
5653     // a constant pool load than it is to do a movd + shuffle.
5654     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5655         (!IsAllConstants || Idx == 0)) {
5656       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5657         // Handle SSE only.
5658         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5659         EVT VecVT = MVT::v4i32;
5660
5661         // Truncate the value (which may itself be a constant) to i32, and
5662         // convert it to a vector with movd (S2V+shuffle to zero extend).
5663         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5664         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5665         return DAG.getNode(
5666             ISD::BITCAST, dl, VT,
5667             getShuffleVectorZeroOrUndef(Item, Idx * 2, true, Subtarget, DAG));
5668       }
5669     }
5670
5671     // If we have a constant or non-constant insertion into the low element of
5672     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5673     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
5674     // depending on what the source datatype is.
5675     if (Idx == 0) {
5676       if (NumZero == 0)
5677         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5678
5679       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5680           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5681         if (VT.is512BitVector()) {
5682           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
5683           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
5684                              Item, DAG.getIntPtrConstant(0));
5685         }
5686         assert((VT.is128BitVector() || VT.is256BitVector()) &&
5687                "Expected an SSE value type!");
5688         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5689         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5690         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5691       }
5692
5693       // We can't directly insert an i8 or i16 into a vector, so zero extend
5694       // it to i32 first.
5695       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5696         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5697         if (VT.is256BitVector()) {
5698           if (Subtarget->hasAVX()) {
5699             Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v8i32, Item);
5700             Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5701           } else {
5702             // Without AVX, we need to extend to a 128-bit vector and then
5703             // insert into the 256-bit vector.
5704             Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5705             SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
5706             Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
5707           }
5708         } else {
5709           assert(VT.is128BitVector() && "Expected an SSE value type!");
5710           Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5711           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5712         }
5713         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5714       }
5715     }
5716
5717     // Is it a vector logical left shift?
5718     if (NumElems == 2 && Idx == 1 &&
5719         X86::isZeroNode(Op.getOperand(0)) &&
5720         !X86::isZeroNode(Op.getOperand(1))) {
5721       unsigned NumBits = VT.getSizeInBits();
5722       return getVShift(true, VT,
5723                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5724                                    VT, Op.getOperand(1)),
5725                        NumBits/2, DAG, *this, dl);
5726     }
5727
5728     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5729       return SDValue();
5730
5731     // Otherwise, if this is a vector with i32 or f32 elements, and the element
5732     // is a non-constant being inserted into an element other than the low one,
5733     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
5734     // movd/movss) to move this into the low element, then shuffle it into
5735     // place.
5736     if (EVTBits == 32) {
5737       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5738       return getShuffleVectorZeroOrUndef(Item, Idx, NumZero > 0, Subtarget, DAG);
5739     }
5740   }
5741
5742   // Splat is obviously ok. Let legalizer expand it to a shuffle.
5743   if (Values.size() == 1) {
5744     if (EVTBits == 32) {
5745       // Instead of a shuffle like this:
5746       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
5747       // Check if it's possible to issue this instead.
5748       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
5749       unsigned Idx = countTrailingZeros(NonZeros);
5750       SDValue Item = Op.getOperand(Idx);
5751       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
5752         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
5753     }
5754     return SDValue();
5755   }
5756
5757   // A vector full of immediates; various special cases are already
5758   // handled, so this is best done with a single constant-pool load.
5759   if (IsAllConstants)
5760     return SDValue();
5761
5762   // For AVX-length vectors, see if we can use a vector load to get all of the
5763   // elements, otherwise build the individual 128-bit pieces and use
5764   // shuffles to put them in place.
5765   if (VT.is256BitVector() || VT.is512BitVector()) {
5766     SmallVector<SDValue, 64> V(Op->op_begin(), Op->op_begin() + NumElems);
5767
5768     // Check for a build vector of consecutive loads.
5769     if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
5770       return LD;
5771
5772     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
5773
5774     // Build both the lower and upper subvector.
5775     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
5776                                 makeArrayRef(&V[0], NumElems/2));
5777     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
5778                                 makeArrayRef(&V[NumElems / 2], NumElems/2));
5779
5780     // Recreate the wider vector with the lower and upper part.
5781     if (VT.is256BitVector())
5782       return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
5783     return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
5784   }
5785
5786   // Let legalizer expand 2-wide build_vectors.
5787   if (EVTBits == 64) {
5788     if (NumNonZero == 1) {
5789       // One half is zero or undef.
5790       unsigned Idx = countTrailingZeros(NonZeros);
5791       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
5792                                  Op.getOperand(Idx));
5793       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
5794     }
5795     return SDValue();
5796   }
5797
5798   // If element VT is < 32 bits, convert it to inserts into a zero vector.
5799   if (EVTBits == 8 && NumElems == 16)
5800     if (SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
5801                                         Subtarget, *this))
5802       return V;
5803
5804   if (EVTBits == 16 && NumElems == 8)
5805     if (SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
5806                                       Subtarget, *this))
5807       return V;
5808
5809   // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
5810   if (EVTBits == 32 && NumElems == 4)
5811     if (SDValue V = LowerBuildVectorv4x32(Op, DAG, Subtarget, *this))
5812       return V;
5813
5814   // If element VT is == 32 bits, turn it into a number of shuffles.
5815   SmallVector<SDValue, 8> V(NumElems);
5816   if (NumElems == 4 && NumZero > 0) {
5817     for (unsigned i = 0; i < 4; ++i) {
5818       bool isZero = !(NonZeros & (1 << i));
5819       if (isZero)
5820         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
5821       else
5822         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5823     }
5824
5825     for (unsigned i = 0; i < 2; ++i) {
5826       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
5827         default: break;
5828         case 0:
5829           V[i] = V[i*2];  // Must be a zero vector.
5830           break;
5831         case 1:
5832           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
5833           break;
5834         case 2:
5835           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
5836           break;
5837         case 3:
5838           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
5839           break;
5840       }
5841     }
5842
5843     bool Reverse1 = (NonZeros & 0x3) == 2;
5844     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
5845     int MaskVec[] = {
5846       Reverse1 ? 1 : 0,
5847       Reverse1 ? 0 : 1,
5848       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
5849       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
5850     };
5851     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
5852   }
5853
5854   if (Values.size() > 1 && VT.is128BitVector()) {
5855     // Check for a build vector of consecutive loads.
5856     for (unsigned i = 0; i < NumElems; ++i)
5857       V[i] = Op.getOperand(i);
5858
5859     // Check for elements which are consecutive loads.
5860     if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
5861       return LD;
5862
5863     // Check for a build vector from mostly shuffle plus few inserting.
5864     if (SDValue Sh = buildFromShuffleMostly(Op, DAG))
5865       return Sh;
5866
5867     // For SSE 4.1, use insertps to put the high elements into the low element.
5868     if (Subtarget->hasSSE41()) {
5869       SDValue Result;
5870       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
5871         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
5872       else
5873         Result = DAG.getUNDEF(VT);
5874
5875       for (unsigned i = 1; i < NumElems; ++i) {
5876         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
5877         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
5878                              Op.getOperand(i), DAG.getIntPtrConstant(i));
5879       }
5880       return Result;
5881     }
5882
5883     // Otherwise, expand into a number of unpckl*, start by extending each of
5884     // our (non-undef) elements to the full vector width with the element in the
5885     // bottom slot of the vector (which generates no code for SSE).
5886     for (unsigned i = 0; i < NumElems; ++i) {
5887       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
5888         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5889       else
5890         V[i] = DAG.getUNDEF(VT);
5891     }
5892
5893     // Next, we iteratively mix elements, e.g. for v4f32:
5894     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
5895     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
5896     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
5897     unsigned EltStride = NumElems >> 1;
5898     while (EltStride != 0) {
5899       for (unsigned i = 0; i < EltStride; ++i) {
5900         // If V[i+EltStride] is undef and this is the first round of mixing,
5901         // then it is safe to just drop this shuffle: V[i] is already in the
5902         // right place, the one element (since it's the first round) being
5903         // inserted as undef can be dropped.  This isn't safe for successive
5904         // rounds because they will permute elements within both vectors.
5905         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
5906             EltStride == NumElems/2)
5907           continue;
5908
5909         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
5910       }
5911       EltStride >>= 1;
5912     }
5913     return V[0];
5914   }
5915   return SDValue();
5916 }
5917
5918 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
5919 // to create 256-bit vectors from two other 128-bit ones.
5920 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5921   SDLoc dl(Op);
5922   MVT ResVT = Op.getSimpleValueType();
5923
5924   assert((ResVT.is256BitVector() ||
5925           ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
5926
5927   SDValue V1 = Op.getOperand(0);
5928   SDValue V2 = Op.getOperand(1);
5929   unsigned NumElems = ResVT.getVectorNumElements();
5930   if (ResVT.is256BitVector())
5931     return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
5932
5933   if (Op.getNumOperands() == 4) {
5934     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
5935                                 ResVT.getVectorNumElements()/2);
5936     SDValue V3 = Op.getOperand(2);
5937     SDValue V4 = Op.getOperand(3);
5938     return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
5939       Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
5940   }
5941   return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
5942 }
5943
5944 static SDValue LowerCONCAT_VECTORSvXi1(SDValue Op,
5945                                        const X86Subtarget *Subtarget,
5946                                        SelectionDAG & DAG) {
5947   SDLoc dl(Op);
5948   MVT ResVT = Op.getSimpleValueType();
5949   unsigned NumOfOperands = Op.getNumOperands();
5950
5951   assert(isPowerOf2_32(NumOfOperands) &&
5952          "Unexpected number of operands in CONCAT_VECTORS");
5953
5954   if (NumOfOperands > 2) {
5955     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
5956                                   ResVT.getVectorNumElements()/2);
5957     SmallVector<SDValue, 2> Ops;
5958     for (unsigned i = 0; i < NumOfOperands/2; i++)
5959       Ops.push_back(Op.getOperand(i));
5960     SDValue Lo = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
5961     Ops.clear();
5962     for (unsigned i = NumOfOperands/2; i < NumOfOperands; i++)
5963       Ops.push_back(Op.getOperand(i));
5964     SDValue Hi = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
5965     return DAG.getNode(ISD::CONCAT_VECTORS, dl, ResVT, Lo, Hi);
5966   }
5967
5968   SDValue V1 = Op.getOperand(0);
5969   SDValue V2 = Op.getOperand(1);
5970   bool IsZeroV1 = ISD::isBuildVectorAllZeros(V1.getNode());
5971   bool IsZeroV2 = ISD::isBuildVectorAllZeros(V2.getNode());
5972
5973   if (IsZeroV1 && IsZeroV2)
5974     return getZeroVector(ResVT, Subtarget, DAG, dl);
5975
5976   SDValue ZeroIdx = DAG.getIntPtrConstant(0);
5977   SDValue Undef = DAG.getUNDEF(ResVT);
5978   unsigned NumElems = ResVT.getVectorNumElements();
5979   SDValue ShiftBits = DAG.getConstant(NumElems/2, MVT::i8);
5980
5981   V2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V2, ZeroIdx);
5982   V2 = DAG.getNode(X86ISD::VSHLI, dl, ResVT, V2, ShiftBits);
5983   if (IsZeroV1)
5984     return V2;
5985
5986   V1 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V1, ZeroIdx);
5987   // Zero the upper bits of V1
5988   V1 = DAG.getNode(X86ISD::VSHLI, dl, ResVT, V1, ShiftBits);
5989   V1 = DAG.getNode(X86ISD::VSRLI, dl, ResVT, V1, ShiftBits);
5990   if (IsZeroV2)
5991     return V1;
5992   return DAG.getNode(ISD::OR, dl, ResVT, V1, V2);
5993 }
5994
5995 static SDValue LowerCONCAT_VECTORS(SDValue Op,
5996                                    const X86Subtarget *Subtarget,
5997                                    SelectionDAG &DAG) {
5998   MVT VT = Op.getSimpleValueType();
5999   if (VT.getVectorElementType() == MVT::i1)
6000     return LowerCONCAT_VECTORSvXi1(Op, Subtarget, DAG);
6001
6002   assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6003          (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6004           Op.getNumOperands() == 4)));
6005
6006   // AVX can use the vinsertf128 instruction to create 256-bit vectors
6007   // from two other 128-bit ones.
6008
6009   // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6010   return LowerAVXCONCAT_VECTORS(Op, DAG);
6011 }
6012
6013
6014 //===----------------------------------------------------------------------===//
6015 // Vector shuffle lowering
6016 //
6017 // This is an experimental code path for lowering vector shuffles on x86. It is
6018 // designed to handle arbitrary vector shuffles and blends, gracefully
6019 // degrading performance as necessary. It works hard to recognize idiomatic
6020 // shuffles and lower them to optimal instruction patterns without leaving
6021 // a framework that allows reasonably efficient handling of all vector shuffle
6022 // patterns.
6023 //===----------------------------------------------------------------------===//
6024
6025 /// \brief Tiny helper function to identify a no-op mask.
6026 ///
6027 /// This is a somewhat boring predicate function. It checks whether the mask
6028 /// array input, which is assumed to be a single-input shuffle mask of the kind
6029 /// used by the X86 shuffle instructions (not a fully general
6030 /// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
6031 /// in-place shuffle are 'no-op's.
6032 static bool isNoopShuffleMask(ArrayRef<int> Mask) {
6033   for (int i = 0, Size = Mask.size(); i < Size; ++i)
6034     if (Mask[i] != -1 && Mask[i] != i)
6035       return false;
6036   return true;
6037 }
6038
6039 /// \brief Helper function to classify a mask as a single-input mask.
6040 ///
6041 /// This isn't a generic single-input test because in the vector shuffle
6042 /// lowering we canonicalize single inputs to be the first input operand. This
6043 /// means we can more quickly test for a single input by only checking whether
6044 /// an input from the second operand exists. We also assume that the size of
6045 /// mask corresponds to the size of the input vectors which isn't true in the
6046 /// fully general case.
6047 static bool isSingleInputShuffleMask(ArrayRef<int> Mask) {
6048   for (int M : Mask)
6049     if (M >= (int)Mask.size())
6050       return false;
6051   return true;
6052 }
6053
6054 /// \brief Test whether there are elements crossing 128-bit lanes in this
6055 /// shuffle mask.
6056 ///
6057 /// X86 divides up its shuffles into in-lane and cross-lane shuffle operations
6058 /// and we routinely test for these.
6059 static bool is128BitLaneCrossingShuffleMask(MVT VT, ArrayRef<int> Mask) {
6060   int LaneSize = 128 / VT.getScalarSizeInBits();
6061   int Size = Mask.size();
6062   for (int i = 0; i < Size; ++i)
6063     if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
6064       return true;
6065   return false;
6066 }
6067
6068 /// \brief Test whether a shuffle mask is equivalent within each 128-bit lane.
6069 ///
6070 /// This checks a shuffle mask to see if it is performing the same
6071 /// 128-bit lane-relative shuffle in each 128-bit lane. This trivially implies
6072 /// that it is also not lane-crossing. It may however involve a blend from the
6073 /// same lane of a second vector.
6074 ///
6075 /// The specific repeated shuffle mask is populated in \p RepeatedMask, as it is
6076 /// non-trivial to compute in the face of undef lanes. The representation is
6077 /// *not* suitable for use with existing 128-bit shuffles as it will contain
6078 /// entries from both V1 and V2 inputs to the wider mask.
6079 static bool
6080 is128BitLaneRepeatedShuffleMask(MVT VT, ArrayRef<int> Mask,
6081                                 SmallVectorImpl<int> &RepeatedMask) {
6082   int LaneSize = 128 / VT.getScalarSizeInBits();
6083   RepeatedMask.resize(LaneSize, -1);
6084   int Size = Mask.size();
6085   for (int i = 0; i < Size; ++i) {
6086     if (Mask[i] < 0)
6087       continue;
6088     if ((Mask[i] % Size) / LaneSize != i / LaneSize)
6089       // This entry crosses lanes, so there is no way to model this shuffle.
6090       return false;
6091
6092     // Ok, handle the in-lane shuffles by detecting if and when they repeat.
6093     if (RepeatedMask[i % LaneSize] == -1)
6094       // This is the first non-undef entry in this slot of a 128-bit lane.
6095       RepeatedMask[i % LaneSize] =
6096           Mask[i] < Size ? Mask[i] % LaneSize : Mask[i] % LaneSize + Size;
6097     else if (RepeatedMask[i % LaneSize] + (i / LaneSize) * LaneSize != Mask[i])
6098       // Found a mismatch with the repeated mask.
6099       return false;
6100   }
6101   return true;
6102 }
6103
6104 /// \brief Checks whether a shuffle mask is equivalent to an explicit list of
6105 /// arguments.
6106 ///
6107 /// This is a fast way to test a shuffle mask against a fixed pattern:
6108 ///
6109 ///   if (isShuffleEquivalent(Mask, 3, 2, {1, 0})) { ... }
6110 ///
6111 /// It returns true if the mask is exactly as wide as the argument list, and
6112 /// each element of the mask is either -1 (signifying undef) or the value given
6113 /// in the argument.
6114 static bool isShuffleEquivalent(SDValue V1, SDValue V2, ArrayRef<int> Mask,
6115                                 ArrayRef<int> ExpectedMask) {
6116   if (Mask.size() != ExpectedMask.size())
6117     return false;
6118
6119   int Size = Mask.size();
6120
6121   // If the values are build vectors, we can look through them to find
6122   // equivalent inputs that make the shuffles equivalent.
6123   auto *BV1 = dyn_cast<BuildVectorSDNode>(V1);
6124   auto *BV2 = dyn_cast<BuildVectorSDNode>(V2);
6125
6126   for (int i = 0; i < Size; ++i)
6127     if (Mask[i] != -1 && Mask[i] != ExpectedMask[i]) {
6128       auto *MaskBV = Mask[i] < Size ? BV1 : BV2;
6129       auto *ExpectedBV = ExpectedMask[i] < Size ? BV1 : BV2;
6130       if (!MaskBV || !ExpectedBV ||
6131           MaskBV->getOperand(Mask[i] % Size) !=
6132               ExpectedBV->getOperand(ExpectedMask[i] % Size))
6133         return false;
6134     }
6135
6136   return true;
6137 }
6138
6139 /// \brief Get a 4-lane 8-bit shuffle immediate for a mask.
6140 ///
6141 /// This helper function produces an 8-bit shuffle immediate corresponding to
6142 /// the ubiquitous shuffle encoding scheme used in x86 instructions for
6143 /// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
6144 /// example.
6145 ///
6146 /// NB: We rely heavily on "undef" masks preserving the input lane.
6147 static SDValue getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask,
6148                                           SelectionDAG &DAG) {
6149   assert(Mask.size() == 4 && "Only 4-lane shuffle masks");
6150   assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!");
6151   assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!");
6152   assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!");
6153   assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!");
6154
6155   unsigned Imm = 0;
6156   Imm |= (Mask[0] == -1 ? 0 : Mask[0]) << 0;
6157   Imm |= (Mask[1] == -1 ? 1 : Mask[1]) << 2;
6158   Imm |= (Mask[2] == -1 ? 2 : Mask[2]) << 4;
6159   Imm |= (Mask[3] == -1 ? 3 : Mask[3]) << 6;
6160   return DAG.getConstant(Imm, MVT::i8);
6161 }
6162
6163 /// \brief Try to emit a blend instruction for a shuffle using bit math.
6164 ///
6165 /// This is used as a fallback approach when first class blend instructions are
6166 /// unavailable. Currently it is only suitable for integer vectors, but could
6167 /// be generalized for floating point vectors if desirable.
6168 static SDValue lowerVectorShuffleAsBitBlend(SDLoc DL, MVT VT, SDValue V1,
6169                                             SDValue V2, ArrayRef<int> Mask,
6170                                             SelectionDAG &DAG) {
6171   assert(VT.isInteger() && "Only supports integer vector types!");
6172   MVT EltVT = VT.getScalarType();
6173   int NumEltBits = EltVT.getSizeInBits();
6174   SDValue Zero = DAG.getConstant(0, EltVT);
6175   SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), EltVT);
6176   SmallVector<SDValue, 16> MaskOps;
6177   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6178     if (Mask[i] != -1 && Mask[i] != i && Mask[i] != i + Size)
6179       return SDValue(); // Shuffled input!
6180     MaskOps.push_back(Mask[i] < Size ? AllOnes : Zero);
6181   }
6182
6183   SDValue V1Mask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, MaskOps);
6184   V1 = DAG.getNode(ISD::AND, DL, VT, V1, V1Mask);
6185   // We have to cast V2 around.
6186   MVT MaskVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
6187   V2 = DAG.getNode(ISD::BITCAST, DL, VT,
6188                    DAG.getNode(X86ISD::ANDNP, DL, MaskVT,
6189                                DAG.getNode(ISD::BITCAST, DL, MaskVT, V1Mask),
6190                                DAG.getNode(ISD::BITCAST, DL, MaskVT, V2)));
6191   return DAG.getNode(ISD::OR, DL, VT, V1, V2);
6192 }
6193
6194 /// \brief Try to emit a blend instruction for a shuffle.
6195 ///
6196 /// This doesn't do any checks for the availability of instructions for blending
6197 /// these values. It relies on the availability of the X86ISD::BLENDI pattern to
6198 /// be matched in the backend with the type given. What it does check for is
6199 /// that the shuffle mask is in fact a blend.
6200 static SDValue lowerVectorShuffleAsBlend(SDLoc DL, MVT VT, SDValue V1,
6201                                          SDValue V2, ArrayRef<int> Mask,
6202                                          const X86Subtarget *Subtarget,
6203                                          SelectionDAG &DAG) {
6204   unsigned BlendMask = 0;
6205   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6206     if (Mask[i] >= Size) {
6207       if (Mask[i] != i + Size)
6208         return SDValue(); // Shuffled V2 input!
6209       BlendMask |= 1u << i;
6210       continue;
6211     }
6212     if (Mask[i] >= 0 && Mask[i] != i)
6213       return SDValue(); // Shuffled V1 input!
6214   }
6215   switch (VT.SimpleTy) {
6216   case MVT::v2f64:
6217   case MVT::v4f32:
6218   case MVT::v4f64:
6219   case MVT::v8f32:
6220     return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V2,
6221                        DAG.getConstant(BlendMask, MVT::i8));
6222
6223   case MVT::v4i64:
6224   case MVT::v8i32:
6225     assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6226     // FALLTHROUGH
6227   case MVT::v2i64:
6228   case MVT::v4i32:
6229     // If we have AVX2 it is faster to use VPBLENDD when the shuffle fits into
6230     // that instruction.
6231     if (Subtarget->hasAVX2()) {
6232       // Scale the blend by the number of 32-bit dwords per element.
6233       int Scale =  VT.getScalarSizeInBits() / 32;
6234       BlendMask = 0;
6235       for (int i = 0, Size = Mask.size(); i < Size; ++i)
6236         if (Mask[i] >= Size)
6237           for (int j = 0; j < Scale; ++j)
6238             BlendMask |= 1u << (i * Scale + j);
6239
6240       MVT BlendVT = VT.getSizeInBits() > 128 ? MVT::v8i32 : MVT::v4i32;
6241       V1 = DAG.getNode(ISD::BITCAST, DL, BlendVT, V1);
6242       V2 = DAG.getNode(ISD::BITCAST, DL, BlendVT, V2);
6243       return DAG.getNode(ISD::BITCAST, DL, VT,
6244                          DAG.getNode(X86ISD::BLENDI, DL, BlendVT, V1, V2,
6245                                      DAG.getConstant(BlendMask, MVT::i8)));
6246     }
6247     // FALLTHROUGH
6248   case MVT::v8i16: {
6249     // For integer shuffles we need to expand the mask and cast the inputs to
6250     // v8i16s prior to blending.
6251     int Scale = 8 / VT.getVectorNumElements();
6252     BlendMask = 0;
6253     for (int i = 0, Size = Mask.size(); i < Size; ++i)
6254       if (Mask[i] >= Size)
6255         for (int j = 0; j < Scale; ++j)
6256           BlendMask |= 1u << (i * Scale + j);
6257
6258     V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1);
6259     V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V2);
6260     return DAG.getNode(ISD::BITCAST, DL, VT,
6261                        DAG.getNode(X86ISD::BLENDI, DL, MVT::v8i16, V1, V2,
6262                                    DAG.getConstant(BlendMask, MVT::i8)));
6263   }
6264
6265   case MVT::v16i16: {
6266     assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6267     SmallVector<int, 8> RepeatedMask;
6268     if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
6269       // We can lower these with PBLENDW which is mirrored across 128-bit lanes.
6270       assert(RepeatedMask.size() == 8 && "Repeated mask size doesn't match!");
6271       BlendMask = 0;
6272       for (int i = 0; i < 8; ++i)
6273         if (RepeatedMask[i] >= 16)
6274           BlendMask |= 1u << i;
6275       return DAG.getNode(X86ISD::BLENDI, DL, MVT::v16i16, V1, V2,
6276                          DAG.getConstant(BlendMask, MVT::i8));
6277     }
6278   }
6279     // FALLTHROUGH
6280   case MVT::v16i8:
6281   case MVT::v32i8: {
6282     assert((VT.getSizeInBits() == 128 || Subtarget->hasAVX2()) &&
6283            "256-bit byte-blends require AVX2 support!");
6284
6285     // Scale the blend by the number of bytes per element.
6286     int Scale = VT.getScalarSizeInBits() / 8;
6287
6288     // This form of blend is always done on bytes. Compute the byte vector
6289     // type.
6290     MVT BlendVT = MVT::getVectorVT(MVT::i8, VT.getSizeInBits() / 8);
6291
6292     // Compute the VSELECT mask. Note that VSELECT is really confusing in the
6293     // mix of LLVM's code generator and the x86 backend. We tell the code
6294     // generator that boolean values in the elements of an x86 vector register
6295     // are -1 for true and 0 for false. We then use the LLVM semantics of 'true'
6296     // mapping a select to operand #1, and 'false' mapping to operand #2. The
6297     // reality in x86 is that vector masks (pre-AVX-512) use only the high bit
6298     // of the element (the remaining are ignored) and 0 in that high bit would
6299     // mean operand #1 while 1 in the high bit would mean operand #2. So while
6300     // the LLVM model for boolean values in vector elements gets the relevant
6301     // bit set, it is set backwards and over constrained relative to x86's
6302     // actual model.
6303     SmallVector<SDValue, 32> VSELECTMask;
6304     for (int i = 0, Size = Mask.size(); i < Size; ++i)
6305       for (int j = 0; j < Scale; ++j)
6306         VSELECTMask.push_back(
6307             Mask[i] < 0 ? DAG.getUNDEF(MVT::i8)
6308                         : DAG.getConstant(Mask[i] < Size ? -1 : 0, MVT::i8));
6309
6310     V1 = DAG.getNode(ISD::BITCAST, DL, BlendVT, V1);
6311     V2 = DAG.getNode(ISD::BITCAST, DL, BlendVT, V2);
6312     return DAG.getNode(
6313         ISD::BITCAST, DL, VT,
6314         DAG.getNode(ISD::VSELECT, DL, BlendVT,
6315                     DAG.getNode(ISD::BUILD_VECTOR, DL, BlendVT, VSELECTMask),
6316                     V1, V2));
6317   }
6318
6319   default:
6320     llvm_unreachable("Not a supported integer vector type!");
6321   }
6322 }
6323
6324 /// \brief Try to lower as a blend of elements from two inputs followed by
6325 /// a single-input permutation.
6326 ///
6327 /// This matches the pattern where we can blend elements from two inputs and
6328 /// then reduce the shuffle to a single-input permutation.
6329 static SDValue lowerVectorShuffleAsBlendAndPermute(SDLoc DL, MVT VT, SDValue V1,
6330                                                    SDValue V2,
6331                                                    ArrayRef<int> Mask,
6332                                                    SelectionDAG &DAG) {
6333   // We build up the blend mask while checking whether a blend is a viable way
6334   // to reduce the shuffle.
6335   SmallVector<int, 32> BlendMask(Mask.size(), -1);
6336   SmallVector<int, 32> PermuteMask(Mask.size(), -1);
6337
6338   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6339     if (Mask[i] < 0)
6340       continue;
6341
6342     assert(Mask[i] < Size * 2 && "Shuffle input is out of bounds.");
6343
6344     if (BlendMask[Mask[i] % Size] == -1)
6345       BlendMask[Mask[i] % Size] = Mask[i];
6346     else if (BlendMask[Mask[i] % Size] != Mask[i])
6347       return SDValue(); // Can't blend in the needed input!
6348
6349     PermuteMask[i] = Mask[i] % Size;
6350   }
6351
6352   SDValue V = DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
6353   return DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), PermuteMask);
6354 }
6355
6356 /// \brief Generic routine to decompose a shuffle and blend into indepndent
6357 /// blends and permutes.
6358 ///
6359 /// This matches the extremely common pattern for handling combined
6360 /// shuffle+blend operations on newer X86 ISAs where we have very fast blend
6361 /// operations. It will try to pick the best arrangement of shuffles and
6362 /// blends.
6363 static SDValue lowerVectorShuffleAsDecomposedShuffleBlend(SDLoc DL, MVT VT,
6364                                                           SDValue V1,
6365                                                           SDValue V2,
6366                                                           ArrayRef<int> Mask,
6367                                                           SelectionDAG &DAG) {
6368   // Shuffle the input elements into the desired positions in V1 and V2 and
6369   // blend them together.
6370   SmallVector<int, 32> V1Mask(Mask.size(), -1);
6371   SmallVector<int, 32> V2Mask(Mask.size(), -1);
6372   SmallVector<int, 32> BlendMask(Mask.size(), -1);
6373   for (int i = 0, Size = Mask.size(); i < Size; ++i)
6374     if (Mask[i] >= 0 && Mask[i] < Size) {
6375       V1Mask[i] = Mask[i];
6376       BlendMask[i] = i;
6377     } else if (Mask[i] >= Size) {
6378       V2Mask[i] = Mask[i] - Size;
6379       BlendMask[i] = i + Size;
6380     }
6381
6382   // Try to lower with the simpler initial blend strategy unless one of the
6383   // input shuffles would be a no-op. We prefer to shuffle inputs as the
6384   // shuffle may be able to fold with a load or other benefit. However, when
6385   // we'll have to do 2x as many shuffles in order to achieve this, blending
6386   // first is a better strategy.
6387   if (!isNoopShuffleMask(V1Mask) && !isNoopShuffleMask(V2Mask))
6388     if (SDValue BlendPerm =
6389             lowerVectorShuffleAsBlendAndPermute(DL, VT, V1, V2, Mask, DAG))
6390       return BlendPerm;
6391
6392   V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
6393   V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
6394   return DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
6395 }
6396
6397 /// \brief Try to lower a vector shuffle as a byte rotation.
6398 ///
6399 /// SSSE3 has a generic PALIGNR instruction in x86 that will do an arbitrary
6400 /// byte-rotation of the concatenation of two vectors; pre-SSSE3 can use
6401 /// a PSRLDQ/PSLLDQ/POR pattern to get a similar effect. This routine will
6402 /// try to generically lower a vector shuffle through such an pattern. It
6403 /// does not check for the profitability of lowering either as PALIGNR or
6404 /// PSRLDQ/PSLLDQ/POR, only whether the mask is valid to lower in that form.
6405 /// This matches shuffle vectors that look like:
6406 ///
6407 ///   v8i16 [11, 12, 13, 14, 15, 0, 1, 2]
6408 ///
6409 /// Essentially it concatenates V1 and V2, shifts right by some number of
6410 /// elements, and takes the low elements as the result. Note that while this is
6411 /// specified as a *right shift* because x86 is little-endian, it is a *left
6412 /// rotate* of the vector lanes.
6413 static SDValue lowerVectorShuffleAsByteRotate(SDLoc DL, MVT VT, SDValue V1,
6414                                               SDValue V2,
6415                                               ArrayRef<int> Mask,
6416                                               const X86Subtarget *Subtarget,
6417                                               SelectionDAG &DAG) {
6418   assert(!isNoopShuffleMask(Mask) && "We shouldn't lower no-op shuffles!");
6419
6420   int NumElts = Mask.size();
6421   int NumLanes = VT.getSizeInBits() / 128;
6422   int NumLaneElts = NumElts / NumLanes;
6423
6424   // We need to detect various ways of spelling a rotation:
6425   //   [11, 12, 13, 14, 15,  0,  1,  2]
6426   //   [-1, 12, 13, 14, -1, -1,  1, -1]
6427   //   [-1, -1, -1, -1, -1, -1,  1,  2]
6428   //   [ 3,  4,  5,  6,  7,  8,  9, 10]
6429   //   [-1,  4,  5,  6, -1, -1,  9, -1]
6430   //   [-1,  4,  5,  6, -1, -1, -1, -1]
6431   int Rotation = 0;
6432   SDValue Lo, Hi;
6433   for (int l = 0; l < NumElts; l += NumLaneElts) {
6434     for (int i = 0; i < NumLaneElts; ++i) {
6435       if (Mask[l + i] == -1)
6436         continue;
6437       assert(Mask[l + i] >= 0 && "Only -1 is a valid negative mask element!");
6438
6439       // Get the mod-Size index and lane correct it.
6440       int LaneIdx = (Mask[l + i] % NumElts) - l;
6441       // Make sure it was in this lane.
6442       if (LaneIdx < 0 || LaneIdx >= NumLaneElts)
6443         return SDValue();
6444
6445       // Determine where a rotated vector would have started.
6446       int StartIdx = i - LaneIdx;
6447       if (StartIdx == 0)
6448         // The identity rotation isn't interesting, stop.
6449         return SDValue();
6450
6451       // If we found the tail of a vector the rotation must be the missing
6452       // front. If we found the head of a vector, it must be how much of the
6453       // head.
6454       int CandidateRotation = StartIdx < 0 ? -StartIdx : NumLaneElts - StartIdx;
6455
6456       if (Rotation == 0)
6457         Rotation = CandidateRotation;
6458       else if (Rotation != CandidateRotation)
6459         // The rotations don't match, so we can't match this mask.
6460         return SDValue();
6461
6462       // Compute which value this mask is pointing at.
6463       SDValue MaskV = Mask[l + i] < NumElts ? V1 : V2;
6464
6465       // Compute which of the two target values this index should be assigned
6466       // to. This reflects whether the high elements are remaining or the low
6467       // elements are remaining.
6468       SDValue &TargetV = StartIdx < 0 ? Hi : Lo;
6469
6470       // Either set up this value if we've not encountered it before, or check
6471       // that it remains consistent.
6472       if (!TargetV)
6473         TargetV = MaskV;
6474       else if (TargetV != MaskV)
6475         // This may be a rotation, but it pulls from the inputs in some
6476         // unsupported interleaving.
6477         return SDValue();
6478     }
6479   }
6480
6481   // Check that we successfully analyzed the mask, and normalize the results.
6482   assert(Rotation != 0 && "Failed to locate a viable rotation!");
6483   assert((Lo || Hi) && "Failed to find a rotated input vector!");
6484   if (!Lo)
6485     Lo = Hi;
6486   else if (!Hi)
6487     Hi = Lo;
6488
6489   // The actual rotate instruction rotates bytes, so we need to scale the
6490   // rotation based on how many bytes are in the vector lane.
6491   int Scale = 16 / NumLaneElts;
6492
6493   // SSSE3 targets can use the palignr instruction.
6494   if (Subtarget->hasSSSE3()) {
6495     // Cast the inputs to i8 vector of correct length to match PALIGNR.
6496     MVT AlignVT = MVT::getVectorVT(MVT::i8, 16 * NumLanes);
6497     Lo = DAG.getNode(ISD::BITCAST, DL, AlignVT, Lo);
6498     Hi = DAG.getNode(ISD::BITCAST, DL, AlignVT, Hi);
6499
6500     return DAG.getNode(ISD::BITCAST, DL, VT,
6501                        DAG.getNode(X86ISD::PALIGNR, DL, AlignVT, Hi, Lo,
6502                                    DAG.getConstant(Rotation * Scale, MVT::i8)));
6503   }
6504
6505   assert(VT.getSizeInBits() == 128 &&
6506          "Rotate-based lowering only supports 128-bit lowering!");
6507   assert(Mask.size() <= 16 &&
6508          "Can shuffle at most 16 bytes in a 128-bit vector!");
6509
6510   // Default SSE2 implementation
6511   int LoByteShift = 16 - Rotation * Scale;
6512   int HiByteShift = Rotation * Scale;
6513
6514   // Cast the inputs to v2i64 to match PSLLDQ/PSRLDQ.
6515   Lo = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Lo);
6516   Hi = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Hi);
6517
6518   SDValue LoShift = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v2i64, Lo,
6519                                 DAG.getConstant(LoByteShift, MVT::i8));
6520   SDValue HiShift = DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v2i64, Hi,
6521                                 DAG.getConstant(HiByteShift, MVT::i8));
6522   return DAG.getNode(ISD::BITCAST, DL, VT,
6523                      DAG.getNode(ISD::OR, DL, MVT::v2i64, LoShift, HiShift));
6524 }
6525
6526 /// \brief Compute whether each element of a shuffle is zeroable.
6527 ///
6528 /// A "zeroable" vector shuffle element is one which can be lowered to zero.
6529 /// Either it is an undef element in the shuffle mask, the element of the input
6530 /// referenced is undef, or the element of the input referenced is known to be
6531 /// zero. Many x86 shuffles can zero lanes cheaply and we often want to handle
6532 /// as many lanes with this technique as possible to simplify the remaining
6533 /// shuffle.
6534 static SmallBitVector computeZeroableShuffleElements(ArrayRef<int> Mask,
6535                                                      SDValue V1, SDValue V2) {
6536   SmallBitVector Zeroable(Mask.size(), false);
6537
6538   while (V1.getOpcode() == ISD::BITCAST)
6539     V1 = V1->getOperand(0);
6540   while (V2.getOpcode() == ISD::BITCAST)
6541     V2 = V2->getOperand(0);
6542
6543   bool V1IsZero = ISD::isBuildVectorAllZeros(V1.getNode());
6544   bool V2IsZero = ISD::isBuildVectorAllZeros(V2.getNode());
6545
6546   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6547     int M = Mask[i];
6548     // Handle the easy cases.
6549     if (M < 0 || (M >= 0 && M < Size && V1IsZero) || (M >= Size && V2IsZero)) {
6550       Zeroable[i] = true;
6551       continue;
6552     }
6553
6554     // If this is an index into a build_vector node (which has the same number
6555     // of elements), dig out the input value and use it.
6556     SDValue V = M < Size ? V1 : V2;
6557     if (V.getOpcode() != ISD::BUILD_VECTOR || Size != (int)V.getNumOperands())
6558       continue;
6559
6560     SDValue Input = V.getOperand(M % Size);
6561     // The UNDEF opcode check really should be dead code here, but not quite
6562     // worth asserting on (it isn't invalid, just unexpected).
6563     if (Input.getOpcode() == ISD::UNDEF || X86::isZeroNode(Input))
6564       Zeroable[i] = true;
6565   }
6566
6567   return Zeroable;
6568 }
6569
6570 /// \brief Try to emit a bitmask instruction for a shuffle.
6571 ///
6572 /// This handles cases where we can model a blend exactly as a bitmask due to
6573 /// one of the inputs being zeroable.
6574 static SDValue lowerVectorShuffleAsBitMask(SDLoc DL, MVT VT, SDValue V1,
6575                                            SDValue V2, ArrayRef<int> Mask,
6576                                            SelectionDAG &DAG) {
6577   MVT EltVT = VT.getScalarType();
6578   int NumEltBits = EltVT.getSizeInBits();
6579   MVT IntEltVT = MVT::getIntegerVT(NumEltBits);
6580   SDValue Zero = DAG.getConstant(0, IntEltVT);
6581   SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), IntEltVT);
6582   if (EltVT.isFloatingPoint()) {
6583     Zero = DAG.getNode(ISD::BITCAST, DL, EltVT, Zero);
6584     AllOnes = DAG.getNode(ISD::BITCAST, DL, EltVT, AllOnes);
6585   }
6586   SmallVector<SDValue, 16> VMaskOps(Mask.size(), Zero);
6587   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6588   SDValue V;
6589   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6590     if (Zeroable[i])
6591       continue;
6592     if (Mask[i] % Size != i)
6593       return SDValue(); // Not a blend.
6594     if (!V)
6595       V = Mask[i] < Size ? V1 : V2;
6596     else if (V != (Mask[i] < Size ? V1 : V2))
6597       return SDValue(); // Can only let one input through the mask.
6598
6599     VMaskOps[i] = AllOnes;
6600   }
6601   if (!V)
6602     return SDValue(); // No non-zeroable elements!
6603
6604   SDValue VMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, VMaskOps);
6605   V = DAG.getNode(VT.isFloatingPoint()
6606                   ? (unsigned) X86ISD::FAND : (unsigned) ISD::AND,
6607                   DL, VT, V, VMask);
6608   return V;
6609 }
6610
6611 /// \brief Try to lower a vector shuffle as a bit shift (shifts in zeros).
6612 ///
6613 /// Attempts to match a shuffle mask against the PSLL(W/D/Q/DQ) and
6614 /// PSRL(W/D/Q/DQ) SSE2 and AVX2 logical bit-shift instructions. The function
6615 /// matches elements from one of the input vectors shuffled to the left or
6616 /// right with zeroable elements 'shifted in'. It handles both the strictly
6617 /// bit-wise element shifts and the byte shift across an entire 128-bit double
6618 /// quad word lane.
6619 ///
6620 /// PSHL : (little-endian) left bit shift.
6621 /// [ zz, 0, zz,  2 ]
6622 /// [ -1, 4, zz, -1 ]
6623 /// PSRL : (little-endian) right bit shift.
6624 /// [  1, zz,  3, zz]
6625 /// [ -1, -1,  7, zz]
6626 /// PSLLDQ : (little-endian) left byte shift
6627 /// [ zz,  0,  1,  2,  3,  4,  5,  6]
6628 /// [ zz, zz, -1, -1,  2,  3,  4, -1]
6629 /// [ zz, zz, zz, zz, zz, zz, -1,  1]
6630 /// PSRLDQ : (little-endian) right byte shift
6631 /// [  5, 6,  7, zz, zz, zz, zz, zz]
6632 /// [ -1, 5,  6,  7, zz, zz, zz, zz]
6633 /// [  1, 2, -1, -1, -1, -1, zz, zz]
6634 static SDValue lowerVectorShuffleAsShift(SDLoc DL, MVT VT, SDValue V1,
6635                                          SDValue V2, ArrayRef<int> Mask,
6636                                          SelectionDAG &DAG) {
6637   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6638
6639   int Size = Mask.size();
6640   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
6641
6642   auto CheckZeros = [&](int Shift, int Scale, bool Left) {
6643     for (int i = 0; i < Size; i += Scale)
6644       for (int j = 0; j < Shift; ++j)
6645         if (!Zeroable[i + j + (Left ? 0 : (Scale - Shift))])
6646           return false;
6647
6648     return true;
6649   };
6650
6651   auto MatchShift = [&](int Shift, int Scale, bool Left, SDValue V) {
6652     for (int i = 0; i != Size; i += Scale) {
6653       unsigned Pos = Left ? i + Shift : i;
6654       unsigned Low = Left ? i : i + Shift;
6655       unsigned Len = Scale - Shift;
6656       if (!isSequentialOrUndefInRange(Mask, Pos, Len,
6657                                       Low + (V == V1 ? 0 : Size)))
6658         return SDValue();
6659     }
6660
6661     int ShiftEltBits = VT.getScalarSizeInBits() * Scale;
6662     bool ByteShift = ShiftEltBits > 64;
6663     unsigned OpCode = Left ? (ByteShift ? X86ISD::VSHLDQ : X86ISD::VSHLI)
6664                            : (ByteShift ? X86ISD::VSRLDQ : X86ISD::VSRLI);
6665     int ShiftAmt = Shift * VT.getScalarSizeInBits() / (ByteShift ? 8 : 1);
6666
6667     // Normalize the scale for byte shifts to still produce an i64 element
6668     // type.
6669     Scale = ByteShift ? Scale / 2 : Scale;
6670
6671     // We need to round trip through the appropriate type for the shift.
6672     MVT ShiftSVT = MVT::getIntegerVT(VT.getScalarSizeInBits() * Scale);
6673     MVT ShiftVT = MVT::getVectorVT(ShiftSVT, Size / Scale);
6674     assert(DAG.getTargetLoweringInfo().isTypeLegal(ShiftVT) &&
6675            "Illegal integer vector type");
6676     V = DAG.getNode(ISD::BITCAST, DL, ShiftVT, V);
6677
6678     V = DAG.getNode(OpCode, DL, ShiftVT, V, DAG.getConstant(ShiftAmt, MVT::i8));
6679     return DAG.getNode(ISD::BITCAST, DL, VT, V);
6680   };
6681
6682   // SSE/AVX supports logical shifts up to 64-bit integers - so we can just
6683   // keep doubling the size of the integer elements up to that. We can
6684   // then shift the elements of the integer vector by whole multiples of
6685   // their width within the elements of the larger integer vector. Test each
6686   // multiple to see if we can find a match with the moved element indices
6687   // and that the shifted in elements are all zeroable.
6688   for (int Scale = 2; Scale * VT.getScalarSizeInBits() <= 128; Scale *= 2)
6689     for (int Shift = 1; Shift != Scale; ++Shift)
6690       for (bool Left : {true, false})
6691         if (CheckZeros(Shift, Scale, Left))
6692           for (SDValue V : {V1, V2})
6693             if (SDValue Match = MatchShift(Shift, Scale, Left, V))
6694               return Match;
6695
6696   // no match
6697   return SDValue();
6698 }
6699
6700 /// \brief Lower a vector shuffle as a zero or any extension.
6701 ///
6702 /// Given a specific number of elements, element bit width, and extension
6703 /// stride, produce either a zero or any extension based on the available
6704 /// features of the subtarget.
6705 static SDValue lowerVectorShuffleAsSpecificZeroOrAnyExtend(
6706     SDLoc DL, MVT VT, int Scale, bool AnyExt, SDValue InputV,
6707     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
6708   assert(Scale > 1 && "Need a scale to extend.");
6709   int NumElements = VT.getVectorNumElements();
6710   int EltBits = VT.getScalarSizeInBits();
6711   assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
6712          "Only 8, 16, and 32 bit elements can be extended.");
6713   assert(Scale * EltBits <= 64 && "Cannot zero extend past 64 bits.");
6714
6715   // Found a valid zext mask! Try various lowering strategies based on the
6716   // input type and available ISA extensions.
6717   if (Subtarget->hasSSE41()) {
6718     MVT ExtVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits * Scale),
6719                                  NumElements / Scale);
6720     return DAG.getNode(ISD::BITCAST, DL, VT,
6721                        DAG.getNode(X86ISD::VZEXT, DL, ExtVT, InputV));
6722   }
6723
6724   // For any extends we can cheat for larger element sizes and use shuffle
6725   // instructions that can fold with a load and/or copy.
6726   if (AnyExt && EltBits == 32) {
6727     int PSHUFDMask[4] = {0, -1, 1, -1};
6728     return DAG.getNode(
6729         ISD::BITCAST, DL, VT,
6730         DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
6731                     DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, InputV),
6732                     getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
6733   }
6734   if (AnyExt && EltBits == 16 && Scale > 2) {
6735     int PSHUFDMask[4] = {0, -1, 0, -1};
6736     InputV = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
6737                          DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, InputV),
6738                          getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG));
6739     int PSHUFHWMask[4] = {1, -1, -1, -1};
6740     return DAG.getNode(
6741         ISD::BITCAST, DL, VT,
6742         DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16,
6743                     DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, InputV),
6744                     getV4X86ShuffleImm8ForMask(PSHUFHWMask, DAG)));
6745   }
6746
6747   // If this would require more than 2 unpack instructions to expand, use
6748   // pshufb when available. We can only use more than 2 unpack instructions
6749   // when zero extending i8 elements which also makes it easier to use pshufb.
6750   if (Scale > 4 && EltBits == 8 && Subtarget->hasSSSE3()) {
6751     assert(NumElements == 16 && "Unexpected byte vector width!");
6752     SDValue PSHUFBMask[16];
6753     for (int i = 0; i < 16; ++i)
6754       PSHUFBMask[i] =
6755           DAG.getConstant((i % Scale == 0) ? i / Scale : 0x80, MVT::i8);
6756     InputV = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, InputV);
6757     return DAG.getNode(ISD::BITCAST, DL, VT,
6758                        DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, InputV,
6759                                    DAG.getNode(ISD::BUILD_VECTOR, DL,
6760                                                MVT::v16i8, PSHUFBMask)));
6761   }
6762
6763   // Otherwise emit a sequence of unpacks.
6764   do {
6765     MVT InputVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits), NumElements);
6766     SDValue Ext = AnyExt ? DAG.getUNDEF(InputVT)
6767                          : getZeroVector(InputVT, Subtarget, DAG, DL);
6768     InputV = DAG.getNode(ISD::BITCAST, DL, InputVT, InputV);
6769     InputV = DAG.getNode(X86ISD::UNPCKL, DL, InputVT, InputV, Ext);
6770     Scale /= 2;
6771     EltBits *= 2;
6772     NumElements /= 2;
6773   } while (Scale > 1);
6774   return DAG.getNode(ISD::BITCAST, DL, VT, InputV);
6775 }
6776
6777 /// \brief Try to lower a vector shuffle as a zero extension on any microarch.
6778 ///
6779 /// This routine will try to do everything in its power to cleverly lower
6780 /// a shuffle which happens to match the pattern of a zero extend. It doesn't
6781 /// check for the profitability of this lowering,  it tries to aggressively
6782 /// match this pattern. It will use all of the micro-architectural details it
6783 /// can to emit an efficient lowering. It handles both blends with all-zero
6784 /// inputs to explicitly zero-extend and undef-lanes (sometimes undef due to
6785 /// masking out later).
6786 ///
6787 /// The reason we have dedicated lowering for zext-style shuffles is that they
6788 /// are both incredibly common and often quite performance sensitive.
6789 static SDValue lowerVectorShuffleAsZeroOrAnyExtend(
6790     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
6791     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
6792   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6793
6794   int Bits = VT.getSizeInBits();
6795   int NumElements = VT.getVectorNumElements();
6796   assert(VT.getScalarSizeInBits() <= 32 &&
6797          "Exceeds 32-bit integer zero extension limit");
6798   assert((int)Mask.size() == NumElements && "Unexpected shuffle mask size");
6799
6800   // Define a helper function to check a particular ext-scale and lower to it if
6801   // valid.
6802   auto Lower = [&](int Scale) -> SDValue {
6803     SDValue InputV;
6804     bool AnyExt = true;
6805     for (int i = 0; i < NumElements; ++i) {
6806       if (Mask[i] == -1)
6807         continue; // Valid anywhere but doesn't tell us anything.
6808       if (i % Scale != 0) {
6809         // Each of the extended elements need to be zeroable.
6810         if (!Zeroable[i])
6811           return SDValue();
6812
6813         // We no longer are in the anyext case.
6814         AnyExt = false;
6815         continue;
6816       }
6817
6818       // Each of the base elements needs to be consecutive indices into the
6819       // same input vector.
6820       SDValue V = Mask[i] < NumElements ? V1 : V2;
6821       if (!InputV)
6822         InputV = V;
6823       else if (InputV != V)
6824         return SDValue(); // Flip-flopping inputs.
6825
6826       if (Mask[i] % NumElements != i / Scale)
6827         return SDValue(); // Non-consecutive strided elements.
6828     }
6829
6830     // If we fail to find an input, we have a zero-shuffle which should always
6831     // have already been handled.
6832     // FIXME: Maybe handle this here in case during blending we end up with one?
6833     if (!InputV)
6834       return SDValue();
6835
6836     return lowerVectorShuffleAsSpecificZeroOrAnyExtend(
6837         DL, VT, Scale, AnyExt, InputV, Subtarget, DAG);
6838   };
6839
6840   // The widest scale possible for extending is to a 64-bit integer.
6841   assert(Bits % 64 == 0 &&
6842          "The number of bits in a vector must be divisible by 64 on x86!");
6843   int NumExtElements = Bits / 64;
6844
6845   // Each iteration, try extending the elements half as much, but into twice as
6846   // many elements.
6847   for (; NumExtElements < NumElements; NumExtElements *= 2) {
6848     assert(NumElements % NumExtElements == 0 &&
6849            "The input vector size must be divisible by the extended size.");
6850     if (SDValue V = Lower(NumElements / NumExtElements))
6851       return V;
6852   }
6853
6854   // General extends failed, but 128-bit vectors may be able to use MOVQ.
6855   if (Bits != 128)
6856     return SDValue();
6857
6858   // Returns one of the source operands if the shuffle can be reduced to a
6859   // MOVQ, copying the lower 64-bits and zero-extending to the upper 64-bits.
6860   auto CanZExtLowHalf = [&]() {
6861     for (int i = NumElements / 2; i != NumElements; ++i)
6862       if (!Zeroable[i])
6863         return SDValue();
6864     if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, 0))
6865       return V1;
6866     if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, NumElements))
6867       return V2;
6868     return SDValue();
6869   };
6870
6871   if (SDValue V = CanZExtLowHalf()) {
6872     V = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, V);
6873     V = DAG.getNode(X86ISD::VZEXT_MOVL, DL, MVT::v2i64, V);
6874     return DAG.getNode(ISD::BITCAST, DL, VT, V);
6875   }
6876
6877   // No viable ext lowering found.
6878   return SDValue();
6879 }
6880
6881 /// \brief Try to get a scalar value for a specific element of a vector.
6882 ///
6883 /// Looks through BUILD_VECTOR and SCALAR_TO_VECTOR nodes to find a scalar.
6884 static SDValue getScalarValueForVectorElement(SDValue V, int Idx,
6885                                               SelectionDAG &DAG) {
6886   MVT VT = V.getSimpleValueType();
6887   MVT EltVT = VT.getVectorElementType();
6888   while (V.getOpcode() == ISD::BITCAST)
6889     V = V.getOperand(0);
6890   // If the bitcasts shift the element size, we can't extract an equivalent
6891   // element from it.
6892   MVT NewVT = V.getSimpleValueType();
6893   if (!NewVT.isVector() || NewVT.getScalarSizeInBits() != VT.getScalarSizeInBits())
6894     return SDValue();
6895
6896   if (V.getOpcode() == ISD::BUILD_VECTOR ||
6897       (Idx == 0 && V.getOpcode() == ISD::SCALAR_TO_VECTOR))
6898     return DAG.getNode(ISD::BITCAST, SDLoc(V), EltVT, V.getOperand(Idx));
6899
6900   return SDValue();
6901 }
6902
6903 /// \brief Helper to test for a load that can be folded with x86 shuffles.
6904 ///
6905 /// This is particularly important because the set of instructions varies
6906 /// significantly based on whether the operand is a load or not.
6907 static bool isShuffleFoldableLoad(SDValue V) {
6908   while (V.getOpcode() == ISD::BITCAST)
6909     V = V.getOperand(0);
6910
6911   return ISD::isNON_EXTLoad(V.getNode());
6912 }
6913
6914 /// \brief Try to lower insertion of a single element into a zero vector.
6915 ///
6916 /// This is a common pattern that we have especially efficient patterns to lower
6917 /// across all subtarget feature sets.
6918 static SDValue lowerVectorShuffleAsElementInsertion(
6919     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
6920     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
6921   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6922   MVT ExtVT = VT;
6923   MVT EltVT = VT.getVectorElementType();
6924
6925   int V2Index = std::find_if(Mask.begin(), Mask.end(),
6926                              [&Mask](int M) { return M >= (int)Mask.size(); }) -
6927                 Mask.begin();
6928   bool IsV1Zeroable = true;
6929   for (int i = 0, Size = Mask.size(); i < Size; ++i)
6930     if (i != V2Index && !Zeroable[i]) {
6931       IsV1Zeroable = false;
6932       break;
6933     }
6934
6935   // Check for a single input from a SCALAR_TO_VECTOR node.
6936   // FIXME: All of this should be canonicalized into INSERT_VECTOR_ELT and
6937   // all the smarts here sunk into that routine. However, the current
6938   // lowering of BUILD_VECTOR makes that nearly impossible until the old
6939   // vector shuffle lowering is dead.
6940   if (SDValue V2S = getScalarValueForVectorElement(
6941           V2, Mask[V2Index] - Mask.size(), DAG)) {
6942     // We need to zext the scalar if it is smaller than an i32.
6943     V2S = DAG.getNode(ISD::BITCAST, DL, EltVT, V2S);
6944     if (EltVT == MVT::i8 || EltVT == MVT::i16) {
6945       // Using zext to expand a narrow element won't work for non-zero
6946       // insertions.
6947       if (!IsV1Zeroable)
6948         return SDValue();
6949
6950       // Zero-extend directly to i32.
6951       ExtVT = MVT::v4i32;
6952       V2S = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, V2S);
6953     }
6954     V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, ExtVT, V2S);
6955   } else if (Mask[V2Index] != (int)Mask.size() || EltVT == MVT::i8 ||
6956              EltVT == MVT::i16) {
6957     // Either not inserting from the low element of the input or the input
6958     // element size is too small to use VZEXT_MOVL to clear the high bits.
6959     return SDValue();
6960   }
6961
6962   if (!IsV1Zeroable) {
6963     // If V1 can't be treated as a zero vector we have fewer options to lower
6964     // this. We can't support integer vectors or non-zero targets cheaply, and
6965     // the V1 elements can't be permuted in any way.
6966     assert(VT == ExtVT && "Cannot change extended type when non-zeroable!");
6967     if (!VT.isFloatingPoint() || V2Index != 0)
6968       return SDValue();
6969     SmallVector<int, 8> V1Mask(Mask.begin(), Mask.end());
6970     V1Mask[V2Index] = -1;
6971     if (!isNoopShuffleMask(V1Mask))
6972       return SDValue();
6973     // This is essentially a special case blend operation, but if we have
6974     // general purpose blend operations, they are always faster. Bail and let
6975     // the rest of the lowering handle these as blends.
6976     if (Subtarget->hasSSE41())
6977       return SDValue();
6978
6979     // Otherwise, use MOVSD or MOVSS.
6980     assert((EltVT == MVT::f32 || EltVT == MVT::f64) &&
6981            "Only two types of floating point element types to handle!");
6982     return DAG.getNode(EltVT == MVT::f32 ? X86ISD::MOVSS : X86ISD::MOVSD, DL,
6983                        ExtVT, V1, V2);
6984   }
6985
6986   // This lowering only works for the low element with floating point vectors.
6987   if (VT.isFloatingPoint() && V2Index != 0)
6988     return SDValue();
6989
6990   V2 = DAG.getNode(X86ISD::VZEXT_MOVL, DL, ExtVT, V2);
6991   if (ExtVT != VT)
6992     V2 = DAG.getNode(ISD::BITCAST, DL, VT, V2);
6993
6994   if (V2Index != 0) {
6995     // If we have 4 or fewer lanes we can cheaply shuffle the element into
6996     // the desired position. Otherwise it is more efficient to do a vector
6997     // shift left. We know that we can do a vector shift left because all
6998     // the inputs are zero.
6999     if (VT.isFloatingPoint() || VT.getVectorNumElements() <= 4) {
7000       SmallVector<int, 4> V2Shuffle(Mask.size(), 1);
7001       V2Shuffle[V2Index] = 0;
7002       V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Shuffle);
7003     } else {
7004       V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, V2);
7005       V2 = DAG.getNode(
7006           X86ISD::VSHLDQ, DL, MVT::v2i64, V2,
7007           DAG.getConstant(
7008               V2Index * EltVT.getSizeInBits()/8,
7009               DAG.getTargetLoweringInfo().getScalarShiftAmountTy(MVT::v2i64)));
7010       V2 = DAG.getNode(ISD::BITCAST, DL, VT, V2);
7011     }
7012   }
7013   return V2;
7014 }
7015
7016 /// \brief Try to lower broadcast of a single element.
7017 ///
7018 /// For convenience, this code also bundles all of the subtarget feature set
7019 /// filtering. While a little annoying to re-dispatch on type here, there isn't
7020 /// a convenient way to factor it out.
7021 static SDValue lowerVectorShuffleAsBroadcast(SDLoc DL, MVT VT, SDValue V,
7022                                              ArrayRef<int> Mask,
7023                                              const X86Subtarget *Subtarget,
7024                                              SelectionDAG &DAG) {
7025   if (!Subtarget->hasAVX())
7026     return SDValue();
7027   if (VT.isInteger() && !Subtarget->hasAVX2())
7028     return SDValue();
7029
7030   // Check that the mask is a broadcast.
7031   int BroadcastIdx = -1;
7032   for (int M : Mask)
7033     if (M >= 0 && BroadcastIdx == -1)
7034       BroadcastIdx = M;
7035     else if (M >= 0 && M != BroadcastIdx)
7036       return SDValue();
7037
7038   assert(BroadcastIdx < (int)Mask.size() && "We only expect to be called with "
7039                                             "a sorted mask where the broadcast "
7040                                             "comes from V1.");
7041
7042   // Go up the chain of (vector) values to find a scalar load that we can
7043   // combine with the broadcast.
7044   for (;;) {
7045     switch (V.getOpcode()) {
7046     case ISD::CONCAT_VECTORS: {
7047       int OperandSize = Mask.size() / V.getNumOperands();
7048       V = V.getOperand(BroadcastIdx / OperandSize);
7049       BroadcastIdx %= OperandSize;
7050       continue;
7051     }
7052
7053     case ISD::INSERT_SUBVECTOR: {
7054       SDValue VOuter = V.getOperand(0), VInner = V.getOperand(1);
7055       auto ConstantIdx = dyn_cast<ConstantSDNode>(V.getOperand(2));
7056       if (!ConstantIdx)
7057         break;
7058
7059       int BeginIdx = (int)ConstantIdx->getZExtValue();
7060       int EndIdx =
7061           BeginIdx + (int)VInner.getValueType().getVectorNumElements();
7062       if (BroadcastIdx >= BeginIdx && BroadcastIdx < EndIdx) {
7063         BroadcastIdx -= BeginIdx;
7064         V = VInner;
7065       } else {
7066         V = VOuter;
7067       }
7068       continue;
7069     }
7070     }
7071     break;
7072   }
7073
7074   // Check if this is a broadcast of a scalar. We special case lowering
7075   // for scalars so that we can more effectively fold with loads.
7076   if (V.getOpcode() == ISD::BUILD_VECTOR ||
7077       (V.getOpcode() == ISD::SCALAR_TO_VECTOR && BroadcastIdx == 0)) {
7078     V = V.getOperand(BroadcastIdx);
7079
7080     // If the scalar isn't a load, we can't broadcast from it in AVX1.
7081     // Only AVX2 has register broadcasts.
7082     if (!Subtarget->hasAVX2() && !isShuffleFoldableLoad(V))
7083       return SDValue();
7084   } else if (BroadcastIdx != 0 || !Subtarget->hasAVX2()) {
7085     // We can't broadcast from a vector register without AVX2, and we can only
7086     // broadcast from the zero-element of a vector register.
7087     return SDValue();
7088   }
7089
7090   return DAG.getNode(X86ISD::VBROADCAST, DL, VT, V);
7091 }
7092
7093 // Check for whether we can use INSERTPS to perform the shuffle. We only use
7094 // INSERTPS when the V1 elements are already in the correct locations
7095 // because otherwise we can just always use two SHUFPS instructions which
7096 // are much smaller to encode than a SHUFPS and an INSERTPS. We can also
7097 // perform INSERTPS if a single V1 element is out of place and all V2
7098 // elements are zeroable.
7099 static SDValue lowerVectorShuffleAsInsertPS(SDValue Op, SDValue V1, SDValue V2,
7100                                             ArrayRef<int> Mask,
7101                                             SelectionDAG &DAG) {
7102   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
7103   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7104   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7105   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7106
7107   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7108
7109   unsigned ZMask = 0;
7110   int V1DstIndex = -1;
7111   int V2DstIndex = -1;
7112   bool V1UsedInPlace = false;
7113
7114   for (int i = 0; i < 4; ++i) {
7115     // Synthesize a zero mask from the zeroable elements (includes undefs).
7116     if (Zeroable[i]) {
7117       ZMask |= 1 << i;
7118       continue;
7119     }
7120
7121     // Flag if we use any V1 inputs in place.
7122     if (i == Mask[i]) {
7123       V1UsedInPlace = true;
7124       continue;
7125     }
7126
7127     // We can only insert a single non-zeroable element.
7128     if (V1DstIndex != -1 || V2DstIndex != -1)
7129       return SDValue();
7130
7131     if (Mask[i] < 4) {
7132       // V1 input out of place for insertion.
7133       V1DstIndex = i;
7134     } else {
7135       // V2 input for insertion.
7136       V2DstIndex = i;
7137     }
7138   }
7139
7140   // Don't bother if we have no (non-zeroable) element for insertion.
7141   if (V1DstIndex == -1 && V2DstIndex == -1)
7142     return SDValue();
7143
7144   // Determine element insertion src/dst indices. The src index is from the
7145   // start of the inserted vector, not the start of the concatenated vector.
7146   unsigned V2SrcIndex = 0;
7147   if (V1DstIndex != -1) {
7148     // If we have a V1 input out of place, we use V1 as the V2 element insertion
7149     // and don't use the original V2 at all.
7150     V2SrcIndex = Mask[V1DstIndex];
7151     V2DstIndex = V1DstIndex;
7152     V2 = V1;
7153   } else {
7154     V2SrcIndex = Mask[V2DstIndex] - 4;
7155   }
7156
7157   // If no V1 inputs are used in place, then the result is created only from
7158   // the zero mask and the V2 insertion - so remove V1 dependency.
7159   if (!V1UsedInPlace)
7160     V1 = DAG.getUNDEF(MVT::v4f32);
7161
7162   unsigned InsertPSMask = V2SrcIndex << 6 | V2DstIndex << 4 | ZMask;
7163   assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
7164
7165   // Insert the V2 element into the desired position.
7166   SDLoc DL(Op);
7167   return DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
7168                      DAG.getConstant(InsertPSMask, MVT::i8));
7169 }
7170
7171 /// \brief Try to lower a shuffle as a permute of the inputs followed by an
7172 /// UNPCK instruction.
7173 ///
7174 /// This specifically targets cases where we end up with alternating between
7175 /// the two inputs, and so can permute them into something that feeds a single
7176 /// UNPCK instruction. Note that this routine only targets integer vectors
7177 /// because for floating point vectors we have a generalized SHUFPS lowering
7178 /// strategy that handles everything that doesn't *exactly* match an unpack,
7179 /// making this clever lowering unnecessary.
7180 static SDValue lowerVectorShuffleAsUnpack(SDLoc DL, MVT VT, SDValue V1,
7181                                           SDValue V2, ArrayRef<int> Mask,
7182                                           SelectionDAG &DAG) {
7183   assert(!VT.isFloatingPoint() &&
7184          "This routine only supports integer vectors.");
7185   assert(!isSingleInputShuffleMask(Mask) &&
7186          "This routine should only be used when blending two inputs.");
7187   assert(Mask.size() >= 2 && "Single element masks are invalid.");
7188
7189   int Size = Mask.size();
7190
7191   int NumLoInputs = std::count_if(Mask.begin(), Mask.end(), [Size](int M) {
7192     return M >= 0 && M % Size < Size / 2;
7193   });
7194   int NumHiInputs = std::count_if(
7195       Mask.begin(), Mask.end(), [Size](int M) { return M % Size >= Size / 2; });
7196
7197   bool UnpackLo = NumLoInputs >= NumHiInputs;
7198
7199   auto TryUnpack = [&](MVT UnpackVT, int Scale) {
7200     SmallVector<int, 32> V1Mask(Mask.size(), -1);
7201     SmallVector<int, 32> V2Mask(Mask.size(), -1);
7202
7203     for (int i = 0; i < Size; ++i) {
7204       if (Mask[i] < 0)
7205         continue;
7206
7207       // Each element of the unpack contains Scale elements from this mask.
7208       int UnpackIdx = i / Scale;
7209
7210       // We only handle the case where V1 feeds the first slots of the unpack.
7211       // We rely on canonicalization to ensure this is the case.
7212       if ((UnpackIdx % 2 == 0) != (Mask[i] < Size))
7213         return SDValue();
7214
7215       // Setup the mask for this input. The indexing is tricky as we have to
7216       // handle the unpack stride.
7217       SmallVectorImpl<int> &VMask = (UnpackIdx % 2 == 0) ? V1Mask : V2Mask;
7218       VMask[(UnpackIdx / 2) * Scale + i % Scale + (UnpackLo ? 0 : Size / 2)] =
7219           Mask[i] % Size;
7220     }
7221
7222     // If we will have to shuffle both inputs to use the unpack, check whether
7223     // we can just unpack first and shuffle the result. If so, skip this unpack.
7224     if ((NumLoInputs == 0 || NumHiInputs == 0) && !isNoopShuffleMask(V1Mask) &&
7225         !isNoopShuffleMask(V2Mask))
7226       return SDValue();
7227
7228     // Shuffle the inputs into place.
7229     V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
7230     V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
7231
7232     // Cast the inputs to the type we will use to unpack them.
7233     V1 = DAG.getNode(ISD::BITCAST, DL, UnpackVT, V1);
7234     V2 = DAG.getNode(ISD::BITCAST, DL, UnpackVT, V2);
7235
7236     // Unpack the inputs and cast the result back to the desired type.
7237     return DAG.getNode(ISD::BITCAST, DL, VT,
7238                        DAG.getNode(UnpackLo ? X86ISD::UNPCKL : X86ISD::UNPCKH,
7239                                    DL, UnpackVT, V1, V2));
7240   };
7241
7242   // We try each unpack from the largest to the smallest to try and find one
7243   // that fits this mask.
7244   int OrigNumElements = VT.getVectorNumElements();
7245   int OrigScalarSize = VT.getScalarSizeInBits();
7246   for (int ScalarSize = 64; ScalarSize >= OrigScalarSize; ScalarSize /= 2) {
7247     int Scale = ScalarSize / OrigScalarSize;
7248     int NumElements = OrigNumElements / Scale;
7249     MVT UnpackVT = MVT::getVectorVT(MVT::getIntegerVT(ScalarSize), NumElements);
7250     if (SDValue Unpack = TryUnpack(UnpackVT, Scale))
7251       return Unpack;
7252   }
7253
7254   // If none of the unpack-rooted lowerings worked (or were profitable) try an
7255   // initial unpack.
7256   if (NumLoInputs == 0 || NumHiInputs == 0) {
7257     assert((NumLoInputs > 0 || NumHiInputs > 0) &&
7258            "We have to have *some* inputs!");
7259     int HalfOffset = NumLoInputs == 0 ? Size / 2 : 0;
7260
7261     // FIXME: We could consider the total complexity of the permute of each
7262     // possible unpacking. Or at the least we should consider how many
7263     // half-crossings are created.
7264     // FIXME: We could consider commuting the unpacks.
7265
7266     SmallVector<int, 32> PermMask;
7267     PermMask.assign(Size, -1);
7268     for (int i = 0; i < Size; ++i) {
7269       if (Mask[i] < 0)
7270         continue;
7271
7272       assert(Mask[i] % Size >= HalfOffset && "Found input from wrong half!");
7273
7274       PermMask[i] =
7275           2 * ((Mask[i] % Size) - HalfOffset) + (Mask[i] < Size ? 0 : 1);
7276     }
7277     return DAG.getVectorShuffle(
7278         VT, DL, DAG.getNode(NumLoInputs == 0 ? X86ISD::UNPCKH : X86ISD::UNPCKL,
7279                             DL, VT, V1, V2),
7280         DAG.getUNDEF(VT), PermMask);
7281   }
7282
7283   return SDValue();
7284 }
7285
7286 /// \brief Handle lowering of 2-lane 64-bit floating point shuffles.
7287 ///
7288 /// This is the basis function for the 2-lane 64-bit shuffles as we have full
7289 /// support for floating point shuffles but not integer shuffles. These
7290 /// instructions will incur a domain crossing penalty on some chips though so
7291 /// it is better to avoid lowering through this for integer vectors where
7292 /// possible.
7293 static SDValue lowerV2F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7294                                        const X86Subtarget *Subtarget,
7295                                        SelectionDAG &DAG) {
7296   SDLoc DL(Op);
7297   assert(Op.getSimpleValueType() == MVT::v2f64 && "Bad shuffle type!");
7298   assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7299   assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7300   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7301   ArrayRef<int> Mask = SVOp->getMask();
7302   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7303
7304   if (isSingleInputShuffleMask(Mask)) {
7305     // Use low duplicate instructions for masks that match their pattern.
7306     if (Subtarget->hasSSE3())
7307       if (isShuffleEquivalent(V1, V2, Mask, {0, 0}))
7308         return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v2f64, V1);
7309
7310     // Straight shuffle of a single input vector. Simulate this by using the
7311     // single input as both of the "inputs" to this instruction..
7312     unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
7313
7314     if (Subtarget->hasAVX()) {
7315       // If we have AVX, we can use VPERMILPS which will allow folding a load
7316       // into the shuffle.
7317       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v2f64, V1,
7318                          DAG.getConstant(SHUFPDMask, MVT::i8));
7319     }
7320
7321     return DAG.getNode(X86ISD::SHUFP, SDLoc(Op), MVT::v2f64, V1, V1,
7322                        DAG.getConstant(SHUFPDMask, MVT::i8));
7323   }
7324   assert(Mask[0] >= 0 && Mask[0] < 2 && "Non-canonicalized blend!");
7325   assert(Mask[1] >= 2 && "Non-canonicalized blend!");
7326
7327   // If we have a single input, insert that into V1 if we can do so cheaply.
7328   if ((Mask[0] >= 2) + (Mask[1] >= 2) == 1) {
7329     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7330             DL, MVT::v2f64, V1, V2, Mask, Subtarget, DAG))
7331       return Insertion;
7332     // Try inverting the insertion since for v2 masks it is easy to do and we
7333     // can't reliably sort the mask one way or the other.
7334     int InverseMask[2] = {Mask[0] < 0 ? -1 : (Mask[0] ^ 2),
7335                           Mask[1] < 0 ? -1 : (Mask[1] ^ 2)};
7336     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7337             DL, MVT::v2f64, V2, V1, InverseMask, Subtarget, DAG))
7338       return Insertion;
7339   }
7340
7341   // Try to use one of the special instruction patterns to handle two common
7342   // blend patterns if a zero-blend above didn't work.
7343   if (isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
7344       isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7345     if (SDValue V1S = getScalarValueForVectorElement(V1, Mask[0], DAG))
7346       // We can either use a special instruction to load over the low double or
7347       // to move just the low double.
7348       return DAG.getNode(
7349           isShuffleFoldableLoad(V1S) ? X86ISD::MOVLPD : X86ISD::MOVSD,
7350           DL, MVT::v2f64, V2,
7351           DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64, V1S));
7352
7353   if (Subtarget->hasSSE41())
7354     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2f64, V1, V2, Mask,
7355                                                   Subtarget, DAG))
7356       return Blend;
7357
7358   // Use dedicated unpack instructions for masks that match their pattern.
7359   if (isShuffleEquivalent(V1, V2, Mask, {0, 2}))
7360     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2f64, V1, V2);
7361   if (isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7362     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2f64, V1, V2);
7363
7364   unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
7365   return DAG.getNode(X86ISD::SHUFP, SDLoc(Op), MVT::v2f64, V1, V2,
7366                      DAG.getConstant(SHUFPDMask, MVT::i8));
7367 }
7368
7369 /// \brief Handle lowering of 2-lane 64-bit integer shuffles.
7370 ///
7371 /// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
7372 /// the integer unit to minimize domain crossing penalties. However, for blends
7373 /// it falls back to the floating point shuffle operation with appropriate bit
7374 /// casting.
7375 static SDValue lowerV2I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7376                                        const X86Subtarget *Subtarget,
7377                                        SelectionDAG &DAG) {
7378   SDLoc DL(Op);
7379   assert(Op.getSimpleValueType() == MVT::v2i64 && "Bad shuffle type!");
7380   assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7381   assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7382   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7383   ArrayRef<int> Mask = SVOp->getMask();
7384   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7385
7386   if (isSingleInputShuffleMask(Mask)) {
7387     // Check for being able to broadcast a single element.
7388     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v2i64, V1,
7389                                                           Mask, Subtarget, DAG))
7390       return Broadcast;
7391
7392     // Straight shuffle of a single input vector. For everything from SSE2
7393     // onward this has a single fast instruction with no scary immediates.
7394     // We have to map the mask as it is actually a v4i32 shuffle instruction.
7395     V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V1);
7396     int WidenedMask[4] = {
7397         std::max(Mask[0], 0) * 2, std::max(Mask[0], 0) * 2 + 1,
7398         std::max(Mask[1], 0) * 2, std::max(Mask[1], 0) * 2 + 1};
7399     return DAG.getNode(
7400         ISD::BITCAST, DL, MVT::v2i64,
7401         DAG.getNode(X86ISD::PSHUFD, SDLoc(Op), MVT::v4i32, V1,
7402                     getV4X86ShuffleImm8ForMask(WidenedMask, DAG)));
7403   }
7404   assert(Mask[0] != -1 && "No undef lanes in multi-input v2 shuffles!");
7405   assert(Mask[1] != -1 && "No undef lanes in multi-input v2 shuffles!");
7406   assert(Mask[0] < 2 && "We sort V1 to be the first input.");
7407   assert(Mask[1] >= 2 && "We sort V2 to be the second input.");
7408
7409   // If we have a blend of two PACKUS operations an the blend aligns with the
7410   // low and half halves, we can just merge the PACKUS operations. This is
7411   // particularly important as it lets us merge shuffles that this routine itself
7412   // creates.
7413   auto GetPackNode = [](SDValue V) {
7414     while (V.getOpcode() == ISD::BITCAST)
7415       V = V.getOperand(0);
7416
7417     return V.getOpcode() == X86ISD::PACKUS ? V : SDValue();
7418   };
7419   if (SDValue V1Pack = GetPackNode(V1))
7420     if (SDValue V2Pack = GetPackNode(V2))
7421       return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7422                          DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8,
7423                                      Mask[0] == 0 ? V1Pack.getOperand(0)
7424                                                   : V1Pack.getOperand(1),
7425                                      Mask[1] == 2 ? V2Pack.getOperand(0)
7426                                                   : V2Pack.getOperand(1)));
7427
7428   // Try to use shift instructions.
7429   if (SDValue Shift =
7430           lowerVectorShuffleAsShift(DL, MVT::v2i64, V1, V2, Mask, DAG))
7431     return Shift;
7432
7433   // When loading a scalar and then shuffling it into a vector we can often do
7434   // the insertion cheaply.
7435   if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7436           DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
7437     return Insertion;
7438   // Try inverting the insertion since for v2 masks it is easy to do and we
7439   // can't reliably sort the mask one way or the other.
7440   int InverseMask[2] = {Mask[0] ^ 2, Mask[1] ^ 2};
7441   if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7442           DL, MVT::v2i64, V2, V1, InverseMask, Subtarget, DAG))
7443     return Insertion;
7444
7445   // We have different paths for blend lowering, but they all must use the
7446   // *exact* same predicate.
7447   bool IsBlendSupported = Subtarget->hasSSE41();
7448   if (IsBlendSupported)
7449     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2i64, V1, V2, Mask,
7450                                                   Subtarget, DAG))
7451       return Blend;
7452
7453   // Use dedicated unpack instructions for masks that match their pattern.
7454   if (isShuffleEquivalent(V1, V2, Mask, {0, 2}))
7455     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, V1, V2);
7456   if (isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7457     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2i64, V1, V2);
7458
7459   // Try to use byte rotation instructions.
7460   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
7461   if (Subtarget->hasSSSE3())
7462     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
7463             DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
7464       return Rotate;
7465
7466   // If we have direct support for blends, we should lower by decomposing into
7467   // a permute. That will be faster than the domain cross.
7468   if (IsBlendSupported)
7469     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v2i64, V1, V2,
7470                                                       Mask, DAG);
7471
7472   // We implement this with SHUFPD which is pretty lame because it will likely
7473   // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
7474   // However, all the alternatives are still more cycles and newer chips don't
7475   // have this problem. It would be really nice if x86 had better shuffles here.
7476   V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V1);
7477   V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V2);
7478   return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7479                      DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
7480 }
7481
7482 /// \brief Test whether this can be lowered with a single SHUFPS instruction.
7483 ///
7484 /// This is used to disable more specialized lowerings when the shufps lowering
7485 /// will happen to be efficient.
7486 static bool isSingleSHUFPSMask(ArrayRef<int> Mask) {
7487   // This routine only handles 128-bit shufps.
7488   assert(Mask.size() == 4 && "Unsupported mask size!");
7489
7490   // To lower with a single SHUFPS we need to have the low half and high half
7491   // each requiring a single input.
7492   if (Mask[0] != -1 && Mask[1] != -1 && (Mask[0] < 4) != (Mask[1] < 4))
7493     return false;
7494   if (Mask[2] != -1 && Mask[3] != -1 && (Mask[2] < 4) != (Mask[3] < 4))
7495     return false;
7496
7497   return true;
7498 }
7499
7500 /// \brief Lower a vector shuffle using the SHUFPS instruction.
7501 ///
7502 /// This is a helper routine dedicated to lowering vector shuffles using SHUFPS.
7503 /// It makes no assumptions about whether this is the *best* lowering, it simply
7504 /// uses it.
7505 static SDValue lowerVectorShuffleWithSHUFPS(SDLoc DL, MVT VT,
7506                                             ArrayRef<int> Mask, SDValue V1,
7507                                             SDValue V2, SelectionDAG &DAG) {
7508   SDValue LowV = V1, HighV = V2;
7509   int NewMask[4] = {Mask[0], Mask[1], Mask[2], Mask[3]};
7510
7511   int NumV2Elements =
7512       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7513
7514   if (NumV2Elements == 1) {
7515     int V2Index =
7516         std::find_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; }) -
7517         Mask.begin();
7518
7519     // Compute the index adjacent to V2Index and in the same half by toggling
7520     // the low bit.
7521     int V2AdjIndex = V2Index ^ 1;
7522
7523     if (Mask[V2AdjIndex] == -1) {
7524       // Handles all the cases where we have a single V2 element and an undef.
7525       // This will only ever happen in the high lanes because we commute the
7526       // vector otherwise.
7527       if (V2Index < 2)
7528         std::swap(LowV, HighV);
7529       NewMask[V2Index] -= 4;
7530     } else {
7531       // Handle the case where the V2 element ends up adjacent to a V1 element.
7532       // To make this work, blend them together as the first step.
7533       int V1Index = V2AdjIndex;
7534       int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
7535       V2 = DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
7536                        getV4X86ShuffleImm8ForMask(BlendMask, DAG));
7537
7538       // Now proceed to reconstruct the final blend as we have the necessary
7539       // high or low half formed.
7540       if (V2Index < 2) {
7541         LowV = V2;
7542         HighV = V1;
7543       } else {
7544         HighV = V2;
7545       }
7546       NewMask[V1Index] = 2; // We put the V1 element in V2[2].
7547       NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
7548     }
7549   } else if (NumV2Elements == 2) {
7550     if (Mask[0] < 4 && Mask[1] < 4) {
7551       // Handle the easy case where we have V1 in the low lanes and V2 in the
7552       // high lanes.
7553       NewMask[2] -= 4;
7554       NewMask[3] -= 4;
7555     } else if (Mask[2] < 4 && Mask[3] < 4) {
7556       // We also handle the reversed case because this utility may get called
7557       // when we detect a SHUFPS pattern but can't easily commute the shuffle to
7558       // arrange things in the right direction.
7559       NewMask[0] -= 4;
7560       NewMask[1] -= 4;
7561       HighV = V1;
7562       LowV = V2;
7563     } else {
7564       // We have a mixture of V1 and V2 in both low and high lanes. Rather than
7565       // trying to place elements directly, just blend them and set up the final
7566       // shuffle to place them.
7567
7568       // The first two blend mask elements are for V1, the second two are for
7569       // V2.
7570       int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
7571                           Mask[2] < 4 ? Mask[2] : Mask[3],
7572                           (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
7573                           (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
7574       V1 = DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
7575                        getV4X86ShuffleImm8ForMask(BlendMask, DAG));
7576
7577       // Now we do a normal shuffle of V1 by giving V1 as both operands to
7578       // a blend.
7579       LowV = HighV = V1;
7580       NewMask[0] = Mask[0] < 4 ? 0 : 2;
7581       NewMask[1] = Mask[0] < 4 ? 2 : 0;
7582       NewMask[2] = Mask[2] < 4 ? 1 : 3;
7583       NewMask[3] = Mask[2] < 4 ? 3 : 1;
7584     }
7585   }
7586   return DAG.getNode(X86ISD::SHUFP, DL, VT, LowV, HighV,
7587                      getV4X86ShuffleImm8ForMask(NewMask, DAG));
7588 }
7589
7590 /// \brief Lower 4-lane 32-bit floating point shuffles.
7591 ///
7592 /// Uses instructions exclusively from the floating point unit to minimize
7593 /// domain crossing penalties, as these are sufficient to implement all v4f32
7594 /// shuffles.
7595 static SDValue lowerV4F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7596                                        const X86Subtarget *Subtarget,
7597                                        SelectionDAG &DAG) {
7598   SDLoc DL(Op);
7599   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
7600   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7601   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7602   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7603   ArrayRef<int> Mask = SVOp->getMask();
7604   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7605
7606   int NumV2Elements =
7607       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7608
7609   if (NumV2Elements == 0) {
7610     // Check for being able to broadcast a single element.
7611     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f32, V1,
7612                                                           Mask, Subtarget, DAG))
7613       return Broadcast;
7614
7615     // Use even/odd duplicate instructions for masks that match their pattern.
7616     if (Subtarget->hasSSE3()) {
7617       if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
7618         return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v4f32, V1);
7619       if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3}))
7620         return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v4f32, V1);
7621     }
7622
7623     if (Subtarget->hasAVX()) {
7624       // If we have AVX, we can use VPERMILPS which will allow folding a load
7625       // into the shuffle.
7626       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f32, V1,
7627                          getV4X86ShuffleImm8ForMask(Mask, DAG));
7628     }
7629
7630     // Otherwise, use a straight shuffle of a single input vector. We pass the
7631     // input vector to both operands to simulate this with a SHUFPS.
7632     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
7633                        getV4X86ShuffleImm8ForMask(Mask, DAG));
7634   }
7635
7636   // There are special ways we can lower some single-element blends. However, we
7637   // have custom ways we can lower more complex single-element blends below that
7638   // we defer to if both this and BLENDPS fail to match, so restrict this to
7639   // when the V2 input is targeting element 0 of the mask -- that is the fast
7640   // case here.
7641   if (NumV2Elements == 1 && Mask[0] >= 4)
7642     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4f32, V1, V2,
7643                                                          Mask, Subtarget, DAG))
7644       return V;
7645
7646   if (Subtarget->hasSSE41()) {
7647     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f32, V1, V2, Mask,
7648                                                   Subtarget, DAG))
7649       return Blend;
7650
7651     // Use INSERTPS if we can complete the shuffle efficiently.
7652     if (SDValue V = lowerVectorShuffleAsInsertPS(Op, V1, V2, Mask, DAG))
7653       return V;
7654
7655     if (!isSingleSHUFPSMask(Mask))
7656       if (SDValue BlendPerm = lowerVectorShuffleAsBlendAndPermute(
7657               DL, MVT::v4f32, V1, V2, Mask, DAG))
7658         return BlendPerm;
7659   }
7660
7661   // Use dedicated unpack instructions for masks that match their pattern.
7662   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 1, 5}))
7663     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V1, V2);
7664   if (isShuffleEquivalent(V1, V2, Mask, {2, 6, 3, 7}))
7665     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V1, V2);
7666   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 5, 1}))
7667     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V2, V1);
7668   if (isShuffleEquivalent(V1, V2, Mask, {6, 2, 7, 3}))
7669     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V2, V1);
7670
7671   // Otherwise fall back to a SHUFPS lowering strategy.
7672   return lowerVectorShuffleWithSHUFPS(DL, MVT::v4f32, Mask, V1, V2, DAG);
7673 }
7674
7675 /// \brief Lower 4-lane i32 vector shuffles.
7676 ///
7677 /// We try to handle these with integer-domain shuffles where we can, but for
7678 /// blends we use the floating point domain blend instructions.
7679 static SDValue lowerV4I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7680                                        const X86Subtarget *Subtarget,
7681                                        SelectionDAG &DAG) {
7682   SDLoc DL(Op);
7683   assert(Op.getSimpleValueType() == MVT::v4i32 && "Bad shuffle type!");
7684   assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
7685   assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
7686   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7687   ArrayRef<int> Mask = SVOp->getMask();
7688   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7689
7690   // Whenever we can lower this as a zext, that instruction is strictly faster
7691   // than any alternative. It also allows us to fold memory operands into the
7692   // shuffle in many cases.
7693   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v4i32, V1, V2,
7694                                                          Mask, Subtarget, DAG))
7695     return ZExt;
7696
7697   int NumV2Elements =
7698       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7699
7700   if (NumV2Elements == 0) {
7701     // Check for being able to broadcast a single element.
7702     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i32, V1,
7703                                                           Mask, Subtarget, DAG))
7704       return Broadcast;
7705
7706     // Straight shuffle of a single input vector. For everything from SSE2
7707     // onward this has a single fast instruction with no scary immediates.
7708     // We coerce the shuffle pattern to be compatible with UNPCK instructions
7709     // but we aren't actually going to use the UNPCK instruction because doing
7710     // so prevents folding a load into this instruction or making a copy.
7711     const int UnpackLoMask[] = {0, 0, 1, 1};
7712     const int UnpackHiMask[] = {2, 2, 3, 3};
7713     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 1, 1}))
7714       Mask = UnpackLoMask;
7715     else if (isShuffleEquivalent(V1, V2, Mask, {2, 2, 3, 3}))
7716       Mask = UnpackHiMask;
7717
7718     return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
7719                        getV4X86ShuffleImm8ForMask(Mask, DAG));
7720   }
7721
7722   // Try to use shift instructions.
7723   if (SDValue Shift =
7724           lowerVectorShuffleAsShift(DL, MVT::v4i32, V1, V2, Mask, DAG))
7725     return Shift;
7726
7727   // There are special ways we can lower some single-element blends.
7728   if (NumV2Elements == 1)
7729     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4i32, V1, V2,
7730                                                          Mask, Subtarget, DAG))
7731       return V;
7732
7733   // We have different paths for blend lowering, but they all must use the
7734   // *exact* same predicate.
7735   bool IsBlendSupported = Subtarget->hasSSE41();
7736   if (IsBlendSupported)
7737     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i32, V1, V2, Mask,
7738                                                   Subtarget, DAG))
7739       return Blend;
7740
7741   if (SDValue Masked =
7742           lowerVectorShuffleAsBitMask(DL, MVT::v4i32, V1, V2, Mask, DAG))
7743     return Masked;
7744
7745   // Use dedicated unpack instructions for masks that match their pattern.
7746   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 1, 5}))
7747     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V1, V2);
7748   if (isShuffleEquivalent(V1, V2, Mask, {2, 6, 3, 7}))
7749     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V1, V2);
7750   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 5, 1}))
7751     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V2, V1);
7752   if (isShuffleEquivalent(V1, V2, Mask, {6, 2, 7, 3}))
7753     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V2, V1);
7754
7755   // Try to use byte rotation instructions.
7756   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
7757   if (Subtarget->hasSSSE3())
7758     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
7759             DL, MVT::v4i32, V1, V2, Mask, Subtarget, DAG))
7760       return Rotate;
7761
7762   // If we have direct support for blends, we should lower by decomposing into
7763   // a permute. That will be faster than the domain cross.
7764   if (IsBlendSupported)
7765     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i32, V1, V2,
7766                                                       Mask, DAG);
7767
7768   // Try to lower by permuting the inputs into an unpack instruction.
7769   if (SDValue Unpack =
7770           lowerVectorShuffleAsUnpack(DL, MVT::v4i32, V1, V2, Mask, DAG))
7771     return Unpack;
7772
7773   // We implement this with SHUFPS because it can blend from two vectors.
7774   // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
7775   // up the inputs, bypassing domain shift penalties that we would encur if we
7776   // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
7777   // relevant.
7778   return DAG.getNode(ISD::BITCAST, DL, MVT::v4i32,
7779                      DAG.getVectorShuffle(
7780                          MVT::v4f32, DL,
7781                          DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V1),
7782                          DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V2), Mask));
7783 }
7784
7785 /// \brief Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
7786 /// shuffle lowering, and the most complex part.
7787 ///
7788 /// The lowering strategy is to try to form pairs of input lanes which are
7789 /// targeted at the same half of the final vector, and then use a dword shuffle
7790 /// to place them onto the right half, and finally unpack the paired lanes into
7791 /// their final position.
7792 ///
7793 /// The exact breakdown of how to form these dword pairs and align them on the
7794 /// correct sides is really tricky. See the comments within the function for
7795 /// more of the details.
7796 ///
7797 /// This code also handles repeated 128-bit lanes of v8i16 shuffles, but each
7798 /// lane must shuffle the *exact* same way. In fact, you must pass a v8 Mask to
7799 /// this routine for it to work correctly. To shuffle a 256-bit or 512-bit i16
7800 /// vector, form the analogous 128-bit 8-element Mask.
7801 static SDValue lowerV8I16GeneralSingleInputVectorShuffle(
7802     SDLoc DL, MVT VT, SDValue V, MutableArrayRef<int> Mask,
7803     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7804   assert(VT.getScalarType() == MVT::i16 && "Bad input type!");
7805   MVT PSHUFDVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
7806
7807   assert(Mask.size() == 8 && "Shuffle mask length doen't match!");
7808   MutableArrayRef<int> LoMask = Mask.slice(0, 4);
7809   MutableArrayRef<int> HiMask = Mask.slice(4, 4);
7810
7811   SmallVector<int, 4> LoInputs;
7812   std::copy_if(LoMask.begin(), LoMask.end(), std::back_inserter(LoInputs),
7813                [](int M) { return M >= 0; });
7814   std::sort(LoInputs.begin(), LoInputs.end());
7815   LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()), LoInputs.end());
7816   SmallVector<int, 4> HiInputs;
7817   std::copy_if(HiMask.begin(), HiMask.end(), std::back_inserter(HiInputs),
7818                [](int M) { return M >= 0; });
7819   std::sort(HiInputs.begin(), HiInputs.end());
7820   HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()), HiInputs.end());
7821   int NumLToL =
7822       std::lower_bound(LoInputs.begin(), LoInputs.end(), 4) - LoInputs.begin();
7823   int NumHToL = LoInputs.size() - NumLToL;
7824   int NumLToH =
7825       std::lower_bound(HiInputs.begin(), HiInputs.end(), 4) - HiInputs.begin();
7826   int NumHToH = HiInputs.size() - NumLToH;
7827   MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
7828   MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
7829   MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
7830   MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
7831
7832   // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
7833   // such inputs we can swap two of the dwords across the half mark and end up
7834   // with <=2 inputs to each half in each half. Once there, we can fall through
7835   // to the generic code below. For example:
7836   //
7837   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
7838   // Mask:  [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
7839   //
7840   // However in some very rare cases we have a 1-into-3 or 3-into-1 on one half
7841   // and an existing 2-into-2 on the other half. In this case we may have to
7842   // pre-shuffle the 2-into-2 half to avoid turning it into a 3-into-1 or
7843   // 1-into-3 which could cause us to cycle endlessly fixing each side in turn.
7844   // Fortunately, we don't have to handle anything but a 2-into-2 pattern
7845   // because any other situation (including a 3-into-1 or 1-into-3 in the other
7846   // half than the one we target for fixing) will be fixed when we re-enter this
7847   // path. We will also combine away any sequence of PSHUFD instructions that
7848   // result into a single instruction. Here is an example of the tricky case:
7849   //
7850   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
7851   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -THIS-IS-BAD!!!!-> [5, 7, 1, 0, 4, 7, 5, 3]
7852   //
7853   // This now has a 1-into-3 in the high half! Instead, we do two shuffles:
7854   //
7855   // Input: [a, b, c, d, e, f, g, h] PSHUFHW[0,2,1,3]-> [a, b, c, d, e, g, f, h]
7856   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -----------------> [3, 7, 1, 0, 2, 7, 3, 6]
7857   //
7858   // Input: [a, b, c, d, e, g, f, h] -PSHUFD[0,2,1,3]-> [a, b, e, g, c, d, f, h]
7859   // Mask:  [3, 7, 1, 0, 2, 7, 3, 6] -----------------> [5, 7, 1, 0, 4, 7, 5, 6]
7860   //
7861   // The result is fine to be handled by the generic logic.
7862   auto balanceSides = [&](ArrayRef<int> AToAInputs, ArrayRef<int> BToAInputs,
7863                           ArrayRef<int> BToBInputs, ArrayRef<int> AToBInputs,
7864                           int AOffset, int BOffset) {
7865     assert((AToAInputs.size() == 3 || AToAInputs.size() == 1) &&
7866            "Must call this with A having 3 or 1 inputs from the A half.");
7867     assert((BToAInputs.size() == 1 || BToAInputs.size() == 3) &&
7868            "Must call this with B having 1 or 3 inputs from the B half.");
7869     assert(AToAInputs.size() + BToAInputs.size() == 4 &&
7870            "Must call this with either 3:1 or 1:3 inputs (summing to 4).");
7871
7872     // Compute the index of dword with only one word among the three inputs in
7873     // a half by taking the sum of the half with three inputs and subtracting
7874     // the sum of the actual three inputs. The difference is the remaining
7875     // slot.
7876     int ADWord, BDWord;
7877     int &TripleDWord = AToAInputs.size() == 3 ? ADWord : BDWord;
7878     int &OneInputDWord = AToAInputs.size() == 3 ? BDWord : ADWord;
7879     int TripleInputOffset = AToAInputs.size() == 3 ? AOffset : BOffset;
7880     ArrayRef<int> TripleInputs = AToAInputs.size() == 3 ? AToAInputs : BToAInputs;
7881     int OneInput = AToAInputs.size() == 3 ? BToAInputs[0] : AToAInputs[0];
7882     int TripleInputSum = 0 + 1 + 2 + 3 + (4 * TripleInputOffset);
7883     int TripleNonInputIdx =
7884         TripleInputSum - std::accumulate(TripleInputs.begin(), TripleInputs.end(), 0);
7885     TripleDWord = TripleNonInputIdx / 2;
7886
7887     // We use xor with one to compute the adjacent DWord to whichever one the
7888     // OneInput is in.
7889     OneInputDWord = (OneInput / 2) ^ 1;
7890
7891     // Check for one tricky case: We're fixing a 3<-1 or a 1<-3 shuffle for AToA
7892     // and BToA inputs. If there is also such a problem with the BToB and AToB
7893     // inputs, we don't try to fix it necessarily -- we'll recurse and see it in
7894     // the next pass. However, if we have a 2<-2 in the BToB and AToB inputs, it
7895     // is essential that we don't *create* a 3<-1 as then we might oscillate.
7896     if (BToBInputs.size() == 2 && AToBInputs.size() == 2) {
7897       // Compute how many inputs will be flipped by swapping these DWords. We
7898       // need
7899       // to balance this to ensure we don't form a 3-1 shuffle in the other
7900       // half.
7901       int NumFlippedAToBInputs =
7902           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord) +
7903           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord + 1);
7904       int NumFlippedBToBInputs =
7905           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord) +
7906           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord + 1);
7907       if ((NumFlippedAToBInputs == 1 &&
7908            (NumFlippedBToBInputs == 0 || NumFlippedBToBInputs == 2)) ||
7909           (NumFlippedBToBInputs == 1 &&
7910            (NumFlippedAToBInputs == 0 || NumFlippedAToBInputs == 2))) {
7911         // We choose whether to fix the A half or B half based on whether that
7912         // half has zero flipped inputs. At zero, we may not be able to fix it
7913         // with that half. We also bias towards fixing the B half because that
7914         // will more commonly be the high half, and we have to bias one way.
7915         auto FixFlippedInputs = [&V, &DL, &Mask, &DAG](int PinnedIdx, int DWord,
7916                                                        ArrayRef<int> Inputs) {
7917           int FixIdx = PinnedIdx ^ 1; // The adjacent slot to the pinned slot.
7918           bool IsFixIdxInput = std::find(Inputs.begin(), Inputs.end(),
7919                                          PinnedIdx ^ 1) != Inputs.end();
7920           // Determine whether the free index is in the flipped dword or the
7921           // unflipped dword based on where the pinned index is. We use this bit
7922           // in an xor to conditionally select the adjacent dword.
7923           int FixFreeIdx = 2 * (DWord ^ (PinnedIdx / 2 == DWord));
7924           bool IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
7925                                              FixFreeIdx) != Inputs.end();
7926           if (IsFixIdxInput == IsFixFreeIdxInput)
7927             FixFreeIdx += 1;
7928           IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
7929                                         FixFreeIdx) != Inputs.end();
7930           assert(IsFixIdxInput != IsFixFreeIdxInput &&
7931                  "We need to be changing the number of flipped inputs!");
7932           int PSHUFHalfMask[] = {0, 1, 2, 3};
7933           std::swap(PSHUFHalfMask[FixFreeIdx % 4], PSHUFHalfMask[FixIdx % 4]);
7934           V = DAG.getNode(FixIdx < 4 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW, DL,
7935                           MVT::v8i16, V,
7936                           getV4X86ShuffleImm8ForMask(PSHUFHalfMask, DAG));
7937
7938           for (int &M : Mask)
7939             if (M != -1 && M == FixIdx)
7940               M = FixFreeIdx;
7941             else if (M != -1 && M == FixFreeIdx)
7942               M = FixIdx;
7943         };
7944         if (NumFlippedBToBInputs != 0) {
7945           int BPinnedIdx =
7946               BToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
7947           FixFlippedInputs(BPinnedIdx, BDWord, BToBInputs);
7948         } else {
7949           assert(NumFlippedAToBInputs != 0 && "Impossible given predicates!");
7950           int APinnedIdx =
7951               AToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
7952           FixFlippedInputs(APinnedIdx, ADWord, AToBInputs);
7953         }
7954       }
7955     }
7956
7957     int PSHUFDMask[] = {0, 1, 2, 3};
7958     PSHUFDMask[ADWord] = BDWord;
7959     PSHUFDMask[BDWord] = ADWord;
7960     V = DAG.getNode(ISD::BITCAST, DL, VT,
7961                     DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT,
7962                                 DAG.getNode(ISD::BITCAST, DL, PSHUFDVT, V),
7963                                 getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
7964
7965     // Adjust the mask to match the new locations of A and B.
7966     for (int &M : Mask)
7967       if (M != -1 && M/2 == ADWord)
7968         M = 2 * BDWord + M % 2;
7969       else if (M != -1 && M/2 == BDWord)
7970         M = 2 * ADWord + M % 2;
7971
7972     // Recurse back into this routine to re-compute state now that this isn't
7973     // a 3 and 1 problem.
7974     return lowerV8I16GeneralSingleInputVectorShuffle(DL, VT, V, Mask, Subtarget,
7975                                                      DAG);
7976   };
7977   if ((NumLToL == 3 && NumHToL == 1) || (NumLToL == 1 && NumHToL == 3))
7978     return balanceSides(LToLInputs, HToLInputs, HToHInputs, LToHInputs, 0, 4);
7979   else if ((NumHToH == 3 && NumLToH == 1) || (NumHToH == 1 && NumLToH == 3))
7980     return balanceSides(HToHInputs, LToHInputs, LToLInputs, HToLInputs, 4, 0);
7981
7982   // At this point there are at most two inputs to the low and high halves from
7983   // each half. That means the inputs can always be grouped into dwords and
7984   // those dwords can then be moved to the correct half with a dword shuffle.
7985   // We use at most one low and one high word shuffle to collect these paired
7986   // inputs into dwords, and finally a dword shuffle to place them.
7987   int PSHUFLMask[4] = {-1, -1, -1, -1};
7988   int PSHUFHMask[4] = {-1, -1, -1, -1};
7989   int PSHUFDMask[4] = {-1, -1, -1, -1};
7990
7991   // First fix the masks for all the inputs that are staying in their
7992   // original halves. This will then dictate the targets of the cross-half
7993   // shuffles.
7994   auto fixInPlaceInputs =
7995       [&PSHUFDMask](ArrayRef<int> InPlaceInputs, ArrayRef<int> IncomingInputs,
7996                     MutableArrayRef<int> SourceHalfMask,
7997                     MutableArrayRef<int> HalfMask, int HalfOffset) {
7998     if (InPlaceInputs.empty())
7999       return;
8000     if (InPlaceInputs.size() == 1) {
8001       SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8002           InPlaceInputs[0] - HalfOffset;
8003       PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
8004       return;
8005     }
8006     if (IncomingInputs.empty()) {
8007       // Just fix all of the in place inputs.
8008       for (int Input : InPlaceInputs) {
8009         SourceHalfMask[Input - HalfOffset] = Input - HalfOffset;
8010         PSHUFDMask[Input / 2] = Input / 2;
8011       }
8012       return;
8013     }
8014
8015     assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!");
8016     SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8017         InPlaceInputs[0] - HalfOffset;
8018     // Put the second input next to the first so that they are packed into
8019     // a dword. We find the adjacent index by toggling the low bit.
8020     int AdjIndex = InPlaceInputs[0] ^ 1;
8021     SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
8022     std::replace(HalfMask.begin(), HalfMask.end(), InPlaceInputs[1], AdjIndex);
8023     PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
8024   };
8025   fixInPlaceInputs(LToLInputs, HToLInputs, PSHUFLMask, LoMask, 0);
8026   fixInPlaceInputs(HToHInputs, LToHInputs, PSHUFHMask, HiMask, 4);
8027
8028   // Now gather the cross-half inputs and place them into a free dword of
8029   // their target half.
8030   // FIXME: This operation could almost certainly be simplified dramatically to
8031   // look more like the 3-1 fixing operation.
8032   auto moveInputsToRightHalf = [&PSHUFDMask](
8033       MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
8034       MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
8035       MutableArrayRef<int> FinalSourceHalfMask, int SourceOffset,
8036       int DestOffset) {
8037     auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
8038       return SourceHalfMask[Word] != -1 && SourceHalfMask[Word] != Word;
8039     };
8040     auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
8041                                                int Word) {
8042       int LowWord = Word & ~1;
8043       int HighWord = Word | 1;
8044       return isWordClobbered(SourceHalfMask, LowWord) ||
8045              isWordClobbered(SourceHalfMask, HighWord);
8046     };
8047
8048     if (IncomingInputs.empty())
8049       return;
8050
8051     if (ExistingInputs.empty()) {
8052       // Map any dwords with inputs from them into the right half.
8053       for (int Input : IncomingInputs) {
8054         // If the source half mask maps over the inputs, turn those into
8055         // swaps and use the swapped lane.
8056         if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
8057           if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] == -1) {
8058             SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
8059                 Input - SourceOffset;
8060             // We have to swap the uses in our half mask in one sweep.
8061             for (int &M : HalfMask)
8062               if (M == SourceHalfMask[Input - SourceOffset] + SourceOffset)
8063                 M = Input;
8064               else if (M == Input)
8065                 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8066           } else {
8067             assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==
8068                        Input - SourceOffset &&
8069                    "Previous placement doesn't match!");
8070           }
8071           // Note that this correctly re-maps both when we do a swap and when
8072           // we observe the other side of the swap above. We rely on that to
8073           // avoid swapping the members of the input list directly.
8074           Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8075         }
8076
8077         // Map the input's dword into the correct half.
8078         if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] == -1)
8079           PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
8080         else
8081           assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==
8082                      Input / 2 &&
8083                  "Previous placement doesn't match!");
8084       }
8085
8086       // And just directly shift any other-half mask elements to be same-half
8087       // as we will have mirrored the dword containing the element into the
8088       // same position within that half.
8089       for (int &M : HalfMask)
8090         if (M >= SourceOffset && M < SourceOffset + 4) {
8091           M = M - SourceOffset + DestOffset;
8092           assert(M >= 0 && "This should never wrap below zero!");
8093         }
8094       return;
8095     }
8096
8097     // Ensure we have the input in a viable dword of its current half. This
8098     // is particularly tricky because the original position may be clobbered
8099     // by inputs being moved and *staying* in that half.
8100     if (IncomingInputs.size() == 1) {
8101       if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8102         int InputFixed = std::find(std::begin(SourceHalfMask),
8103                                    std::end(SourceHalfMask), -1) -
8104                          std::begin(SourceHalfMask) + SourceOffset;
8105         SourceHalfMask[InputFixed - SourceOffset] =
8106             IncomingInputs[0] - SourceOffset;
8107         std::replace(HalfMask.begin(), HalfMask.end(), IncomingInputs[0],
8108                      InputFixed);
8109         IncomingInputs[0] = InputFixed;
8110       }
8111     } else if (IncomingInputs.size() == 2) {
8112       if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
8113           isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8114         // We have two non-adjacent or clobbered inputs we need to extract from
8115         // the source half. To do this, we need to map them into some adjacent
8116         // dword slot in the source mask.
8117         int InputsFixed[2] = {IncomingInputs[0] - SourceOffset,
8118                               IncomingInputs[1] - SourceOffset};
8119
8120         // If there is a free slot in the source half mask adjacent to one of
8121         // the inputs, place the other input in it. We use (Index XOR 1) to
8122         // compute an adjacent index.
8123         if (!isWordClobbered(SourceHalfMask, InputsFixed[0]) &&
8124             SourceHalfMask[InputsFixed[0] ^ 1] == -1) {
8125           SourceHalfMask[InputsFixed[0]] = InputsFixed[0];
8126           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8127           InputsFixed[1] = InputsFixed[0] ^ 1;
8128         } else if (!isWordClobbered(SourceHalfMask, InputsFixed[1]) &&
8129                    SourceHalfMask[InputsFixed[1] ^ 1] == -1) {
8130           SourceHalfMask[InputsFixed[1]] = InputsFixed[1];
8131           SourceHalfMask[InputsFixed[1] ^ 1] = InputsFixed[0];
8132           InputsFixed[0] = InputsFixed[1] ^ 1;
8133         } else if (SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] == -1 &&
8134                    SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] == -1) {
8135           // The two inputs are in the same DWord but it is clobbered and the
8136           // adjacent DWord isn't used at all. Move both inputs to the free
8137           // slot.
8138           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] = InputsFixed[0];
8139           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] = InputsFixed[1];
8140           InputsFixed[0] = 2 * ((InputsFixed[0] / 2) ^ 1);
8141           InputsFixed[1] = 2 * ((InputsFixed[0] / 2) ^ 1) + 1;
8142         } else {
8143           // The only way we hit this point is if there is no clobbering
8144           // (because there are no off-half inputs to this half) and there is no
8145           // free slot adjacent to one of the inputs. In this case, we have to
8146           // swap an input with a non-input.
8147           for (int i = 0; i < 4; ++i)
8148             assert((SourceHalfMask[i] == -1 || SourceHalfMask[i] == i) &&
8149                    "We can't handle any clobbers here!");
8150           assert(InputsFixed[1] != (InputsFixed[0] ^ 1) &&
8151                  "Cannot have adjacent inputs here!");
8152
8153           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8154           SourceHalfMask[InputsFixed[1]] = InputsFixed[0] ^ 1;
8155
8156           // We also have to update the final source mask in this case because
8157           // it may need to undo the above swap.
8158           for (int &M : FinalSourceHalfMask)
8159             if (M == (InputsFixed[0] ^ 1) + SourceOffset)
8160               M = InputsFixed[1] + SourceOffset;
8161             else if (M == InputsFixed[1] + SourceOffset)
8162               M = (InputsFixed[0] ^ 1) + SourceOffset;
8163
8164           InputsFixed[1] = InputsFixed[0] ^ 1;
8165         }
8166
8167         // Point everything at the fixed inputs.
8168         for (int &M : HalfMask)
8169           if (M == IncomingInputs[0])
8170             M = InputsFixed[0] + SourceOffset;
8171           else if (M == IncomingInputs[1])
8172             M = InputsFixed[1] + SourceOffset;
8173
8174         IncomingInputs[0] = InputsFixed[0] + SourceOffset;
8175         IncomingInputs[1] = InputsFixed[1] + SourceOffset;
8176       }
8177     } else {
8178       llvm_unreachable("Unhandled input size!");
8179     }
8180
8181     // Now hoist the DWord down to the right half.
8182     int FreeDWord = (PSHUFDMask[DestOffset / 2] == -1 ? 0 : 1) + DestOffset / 2;
8183     assert(PSHUFDMask[FreeDWord] == -1 && "DWord not free");
8184     PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
8185     for (int &M : HalfMask)
8186       for (int Input : IncomingInputs)
8187         if (M == Input)
8188           M = FreeDWord * 2 + Input % 2;
8189   };
8190   moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask, HiMask,
8191                         /*SourceOffset*/ 4, /*DestOffset*/ 0);
8192   moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask, LoMask,
8193                         /*SourceOffset*/ 0, /*DestOffset*/ 4);
8194
8195   // Now enact all the shuffles we've computed to move the inputs into their
8196   // target half.
8197   if (!isNoopShuffleMask(PSHUFLMask))
8198     V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
8199                     getV4X86ShuffleImm8ForMask(PSHUFLMask, DAG));
8200   if (!isNoopShuffleMask(PSHUFHMask))
8201     V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
8202                     getV4X86ShuffleImm8ForMask(PSHUFHMask, DAG));
8203   if (!isNoopShuffleMask(PSHUFDMask))
8204     V = DAG.getNode(ISD::BITCAST, DL, VT,
8205                     DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT,
8206                                 DAG.getNode(ISD::BITCAST, DL, PSHUFDVT, V),
8207                                 getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
8208
8209   // At this point, each half should contain all its inputs, and we can then
8210   // just shuffle them into their final position.
8211   assert(std::count_if(LoMask.begin(), LoMask.end(),
8212                        [](int M) { return M >= 4; }) == 0 &&
8213          "Failed to lift all the high half inputs to the low mask!");
8214   assert(std::count_if(HiMask.begin(), HiMask.end(),
8215                        [](int M) { return M >= 0 && M < 4; }) == 0 &&
8216          "Failed to lift all the low half inputs to the high mask!");
8217
8218   // Do a half shuffle for the low mask.
8219   if (!isNoopShuffleMask(LoMask))
8220     V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
8221                     getV4X86ShuffleImm8ForMask(LoMask, DAG));
8222
8223   // Do a half shuffle with the high mask after shifting its values down.
8224   for (int &M : HiMask)
8225     if (M >= 0)
8226       M -= 4;
8227   if (!isNoopShuffleMask(HiMask))
8228     V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
8229                     getV4X86ShuffleImm8ForMask(HiMask, DAG));
8230
8231   return V;
8232 }
8233
8234 /// \brief Helper to form a PSHUFB-based shuffle+blend.
8235 static SDValue lowerVectorShuffleAsPSHUFB(SDLoc DL, MVT VT, SDValue V1,
8236                                           SDValue V2, ArrayRef<int> Mask,
8237                                           SelectionDAG &DAG, bool &V1InUse,
8238                                           bool &V2InUse) {
8239   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
8240   SDValue V1Mask[16];
8241   SDValue V2Mask[16];
8242   V1InUse = false;
8243   V2InUse = false;
8244
8245   int Size = Mask.size();
8246   int Scale = 16 / Size;
8247   for (int i = 0; i < 16; ++i) {
8248     if (Mask[i / Scale] == -1) {
8249       V1Mask[i] = V2Mask[i] = DAG.getUNDEF(MVT::i8);
8250     } else {
8251       const int ZeroMask = 0x80;
8252       int V1Idx = Mask[i / Scale] < Size ? Mask[i / Scale] * Scale + i % Scale
8253                                           : ZeroMask;
8254       int V2Idx = Mask[i / Scale] < Size
8255                       ? ZeroMask
8256                       : (Mask[i / Scale] - Size) * Scale + i % Scale;
8257       if (Zeroable[i / Scale])
8258         V1Idx = V2Idx = ZeroMask;
8259       V1Mask[i] = DAG.getConstant(V1Idx, MVT::i8);
8260       V2Mask[i] = DAG.getConstant(V2Idx, MVT::i8);
8261       V1InUse |= (ZeroMask != V1Idx);
8262       V2InUse |= (ZeroMask != V2Idx);
8263     }
8264   }
8265
8266   if (V1InUse)
8267     V1 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
8268                      DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, V1),
8269                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V1Mask));
8270   if (V2InUse)
8271     V2 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
8272                      DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, V2),
8273                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V2Mask));
8274
8275   // If we need shuffled inputs from both, blend the two.
8276   SDValue V;
8277   if (V1InUse && V2InUse)
8278     V = DAG.getNode(ISD::OR, DL, MVT::v16i8, V1, V2);
8279   else
8280     V = V1InUse ? V1 : V2;
8281
8282   // Cast the result back to the correct type.
8283   return DAG.getNode(ISD::BITCAST, DL, VT, V);
8284 }
8285
8286 /// \brief Generic lowering of 8-lane i16 shuffles.
8287 ///
8288 /// This handles both single-input shuffles and combined shuffle/blends with
8289 /// two inputs. The single input shuffles are immediately delegated to
8290 /// a dedicated lowering routine.
8291 ///
8292 /// The blends are lowered in one of three fundamental ways. If there are few
8293 /// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
8294 /// of the input is significantly cheaper when lowered as an interleaving of
8295 /// the two inputs, try to interleave them. Otherwise, blend the low and high
8296 /// halves of the inputs separately (making them have relatively few inputs)
8297 /// and then concatenate them.
8298 static SDValue lowerV8I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8299                                        const X86Subtarget *Subtarget,
8300                                        SelectionDAG &DAG) {
8301   SDLoc DL(Op);
8302   assert(Op.getSimpleValueType() == MVT::v8i16 && "Bad shuffle type!");
8303   assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
8304   assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
8305   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8306   ArrayRef<int> OrigMask = SVOp->getMask();
8307   int MaskStorage[8] = {OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
8308                         OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7]};
8309   MutableArrayRef<int> Mask(MaskStorage);
8310
8311   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
8312
8313   // Whenever we can lower this as a zext, that instruction is strictly faster
8314   // than any alternative.
8315   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
8316           DL, MVT::v8i16, V1, V2, OrigMask, Subtarget, DAG))
8317     return ZExt;
8318
8319   auto isV1 = [](int M) { return M >= 0 && M < 8; };
8320   (void)isV1;
8321   auto isV2 = [](int M) { return M >= 8; };
8322
8323   int NumV2Inputs = std::count_if(Mask.begin(), Mask.end(), isV2);
8324
8325   if (NumV2Inputs == 0) {
8326     // Check for being able to broadcast a single element.
8327     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i16, V1,
8328                                                           Mask, Subtarget, DAG))
8329       return Broadcast;
8330
8331     // Try to use shift instructions.
8332     if (SDValue Shift =
8333             lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V1, Mask, DAG))
8334       return Shift;
8335
8336     // Use dedicated unpack instructions for masks that match their pattern.
8337     if (isShuffleEquivalent(V1, V1, Mask, {0, 0, 1, 1, 2, 2, 3, 3}))
8338       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V1, V1);
8339     if (isShuffleEquivalent(V1, V1, Mask, {4, 4, 5, 5, 6, 6, 7, 7}))
8340       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V1, V1);
8341
8342     // Try to use byte rotation instructions.
8343     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(DL, MVT::v8i16, V1, V1,
8344                                                         Mask, Subtarget, DAG))
8345       return Rotate;
8346
8347     return lowerV8I16GeneralSingleInputVectorShuffle(DL, MVT::v8i16, V1, Mask,
8348                                                      Subtarget, DAG);
8349   }
8350
8351   assert(std::any_of(Mask.begin(), Mask.end(), isV1) &&
8352          "All single-input shuffles should be canonicalized to be V1-input "
8353          "shuffles.");
8354
8355   // Try to use shift instructions.
8356   if (SDValue Shift =
8357           lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V2, Mask, DAG))
8358     return Shift;
8359
8360   // There are special ways we can lower some single-element blends.
8361   if (NumV2Inputs == 1)
8362     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v8i16, V1, V2,
8363                                                          Mask, Subtarget, DAG))
8364       return V;
8365
8366   // We have different paths for blend lowering, but they all must use the
8367   // *exact* same predicate.
8368   bool IsBlendSupported = Subtarget->hasSSE41();
8369   if (IsBlendSupported)
8370     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i16, V1, V2, Mask,
8371                                                   Subtarget, DAG))
8372       return Blend;
8373
8374   if (SDValue Masked =
8375           lowerVectorShuffleAsBitMask(DL, MVT::v8i16, V1, V2, Mask, DAG))
8376     return Masked;
8377
8378   // Use dedicated unpack instructions for masks that match their pattern.
8379   if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 2, 10, 3, 11}))
8380     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V1, V2);
8381   if (isShuffleEquivalent(V1, V2, Mask, {4, 12, 5, 13, 6, 14, 7, 15}))
8382     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V1, V2);
8383
8384   // Try to use byte rotation instructions.
8385   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8386           DL, MVT::v8i16, V1, V2, Mask, Subtarget, DAG))
8387     return Rotate;
8388
8389   if (SDValue BitBlend =
8390           lowerVectorShuffleAsBitBlend(DL, MVT::v8i16, V1, V2, Mask, DAG))
8391     return BitBlend;
8392
8393   if (SDValue Unpack =
8394           lowerVectorShuffleAsUnpack(DL, MVT::v8i16, V1, V2, Mask, DAG))
8395     return Unpack;
8396
8397   // If we can't directly blend but can use PSHUFB, that will be better as it
8398   // can both shuffle and set up the inefficient blend.
8399   if (!IsBlendSupported && Subtarget->hasSSSE3()) {
8400     bool V1InUse, V2InUse;
8401     return lowerVectorShuffleAsPSHUFB(DL, MVT::v8i16, V1, V2, Mask, DAG,
8402                                       V1InUse, V2InUse);
8403   }
8404
8405   // We can always bit-blend if we have to so the fallback strategy is to
8406   // decompose into single-input permutes and blends.
8407   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i16, V1, V2,
8408                                                       Mask, DAG);
8409 }
8410
8411 /// \brief Check whether a compaction lowering can be done by dropping even
8412 /// elements and compute how many times even elements must be dropped.
8413 ///
8414 /// This handles shuffles which take every Nth element where N is a power of
8415 /// two. Example shuffle masks:
8416 ///
8417 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14,  0,  2,  4,  6,  8, 10, 12, 14
8418 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30
8419 ///  N = 2:  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12
8420 ///  N = 2:  0,  4,  8, 12, 16, 20, 24, 28,  0,  4,  8, 12, 16, 20, 24, 28
8421 ///  N = 3:  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8
8422 ///  N = 3:  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24
8423 ///
8424 /// Any of these lanes can of course be undef.
8425 ///
8426 /// This routine only supports N <= 3.
8427 /// FIXME: Evaluate whether either AVX or AVX-512 have any opportunities here
8428 /// for larger N.
8429 ///
8430 /// \returns N above, or the number of times even elements must be dropped if
8431 /// there is such a number. Otherwise returns zero.
8432 static int canLowerByDroppingEvenElements(ArrayRef<int> Mask) {
8433   // Figure out whether we're looping over two inputs or just one.
8434   bool IsSingleInput = isSingleInputShuffleMask(Mask);
8435
8436   // The modulus for the shuffle vector entries is based on whether this is
8437   // a single input or not.
8438   int ShuffleModulus = Mask.size() * (IsSingleInput ? 1 : 2);
8439   assert(isPowerOf2_32((uint32_t)ShuffleModulus) &&
8440          "We should only be called with masks with a power-of-2 size!");
8441
8442   uint64_t ModMask = (uint64_t)ShuffleModulus - 1;
8443
8444   // We track whether the input is viable for all power-of-2 strides 2^1, 2^2,
8445   // and 2^3 simultaneously. This is because we may have ambiguity with
8446   // partially undef inputs.
8447   bool ViableForN[3] = {true, true, true};
8448
8449   for (int i = 0, e = Mask.size(); i < e; ++i) {
8450     // Ignore undef lanes, we'll optimistically collapse them to the pattern we
8451     // want.
8452     if (Mask[i] == -1)
8453       continue;
8454
8455     bool IsAnyViable = false;
8456     for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
8457       if (ViableForN[j]) {
8458         uint64_t N = j + 1;
8459
8460         // The shuffle mask must be equal to (i * 2^N) % M.
8461         if ((uint64_t)Mask[i] == (((uint64_t)i << N) & ModMask))
8462           IsAnyViable = true;
8463         else
8464           ViableForN[j] = false;
8465       }
8466     // Early exit if we exhaust the possible powers of two.
8467     if (!IsAnyViable)
8468       break;
8469   }
8470
8471   for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
8472     if (ViableForN[j])
8473       return j + 1;
8474
8475   // Return 0 as there is no viable power of two.
8476   return 0;
8477 }
8478
8479 /// \brief Generic lowering of v16i8 shuffles.
8480 ///
8481 /// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
8482 /// detect any complexity reducing interleaving. If that doesn't help, it uses
8483 /// UNPCK to spread the i8 elements across two i16-element vectors, and uses
8484 /// the existing lowering for v8i16 blends on each half, finally PACK-ing them
8485 /// back together.
8486 static SDValue lowerV16I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8487                                        const X86Subtarget *Subtarget,
8488                                        SelectionDAG &DAG) {
8489   SDLoc DL(Op);
8490   assert(Op.getSimpleValueType() == MVT::v16i8 && "Bad shuffle type!");
8491   assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
8492   assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
8493   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8494   ArrayRef<int> Mask = SVOp->getMask();
8495   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
8496
8497   // Try to use shift instructions.
8498   if (SDValue Shift =
8499           lowerVectorShuffleAsShift(DL, MVT::v16i8, V1, V2, Mask, DAG))
8500     return Shift;
8501
8502   // Try to use byte rotation instructions.
8503   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8504           DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
8505     return Rotate;
8506
8507   // Try to use a zext lowering.
8508   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
8509           DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
8510     return ZExt;
8511
8512   int NumV2Elements =
8513       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 16; });
8514
8515   // For single-input shuffles, there are some nicer lowering tricks we can use.
8516   if (NumV2Elements == 0) {
8517     // Check for being able to broadcast a single element.
8518     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i8, V1,
8519                                                           Mask, Subtarget, DAG))
8520       return Broadcast;
8521
8522     // Check whether we can widen this to an i16 shuffle by duplicating bytes.
8523     // Notably, this handles splat and partial-splat shuffles more efficiently.
8524     // However, it only makes sense if the pre-duplication shuffle simplifies
8525     // things significantly. Currently, this means we need to be able to
8526     // express the pre-duplication shuffle as an i16 shuffle.
8527     //
8528     // FIXME: We should check for other patterns which can be widened into an
8529     // i16 shuffle as well.
8530     auto canWidenViaDuplication = [](ArrayRef<int> Mask) {
8531       for (int i = 0; i < 16; i += 2)
8532         if (Mask[i] != -1 && Mask[i + 1] != -1 && Mask[i] != Mask[i + 1])
8533           return false;
8534
8535       return true;
8536     };
8537     auto tryToWidenViaDuplication = [&]() -> SDValue {
8538       if (!canWidenViaDuplication(Mask))
8539         return SDValue();
8540       SmallVector<int, 4> LoInputs;
8541       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(LoInputs),
8542                    [](int M) { return M >= 0 && M < 8; });
8543       std::sort(LoInputs.begin(), LoInputs.end());
8544       LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()),
8545                      LoInputs.end());
8546       SmallVector<int, 4> HiInputs;
8547       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(HiInputs),
8548                    [](int M) { return M >= 8; });
8549       std::sort(HiInputs.begin(), HiInputs.end());
8550       HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()),
8551                      HiInputs.end());
8552
8553       bool TargetLo = LoInputs.size() >= HiInputs.size();
8554       ArrayRef<int> InPlaceInputs = TargetLo ? LoInputs : HiInputs;
8555       ArrayRef<int> MovingInputs = TargetLo ? HiInputs : LoInputs;
8556
8557       int PreDupI16Shuffle[] = {-1, -1, -1, -1, -1, -1, -1, -1};
8558       SmallDenseMap<int, int, 8> LaneMap;
8559       for (int I : InPlaceInputs) {
8560         PreDupI16Shuffle[I/2] = I/2;
8561         LaneMap[I] = I;
8562       }
8563       int j = TargetLo ? 0 : 4, je = j + 4;
8564       for (int i = 0, ie = MovingInputs.size(); i < ie; ++i) {
8565         // Check if j is already a shuffle of this input. This happens when
8566         // there are two adjacent bytes after we move the low one.
8567         if (PreDupI16Shuffle[j] != MovingInputs[i] / 2) {
8568           // If we haven't yet mapped the input, search for a slot into which
8569           // we can map it.
8570           while (j < je && PreDupI16Shuffle[j] != -1)
8571             ++j;
8572
8573           if (j == je)
8574             // We can't place the inputs into a single half with a simple i16 shuffle, so bail.
8575             return SDValue();
8576
8577           // Map this input with the i16 shuffle.
8578           PreDupI16Shuffle[j] = MovingInputs[i] / 2;
8579         }
8580
8581         // Update the lane map based on the mapping we ended up with.
8582         LaneMap[MovingInputs[i]] = 2 * j + MovingInputs[i] % 2;
8583       }
8584       V1 = DAG.getNode(
8585           ISD::BITCAST, DL, MVT::v16i8,
8586           DAG.getVectorShuffle(MVT::v8i16, DL,
8587                                DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1),
8588                                DAG.getUNDEF(MVT::v8i16), PreDupI16Shuffle));
8589
8590       // Unpack the bytes to form the i16s that will be shuffled into place.
8591       V1 = DAG.getNode(TargetLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
8592                        MVT::v16i8, V1, V1);
8593
8594       int PostDupI16Shuffle[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8595       for (int i = 0; i < 16; ++i)
8596         if (Mask[i] != -1) {
8597           int MappedMask = LaneMap[Mask[i]] - (TargetLo ? 0 : 8);
8598           assert(MappedMask < 8 && "Invalid v8 shuffle mask!");
8599           if (PostDupI16Shuffle[i / 2] == -1)
8600             PostDupI16Shuffle[i / 2] = MappedMask;
8601           else
8602             assert(PostDupI16Shuffle[i / 2] == MappedMask &&
8603                    "Conflicting entrties in the original shuffle!");
8604         }
8605       return DAG.getNode(
8606           ISD::BITCAST, DL, MVT::v16i8,
8607           DAG.getVectorShuffle(MVT::v8i16, DL,
8608                                DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1),
8609                                DAG.getUNDEF(MVT::v8i16), PostDupI16Shuffle));
8610     };
8611     if (SDValue V = tryToWidenViaDuplication())
8612       return V;
8613   }
8614
8615   // Use dedicated unpack instructions for masks that match their pattern.
8616   if (isShuffleEquivalent(V1, V2, Mask, {// Low half.
8617                                          0, 16, 1, 17, 2, 18, 3, 19,
8618                                          // High half.
8619                                          4, 20, 5, 21, 6, 22, 7, 23}))
8620     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V1, V2);
8621   if (isShuffleEquivalent(V1, V2, Mask, {// Low half.
8622                                          8, 24, 9, 25, 10, 26, 11, 27,
8623                                          // High half.
8624                                          12, 28, 13, 29, 14, 30, 15, 31}))
8625     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V1, V2);
8626
8627   // Check for SSSE3 which lets us lower all v16i8 shuffles much more directly
8628   // with PSHUFB. It is important to do this before we attempt to generate any
8629   // blends but after all of the single-input lowerings. If the single input
8630   // lowerings can find an instruction sequence that is faster than a PSHUFB, we
8631   // want to preserve that and we can DAG combine any longer sequences into
8632   // a PSHUFB in the end. But once we start blending from multiple inputs,
8633   // the complexity of DAG combining bad patterns back into PSHUFB is too high,
8634   // and there are *very* few patterns that would actually be faster than the
8635   // PSHUFB approach because of its ability to zero lanes.
8636   //
8637   // FIXME: The only exceptions to the above are blends which are exact
8638   // interleavings with direct instructions supporting them. We currently don't
8639   // handle those well here.
8640   if (Subtarget->hasSSSE3()) {
8641     bool V1InUse = false;
8642     bool V2InUse = false;
8643
8644     SDValue PSHUFB = lowerVectorShuffleAsPSHUFB(DL, MVT::v16i8, V1, V2, Mask,
8645                                                 DAG, V1InUse, V2InUse);
8646
8647     // If both V1 and V2 are in use and we can use a direct blend or an unpack,
8648     // do so. This avoids using them to handle blends-with-zero which is
8649     // important as a single pshufb is significantly faster for that.
8650     if (V1InUse && V2InUse) {
8651       if (Subtarget->hasSSE41())
8652         if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i8, V1, V2,
8653                                                       Mask, Subtarget, DAG))
8654           return Blend;
8655
8656       // We can use an unpack to do the blending rather than an or in some
8657       // cases. Even though the or may be (very minorly) more efficient, we
8658       // preference this lowering because there are common cases where part of
8659       // the complexity of the shuffles goes away when we do the final blend as
8660       // an unpack.
8661       // FIXME: It might be worth trying to detect if the unpack-feeding
8662       // shuffles will both be pshufb, in which case we shouldn't bother with
8663       // this.
8664       if (SDValue Unpack =
8665               lowerVectorShuffleAsUnpack(DL, MVT::v16i8, V1, V2, Mask, DAG))
8666         return Unpack;
8667     }
8668
8669     return PSHUFB;
8670   }
8671
8672   // There are special ways we can lower some single-element blends.
8673   if (NumV2Elements == 1)
8674     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v16i8, V1, V2,
8675                                                          Mask, Subtarget, DAG))
8676       return V;
8677
8678   if (SDValue BitBlend =
8679           lowerVectorShuffleAsBitBlend(DL, MVT::v16i8, V1, V2, Mask, DAG))
8680     return BitBlend;
8681
8682   // Check whether a compaction lowering can be done. This handles shuffles
8683   // which take every Nth element for some even N. See the helper function for
8684   // details.
8685   //
8686   // We special case these as they can be particularly efficiently handled with
8687   // the PACKUSB instruction on x86 and they show up in common patterns of
8688   // rearranging bytes to truncate wide elements.
8689   if (int NumEvenDrops = canLowerByDroppingEvenElements(Mask)) {
8690     // NumEvenDrops is the power of two stride of the elements. Another way of
8691     // thinking about it is that we need to drop the even elements this many
8692     // times to get the original input.
8693     bool IsSingleInput = isSingleInputShuffleMask(Mask);
8694
8695     // First we need to zero all the dropped bytes.
8696     assert(NumEvenDrops <= 3 &&
8697            "No support for dropping even elements more than 3 times.");
8698     // We use the mask type to pick which bytes are preserved based on how many
8699     // elements are dropped.
8700     MVT MaskVTs[] = { MVT::v8i16, MVT::v4i32, MVT::v2i64 };
8701     SDValue ByteClearMask =
8702         DAG.getNode(ISD::BITCAST, DL, MVT::v16i8,
8703                     DAG.getConstant(0xFF, MaskVTs[NumEvenDrops - 1]));
8704     V1 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V1, ByteClearMask);
8705     if (!IsSingleInput)
8706       V2 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V2, ByteClearMask);
8707
8708     // Now pack things back together.
8709     V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1);
8710     V2 = IsSingleInput ? V1 : DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V2);
8711     SDValue Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, V1, V2);
8712     for (int i = 1; i < NumEvenDrops; ++i) {
8713       Result = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, Result);
8714       Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, Result, Result);
8715     }
8716
8717     return Result;
8718   }
8719
8720   // Handle multi-input cases by blending single-input shuffles.
8721   if (NumV2Elements > 0)
8722     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v16i8, V1, V2,
8723                                                       Mask, DAG);
8724
8725   // The fallback path for single-input shuffles widens this into two v8i16
8726   // vectors with unpacks, shuffles those, and then pulls them back together
8727   // with a pack.
8728   SDValue V = V1;
8729
8730   int LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8731   int HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8732   for (int i = 0; i < 16; ++i)
8733     if (Mask[i] >= 0)
8734       (i < 8 ? LoBlendMask[i] : HiBlendMask[i % 8]) = Mask[i];
8735
8736   SDValue Zero = getZeroVector(MVT::v8i16, Subtarget, DAG, DL);
8737
8738   SDValue VLoHalf, VHiHalf;
8739   // Check if any of the odd lanes in the v16i8 are used. If not, we can mask
8740   // them out and avoid using UNPCK{L,H} to extract the elements of V as
8741   // i16s.
8742   if (std::none_of(std::begin(LoBlendMask), std::end(LoBlendMask),
8743                    [](int M) { return M >= 0 && M % 2 == 1; }) &&
8744       std::none_of(std::begin(HiBlendMask), std::end(HiBlendMask),
8745                    [](int M) { return M >= 0 && M % 2 == 1; })) {
8746     // Use a mask to drop the high bytes.
8747     VLoHalf = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V);
8748     VLoHalf = DAG.getNode(ISD::AND, DL, MVT::v8i16, VLoHalf,
8749                      DAG.getConstant(0x00FF, MVT::v8i16));
8750
8751     // This will be a single vector shuffle instead of a blend so nuke VHiHalf.
8752     VHiHalf = DAG.getUNDEF(MVT::v8i16);
8753
8754     // Squash the masks to point directly into VLoHalf.
8755     for (int &M : LoBlendMask)
8756       if (M >= 0)
8757         M /= 2;
8758     for (int &M : HiBlendMask)
8759       if (M >= 0)
8760         M /= 2;
8761   } else {
8762     // Otherwise just unpack the low half of V into VLoHalf and the high half into
8763     // VHiHalf so that we can blend them as i16s.
8764     VLoHalf = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
8765                      DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V, Zero));
8766     VHiHalf = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
8767                      DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V, Zero));
8768   }
8769
8770   SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, LoBlendMask);
8771   SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, HiBlendMask);
8772
8773   return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
8774 }
8775
8776 /// \brief Dispatching routine to lower various 128-bit x86 vector shuffles.
8777 ///
8778 /// This routine breaks down the specific type of 128-bit shuffle and
8779 /// dispatches to the lowering routines accordingly.
8780 static SDValue lower128BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8781                                         MVT VT, const X86Subtarget *Subtarget,
8782                                         SelectionDAG &DAG) {
8783   switch (VT.SimpleTy) {
8784   case MVT::v2i64:
8785     return lowerV2I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
8786   case MVT::v2f64:
8787     return lowerV2F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
8788   case MVT::v4i32:
8789     return lowerV4I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
8790   case MVT::v4f32:
8791     return lowerV4F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
8792   case MVT::v8i16:
8793     return lowerV8I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
8794   case MVT::v16i8:
8795     return lowerV16I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
8796
8797   default:
8798     llvm_unreachable("Unimplemented!");
8799   }
8800 }
8801
8802 /// \brief Helper function to test whether a shuffle mask could be
8803 /// simplified by widening the elements being shuffled.
8804 ///
8805 /// Appends the mask for wider elements in WidenedMask if valid. Otherwise
8806 /// leaves it in an unspecified state.
8807 ///
8808 /// NOTE: This must handle normal vector shuffle masks and *target* vector
8809 /// shuffle masks. The latter have the special property of a '-2' representing
8810 /// a zero-ed lane of a vector.
8811 static bool canWidenShuffleElements(ArrayRef<int> Mask,
8812                                     SmallVectorImpl<int> &WidenedMask) {
8813   for (int i = 0, Size = Mask.size(); i < Size; i += 2) {
8814     // If both elements are undef, its trivial.
8815     if (Mask[i] == SM_SentinelUndef && Mask[i + 1] == SM_SentinelUndef) {
8816       WidenedMask.push_back(SM_SentinelUndef);
8817       continue;
8818     }
8819
8820     // Check for an undef mask and a mask value properly aligned to fit with
8821     // a pair of values. If we find such a case, use the non-undef mask's value.
8822     if (Mask[i] == SM_SentinelUndef && Mask[i + 1] >= 0 && Mask[i + 1] % 2 == 1) {
8823       WidenedMask.push_back(Mask[i + 1] / 2);
8824       continue;
8825     }
8826     if (Mask[i + 1] == SM_SentinelUndef && Mask[i] >= 0 && Mask[i] % 2 == 0) {
8827       WidenedMask.push_back(Mask[i] / 2);
8828       continue;
8829     }
8830
8831     // When zeroing, we need to spread the zeroing across both lanes to widen.
8832     if (Mask[i] == SM_SentinelZero || Mask[i + 1] == SM_SentinelZero) {
8833       if ((Mask[i] == SM_SentinelZero || Mask[i] == SM_SentinelUndef) &&
8834           (Mask[i + 1] == SM_SentinelZero || Mask[i + 1] == SM_SentinelUndef)) {
8835         WidenedMask.push_back(SM_SentinelZero);
8836         continue;
8837       }
8838       return false;
8839     }
8840
8841     // Finally check if the two mask values are adjacent and aligned with
8842     // a pair.
8843     if (Mask[i] != SM_SentinelUndef && Mask[i] % 2 == 0 && Mask[i] + 1 == Mask[i + 1]) {
8844       WidenedMask.push_back(Mask[i] / 2);
8845       continue;
8846     }
8847
8848     // Otherwise we can't safely widen the elements used in this shuffle.
8849     return false;
8850   }
8851   assert(WidenedMask.size() == Mask.size() / 2 &&
8852          "Incorrect size of mask after widening the elements!");
8853
8854   return true;
8855 }
8856
8857 /// \brief Generic routine to split vector shuffle into half-sized shuffles.
8858 ///
8859 /// This routine just extracts two subvectors, shuffles them independently, and
8860 /// then concatenates them back together. This should work effectively with all
8861 /// AVX vector shuffle types.
8862 static SDValue splitAndLowerVectorShuffle(SDLoc DL, MVT VT, SDValue V1,
8863                                           SDValue V2, ArrayRef<int> Mask,
8864                                           SelectionDAG &DAG) {
8865   assert(VT.getSizeInBits() >= 256 &&
8866          "Only for 256-bit or wider vector shuffles!");
8867   assert(V1.getSimpleValueType() == VT && "Bad operand type!");
8868   assert(V2.getSimpleValueType() == VT && "Bad operand type!");
8869
8870   ArrayRef<int> LoMask = Mask.slice(0, Mask.size() / 2);
8871   ArrayRef<int> HiMask = Mask.slice(Mask.size() / 2);
8872
8873   int NumElements = VT.getVectorNumElements();
8874   int SplitNumElements = NumElements / 2;
8875   MVT ScalarVT = VT.getScalarType();
8876   MVT SplitVT = MVT::getVectorVT(ScalarVT, NumElements / 2);
8877
8878   // Rather than splitting build-vectors, just build two narrower build
8879   // vectors. This helps shuffling with splats and zeros.
8880   auto SplitVector = [&](SDValue V) {
8881     while (V.getOpcode() == ISD::BITCAST)
8882       V = V->getOperand(0);
8883
8884     MVT OrigVT = V.getSimpleValueType();
8885     int OrigNumElements = OrigVT.getVectorNumElements();
8886     int OrigSplitNumElements = OrigNumElements / 2;
8887     MVT OrigScalarVT = OrigVT.getScalarType();
8888     MVT OrigSplitVT = MVT::getVectorVT(OrigScalarVT, OrigNumElements / 2);
8889
8890     SDValue LoV, HiV;
8891
8892     auto *BV = dyn_cast<BuildVectorSDNode>(V);
8893     if (!BV) {
8894       LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
8895                         DAG.getIntPtrConstant(0));
8896       HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
8897                         DAG.getIntPtrConstant(OrigSplitNumElements));
8898     } else {
8899
8900       SmallVector<SDValue, 16> LoOps, HiOps;
8901       for (int i = 0; i < OrigSplitNumElements; ++i) {
8902         LoOps.push_back(BV->getOperand(i));
8903         HiOps.push_back(BV->getOperand(i + OrigSplitNumElements));
8904       }
8905       LoV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, LoOps);
8906       HiV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, HiOps);
8907     }
8908     return std::make_pair(DAG.getNode(ISD::BITCAST, DL, SplitVT, LoV),
8909                           DAG.getNode(ISD::BITCAST, DL, SplitVT, HiV));
8910   };
8911
8912   SDValue LoV1, HiV1, LoV2, HiV2;
8913   std::tie(LoV1, HiV1) = SplitVector(V1);
8914   std::tie(LoV2, HiV2) = SplitVector(V2);
8915
8916   // Now create two 4-way blends of these half-width vectors.
8917   auto HalfBlend = [&](ArrayRef<int> HalfMask) {
8918     bool UseLoV1 = false, UseHiV1 = false, UseLoV2 = false, UseHiV2 = false;
8919     SmallVector<int, 32> V1BlendMask, V2BlendMask, BlendMask;
8920     for (int i = 0; i < SplitNumElements; ++i) {
8921       int M = HalfMask[i];
8922       if (M >= NumElements) {
8923         if (M >= NumElements + SplitNumElements)
8924           UseHiV2 = true;
8925         else
8926           UseLoV2 = true;
8927         V2BlendMask.push_back(M - NumElements);
8928         V1BlendMask.push_back(-1);
8929         BlendMask.push_back(SplitNumElements + i);
8930       } else if (M >= 0) {
8931         if (M >= SplitNumElements)
8932           UseHiV1 = true;
8933         else
8934           UseLoV1 = true;
8935         V2BlendMask.push_back(-1);
8936         V1BlendMask.push_back(M);
8937         BlendMask.push_back(i);
8938       } else {
8939         V2BlendMask.push_back(-1);
8940         V1BlendMask.push_back(-1);
8941         BlendMask.push_back(-1);
8942       }
8943     }
8944
8945     // Because the lowering happens after all combining takes place, we need to
8946     // manually combine these blend masks as much as possible so that we create
8947     // a minimal number of high-level vector shuffle nodes.
8948
8949     // First try just blending the halves of V1 or V2.
8950     if (!UseLoV1 && !UseHiV1 && !UseLoV2 && !UseHiV2)
8951       return DAG.getUNDEF(SplitVT);
8952     if (!UseLoV2 && !UseHiV2)
8953       return DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
8954     if (!UseLoV1 && !UseHiV1)
8955       return DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
8956
8957     SDValue V1Blend, V2Blend;
8958     if (UseLoV1 && UseHiV1) {
8959       V1Blend =
8960         DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
8961     } else {
8962       // We only use half of V1 so map the usage down into the final blend mask.
8963       V1Blend = UseLoV1 ? LoV1 : HiV1;
8964       for (int i = 0; i < SplitNumElements; ++i)
8965         if (BlendMask[i] >= 0 && BlendMask[i] < SplitNumElements)
8966           BlendMask[i] = V1BlendMask[i] - (UseLoV1 ? 0 : SplitNumElements);
8967     }
8968     if (UseLoV2 && UseHiV2) {
8969       V2Blend =
8970         DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
8971     } else {
8972       // We only use half of V2 so map the usage down into the final blend mask.
8973       V2Blend = UseLoV2 ? LoV2 : HiV2;
8974       for (int i = 0; i < SplitNumElements; ++i)
8975         if (BlendMask[i] >= SplitNumElements)
8976           BlendMask[i] = V2BlendMask[i] + (UseLoV2 ? SplitNumElements : 0);
8977     }
8978     return DAG.getVectorShuffle(SplitVT, DL, V1Blend, V2Blend, BlendMask);
8979   };
8980   SDValue Lo = HalfBlend(LoMask);
8981   SDValue Hi = HalfBlend(HiMask);
8982   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
8983 }
8984
8985 /// \brief Either split a vector in halves or decompose the shuffles and the
8986 /// blend.
8987 ///
8988 /// This is provided as a good fallback for many lowerings of non-single-input
8989 /// shuffles with more than one 128-bit lane. In those cases, we want to select
8990 /// between splitting the shuffle into 128-bit components and stitching those
8991 /// back together vs. extracting the single-input shuffles and blending those
8992 /// results.
8993 static SDValue lowerVectorShuffleAsSplitOrBlend(SDLoc DL, MVT VT, SDValue V1,
8994                                                 SDValue V2, ArrayRef<int> Mask,
8995                                                 SelectionDAG &DAG) {
8996   assert(!isSingleInputShuffleMask(Mask) && "This routine must not be used to "
8997                                             "lower single-input shuffles as it "
8998                                             "could then recurse on itself.");
8999   int Size = Mask.size();
9000
9001   // If this can be modeled as a broadcast of two elements followed by a blend,
9002   // prefer that lowering. This is especially important because broadcasts can
9003   // often fold with memory operands.
9004   auto DoBothBroadcast = [&] {
9005     int V1BroadcastIdx = -1, V2BroadcastIdx = -1;
9006     for (int M : Mask)
9007       if (M >= Size) {
9008         if (V2BroadcastIdx == -1)
9009           V2BroadcastIdx = M - Size;
9010         else if (M - Size != V2BroadcastIdx)
9011           return false;
9012       } else if (M >= 0) {
9013         if (V1BroadcastIdx == -1)
9014           V1BroadcastIdx = M;
9015         else if (M != V1BroadcastIdx)
9016           return false;
9017       }
9018     return true;
9019   };
9020   if (DoBothBroadcast())
9021     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask,
9022                                                       DAG);
9023
9024   // If the inputs all stem from a single 128-bit lane of each input, then we
9025   // split them rather than blending because the split will decompose to
9026   // unusually few instructions.
9027   int LaneCount = VT.getSizeInBits() / 128;
9028   int LaneSize = Size / LaneCount;
9029   SmallBitVector LaneInputs[2];
9030   LaneInputs[0].resize(LaneCount, false);
9031   LaneInputs[1].resize(LaneCount, false);
9032   for (int i = 0; i < Size; ++i)
9033     if (Mask[i] >= 0)
9034       LaneInputs[Mask[i] / Size][(Mask[i] % Size) / LaneSize] = true;
9035   if (LaneInputs[0].count() <= 1 && LaneInputs[1].count() <= 1)
9036     return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9037
9038   // Otherwise, just fall back to decomposed shuffles and a blend. This requires
9039   // that the decomposed single-input shuffles don't end up here.
9040   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9041 }
9042
9043 /// \brief Lower a vector shuffle crossing multiple 128-bit lanes as
9044 /// a permutation and blend of those lanes.
9045 ///
9046 /// This essentially blends the out-of-lane inputs to each lane into the lane
9047 /// from a permuted copy of the vector. This lowering strategy results in four
9048 /// instructions in the worst case for a single-input cross lane shuffle which
9049 /// is lower than any other fully general cross-lane shuffle strategy I'm aware
9050 /// of. Special cases for each particular shuffle pattern should be handled
9051 /// prior to trying this lowering.
9052 static SDValue lowerVectorShuffleAsLanePermuteAndBlend(SDLoc DL, MVT VT,
9053                                                        SDValue V1, SDValue V2,
9054                                                        ArrayRef<int> Mask,
9055                                                        SelectionDAG &DAG) {
9056   // FIXME: This should probably be generalized for 512-bit vectors as well.
9057   assert(VT.getSizeInBits() == 256 && "Only for 256-bit vector shuffles!");
9058   int LaneSize = Mask.size() / 2;
9059
9060   // If there are only inputs from one 128-bit lane, splitting will in fact be
9061   // less expensive. The flags track whether the given lane contains an element
9062   // that crosses to another lane.
9063   bool LaneCrossing[2] = {false, false};
9064   for (int i = 0, Size = Mask.size(); i < Size; ++i)
9065     if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
9066       LaneCrossing[(Mask[i] % Size) / LaneSize] = true;
9067   if (!LaneCrossing[0] || !LaneCrossing[1])
9068     return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9069
9070   if (isSingleInputShuffleMask(Mask)) {
9071     SmallVector<int, 32> FlippedBlendMask;
9072     for (int i = 0, Size = Mask.size(); i < Size; ++i)
9073       FlippedBlendMask.push_back(
9074           Mask[i] < 0 ? -1 : (((Mask[i] % Size) / LaneSize == i / LaneSize)
9075                                   ? Mask[i]
9076                                   : Mask[i] % LaneSize +
9077                                         (i / LaneSize) * LaneSize + Size));
9078
9079     // Flip the vector, and blend the results which should now be in-lane. The
9080     // VPERM2X128 mask uses the low 2 bits for the low source and bits 4 and
9081     // 5 for the high source. The value 3 selects the high half of source 2 and
9082     // the value 2 selects the low half of source 2. We only use source 2 to
9083     // allow folding it into a memory operand.
9084     unsigned PERMMask = 3 | 2 << 4;
9085     SDValue Flipped = DAG.getNode(X86ISD::VPERM2X128, DL, VT, DAG.getUNDEF(VT),
9086                                   V1, DAG.getConstant(PERMMask, MVT::i8));
9087     return DAG.getVectorShuffle(VT, DL, V1, Flipped, FlippedBlendMask);
9088   }
9089
9090   // This now reduces to two single-input shuffles of V1 and V2 which at worst
9091   // will be handled by the above logic and a blend of the results, much like
9092   // other patterns in AVX.
9093   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9094 }
9095
9096 /// \brief Handle lowering 2-lane 128-bit shuffles.
9097 static SDValue lowerV2X128VectorShuffle(SDLoc DL, MVT VT, SDValue V1,
9098                                         SDValue V2, ArrayRef<int> Mask,
9099                                         const X86Subtarget *Subtarget,
9100                                         SelectionDAG &DAG) {
9101   // TODO: If minimizing size and one of the inputs is a zero vector and the
9102   // the zero vector has only one use, we could use a VPERM2X128 to save the
9103   // instruction bytes needed to explicitly generate the zero vector.
9104
9105   // Blends are faster and handle all the non-lane-crossing cases.
9106   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, VT, V1, V2, Mask,
9107                                                 Subtarget, DAG))
9108     return Blend;
9109
9110   bool IsV1Zero = ISD::isBuildVectorAllZeros(V1.getNode());
9111   bool IsV2Zero = ISD::isBuildVectorAllZeros(V2.getNode());
9112
9113   // If either input operand is a zero vector, use VPERM2X128 because its mask
9114   // allows us to replace the zero input with an implicit zero.
9115   if (!IsV1Zero && !IsV2Zero) {
9116     // Check for patterns which can be matched with a single insert of a 128-bit
9117     // subvector.
9118     bool OnlyUsesV1 = isShuffleEquivalent(V1, V2, Mask, {0, 1, 0, 1});
9119     if (OnlyUsesV1 || isShuffleEquivalent(V1, V2, Mask, {0, 1, 4, 5})) {
9120       MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(),
9121                                    VT.getVectorNumElements() / 2);
9122       SDValue LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V1,
9123                                 DAG.getIntPtrConstant(0));
9124       SDValue HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT,
9125                                 OnlyUsesV1 ? V1 : V2, DAG.getIntPtrConstant(0));
9126       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LoV, HiV);
9127     }
9128   }
9129
9130   // Otherwise form a 128-bit permutation. After accounting for undefs,
9131   // convert the 64-bit shuffle mask selection values into 128-bit
9132   // selection bits by dividing the indexes by 2 and shifting into positions
9133   // defined by a vperm2*128 instruction's immediate control byte.
9134
9135   // The immediate permute control byte looks like this:
9136   //    [1:0] - select 128 bits from sources for low half of destination
9137   //    [2]   - ignore
9138   //    [3]   - zero low half of destination
9139   //    [5:4] - select 128 bits from sources for high half of destination
9140   //    [6]   - ignore
9141   //    [7]   - zero high half of destination
9142
9143   int MaskLO = Mask[0];
9144   if (MaskLO == SM_SentinelUndef)
9145     MaskLO = Mask[1] == SM_SentinelUndef ? 0 : Mask[1];
9146
9147   int MaskHI = Mask[2];
9148   if (MaskHI == SM_SentinelUndef)
9149     MaskHI = Mask[3] == SM_SentinelUndef ? 0 : Mask[3];
9150
9151   unsigned PermMask = MaskLO / 2 | (MaskHI / 2) << 4;
9152
9153   // If either input is a zero vector, replace it with an undef input.
9154   // Shuffle mask values <  4 are selecting elements of V1.
9155   // Shuffle mask values >= 4 are selecting elements of V2.
9156   // Adjust each half of the permute mask by clearing the half that was
9157   // selecting the zero vector and setting the zero mask bit.
9158   if (IsV1Zero) {
9159     V1 = DAG.getUNDEF(VT);
9160     if (MaskLO < 4)
9161       PermMask = (PermMask & 0xf0) | 0x08;
9162     if (MaskHI < 4)
9163       PermMask = (PermMask & 0x0f) | 0x80;
9164   }
9165   if (IsV2Zero) {
9166     V2 = DAG.getUNDEF(VT);
9167     if (MaskLO >= 4)
9168       PermMask = (PermMask & 0xf0) | 0x08;
9169     if (MaskHI >= 4)
9170       PermMask = (PermMask & 0x0f) | 0x80;
9171   }
9172
9173   return DAG.getNode(X86ISD::VPERM2X128, DL, VT, V1, V2,
9174                      DAG.getConstant(PermMask, MVT::i8));
9175 }
9176
9177 /// \brief Lower a vector shuffle by first fixing the 128-bit lanes and then
9178 /// shuffling each lane.
9179 ///
9180 /// This will only succeed when the result of fixing the 128-bit lanes results
9181 /// in a single-input non-lane-crossing shuffle with a repeating shuffle mask in
9182 /// each 128-bit lanes. This handles many cases where we can quickly blend away
9183 /// the lane crosses early and then use simpler shuffles within each lane.
9184 ///
9185 /// FIXME: It might be worthwhile at some point to support this without
9186 /// requiring the 128-bit lane-relative shuffles to be repeating, but currently
9187 /// in x86 only floating point has interesting non-repeating shuffles, and even
9188 /// those are still *marginally* more expensive.
9189 static SDValue lowerVectorShuffleByMerging128BitLanes(
9190     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
9191     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
9192   assert(!isSingleInputShuffleMask(Mask) &&
9193          "This is only useful with multiple inputs.");
9194
9195   int Size = Mask.size();
9196   int LaneSize = 128 / VT.getScalarSizeInBits();
9197   int NumLanes = Size / LaneSize;
9198   assert(NumLanes > 1 && "Only handles 256-bit and wider shuffles.");
9199
9200   // See if we can build a hypothetical 128-bit lane-fixing shuffle mask. Also
9201   // check whether the in-128-bit lane shuffles share a repeating pattern.
9202   SmallVector<int, 4> Lanes;
9203   Lanes.resize(NumLanes, -1);
9204   SmallVector<int, 4> InLaneMask;
9205   InLaneMask.resize(LaneSize, -1);
9206   for (int i = 0; i < Size; ++i) {
9207     if (Mask[i] < 0)
9208       continue;
9209
9210     int j = i / LaneSize;
9211
9212     if (Lanes[j] < 0) {
9213       // First entry we've seen for this lane.
9214       Lanes[j] = Mask[i] / LaneSize;
9215     } else if (Lanes[j] != Mask[i] / LaneSize) {
9216       // This doesn't match the lane selected previously!
9217       return SDValue();
9218     }
9219
9220     // Check that within each lane we have a consistent shuffle mask.
9221     int k = i % LaneSize;
9222     if (InLaneMask[k] < 0) {
9223       InLaneMask[k] = Mask[i] % LaneSize;
9224     } else if (InLaneMask[k] != Mask[i] % LaneSize) {
9225       // This doesn't fit a repeating in-lane mask.
9226       return SDValue();
9227     }
9228   }
9229
9230   // First shuffle the lanes into place.
9231   MVT LaneVT = MVT::getVectorVT(VT.isFloatingPoint() ? MVT::f64 : MVT::i64,
9232                                 VT.getSizeInBits() / 64);
9233   SmallVector<int, 8> LaneMask;
9234   LaneMask.resize(NumLanes * 2, -1);
9235   for (int i = 0; i < NumLanes; ++i)
9236     if (Lanes[i] >= 0) {
9237       LaneMask[2 * i + 0] = 2*Lanes[i] + 0;
9238       LaneMask[2 * i + 1] = 2*Lanes[i] + 1;
9239     }
9240
9241   V1 = DAG.getNode(ISD::BITCAST, DL, LaneVT, V1);
9242   V2 = DAG.getNode(ISD::BITCAST, DL, LaneVT, V2);
9243   SDValue LaneShuffle = DAG.getVectorShuffle(LaneVT, DL, V1, V2, LaneMask);
9244
9245   // Cast it back to the type we actually want.
9246   LaneShuffle = DAG.getNode(ISD::BITCAST, DL, VT, LaneShuffle);
9247
9248   // Now do a simple shuffle that isn't lane crossing.
9249   SmallVector<int, 8> NewMask;
9250   NewMask.resize(Size, -1);
9251   for (int i = 0; i < Size; ++i)
9252     if (Mask[i] >= 0)
9253       NewMask[i] = (i / LaneSize) * LaneSize + Mask[i] % LaneSize;
9254   assert(!is128BitLaneCrossingShuffleMask(VT, NewMask) &&
9255          "Must not introduce lane crosses at this point!");
9256
9257   return DAG.getVectorShuffle(VT, DL, LaneShuffle, DAG.getUNDEF(VT), NewMask);
9258 }
9259
9260 /// \brief Test whether the specified input (0 or 1) is in-place blended by the
9261 /// given mask.
9262 ///
9263 /// This returns true if the elements from a particular input are already in the
9264 /// slot required by the given mask and require no permutation.
9265 static bool isShuffleMaskInputInPlace(int Input, ArrayRef<int> Mask) {
9266   assert((Input == 0 || Input == 1) && "Only two inputs to shuffles.");
9267   int Size = Mask.size();
9268   for (int i = 0; i < Size; ++i)
9269     if (Mask[i] >= 0 && Mask[i] / Size == Input && Mask[i] % Size != i)
9270       return false;
9271
9272   return true;
9273 }
9274
9275 /// \brief Handle lowering of 4-lane 64-bit floating point shuffles.
9276 ///
9277 /// Also ends up handling lowering of 4-lane 64-bit integer shuffles when AVX2
9278 /// isn't available.
9279 static SDValue lowerV4F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9280                                        const X86Subtarget *Subtarget,
9281                                        SelectionDAG &DAG) {
9282   SDLoc DL(Op);
9283   assert(V1.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
9284   assert(V2.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
9285   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9286   ArrayRef<int> Mask = SVOp->getMask();
9287   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
9288
9289   SmallVector<int, 4> WidenedMask;
9290   if (canWidenShuffleElements(Mask, WidenedMask))
9291     return lowerV2X128VectorShuffle(DL, MVT::v4f64, V1, V2, Mask, Subtarget,
9292                                     DAG);
9293
9294   if (isSingleInputShuffleMask(Mask)) {
9295     // Check for being able to broadcast a single element.
9296     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f64, V1,
9297                                                           Mask, Subtarget, DAG))
9298       return Broadcast;
9299
9300     // Use low duplicate instructions for masks that match their pattern.
9301     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
9302       return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v4f64, V1);
9303
9304     if (!is128BitLaneCrossingShuffleMask(MVT::v4f64, Mask)) {
9305       // Non-half-crossing single input shuffles can be lowerid with an
9306       // interleaved permutation.
9307       unsigned VPERMILPMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1) |
9308                               ((Mask[2] == 3) << 2) | ((Mask[3] == 3) << 3);
9309       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f64, V1,
9310                          DAG.getConstant(VPERMILPMask, MVT::i8));
9311     }
9312
9313     // With AVX2 we have direct support for this permutation.
9314     if (Subtarget->hasAVX2())
9315       return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4f64, V1,
9316                          getV4X86ShuffleImm8ForMask(Mask, DAG));
9317
9318     // Otherwise, fall back.
9319     return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v4f64, V1, V2, Mask,
9320                                                    DAG);
9321   }
9322
9323   // X86 has dedicated unpack instructions that can handle specific blend
9324   // operations: UNPCKH and UNPCKL.
9325   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 2, 6}))
9326     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V1, V2);
9327   if (isShuffleEquivalent(V1, V2, Mask, {1, 5, 3, 7}))
9328     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V1, V2);
9329   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 6, 2}))
9330     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V2, V1);
9331   if (isShuffleEquivalent(V1, V2, Mask, {5, 1, 7, 3}))
9332     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V2, V1);
9333
9334   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f64, V1, V2, Mask,
9335                                                 Subtarget, DAG))
9336     return Blend;
9337
9338   // Check if the blend happens to exactly fit that of SHUFPD.
9339   if ((Mask[0] == -1 || Mask[0] < 2) &&
9340       (Mask[1] == -1 || (Mask[1] >= 4 && Mask[1] < 6)) &&
9341       (Mask[2] == -1 || (Mask[2] >= 2 && Mask[2] < 4)) &&
9342       (Mask[3] == -1 || Mask[3] >= 6)) {
9343     unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 5) << 1) |
9344                           ((Mask[2] == 3) << 2) | ((Mask[3] == 7) << 3);
9345     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f64, V1, V2,
9346                        DAG.getConstant(SHUFPDMask, MVT::i8));
9347   }
9348   if ((Mask[0] == -1 || (Mask[0] >= 4 && Mask[0] < 6)) &&
9349       (Mask[1] == -1 || Mask[1] < 2) &&
9350       (Mask[2] == -1 || Mask[2] >= 6) &&
9351       (Mask[3] == -1 || (Mask[3] >= 2 && Mask[3] < 4))) {
9352     unsigned SHUFPDMask = (Mask[0] == 5) | ((Mask[1] == 1) << 1) |
9353                           ((Mask[2] == 7) << 2) | ((Mask[3] == 3) << 3);
9354     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f64, V2, V1,
9355                        DAG.getConstant(SHUFPDMask, MVT::i8));
9356   }
9357
9358   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9359   // shuffle. However, if we have AVX2 and either inputs are already in place,
9360   // we will be able to shuffle even across lanes the other input in a single
9361   // instruction so skip this pattern.
9362   if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
9363                                  isShuffleMaskInputInPlace(1, Mask))))
9364     if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9365             DL, MVT::v4f64, V1, V2, Mask, Subtarget, DAG))
9366       return Result;
9367
9368   // If we have AVX2 then we always want to lower with a blend because an v4 we
9369   // can fully permute the elements.
9370   if (Subtarget->hasAVX2())
9371     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4f64, V1, V2,
9372                                                       Mask, DAG);
9373
9374   // Otherwise fall back on generic lowering.
9375   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v4f64, V1, V2, Mask, DAG);
9376 }
9377
9378 /// \brief Handle lowering of 4-lane 64-bit integer shuffles.
9379 ///
9380 /// This routine is only called when we have AVX2 and thus a reasonable
9381 /// instruction set for v4i64 shuffling..
9382 static SDValue lowerV4I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9383                                        const X86Subtarget *Subtarget,
9384                                        SelectionDAG &DAG) {
9385   SDLoc DL(Op);
9386   assert(V1.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
9387   assert(V2.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
9388   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9389   ArrayRef<int> Mask = SVOp->getMask();
9390   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
9391   assert(Subtarget->hasAVX2() && "We can only lower v4i64 with AVX2!");
9392
9393   SmallVector<int, 4> WidenedMask;
9394   if (canWidenShuffleElements(Mask, WidenedMask))
9395     return lowerV2X128VectorShuffle(DL, MVT::v4i64, V1, V2, Mask, Subtarget,
9396                                     DAG);
9397
9398   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i64, V1, V2, Mask,
9399                                                 Subtarget, DAG))
9400     return Blend;
9401
9402   // Check for being able to broadcast a single element.
9403   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i64, V1,
9404                                                         Mask, Subtarget, DAG))
9405     return Broadcast;
9406
9407   // When the shuffle is mirrored between the 128-bit lanes of the unit, we can
9408   // use lower latency instructions that will operate on both 128-bit lanes.
9409   SmallVector<int, 2> RepeatedMask;
9410   if (is128BitLaneRepeatedShuffleMask(MVT::v4i64, Mask, RepeatedMask)) {
9411     if (isSingleInputShuffleMask(Mask)) {
9412       int PSHUFDMask[] = {-1, -1, -1, -1};
9413       for (int i = 0; i < 2; ++i)
9414         if (RepeatedMask[i] >= 0) {
9415           PSHUFDMask[2 * i] = 2 * RepeatedMask[i];
9416           PSHUFDMask[2 * i + 1] = 2 * RepeatedMask[i] + 1;
9417         }
9418       return DAG.getNode(
9419           ISD::BITCAST, DL, MVT::v4i64,
9420           DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32,
9421                       DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, V1),
9422                       getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
9423     }
9424   }
9425
9426   // AVX2 provides a direct instruction for permuting a single input across
9427   // lanes.
9428   if (isSingleInputShuffleMask(Mask))
9429     return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4i64, V1,
9430                        getV4X86ShuffleImm8ForMask(Mask, DAG));
9431
9432   // Try to use shift instructions.
9433   if (SDValue Shift =
9434           lowerVectorShuffleAsShift(DL, MVT::v4i64, V1, V2, Mask, DAG))
9435     return Shift;
9436
9437   // Use dedicated unpack instructions for masks that match their pattern.
9438   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 2, 6}))
9439     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V1, V2);
9440   if (isShuffleEquivalent(V1, V2, Mask, {1, 5, 3, 7}))
9441     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V1, V2);
9442   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 6, 2}))
9443     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V2, V1);
9444   if (isShuffleEquivalent(V1, V2, Mask, {5, 1, 7, 3}))
9445     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V2, V1);
9446
9447   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9448   // shuffle. However, if we have AVX2 and either inputs are already in place,
9449   // we will be able to shuffle even across lanes the other input in a single
9450   // instruction so skip this pattern.
9451   if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
9452                                  isShuffleMaskInputInPlace(1, Mask))))
9453     if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9454             DL, MVT::v4i64, V1, V2, Mask, Subtarget, DAG))
9455       return Result;
9456
9457   // Otherwise fall back on generic blend lowering.
9458   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i64, V1, V2,
9459                                                     Mask, DAG);
9460 }
9461
9462 /// \brief Handle lowering of 8-lane 32-bit floating point shuffles.
9463 ///
9464 /// Also ends up handling lowering of 8-lane 32-bit integer shuffles when AVX2
9465 /// isn't available.
9466 static SDValue lowerV8F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9467                                        const X86Subtarget *Subtarget,
9468                                        SelectionDAG &DAG) {
9469   SDLoc DL(Op);
9470   assert(V1.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
9471   assert(V2.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
9472   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9473   ArrayRef<int> Mask = SVOp->getMask();
9474   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9475
9476   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8f32, V1, V2, Mask,
9477                                                 Subtarget, DAG))
9478     return Blend;
9479
9480   // Check for being able to broadcast a single element.
9481   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8f32, V1,
9482                                                         Mask, Subtarget, DAG))
9483     return Broadcast;
9484
9485   // If the shuffle mask is repeated in each 128-bit lane, we have many more
9486   // options to efficiently lower the shuffle.
9487   SmallVector<int, 4> RepeatedMask;
9488   if (is128BitLaneRepeatedShuffleMask(MVT::v8f32, Mask, RepeatedMask)) {
9489     assert(RepeatedMask.size() == 4 &&
9490            "Repeated masks must be half the mask width!");
9491
9492     // Use even/odd duplicate instructions for masks that match their pattern.
9493     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2, 4, 4, 6, 6}))
9494       return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v8f32, V1);
9495     if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3, 5, 5, 7, 7}))
9496       return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v8f32, V1);
9497
9498     if (isSingleInputShuffleMask(Mask))
9499       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v8f32, V1,
9500                          getV4X86ShuffleImm8ForMask(RepeatedMask, DAG));
9501
9502     // Use dedicated unpack instructions for masks that match their pattern.
9503     if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 4, 12, 5, 13}))
9504       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V1, V2);
9505     if (isShuffleEquivalent(V1, V2, Mask, {2, 10, 3, 11, 6, 14, 7, 15}))
9506       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V1, V2);
9507     if (isShuffleEquivalent(V1, V2, Mask, {8, 0, 9, 1, 12, 4, 13, 5}))
9508       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V2, V1);
9509     if (isShuffleEquivalent(V1, V2, Mask, {10, 2, 11, 3, 14, 6, 15, 7}))
9510       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V2, V1);
9511
9512     // Otherwise, fall back to a SHUFPS sequence. Here it is important that we
9513     // have already handled any direct blends. We also need to squash the
9514     // repeated mask into a simulated v4f32 mask.
9515     for (int i = 0; i < 4; ++i)
9516       if (RepeatedMask[i] >= 8)
9517         RepeatedMask[i] -= 4;
9518     return lowerVectorShuffleWithSHUFPS(DL, MVT::v8f32, RepeatedMask, V1, V2, DAG);
9519   }
9520
9521   // If we have a single input shuffle with different shuffle patterns in the
9522   // two 128-bit lanes use the variable mask to VPERMILPS.
9523   if (isSingleInputShuffleMask(Mask)) {
9524     SDValue VPermMask[8];
9525     for (int i = 0; i < 8; ++i)
9526       VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
9527                                  : DAG.getConstant(Mask[i], MVT::i32);
9528     if (!is128BitLaneCrossingShuffleMask(MVT::v8f32, Mask))
9529       return DAG.getNode(
9530           X86ISD::VPERMILPV, DL, MVT::v8f32, V1,
9531           DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask));
9532
9533     if (Subtarget->hasAVX2())
9534       return DAG.getNode(X86ISD::VPERMV, DL, MVT::v8f32,
9535                          DAG.getNode(ISD::BITCAST, DL, MVT::v8f32,
9536                                      DAG.getNode(ISD::BUILD_VECTOR, DL,
9537                                                  MVT::v8i32, VPermMask)),
9538                          V1);
9539
9540     // Otherwise, fall back.
9541     return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v8f32, V1, V2, Mask,
9542                                                    DAG);
9543   }
9544
9545   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9546   // shuffle.
9547   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9548           DL, MVT::v8f32, V1, V2, Mask, Subtarget, DAG))
9549     return Result;
9550
9551   // If we have AVX2 then we always want to lower with a blend because at v8 we
9552   // can fully permute the elements.
9553   if (Subtarget->hasAVX2())
9554     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8f32, V1, V2,
9555                                                       Mask, DAG);
9556
9557   // Otherwise fall back on generic lowering.
9558   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v8f32, V1, V2, Mask, DAG);
9559 }
9560
9561 /// \brief Handle lowering of 8-lane 32-bit integer shuffles.
9562 ///
9563 /// This routine is only called when we have AVX2 and thus a reasonable
9564 /// instruction set for v8i32 shuffling..
9565 static SDValue lowerV8I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9566                                        const X86Subtarget *Subtarget,
9567                                        SelectionDAG &DAG) {
9568   SDLoc DL(Op);
9569   assert(V1.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
9570   assert(V2.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
9571   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9572   ArrayRef<int> Mask = SVOp->getMask();
9573   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9574   assert(Subtarget->hasAVX2() && "We can only lower v8i32 with AVX2!");
9575
9576   // Whenever we can lower this as a zext, that instruction is strictly faster
9577   // than any alternative. It also allows us to fold memory operands into the
9578   // shuffle in many cases.
9579   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v8i32, V1, V2,
9580                                                          Mask, Subtarget, DAG))
9581     return ZExt;
9582
9583   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i32, V1, V2, Mask,
9584                                                 Subtarget, DAG))
9585     return Blend;
9586
9587   // Check for being able to broadcast a single element.
9588   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i32, V1,
9589                                                         Mask, Subtarget, DAG))
9590     return Broadcast;
9591
9592   // If the shuffle mask is repeated in each 128-bit lane we can use more
9593   // efficient instructions that mirror the shuffles across the two 128-bit
9594   // lanes.
9595   SmallVector<int, 4> RepeatedMask;
9596   if (is128BitLaneRepeatedShuffleMask(MVT::v8i32, Mask, RepeatedMask)) {
9597     assert(RepeatedMask.size() == 4 && "Unexpected repeated mask size!");
9598     if (isSingleInputShuffleMask(Mask))
9599       return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32, V1,
9600                          getV4X86ShuffleImm8ForMask(RepeatedMask, DAG));
9601
9602     // Use dedicated unpack instructions for masks that match their pattern.
9603     if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 4, 12, 5, 13}))
9604       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V1, V2);
9605     if (isShuffleEquivalent(V1, V2, Mask, {2, 10, 3, 11, 6, 14, 7, 15}))
9606       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V1, V2);
9607     if (isShuffleEquivalent(V1, V2, Mask, {8, 0, 9, 1, 12, 4, 13, 5}))
9608       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V2, V1);
9609     if (isShuffleEquivalent(V1, V2, Mask, {10, 2, 11, 3, 14, 6, 15, 7}))
9610       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V2, V1);
9611   }
9612
9613   // Try to use shift instructions.
9614   if (SDValue Shift =
9615           lowerVectorShuffleAsShift(DL, MVT::v8i32, V1, V2, Mask, DAG))
9616     return Shift;
9617
9618   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9619           DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
9620     return Rotate;
9621
9622   // If the shuffle patterns aren't repeated but it is a single input, directly
9623   // generate a cross-lane VPERMD instruction.
9624   if (isSingleInputShuffleMask(Mask)) {
9625     SDValue VPermMask[8];
9626     for (int i = 0; i < 8; ++i)
9627       VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
9628                                  : DAG.getConstant(Mask[i], MVT::i32);
9629     return DAG.getNode(
9630         X86ISD::VPERMV, DL, MVT::v8i32,
9631         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask), V1);
9632   }
9633
9634   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9635   // shuffle.
9636   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9637           DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
9638     return Result;
9639
9640   // Otherwise fall back on generic blend lowering.
9641   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i32, V1, V2,
9642                                                     Mask, DAG);
9643 }
9644
9645 /// \brief Handle lowering of 16-lane 16-bit integer shuffles.
9646 ///
9647 /// This routine is only called when we have AVX2 and thus a reasonable
9648 /// instruction set for v16i16 shuffling..
9649 static SDValue lowerV16I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9650                                         const X86Subtarget *Subtarget,
9651                                         SelectionDAG &DAG) {
9652   SDLoc DL(Op);
9653   assert(V1.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
9654   assert(V2.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
9655   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9656   ArrayRef<int> Mask = SVOp->getMask();
9657   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
9658   assert(Subtarget->hasAVX2() && "We can only lower v16i16 with AVX2!");
9659
9660   // Whenever we can lower this as a zext, that instruction is strictly faster
9661   // than any alternative. It also allows us to fold memory operands into the
9662   // shuffle in many cases.
9663   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v16i16, V1, V2,
9664                                                          Mask, Subtarget, DAG))
9665     return ZExt;
9666
9667   // Check for being able to broadcast a single element.
9668   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i16, V1,
9669                                                         Mask, Subtarget, DAG))
9670     return Broadcast;
9671
9672   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i16, V1, V2, Mask,
9673                                                 Subtarget, DAG))
9674     return Blend;
9675
9676   // Use dedicated unpack instructions for masks that match their pattern.
9677   if (isShuffleEquivalent(V1, V2, Mask,
9678                           {// First 128-bit lane:
9679                            0, 16, 1, 17, 2, 18, 3, 19,
9680                            // Second 128-bit lane:
9681                            8, 24, 9, 25, 10, 26, 11, 27}))
9682     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i16, V1, V2);
9683   if (isShuffleEquivalent(V1, V2, Mask,
9684                           {// First 128-bit lane:
9685                            4, 20, 5, 21, 6, 22, 7, 23,
9686                            // Second 128-bit lane:
9687                            12, 28, 13, 29, 14, 30, 15, 31}))
9688     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i16, V1, V2);
9689
9690   // Try to use shift instructions.
9691   if (SDValue Shift =
9692           lowerVectorShuffleAsShift(DL, MVT::v16i16, V1, V2, Mask, DAG))
9693     return Shift;
9694
9695   // Try to use byte rotation instructions.
9696   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9697           DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
9698     return Rotate;
9699
9700   if (isSingleInputShuffleMask(Mask)) {
9701     // There are no generalized cross-lane shuffle operations available on i16
9702     // element types.
9703     if (is128BitLaneCrossingShuffleMask(MVT::v16i16, Mask))
9704       return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v16i16, V1, V2,
9705                                                      Mask, DAG);
9706
9707     SmallVector<int, 8> RepeatedMask;
9708     if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
9709       // As this is a single-input shuffle, the repeated mask should be
9710       // a strictly valid v8i16 mask that we can pass through to the v8i16
9711       // lowering to handle even the v16 case.
9712       return lowerV8I16GeneralSingleInputVectorShuffle(
9713           DL, MVT::v16i16, V1, RepeatedMask, Subtarget, DAG);
9714     }
9715
9716     SDValue PSHUFBMask[32];
9717     for (int i = 0; i < 16; ++i) {
9718       if (Mask[i] == -1) {
9719         PSHUFBMask[2 * i] = PSHUFBMask[2 * i + 1] = DAG.getUNDEF(MVT::i8);
9720         continue;
9721       }
9722
9723       int M = i < 8 ? Mask[i] : Mask[i] - 8;
9724       assert(M >= 0 && M < 8 && "Invalid single-input mask!");
9725       PSHUFBMask[2 * i] = DAG.getConstant(2 * M, MVT::i8);
9726       PSHUFBMask[2 * i + 1] = DAG.getConstant(2 * M + 1, MVT::i8);
9727     }
9728     return DAG.getNode(
9729         ISD::BITCAST, DL, MVT::v16i16,
9730         DAG.getNode(
9731             X86ISD::PSHUFB, DL, MVT::v32i8,
9732             DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, V1),
9733             DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, PSHUFBMask)));
9734   }
9735
9736   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9737   // shuffle.
9738   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9739           DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
9740     return Result;
9741
9742   // Otherwise fall back on generic lowering.
9743   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v16i16, V1, V2, Mask, DAG);
9744 }
9745
9746 /// \brief Handle lowering of 32-lane 8-bit integer shuffles.
9747 ///
9748 /// This routine is only called when we have AVX2 and thus a reasonable
9749 /// instruction set for v32i8 shuffling..
9750 static SDValue lowerV32I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9751                                        const X86Subtarget *Subtarget,
9752                                        SelectionDAG &DAG) {
9753   SDLoc DL(Op);
9754   assert(V1.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
9755   assert(V2.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
9756   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9757   ArrayRef<int> Mask = SVOp->getMask();
9758   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
9759   assert(Subtarget->hasAVX2() && "We can only lower v32i8 with AVX2!");
9760
9761   // Whenever we can lower this as a zext, that instruction is strictly faster
9762   // than any alternative. It also allows us to fold memory operands into the
9763   // shuffle in many cases.
9764   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v32i8, V1, V2,
9765                                                          Mask, Subtarget, DAG))
9766     return ZExt;
9767
9768   // Check for being able to broadcast a single element.
9769   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v32i8, V1,
9770                                                         Mask, Subtarget, DAG))
9771     return Broadcast;
9772
9773   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v32i8, V1, V2, Mask,
9774                                                 Subtarget, DAG))
9775     return Blend;
9776
9777   // Use dedicated unpack instructions for masks that match their pattern.
9778   // Note that these are repeated 128-bit lane unpacks, not unpacks across all
9779   // 256-bit lanes.
9780   if (isShuffleEquivalent(
9781           V1, V2, Mask,
9782           {// First 128-bit lane:
9783            0, 32, 1, 33, 2, 34, 3, 35, 4, 36, 5, 37, 6, 38, 7, 39,
9784            // Second 128-bit lane:
9785            16, 48, 17, 49, 18, 50, 19, 51, 20, 52, 21, 53, 22, 54, 23, 55}))
9786     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v32i8, V1, V2);
9787   if (isShuffleEquivalent(
9788           V1, V2, Mask,
9789           {// First 128-bit lane:
9790            8, 40, 9, 41, 10, 42, 11, 43, 12, 44, 13, 45, 14, 46, 15, 47,
9791            // Second 128-bit lane:
9792            24, 56, 25, 57, 26, 58, 27, 59, 28, 60, 29, 61, 30, 62, 31, 63}))
9793     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v32i8, V1, V2);
9794
9795   // Try to use shift instructions.
9796   if (SDValue Shift =
9797           lowerVectorShuffleAsShift(DL, MVT::v32i8, V1, V2, Mask, DAG))
9798     return Shift;
9799
9800   // Try to use byte rotation instructions.
9801   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9802           DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
9803     return Rotate;
9804
9805   if (isSingleInputShuffleMask(Mask)) {
9806     // There are no generalized cross-lane shuffle operations available on i8
9807     // element types.
9808     if (is128BitLaneCrossingShuffleMask(MVT::v32i8, Mask))
9809       return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v32i8, V1, V2,
9810                                                      Mask, DAG);
9811
9812     SDValue PSHUFBMask[32];
9813     for (int i = 0; i < 32; ++i)
9814       PSHUFBMask[i] =
9815           Mask[i] < 0
9816               ? DAG.getUNDEF(MVT::i8)
9817               : DAG.getConstant(Mask[i] < 16 ? Mask[i] : Mask[i] - 16, MVT::i8);
9818
9819     return DAG.getNode(
9820         X86ISD::PSHUFB, DL, MVT::v32i8, V1,
9821         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, PSHUFBMask));
9822   }
9823
9824   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9825   // shuffle.
9826   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9827           DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
9828     return Result;
9829
9830   // Otherwise fall back on generic lowering.
9831   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v32i8, V1, V2, Mask, DAG);
9832 }
9833
9834 /// \brief High-level routine to lower various 256-bit x86 vector shuffles.
9835 ///
9836 /// This routine either breaks down the specific type of a 256-bit x86 vector
9837 /// shuffle or splits it into two 128-bit shuffles and fuses the results back
9838 /// together based on the available instructions.
9839 static SDValue lower256BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9840                                         MVT VT, const X86Subtarget *Subtarget,
9841                                         SelectionDAG &DAG) {
9842   SDLoc DL(Op);
9843   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9844   ArrayRef<int> Mask = SVOp->getMask();
9845
9846   // If we have a single input to the zero element, insert that into V1 if we
9847   // can do so cheaply.
9848   int NumElts = VT.getVectorNumElements();
9849   int NumV2Elements = std::count_if(Mask.begin(), Mask.end(), [NumElts](int M) {
9850     return M >= NumElts;
9851   });
9852   
9853   if (NumV2Elements == 1 && Mask[0] >= NumElts)
9854     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
9855                               DL, VT, V1, V2, Mask, Subtarget, DAG))
9856       return Insertion;
9857
9858   // There is a really nice hard cut-over between AVX1 and AVX2 that means we can
9859   // check for those subtargets here and avoid much of the subtarget querying in
9860   // the per-vector-type lowering routines. With AVX1 we have essentially *zero*
9861   // ability to manipulate a 256-bit vector with integer types. Since we'll use
9862   // floating point types there eventually, just immediately cast everything to
9863   // a float and operate entirely in that domain.
9864   if (VT.isInteger() && !Subtarget->hasAVX2()) {
9865     int ElementBits = VT.getScalarSizeInBits();
9866     if (ElementBits < 32)
9867       // No floating point type available, decompose into 128-bit vectors.
9868       return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9869
9870     MVT FpVT = MVT::getVectorVT(MVT::getFloatingPointVT(ElementBits),
9871                                 VT.getVectorNumElements());
9872     V1 = DAG.getNode(ISD::BITCAST, DL, FpVT, V1);
9873     V2 = DAG.getNode(ISD::BITCAST, DL, FpVT, V2);
9874     return DAG.getNode(ISD::BITCAST, DL, VT,
9875                        DAG.getVectorShuffle(FpVT, DL, V1, V2, Mask));
9876   }
9877
9878   switch (VT.SimpleTy) {
9879   case MVT::v4f64:
9880     return lowerV4F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9881   case MVT::v4i64:
9882     return lowerV4I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9883   case MVT::v8f32:
9884     return lowerV8F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9885   case MVT::v8i32:
9886     return lowerV8I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9887   case MVT::v16i16:
9888     return lowerV16I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
9889   case MVT::v32i8:
9890     return lowerV32I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
9891
9892   default:
9893     llvm_unreachable("Not a valid 256-bit x86 vector type!");
9894   }
9895 }
9896
9897 /// \brief Handle lowering of 8-lane 64-bit floating point shuffles.
9898 static SDValue lowerV8F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9899                                        const X86Subtarget *Subtarget,
9900                                        SelectionDAG &DAG) {
9901   SDLoc DL(Op);
9902   assert(V1.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
9903   assert(V2.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
9904   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9905   ArrayRef<int> Mask = SVOp->getMask();
9906   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9907
9908   // X86 has dedicated unpack instructions that can handle specific blend
9909   // operations: UNPCKH and UNPCKL.
9910   if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 2, 10, 4, 12, 6, 14}))
9911     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f64, V1, V2);
9912   if (isShuffleEquivalent(V1, V2, Mask, {1, 9, 3, 11, 5, 13, 7, 15}))
9913     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f64, V1, V2);
9914
9915   // FIXME: Implement direct support for this type!
9916   return splitAndLowerVectorShuffle(DL, MVT::v8f64, V1, V2, Mask, DAG);
9917 }
9918
9919 /// \brief Handle lowering of 16-lane 32-bit floating point shuffles.
9920 static SDValue lowerV16F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9921                                        const X86Subtarget *Subtarget,
9922                                        SelectionDAG &DAG) {
9923   SDLoc DL(Op);
9924   assert(V1.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
9925   assert(V2.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
9926   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9927   ArrayRef<int> Mask = SVOp->getMask();
9928   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
9929
9930   // Use dedicated unpack instructions for masks that match their pattern.
9931   if (isShuffleEquivalent(V1, V2, Mask,
9932                           {// First 128-bit lane.
9933                            0, 16, 1, 17, 4, 20, 5, 21,
9934                            // Second 128-bit lane.
9935                            8, 24, 9, 25, 12, 28, 13, 29}))
9936     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16f32, V1, V2);
9937   if (isShuffleEquivalent(V1, V2, Mask,
9938                           {// First 128-bit lane.
9939                            2, 18, 3, 19, 6, 22, 7, 23,
9940                            // Second 128-bit lane.
9941                            10, 26, 11, 27, 14, 30, 15, 31}))
9942     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16f32, V1, V2);
9943
9944   // FIXME: Implement direct support for this type!
9945   return splitAndLowerVectorShuffle(DL, MVT::v16f32, V1, V2, Mask, DAG);
9946 }
9947
9948 /// \brief Handle lowering of 8-lane 64-bit integer shuffles.
9949 static SDValue lowerV8I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9950                                        const X86Subtarget *Subtarget,
9951                                        SelectionDAG &DAG) {
9952   SDLoc DL(Op);
9953   assert(V1.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
9954   assert(V2.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
9955   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9956   ArrayRef<int> Mask = SVOp->getMask();
9957   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9958
9959   // X86 has dedicated unpack instructions that can handle specific blend
9960   // operations: UNPCKH and UNPCKL.
9961   if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 2, 10, 4, 12, 6, 14}))
9962     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i64, V1, V2);
9963   if (isShuffleEquivalent(V1, V2, Mask, {1, 9, 3, 11, 5, 13, 7, 15}))
9964     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i64, V1, V2);
9965
9966   // FIXME: Implement direct support for this type!
9967   return splitAndLowerVectorShuffle(DL, MVT::v8i64, V1, V2, Mask, DAG);
9968 }
9969
9970 /// \brief Handle lowering of 16-lane 32-bit integer shuffles.
9971 static SDValue lowerV16I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9972                                        const X86Subtarget *Subtarget,
9973                                        SelectionDAG &DAG) {
9974   SDLoc DL(Op);
9975   assert(V1.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
9976   assert(V2.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
9977   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9978   ArrayRef<int> Mask = SVOp->getMask();
9979   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
9980
9981   // Use dedicated unpack instructions for masks that match their pattern.
9982   if (isShuffleEquivalent(V1, V2, Mask,
9983                           {// First 128-bit lane.
9984                            0, 16, 1, 17, 4, 20, 5, 21,
9985                            // Second 128-bit lane.
9986                            8, 24, 9, 25, 12, 28, 13, 29}))
9987     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i32, V1, V2);
9988   if (isShuffleEquivalent(V1, V2, Mask,
9989                           {// First 128-bit lane.
9990                            2, 18, 3, 19, 6, 22, 7, 23,
9991                            // Second 128-bit lane.
9992                            10, 26, 11, 27, 14, 30, 15, 31}))
9993     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i32, V1, V2);
9994
9995   // FIXME: Implement direct support for this type!
9996   return splitAndLowerVectorShuffle(DL, MVT::v16i32, V1, V2, Mask, DAG);
9997 }
9998
9999 /// \brief Handle lowering of 32-lane 16-bit integer shuffles.
10000 static SDValue lowerV32I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10001                                         const X86Subtarget *Subtarget,
10002                                         SelectionDAG &DAG) {
10003   SDLoc DL(Op);
10004   assert(V1.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10005   assert(V2.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10006   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10007   ArrayRef<int> Mask = SVOp->getMask();
10008   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
10009   assert(Subtarget->hasBWI() && "We can only lower v32i16 with AVX-512-BWI!");
10010
10011   // FIXME: Implement direct support for this type!
10012   return splitAndLowerVectorShuffle(DL, MVT::v32i16, V1, V2, Mask, DAG);
10013 }
10014
10015 /// \brief Handle lowering of 64-lane 8-bit integer shuffles.
10016 static SDValue lowerV64I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10017                                        const X86Subtarget *Subtarget,
10018                                        SelectionDAG &DAG) {
10019   SDLoc DL(Op);
10020   assert(V1.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10021   assert(V2.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10022   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10023   ArrayRef<int> Mask = SVOp->getMask();
10024   assert(Mask.size() == 64 && "Unexpected mask size for v64 shuffle!");
10025   assert(Subtarget->hasBWI() && "We can only lower v64i8 with AVX-512-BWI!");
10026
10027   // FIXME: Implement direct support for this type!
10028   return splitAndLowerVectorShuffle(DL, MVT::v64i8, V1, V2, Mask, DAG);
10029 }
10030
10031 /// \brief High-level routine to lower various 512-bit x86 vector shuffles.
10032 ///
10033 /// This routine either breaks down the specific type of a 512-bit x86 vector
10034 /// shuffle or splits it into two 256-bit shuffles and fuses the results back
10035 /// together based on the available instructions.
10036 static SDValue lower512BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10037                                         MVT VT, const X86Subtarget *Subtarget,
10038                                         SelectionDAG &DAG) {
10039   SDLoc DL(Op);
10040   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10041   ArrayRef<int> Mask = SVOp->getMask();
10042   assert(Subtarget->hasAVX512() &&
10043          "Cannot lower 512-bit vectors w/ basic ISA!");
10044
10045   // Check for being able to broadcast a single element.
10046   if (SDValue Broadcast =
10047           lowerVectorShuffleAsBroadcast(DL, VT, V1, Mask, Subtarget, DAG))
10048     return Broadcast;
10049
10050   // Dispatch to each element type for lowering. If we don't have supprot for
10051   // specific element type shuffles at 512 bits, immediately split them and
10052   // lower them. Each lowering routine of a given type is allowed to assume that
10053   // the requisite ISA extensions for that element type are available.
10054   switch (VT.SimpleTy) {
10055   case MVT::v8f64:
10056     return lowerV8F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10057   case MVT::v16f32:
10058     return lowerV16F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10059   case MVT::v8i64:
10060     return lowerV8I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10061   case MVT::v16i32:
10062     return lowerV16I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10063   case MVT::v32i16:
10064     if (Subtarget->hasBWI())
10065       return lowerV32I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
10066     break;
10067   case MVT::v64i8:
10068     if (Subtarget->hasBWI())
10069       return lowerV64I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
10070     break;
10071
10072   default:
10073     llvm_unreachable("Not a valid 512-bit x86 vector type!");
10074   }
10075
10076   // Otherwise fall back on splitting.
10077   return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10078 }
10079
10080 /// \brief Top-level lowering for x86 vector shuffles.
10081 ///
10082 /// This handles decomposition, canonicalization, and lowering of all x86
10083 /// vector shuffles. Most of the specific lowering strategies are encapsulated
10084 /// above in helper routines. The canonicalization attempts to widen shuffles
10085 /// to involve fewer lanes of wider elements, consolidate symmetric patterns
10086 /// s.t. only one of the two inputs needs to be tested, etc.
10087 static SDValue lowerVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
10088                                   SelectionDAG &DAG) {
10089   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10090   ArrayRef<int> Mask = SVOp->getMask();
10091   SDValue V1 = Op.getOperand(0);
10092   SDValue V2 = Op.getOperand(1);
10093   MVT VT = Op.getSimpleValueType();
10094   int NumElements = VT.getVectorNumElements();
10095   SDLoc dl(Op);
10096
10097   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
10098
10099   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
10100   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
10101   if (V1IsUndef && V2IsUndef)
10102     return DAG.getUNDEF(VT);
10103
10104   // When we create a shuffle node we put the UNDEF node to second operand,
10105   // but in some cases the first operand may be transformed to UNDEF.
10106   // In this case we should just commute the node.
10107   if (V1IsUndef)
10108     return DAG.getCommutedVectorShuffle(*SVOp);
10109
10110   // Check for non-undef masks pointing at an undef vector and make the masks
10111   // undef as well. This makes it easier to match the shuffle based solely on
10112   // the mask.
10113   if (V2IsUndef)
10114     for (int M : Mask)
10115       if (M >= NumElements) {
10116         SmallVector<int, 8> NewMask(Mask.begin(), Mask.end());
10117         for (int &M : NewMask)
10118           if (M >= NumElements)
10119             M = -1;
10120         return DAG.getVectorShuffle(VT, dl, V1, V2, NewMask);
10121       }
10122
10123   // We actually see shuffles that are entirely re-arrangements of a set of
10124   // zero inputs. This mostly happens while decomposing complex shuffles into
10125   // simple ones. Directly lower these as a buildvector of zeros.
10126   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
10127   if (Zeroable.all())
10128     return getZeroVector(VT, Subtarget, DAG, dl);
10129
10130   // Try to collapse shuffles into using a vector type with fewer elements but
10131   // wider element types. We cap this to not form integers or floating point
10132   // elements wider than 64 bits, but it might be interesting to form i128
10133   // integers to handle flipping the low and high halves of AVX 256-bit vectors.
10134   SmallVector<int, 16> WidenedMask;
10135   if (VT.getScalarSizeInBits() < 64 &&
10136       canWidenShuffleElements(Mask, WidenedMask)) {
10137     MVT NewEltVT = VT.isFloatingPoint()
10138                        ? MVT::getFloatingPointVT(VT.getScalarSizeInBits() * 2)
10139                        : MVT::getIntegerVT(VT.getScalarSizeInBits() * 2);
10140     MVT NewVT = MVT::getVectorVT(NewEltVT, VT.getVectorNumElements() / 2);
10141     // Make sure that the new vector type is legal. For example, v2f64 isn't
10142     // legal on SSE1.
10143     if (DAG.getTargetLoweringInfo().isTypeLegal(NewVT)) {
10144       V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
10145       V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
10146       return DAG.getNode(ISD::BITCAST, dl, VT,
10147                          DAG.getVectorShuffle(NewVT, dl, V1, V2, WidenedMask));
10148     }
10149   }
10150
10151   int NumV1Elements = 0, NumUndefElements = 0, NumV2Elements = 0;
10152   for (int M : SVOp->getMask())
10153     if (M < 0)
10154       ++NumUndefElements;
10155     else if (M < NumElements)
10156       ++NumV1Elements;
10157     else
10158       ++NumV2Elements;
10159
10160   // Commute the shuffle as needed such that more elements come from V1 than
10161   // V2. This allows us to match the shuffle pattern strictly on how many
10162   // elements come from V1 without handling the symmetric cases.
10163   if (NumV2Elements > NumV1Elements)
10164     return DAG.getCommutedVectorShuffle(*SVOp);
10165
10166   // When the number of V1 and V2 elements are the same, try to minimize the
10167   // number of uses of V2 in the low half of the vector. When that is tied,
10168   // ensure that the sum of indices for V1 is equal to or lower than the sum
10169   // indices for V2. When those are equal, try to ensure that the number of odd
10170   // indices for V1 is lower than the number of odd indices for V2.
10171   if (NumV1Elements == NumV2Elements) {
10172     int LowV1Elements = 0, LowV2Elements = 0;
10173     for (int M : SVOp->getMask().slice(0, NumElements / 2))
10174       if (M >= NumElements)
10175         ++LowV2Elements;
10176       else if (M >= 0)
10177         ++LowV1Elements;
10178     if (LowV2Elements > LowV1Elements) {
10179       return DAG.getCommutedVectorShuffle(*SVOp);
10180     } else if (LowV2Elements == LowV1Elements) {
10181       int SumV1Indices = 0, SumV2Indices = 0;
10182       for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
10183         if (SVOp->getMask()[i] >= NumElements)
10184           SumV2Indices += i;
10185         else if (SVOp->getMask()[i] >= 0)
10186           SumV1Indices += i;
10187       if (SumV2Indices < SumV1Indices) {
10188         return DAG.getCommutedVectorShuffle(*SVOp);
10189       } else if (SumV2Indices == SumV1Indices) {
10190         int NumV1OddIndices = 0, NumV2OddIndices = 0;
10191         for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
10192           if (SVOp->getMask()[i] >= NumElements)
10193             NumV2OddIndices += i % 2;
10194           else if (SVOp->getMask()[i] >= 0)
10195             NumV1OddIndices += i % 2;
10196         if (NumV2OddIndices < NumV1OddIndices)
10197           return DAG.getCommutedVectorShuffle(*SVOp);
10198       }
10199     }
10200   }
10201
10202   // For each vector width, delegate to a specialized lowering routine.
10203   if (VT.getSizeInBits() == 128)
10204     return lower128BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10205
10206   if (VT.getSizeInBits() == 256)
10207     return lower256BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10208
10209   // Force AVX-512 vectors to be scalarized for now.
10210   // FIXME: Implement AVX-512 support!
10211   if (VT.getSizeInBits() == 512)
10212     return lower512BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10213
10214   llvm_unreachable("Unimplemented!");
10215 }
10216
10217 // This function assumes its argument is a BUILD_VECTOR of constants or
10218 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
10219 // true.
10220 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
10221                                     unsigned &MaskValue) {
10222   MaskValue = 0;
10223   unsigned NumElems = BuildVector->getNumOperands();
10224   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
10225   unsigned NumLanes = (NumElems - 1) / 8 + 1;
10226   unsigned NumElemsInLane = NumElems / NumLanes;
10227
10228   // Blend for v16i16 should be symetric for the both lanes.
10229   for (unsigned i = 0; i < NumElemsInLane; ++i) {
10230     SDValue EltCond = BuildVector->getOperand(i);
10231     SDValue SndLaneEltCond =
10232         (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
10233
10234     int Lane1Cond = -1, Lane2Cond = -1;
10235     if (isa<ConstantSDNode>(EltCond))
10236       Lane1Cond = !isZero(EltCond);
10237     if (isa<ConstantSDNode>(SndLaneEltCond))
10238       Lane2Cond = !isZero(SndLaneEltCond);
10239
10240     if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
10241       // Lane1Cond != 0, means we want the first argument.
10242       // Lane1Cond == 0, means we want the second argument.
10243       // The encoding of this argument is 0 for the first argument, 1
10244       // for the second. Therefore, invert the condition.
10245       MaskValue |= !Lane1Cond << i;
10246     else if (Lane1Cond < 0)
10247       MaskValue |= !Lane2Cond << i;
10248     else
10249       return false;
10250   }
10251   return true;
10252 }
10253
10254 /// \brief Try to lower a VSELECT instruction to a vector shuffle.
10255 static SDValue lowerVSELECTtoVectorShuffle(SDValue Op,
10256                                            const X86Subtarget *Subtarget,
10257                                            SelectionDAG &DAG) {
10258   SDValue Cond = Op.getOperand(0);
10259   SDValue LHS = Op.getOperand(1);
10260   SDValue RHS = Op.getOperand(2);
10261   SDLoc dl(Op);
10262   MVT VT = Op.getSimpleValueType();
10263
10264   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
10265     return SDValue();
10266   auto *CondBV = cast<BuildVectorSDNode>(Cond);
10267
10268   // Only non-legal VSELECTs reach this lowering, convert those into generic
10269   // shuffles and re-use the shuffle lowering path for blends.
10270   SmallVector<int, 32> Mask;
10271   for (int i = 0, Size = VT.getVectorNumElements(); i < Size; ++i) {
10272     SDValue CondElt = CondBV->getOperand(i);
10273     Mask.push_back(
10274         isa<ConstantSDNode>(CondElt) ? i + (isZero(CondElt) ? Size : 0) : -1);
10275   }
10276   return DAG.getVectorShuffle(VT, dl, LHS, RHS, Mask);
10277 }
10278
10279 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
10280   // A vselect where all conditions and data are constants can be optimized into
10281   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
10282   if (ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(0).getNode()) &&
10283       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(1).getNode()) &&
10284       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(2).getNode()))
10285     return SDValue();
10286
10287   // Try to lower this to a blend-style vector shuffle. This can handle all
10288   // constant condition cases.
10289   if (SDValue BlendOp = lowerVSELECTtoVectorShuffle(Op, Subtarget, DAG))
10290     return BlendOp;
10291
10292   // Variable blends are only legal from SSE4.1 onward.
10293   if (!Subtarget->hasSSE41())
10294     return SDValue();
10295
10296   // Only some types will be legal on some subtargets. If we can emit a legal
10297   // VSELECT-matching blend, return Op, and but if we need to expand, return
10298   // a null value.
10299   switch (Op.getSimpleValueType().SimpleTy) {
10300   default:
10301     // Most of the vector types have blends past SSE4.1.
10302     return Op;
10303
10304   case MVT::v32i8:
10305     // The byte blends for AVX vectors were introduced only in AVX2.
10306     if (Subtarget->hasAVX2())
10307       return Op;
10308
10309     return SDValue();
10310
10311   case MVT::v8i16:
10312   case MVT::v16i16:
10313     // AVX-512 BWI and VLX features support VSELECT with i16 elements.
10314     if (Subtarget->hasBWI() && Subtarget->hasVLX())
10315       return Op;
10316
10317     // FIXME: We should custom lower this by fixing the condition and using i8
10318     // blends.
10319     return SDValue();
10320   }
10321 }
10322
10323 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
10324   MVT VT = Op.getSimpleValueType();
10325   SDLoc dl(Op);
10326
10327   if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
10328     return SDValue();
10329
10330   if (VT.getSizeInBits() == 8) {
10331     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
10332                                   Op.getOperand(0), Op.getOperand(1));
10333     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
10334                                   DAG.getValueType(VT));
10335     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10336   }
10337
10338   if (VT.getSizeInBits() == 16) {
10339     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10340     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
10341     if (Idx == 0)
10342       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
10343                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10344                                      DAG.getNode(ISD::BITCAST, dl,
10345                                                  MVT::v4i32,
10346                                                  Op.getOperand(0)),
10347                                      Op.getOperand(1)));
10348     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
10349                                   Op.getOperand(0), Op.getOperand(1));
10350     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
10351                                   DAG.getValueType(VT));
10352     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10353   }
10354
10355   if (VT == MVT::f32) {
10356     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
10357     // the result back to FR32 register. It's only worth matching if the
10358     // result has a single use which is a store or a bitcast to i32.  And in
10359     // the case of a store, it's not worth it if the index is a constant 0,
10360     // because a MOVSSmr can be used instead, which is smaller and faster.
10361     if (!Op.hasOneUse())
10362       return SDValue();
10363     SDNode *User = *Op.getNode()->use_begin();
10364     if ((User->getOpcode() != ISD::STORE ||
10365          (isa<ConstantSDNode>(Op.getOperand(1)) &&
10366           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
10367         (User->getOpcode() != ISD::BITCAST ||
10368          User->getValueType(0) != MVT::i32))
10369       return SDValue();
10370     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10371                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
10372                                               Op.getOperand(0)),
10373                                               Op.getOperand(1));
10374     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
10375   }
10376
10377   if (VT == MVT::i32 || VT == MVT::i64) {
10378     // ExtractPS/pextrq works with constant index.
10379     if (isa<ConstantSDNode>(Op.getOperand(1)))
10380       return Op;
10381   }
10382   return SDValue();
10383 }
10384
10385 /// Extract one bit from mask vector, like v16i1 or v8i1.
10386 /// AVX-512 feature.
10387 SDValue
10388 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
10389   SDValue Vec = Op.getOperand(0);
10390   SDLoc dl(Vec);
10391   MVT VecVT = Vec.getSimpleValueType();
10392   SDValue Idx = Op.getOperand(1);
10393   MVT EltVT = Op.getSimpleValueType();
10394
10395   assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
10396   assert((VecVT.getVectorNumElements() <= 16 || Subtarget->hasBWI()) &&
10397          "Unexpected vector type in ExtractBitFromMaskVector");
10398
10399   // variable index can't be handled in mask registers,
10400   // extend vector to VR512
10401   if (!isa<ConstantSDNode>(Idx)) {
10402     MVT ExtVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
10403     SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
10404     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
10405                               ExtVT.getVectorElementType(), Ext, Idx);
10406     return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
10407   }
10408
10409   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10410   const TargetRegisterClass* rc = getRegClassFor(VecVT);
10411   if (!Subtarget->hasDQI() && (VecVT.getVectorNumElements() <= 8))
10412     rc = getRegClassFor(MVT::v16i1);
10413   unsigned MaxSift = rc->getSize()*8 - 1;
10414   Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
10415                     DAG.getConstant(MaxSift - IdxVal, MVT::i8));
10416   Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
10417                     DAG.getConstant(MaxSift, MVT::i8));
10418   return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
10419                        DAG.getIntPtrConstant(0));
10420 }
10421
10422 SDValue
10423 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
10424                                            SelectionDAG &DAG) const {
10425   SDLoc dl(Op);
10426   SDValue Vec = Op.getOperand(0);
10427   MVT VecVT = Vec.getSimpleValueType();
10428   SDValue Idx = Op.getOperand(1);
10429
10430   if (Op.getSimpleValueType() == MVT::i1)
10431     return ExtractBitFromMaskVector(Op, DAG);
10432
10433   if (!isa<ConstantSDNode>(Idx)) {
10434     if (VecVT.is512BitVector() ||
10435         (VecVT.is256BitVector() && Subtarget->hasInt256() &&
10436          VecVT.getVectorElementType().getSizeInBits() == 32)) {
10437
10438       MVT MaskEltVT =
10439         MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
10440       MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
10441                                     MaskEltVT.getSizeInBits());
10442
10443       Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
10444       SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
10445                                 getZeroVector(MaskVT, Subtarget, DAG, dl),
10446                                 Idx, DAG.getConstant(0, getPointerTy()));
10447       SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
10448       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(),
10449                         Perm, DAG.getConstant(0, getPointerTy()));
10450     }
10451     return SDValue();
10452   }
10453
10454   // If this is a 256-bit vector result, first extract the 128-bit vector and
10455   // then extract the element from the 128-bit vector.
10456   if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
10457
10458     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10459     // Get the 128-bit vector.
10460     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
10461     MVT EltVT = VecVT.getVectorElementType();
10462
10463     unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
10464
10465     //if (IdxVal >= NumElems/2)
10466     //  IdxVal -= NumElems/2;
10467     IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
10468     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
10469                        DAG.getConstant(IdxVal, MVT::i32));
10470   }
10471
10472   assert(VecVT.is128BitVector() && "Unexpected vector length");
10473
10474   if (Subtarget->hasSSE41()) {
10475     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
10476     if (Res.getNode())
10477       return Res;
10478   }
10479
10480   MVT VT = Op.getSimpleValueType();
10481   // TODO: handle v16i8.
10482   if (VT.getSizeInBits() == 16) {
10483     SDValue Vec = Op.getOperand(0);
10484     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10485     if (Idx == 0)
10486       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
10487                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10488                                      DAG.getNode(ISD::BITCAST, dl,
10489                                                  MVT::v4i32, Vec),
10490                                      Op.getOperand(1)));
10491     // Transform it so it match pextrw which produces a 32-bit result.
10492     MVT EltVT = MVT::i32;
10493     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
10494                                   Op.getOperand(0), Op.getOperand(1));
10495     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
10496                                   DAG.getValueType(VT));
10497     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10498   }
10499
10500   if (VT.getSizeInBits() == 32) {
10501     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10502     if (Idx == 0)
10503       return Op;
10504
10505     // SHUFPS the element to the lowest double word, then movss.
10506     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
10507     MVT VVT = Op.getOperand(0).getSimpleValueType();
10508     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
10509                                        DAG.getUNDEF(VVT), Mask);
10510     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
10511                        DAG.getIntPtrConstant(0));
10512   }
10513
10514   if (VT.getSizeInBits() == 64) {
10515     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
10516     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
10517     //        to match extract_elt for f64.
10518     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10519     if (Idx == 0)
10520       return Op;
10521
10522     // UNPCKHPD the element to the lowest double word, then movsd.
10523     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
10524     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
10525     int Mask[2] = { 1, -1 };
10526     MVT VVT = Op.getOperand(0).getSimpleValueType();
10527     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
10528                                        DAG.getUNDEF(VVT), Mask);
10529     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
10530                        DAG.getIntPtrConstant(0));
10531   }
10532
10533   return SDValue();
10534 }
10535
10536 /// Insert one bit to mask vector, like v16i1 or v8i1.
10537 /// AVX-512 feature.
10538 SDValue
10539 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
10540   SDLoc dl(Op);
10541   SDValue Vec = Op.getOperand(0);
10542   SDValue Elt = Op.getOperand(1);
10543   SDValue Idx = Op.getOperand(2);
10544   MVT VecVT = Vec.getSimpleValueType();
10545
10546   if (!isa<ConstantSDNode>(Idx)) {
10547     // Non constant index. Extend source and destination,
10548     // insert element and then truncate the result.
10549     MVT ExtVecVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
10550     MVT ExtEltVT = (VecVT == MVT::v8i1 ?  MVT::i64 : MVT::i32);
10551     SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT,
10552       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
10553       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
10554     return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
10555   }
10556
10557   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10558   SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
10559   if (Vec.getOpcode() == ISD::UNDEF)
10560     return DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
10561                        DAG.getConstant(IdxVal, MVT::i8));
10562   const TargetRegisterClass* rc = getRegClassFor(VecVT);
10563   unsigned MaxSift = rc->getSize()*8 - 1;
10564   EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
10565                     DAG.getConstant(MaxSift, MVT::i8));
10566   EltInVec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, EltInVec,
10567                     DAG.getConstant(MaxSift - IdxVal, MVT::i8));
10568   return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
10569 }
10570
10571 SDValue X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
10572                                                   SelectionDAG &DAG) const {
10573   MVT VT = Op.getSimpleValueType();
10574   MVT EltVT = VT.getVectorElementType();
10575
10576   if (EltVT == MVT::i1)
10577     return InsertBitToMaskVector(Op, DAG);
10578
10579   SDLoc dl(Op);
10580   SDValue N0 = Op.getOperand(0);
10581   SDValue N1 = Op.getOperand(1);
10582   SDValue N2 = Op.getOperand(2);
10583   if (!isa<ConstantSDNode>(N2))
10584     return SDValue();
10585   auto *N2C = cast<ConstantSDNode>(N2);
10586   unsigned IdxVal = N2C->getZExtValue();
10587
10588   // If the vector is wider than 128 bits, extract the 128-bit subvector, insert
10589   // into that, and then insert the subvector back into the result.
10590   if (VT.is256BitVector() || VT.is512BitVector()) {
10591     // With a 256-bit vector, we can insert into the zero element efficiently
10592     // using a blend if we have AVX or AVX2 and the right data type.
10593     if (VT.is256BitVector() && IdxVal == 0) {
10594       // TODO: It is worthwhile to cast integer to floating point and back
10595       // and incur a domain crossing penalty if that's what we'll end up
10596       // doing anyway after extracting to a 128-bit vector.
10597       if ((Subtarget->hasAVX() && (EltVT == MVT::f64 || EltVT == MVT::f32)) ||
10598           (Subtarget->hasAVX2() && EltVT == MVT::i32)) {
10599         SDValue N1Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, N1);
10600         N2 = DAG.getIntPtrConstant(1);
10601         return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1Vec, N2);
10602       }
10603     }
10604     
10605     // Get the desired 128-bit vector chunk.
10606     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
10607
10608     // Insert the element into the desired chunk.
10609     unsigned NumEltsIn128 = 128 / EltVT.getSizeInBits();
10610     unsigned IdxIn128 = IdxVal - (IdxVal / NumEltsIn128) * NumEltsIn128;
10611
10612     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
10613                     DAG.getConstant(IdxIn128, MVT::i32));
10614
10615     // Insert the changed part back into the bigger vector
10616     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
10617   }
10618   assert(VT.is128BitVector() && "Only 128-bit vector types should be left!");
10619
10620   if (Subtarget->hasSSE41()) {
10621     if (EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) {
10622       unsigned Opc;
10623       if (VT == MVT::v8i16) {
10624         Opc = X86ISD::PINSRW;
10625       } else {
10626         assert(VT == MVT::v16i8);
10627         Opc = X86ISD::PINSRB;
10628       }
10629
10630       // Transform it so it match pinsr{b,w} which expects a GR32 as its second
10631       // argument.
10632       if (N1.getValueType() != MVT::i32)
10633         N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
10634       if (N2.getValueType() != MVT::i32)
10635         N2 = DAG.getIntPtrConstant(IdxVal);
10636       return DAG.getNode(Opc, dl, VT, N0, N1, N2);
10637     }
10638
10639     if (EltVT == MVT::f32) {
10640       // Bits [7:6] of the constant are the source select. This will always be
10641       //   zero here. The DAG Combiner may combine an extract_elt index into
10642       //   these bits. For example (insert (extract, 3), 2) could be matched by
10643       //   putting the '3' into bits [7:6] of X86ISD::INSERTPS.
10644       // Bits [5:4] of the constant are the destination select. This is the
10645       //   value of the incoming immediate.
10646       // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
10647       //   combine either bitwise AND or insert of float 0.0 to set these bits.
10648
10649       const Function *F = DAG.getMachineFunction().getFunction();
10650       bool MinSize = F->hasFnAttribute(Attribute::MinSize);
10651       if (IdxVal == 0 && (!MinSize || !MayFoldLoad(N1))) {
10652         // If this is an insertion of 32-bits into the low 32-bits of
10653         // a vector, we prefer to generate a blend with immediate rather
10654         // than an insertps. Blends are simpler operations in hardware and so
10655         // will always have equal or better performance than insertps.
10656         // But if optimizing for size and there's a load folding opportunity,
10657         // generate insertps because blendps does not have a 32-bit memory
10658         // operand form.
10659         N2 = DAG.getIntPtrConstant(1);
10660         N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
10661         return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1, N2);
10662       }
10663       N2 = DAG.getIntPtrConstant(IdxVal << 4);
10664       // Create this as a scalar to vector..
10665       N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
10666       return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
10667     }
10668
10669     if (EltVT == MVT::i32 || EltVT == MVT::i64) {
10670       // PINSR* works with constant index.
10671       return Op;
10672     }
10673   }
10674
10675   if (EltVT == MVT::i8)
10676     return SDValue();
10677
10678   if (EltVT.getSizeInBits() == 16) {
10679     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
10680     // as its second argument.
10681     if (N1.getValueType() != MVT::i32)
10682       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
10683     if (N2.getValueType() != MVT::i32)
10684       N2 = DAG.getIntPtrConstant(IdxVal);
10685     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
10686   }
10687   return SDValue();
10688 }
10689
10690 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
10691   SDLoc dl(Op);
10692   MVT OpVT = Op.getSimpleValueType();
10693
10694   // If this is a 256-bit vector result, first insert into a 128-bit
10695   // vector and then insert into the 256-bit vector.
10696   if (!OpVT.is128BitVector()) {
10697     // Insert into a 128-bit vector.
10698     unsigned SizeFactor = OpVT.getSizeInBits()/128;
10699     MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
10700                                  OpVT.getVectorNumElements() / SizeFactor);
10701
10702     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
10703
10704     // Insert the 128-bit vector.
10705     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
10706   }
10707
10708   if (OpVT == MVT::v1i64 &&
10709       Op.getOperand(0).getValueType() == MVT::i64)
10710     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
10711
10712   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
10713   assert(OpVT.is128BitVector() && "Expected an SSE type!");
10714   return DAG.getNode(ISD::BITCAST, dl, OpVT,
10715                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
10716 }
10717
10718 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
10719 // a simple subregister reference or explicit instructions to grab
10720 // upper bits of a vector.
10721 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
10722                                       SelectionDAG &DAG) {
10723   SDLoc dl(Op);
10724   SDValue In =  Op.getOperand(0);
10725   SDValue Idx = Op.getOperand(1);
10726   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10727   MVT ResVT   = Op.getSimpleValueType();
10728   MVT InVT    = In.getSimpleValueType();
10729
10730   if (Subtarget->hasFp256()) {
10731     if (ResVT.is128BitVector() &&
10732         (InVT.is256BitVector() || InVT.is512BitVector()) &&
10733         isa<ConstantSDNode>(Idx)) {
10734       return Extract128BitVector(In, IdxVal, DAG, dl);
10735     }
10736     if (ResVT.is256BitVector() && InVT.is512BitVector() &&
10737         isa<ConstantSDNode>(Idx)) {
10738       return Extract256BitVector(In, IdxVal, DAG, dl);
10739     }
10740   }
10741   return SDValue();
10742 }
10743
10744 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
10745 // simple superregister reference or explicit instructions to insert
10746 // the upper bits of a vector.
10747 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
10748                                      SelectionDAG &DAG) {
10749   if (!Subtarget->hasAVX())
10750     return SDValue();
10751
10752   SDLoc dl(Op);
10753   SDValue Vec = Op.getOperand(0);
10754   SDValue SubVec = Op.getOperand(1);
10755   SDValue Idx = Op.getOperand(2);
10756
10757   if (!isa<ConstantSDNode>(Idx))
10758     return SDValue();
10759
10760   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10761   MVT OpVT = Op.getSimpleValueType();
10762   MVT SubVecVT = SubVec.getSimpleValueType();
10763
10764   // Fold two 16-byte subvector loads into one 32-byte load:
10765   // (insert_subvector (insert_subvector undef, (load addr), 0),
10766   //                   (load addr + 16), Elts/2)
10767   // --> load32 addr
10768   if ((IdxVal == OpVT.getVectorNumElements() / 2) &&
10769       Vec.getOpcode() == ISD::INSERT_SUBVECTOR &&
10770       OpVT.is256BitVector() && SubVecVT.is128BitVector() &&
10771       !Subtarget->isUnalignedMem32Slow()) {
10772     SDValue SubVec2 = Vec.getOperand(1);
10773     if (auto *Idx2 = dyn_cast<ConstantSDNode>(Vec.getOperand(2))) {
10774       if (Idx2->getZExtValue() == 0) {
10775         SDValue Ops[] = { SubVec2, SubVec };
10776         SDValue LD = EltsFromConsecutiveLoads(OpVT, Ops, dl, DAG, false);
10777         if (LD.getNode())
10778           return LD;
10779       }
10780     }
10781   }
10782
10783   if ((OpVT.is256BitVector() || OpVT.is512BitVector()) &&
10784       SubVecVT.is128BitVector())
10785     return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
10786
10787   if (OpVT.is512BitVector() && SubVecVT.is256BitVector())
10788     return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
10789
10790   if (OpVT.getVectorElementType() == MVT::i1) {
10791     if (IdxVal == 0  && Vec.getOpcode() == ISD::UNDEF) // the operation is legal
10792       return Op;
10793     SDValue ZeroIdx = DAG.getIntPtrConstant(0);
10794     SDValue Undef = DAG.getUNDEF(OpVT);
10795     unsigned NumElems = OpVT.getVectorNumElements();
10796     SDValue ShiftBits = DAG.getConstant(NumElems/2, MVT::i8);
10797
10798     if (IdxVal == OpVT.getVectorNumElements() / 2) {
10799       // Zero upper bits of the Vec
10800       Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
10801       Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
10802
10803       SDValue Vec2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef,
10804                                  SubVec, ZeroIdx);
10805       Vec2 = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec2, ShiftBits);
10806       return DAG.getNode(ISD::OR, dl, OpVT, Vec, Vec2);
10807     }
10808     if (IdxVal == 0) {
10809       SDValue Vec2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef,
10810                                  SubVec, ZeroIdx);
10811       // Zero upper bits of the Vec2
10812       Vec2 = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec2, ShiftBits);
10813       Vec2 = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec2, ShiftBits);
10814       // Zero lower bits of the Vec
10815       Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
10816       Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
10817       // Merge them together
10818       return DAG.getNode(ISD::OR, dl, OpVT, Vec, Vec2);
10819     }
10820   }
10821   return SDValue();
10822 }
10823
10824 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
10825 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
10826 // one of the above mentioned nodes. It has to be wrapped because otherwise
10827 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
10828 // be used to form addressing mode. These wrapped nodes will be selected
10829 // into MOV32ri.
10830 SDValue
10831 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
10832   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
10833
10834   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10835   // global base reg.
10836   unsigned char OpFlag = 0;
10837   unsigned WrapperKind = X86ISD::Wrapper;
10838   CodeModel::Model M = DAG.getTarget().getCodeModel();
10839
10840   if (Subtarget->isPICStyleRIPRel() &&
10841       (M == CodeModel::Small || M == CodeModel::Kernel))
10842     WrapperKind = X86ISD::WrapperRIP;
10843   else if (Subtarget->isPICStyleGOT())
10844     OpFlag = X86II::MO_GOTOFF;
10845   else if (Subtarget->isPICStyleStubPIC())
10846     OpFlag = X86II::MO_PIC_BASE_OFFSET;
10847
10848   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
10849                                              CP->getAlignment(),
10850                                              CP->getOffset(), OpFlag);
10851   SDLoc DL(CP);
10852   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10853   // With PIC, the address is actually $g + Offset.
10854   if (OpFlag) {
10855     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10856                          DAG.getNode(X86ISD::GlobalBaseReg,
10857                                      SDLoc(), getPointerTy()),
10858                          Result);
10859   }
10860
10861   return Result;
10862 }
10863
10864 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
10865   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
10866
10867   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10868   // global base reg.
10869   unsigned char OpFlag = 0;
10870   unsigned WrapperKind = X86ISD::Wrapper;
10871   CodeModel::Model M = DAG.getTarget().getCodeModel();
10872
10873   if (Subtarget->isPICStyleRIPRel() &&
10874       (M == CodeModel::Small || M == CodeModel::Kernel))
10875     WrapperKind = X86ISD::WrapperRIP;
10876   else if (Subtarget->isPICStyleGOT())
10877     OpFlag = X86II::MO_GOTOFF;
10878   else if (Subtarget->isPICStyleStubPIC())
10879     OpFlag = X86II::MO_PIC_BASE_OFFSET;
10880
10881   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
10882                                           OpFlag);
10883   SDLoc DL(JT);
10884   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10885
10886   // With PIC, the address is actually $g + Offset.
10887   if (OpFlag)
10888     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10889                          DAG.getNode(X86ISD::GlobalBaseReg,
10890                                      SDLoc(), getPointerTy()),
10891                          Result);
10892
10893   return Result;
10894 }
10895
10896 SDValue
10897 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
10898   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
10899
10900   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10901   // global base reg.
10902   unsigned char OpFlag = 0;
10903   unsigned WrapperKind = X86ISD::Wrapper;
10904   CodeModel::Model M = DAG.getTarget().getCodeModel();
10905
10906   if (Subtarget->isPICStyleRIPRel() &&
10907       (M == CodeModel::Small || M == CodeModel::Kernel)) {
10908     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
10909       OpFlag = X86II::MO_GOTPCREL;
10910     WrapperKind = X86ISD::WrapperRIP;
10911   } else if (Subtarget->isPICStyleGOT()) {
10912     OpFlag = X86II::MO_GOT;
10913   } else if (Subtarget->isPICStyleStubPIC()) {
10914     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
10915   } else if (Subtarget->isPICStyleStubNoDynamic()) {
10916     OpFlag = X86II::MO_DARWIN_NONLAZY;
10917   }
10918
10919   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
10920
10921   SDLoc DL(Op);
10922   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10923
10924   // With PIC, the address is actually $g + Offset.
10925   if (DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
10926       !Subtarget->is64Bit()) {
10927     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10928                          DAG.getNode(X86ISD::GlobalBaseReg,
10929                                      SDLoc(), getPointerTy()),
10930                          Result);
10931   }
10932
10933   // For symbols that require a load from a stub to get the address, emit the
10934   // load.
10935   if (isGlobalStubReference(OpFlag))
10936     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
10937                          MachinePointerInfo::getGOT(), false, false, false, 0);
10938
10939   return Result;
10940 }
10941
10942 SDValue
10943 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
10944   // Create the TargetBlockAddressAddress node.
10945   unsigned char OpFlags =
10946     Subtarget->ClassifyBlockAddressReference();
10947   CodeModel::Model M = DAG.getTarget().getCodeModel();
10948   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
10949   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
10950   SDLoc dl(Op);
10951   SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
10952                                              OpFlags);
10953
10954   if (Subtarget->isPICStyleRIPRel() &&
10955       (M == CodeModel::Small || M == CodeModel::Kernel))
10956     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
10957   else
10958     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
10959
10960   // With PIC, the address is actually $g + Offset.
10961   if (isGlobalRelativeToPICBase(OpFlags)) {
10962     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
10963                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
10964                          Result);
10965   }
10966
10967   return Result;
10968 }
10969
10970 SDValue
10971 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
10972                                       int64_t Offset, SelectionDAG &DAG) const {
10973   // Create the TargetGlobalAddress node, folding in the constant
10974   // offset if it is legal.
10975   unsigned char OpFlags =
10976       Subtarget->ClassifyGlobalReference(GV, DAG.getTarget());
10977   CodeModel::Model M = DAG.getTarget().getCodeModel();
10978   SDValue Result;
10979   if (OpFlags == X86II::MO_NO_FLAG &&
10980       X86::isOffsetSuitableForCodeModel(Offset, M)) {
10981     // A direct static reference to a global.
10982     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
10983     Offset = 0;
10984   } else {
10985     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
10986   }
10987
10988   if (Subtarget->isPICStyleRIPRel() &&
10989       (M == CodeModel::Small || M == CodeModel::Kernel))
10990     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
10991   else
10992     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
10993
10994   // With PIC, the address is actually $g + Offset.
10995   if (isGlobalRelativeToPICBase(OpFlags)) {
10996     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
10997                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
10998                          Result);
10999   }
11000
11001   // For globals that require a load from a stub to get the address, emit the
11002   // load.
11003   if (isGlobalStubReference(OpFlags))
11004     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
11005                          MachinePointerInfo::getGOT(), false, false, false, 0);
11006
11007   // If there was a non-zero offset that we didn't fold, create an explicit
11008   // addition for it.
11009   if (Offset != 0)
11010     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
11011                          DAG.getConstant(Offset, getPointerTy()));
11012
11013   return Result;
11014 }
11015
11016 SDValue
11017 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
11018   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
11019   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
11020   return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
11021 }
11022
11023 static SDValue
11024 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
11025            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
11026            unsigned char OperandFlags, bool LocalDynamic = false) {
11027   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11028   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11029   SDLoc dl(GA);
11030   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11031                                            GA->getValueType(0),
11032                                            GA->getOffset(),
11033                                            OperandFlags);
11034
11035   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
11036                                            : X86ISD::TLSADDR;
11037
11038   if (InFlag) {
11039     SDValue Ops[] = { Chain,  TGA, *InFlag };
11040     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11041   } else {
11042     SDValue Ops[]  = { Chain, TGA };
11043     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11044   }
11045
11046   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
11047   MFI->setAdjustsStack(true);
11048   MFI->setHasCalls(true);
11049
11050   SDValue Flag = Chain.getValue(1);
11051   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
11052 }
11053
11054 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
11055 static SDValue
11056 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11057                                 const EVT PtrVT) {
11058   SDValue InFlag;
11059   SDLoc dl(GA);  // ? function entry point might be better
11060   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
11061                                    DAG.getNode(X86ISD::GlobalBaseReg,
11062                                                SDLoc(), PtrVT), InFlag);
11063   InFlag = Chain.getValue(1);
11064
11065   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
11066 }
11067
11068 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
11069 static SDValue
11070 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11071                                 const EVT PtrVT) {
11072   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
11073                     X86::RAX, X86II::MO_TLSGD);
11074 }
11075
11076 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
11077                                            SelectionDAG &DAG,
11078                                            const EVT PtrVT,
11079                                            bool is64Bit) {
11080   SDLoc dl(GA);
11081
11082   // Get the start address of the TLS block for this module.
11083   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
11084       .getInfo<X86MachineFunctionInfo>();
11085   MFI->incNumLocalDynamicTLSAccesses();
11086
11087   SDValue Base;
11088   if (is64Bit) {
11089     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
11090                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
11091   } else {
11092     SDValue InFlag;
11093     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
11094         DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
11095     InFlag = Chain.getValue(1);
11096     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
11097                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
11098   }
11099
11100   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
11101   // of Base.
11102
11103   // Build x@dtpoff.
11104   unsigned char OperandFlags = X86II::MO_DTPOFF;
11105   unsigned WrapperKind = X86ISD::Wrapper;
11106   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11107                                            GA->getValueType(0),
11108                                            GA->getOffset(), OperandFlags);
11109   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
11110
11111   // Add x@dtpoff with the base.
11112   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
11113 }
11114
11115 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
11116 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11117                                    const EVT PtrVT, TLSModel::Model model,
11118                                    bool is64Bit, bool isPIC) {
11119   SDLoc dl(GA);
11120
11121   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
11122   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
11123                                                          is64Bit ? 257 : 256));
11124
11125   SDValue ThreadPointer =
11126       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0),
11127                   MachinePointerInfo(Ptr), false, false, false, 0);
11128
11129   unsigned char OperandFlags = 0;
11130   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
11131   // initialexec.
11132   unsigned WrapperKind = X86ISD::Wrapper;
11133   if (model == TLSModel::LocalExec) {
11134     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
11135   } else if (model == TLSModel::InitialExec) {
11136     if (is64Bit) {
11137       OperandFlags = X86II::MO_GOTTPOFF;
11138       WrapperKind = X86ISD::WrapperRIP;
11139     } else {
11140       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
11141     }
11142   } else {
11143     llvm_unreachable("Unexpected model");
11144   }
11145
11146   // emit "addl x@ntpoff,%eax" (local exec)
11147   // or "addl x@indntpoff,%eax" (initial exec)
11148   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
11149   SDValue TGA =
11150       DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
11151                                  GA->getOffset(), OperandFlags);
11152   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
11153
11154   if (model == TLSModel::InitialExec) {
11155     if (isPIC && !is64Bit) {
11156       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
11157                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
11158                            Offset);
11159     }
11160
11161     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
11162                          MachinePointerInfo::getGOT(), false, false, false, 0);
11163   }
11164
11165   // The address of the thread local variable is the add of the thread
11166   // pointer with the offset of the variable.
11167   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
11168 }
11169
11170 SDValue
11171 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
11172
11173   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
11174   const GlobalValue *GV = GA->getGlobal();
11175
11176   if (Subtarget->isTargetELF()) {
11177     TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
11178
11179     switch (model) {
11180       case TLSModel::GeneralDynamic:
11181         if (Subtarget->is64Bit())
11182           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
11183         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
11184       case TLSModel::LocalDynamic:
11185         return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
11186                                            Subtarget->is64Bit());
11187       case TLSModel::InitialExec:
11188       case TLSModel::LocalExec:
11189         return LowerToTLSExecModel(
11190             GA, DAG, getPointerTy(), model, Subtarget->is64Bit(),
11191             DAG.getTarget().getRelocationModel() == Reloc::PIC_);
11192     }
11193     llvm_unreachable("Unknown TLS model.");
11194   }
11195
11196   if (Subtarget->isTargetDarwin()) {
11197     // Darwin only has one model of TLS.  Lower to that.
11198     unsigned char OpFlag = 0;
11199     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
11200                            X86ISD::WrapperRIP : X86ISD::Wrapper;
11201
11202     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11203     // global base reg.
11204     bool PIC32 = (DAG.getTarget().getRelocationModel() == Reloc::PIC_) &&
11205                  !Subtarget->is64Bit();
11206     if (PIC32)
11207       OpFlag = X86II::MO_TLVP_PIC_BASE;
11208     else
11209       OpFlag = X86II::MO_TLVP;
11210     SDLoc DL(Op);
11211     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
11212                                                 GA->getValueType(0),
11213                                                 GA->getOffset(), OpFlag);
11214     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
11215
11216     // With PIC32, the address is actually $g + Offset.
11217     if (PIC32)
11218       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11219                            DAG.getNode(X86ISD::GlobalBaseReg,
11220                                        SDLoc(), getPointerTy()),
11221                            Offset);
11222
11223     // Lowering the machine isd will make sure everything is in the right
11224     // location.
11225     SDValue Chain = DAG.getEntryNode();
11226     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11227     SDValue Args[] = { Chain, Offset };
11228     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
11229
11230     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
11231     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11232     MFI->setAdjustsStack(true);
11233
11234     // And our return value (tls address) is in the standard call return value
11235     // location.
11236     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
11237     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
11238                               Chain.getValue(1));
11239   }
11240
11241   if (Subtarget->isTargetKnownWindowsMSVC() ||
11242       Subtarget->isTargetWindowsGNU()) {
11243     // Just use the implicit TLS architecture
11244     // Need to generate someting similar to:
11245     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
11246     //                                  ; from TEB
11247     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
11248     //   mov     rcx, qword [rdx+rcx*8]
11249     //   mov     eax, .tls$:tlsvar
11250     //   [rax+rcx] contains the address
11251     // Windows 64bit: gs:0x58
11252     // Windows 32bit: fs:__tls_array
11253
11254     SDLoc dl(GA);
11255     SDValue Chain = DAG.getEntryNode();
11256
11257     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
11258     // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
11259     // use its literal value of 0x2C.
11260     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
11261                                         ? Type::getInt8PtrTy(*DAG.getContext(),
11262                                                              256)
11263                                         : Type::getInt32PtrTy(*DAG.getContext(),
11264                                                               257));
11265
11266     SDValue TlsArray =
11267         Subtarget->is64Bit()
11268             ? DAG.getIntPtrConstant(0x58)
11269             : (Subtarget->isTargetWindowsGNU()
11270                    ? DAG.getIntPtrConstant(0x2C)
11271                    : DAG.getExternalSymbol("_tls_array", getPointerTy()));
11272
11273     SDValue ThreadPointer =
11274         DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
11275                     MachinePointerInfo(Ptr), false, false, false, 0);
11276
11277     // Load the _tls_index variable
11278     SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
11279     if (Subtarget->is64Bit())
11280       IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
11281                            IDX, MachinePointerInfo(), MVT::i32,
11282                            false, false, false, 0);
11283     else
11284       IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
11285                         false, false, false, 0);
11286
11287     SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
11288                                     getPointerTy());
11289     IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
11290
11291     SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
11292     res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
11293                       false, false, false, 0);
11294
11295     // Get the offset of start of .tls section
11296     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11297                                              GA->getValueType(0),
11298                                              GA->getOffset(), X86II::MO_SECREL);
11299     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
11300
11301     // The address of the thread local variable is the add of the thread
11302     // pointer with the offset of the variable.
11303     return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
11304   }
11305
11306   llvm_unreachable("TLS not implemented for this target.");
11307 }
11308
11309 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
11310 /// and take a 2 x i32 value to shift plus a shift amount.
11311 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
11312   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
11313   MVT VT = Op.getSimpleValueType();
11314   unsigned VTBits = VT.getSizeInBits();
11315   SDLoc dl(Op);
11316   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
11317   SDValue ShOpLo = Op.getOperand(0);
11318   SDValue ShOpHi = Op.getOperand(1);
11319   SDValue ShAmt  = Op.getOperand(2);
11320   // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
11321   // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
11322   // during isel.
11323   SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
11324                                   DAG.getConstant(VTBits - 1, MVT::i8));
11325   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
11326                                      DAG.getConstant(VTBits - 1, MVT::i8))
11327                        : DAG.getConstant(0, VT);
11328
11329   SDValue Tmp2, Tmp3;
11330   if (Op.getOpcode() == ISD::SHL_PARTS) {
11331     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
11332     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
11333   } else {
11334     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
11335     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
11336   }
11337
11338   // If the shift amount is larger or equal than the width of a part we can't
11339   // rely on the results of shld/shrd. Insert a test and select the appropriate
11340   // values for large shift amounts.
11341   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
11342                                 DAG.getConstant(VTBits, MVT::i8));
11343   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11344                              AndNode, DAG.getConstant(0, MVT::i8));
11345
11346   SDValue Hi, Lo;
11347   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11348   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
11349   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
11350
11351   if (Op.getOpcode() == ISD::SHL_PARTS) {
11352     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
11353     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
11354   } else {
11355     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
11356     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
11357   }
11358
11359   SDValue Ops[2] = { Lo, Hi };
11360   return DAG.getMergeValues(Ops, dl);
11361 }
11362
11363 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
11364                                            SelectionDAG &DAG) const {
11365   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
11366   SDLoc dl(Op);
11367
11368   if (SrcVT.isVector()) {
11369     if (SrcVT.getVectorElementType() == MVT::i1) {
11370       MVT IntegerVT = MVT::getVectorVT(MVT::i32, SrcVT.getVectorNumElements());
11371       return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
11372                          DAG.getNode(ISD::SIGN_EXTEND, dl, IntegerVT,
11373                                      Op.getOperand(0)));
11374     }
11375     return SDValue();
11376   }
11377
11378   assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
11379          "Unknown SINT_TO_FP to lower!");
11380
11381   // These are really Legal; return the operand so the caller accepts it as
11382   // Legal.
11383   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
11384     return Op;
11385   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
11386       Subtarget->is64Bit()) {
11387     return Op;
11388   }
11389
11390   unsigned Size = SrcVT.getSizeInBits()/8;
11391   MachineFunction &MF = DAG.getMachineFunction();
11392   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
11393   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11394   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11395                                StackSlot,
11396                                MachinePointerInfo::getFixedStack(SSFI),
11397                                false, false, 0);
11398   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
11399 }
11400
11401 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
11402                                      SDValue StackSlot,
11403                                      SelectionDAG &DAG) const {
11404   // Build the FILD
11405   SDLoc DL(Op);
11406   SDVTList Tys;
11407   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
11408   if (useSSE)
11409     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
11410   else
11411     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
11412
11413   unsigned ByteSize = SrcVT.getSizeInBits()/8;
11414
11415   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
11416   MachineMemOperand *MMO;
11417   if (FI) {
11418     int SSFI = FI->getIndex();
11419     MMO =
11420       DAG.getMachineFunction()
11421       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11422                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
11423   } else {
11424     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
11425     StackSlot = StackSlot.getOperand(1);
11426   }
11427   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
11428   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
11429                                            X86ISD::FILD, DL,
11430                                            Tys, Ops, SrcVT, MMO);
11431
11432   if (useSSE) {
11433     Chain = Result.getValue(1);
11434     SDValue InFlag = Result.getValue(2);
11435
11436     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
11437     // shouldn't be necessary except that RFP cannot be live across
11438     // multiple blocks. When stackifier is fixed, they can be uncoupled.
11439     MachineFunction &MF = DAG.getMachineFunction();
11440     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
11441     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
11442     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11443     Tys = DAG.getVTList(MVT::Other);
11444     SDValue Ops[] = {
11445       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
11446     };
11447     MachineMemOperand *MMO =
11448       DAG.getMachineFunction()
11449       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11450                             MachineMemOperand::MOStore, SSFISize, SSFISize);
11451
11452     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
11453                                     Ops, Op.getValueType(), MMO);
11454     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
11455                          MachinePointerInfo::getFixedStack(SSFI),
11456                          false, false, false, 0);
11457   }
11458
11459   return Result;
11460 }
11461
11462 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
11463 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
11464                                                SelectionDAG &DAG) const {
11465   // This algorithm is not obvious. Here it is what we're trying to output:
11466   /*
11467      movq       %rax,  %xmm0
11468      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
11469      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
11470      #ifdef __SSE3__
11471        haddpd   %xmm0, %xmm0
11472      #else
11473        pshufd   $0x4e, %xmm0, %xmm1
11474        addpd    %xmm1, %xmm0
11475      #endif
11476   */
11477
11478   SDLoc dl(Op);
11479   LLVMContext *Context = DAG.getContext();
11480
11481   // Build some magic constants.
11482   static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
11483   Constant *C0 = ConstantDataVector::get(*Context, CV0);
11484   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
11485
11486   SmallVector<Constant*,2> CV1;
11487   CV1.push_back(
11488     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11489                                       APInt(64, 0x4330000000000000ULL))));
11490   CV1.push_back(
11491     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11492                                       APInt(64, 0x4530000000000000ULL))));
11493   Constant *C1 = ConstantVector::get(CV1);
11494   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
11495
11496   // Load the 64-bit value into an XMM register.
11497   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
11498                             Op.getOperand(0));
11499   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
11500                               MachinePointerInfo::getConstantPool(),
11501                               false, false, false, 16);
11502   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
11503                               DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
11504                               CLod0);
11505
11506   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
11507                               MachinePointerInfo::getConstantPool(),
11508                               false, false, false, 16);
11509   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
11510   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
11511   SDValue Result;
11512
11513   if (Subtarget->hasSSE3()) {
11514     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
11515     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
11516   } else {
11517     SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
11518     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
11519                                            S2F, 0x4E, DAG);
11520     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
11521                          DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
11522                          Sub);
11523   }
11524
11525   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
11526                      DAG.getIntPtrConstant(0));
11527 }
11528
11529 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
11530 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
11531                                                SelectionDAG &DAG) const {
11532   SDLoc dl(Op);
11533   // FP constant to bias correct the final result.
11534   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
11535                                    MVT::f64);
11536
11537   // Load the 32-bit value into an XMM register.
11538   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
11539                              Op.getOperand(0));
11540
11541   // Zero out the upper parts of the register.
11542   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
11543
11544   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
11545                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
11546                      DAG.getIntPtrConstant(0));
11547
11548   // Or the load with the bias.
11549   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
11550                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
11551                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
11552                                                    MVT::v2f64, Load)),
11553                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
11554                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
11555                                                    MVT::v2f64, Bias)));
11556   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
11557                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
11558                    DAG.getIntPtrConstant(0));
11559
11560   // Subtract the bias.
11561   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
11562
11563   // Handle final rounding.
11564   EVT DestVT = Op.getValueType();
11565
11566   if (DestVT.bitsLT(MVT::f64))
11567     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
11568                        DAG.getIntPtrConstant(0));
11569   if (DestVT.bitsGT(MVT::f64))
11570     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
11571
11572   // Handle final rounding.
11573   return Sub;
11574 }
11575
11576 static SDValue lowerUINT_TO_FP_vXi32(SDValue Op, SelectionDAG &DAG,
11577                                      const X86Subtarget &Subtarget) {
11578   // The algorithm is the following:
11579   // #ifdef __SSE4_1__
11580   //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
11581   //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
11582   //                                 (uint4) 0x53000000, 0xaa);
11583   // #else
11584   //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
11585   //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
11586   // #endif
11587   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
11588   //     return (float4) lo + fhi;
11589
11590   SDLoc DL(Op);
11591   SDValue V = Op->getOperand(0);
11592   EVT VecIntVT = V.getValueType();
11593   bool Is128 = VecIntVT == MVT::v4i32;
11594   EVT VecFloatVT = Is128 ? MVT::v4f32 : MVT::v8f32;
11595   // If we convert to something else than the supported type, e.g., to v4f64,
11596   // abort early.
11597   if (VecFloatVT != Op->getValueType(0))
11598     return SDValue();
11599
11600   unsigned NumElts = VecIntVT.getVectorNumElements();
11601   assert((VecIntVT == MVT::v4i32 || VecIntVT == MVT::v8i32) &&
11602          "Unsupported custom type");
11603   assert(NumElts <= 8 && "The size of the constant array must be fixed");
11604
11605   // In the #idef/#else code, we have in common:
11606   // - The vector of constants:
11607   // -- 0x4b000000
11608   // -- 0x53000000
11609   // - A shift:
11610   // -- v >> 16
11611
11612   // Create the splat vector for 0x4b000000.
11613   SDValue CstLow = DAG.getConstant(0x4b000000, MVT::i32);
11614   SDValue CstLowArray[] = {CstLow, CstLow, CstLow, CstLow,
11615                            CstLow, CstLow, CstLow, CstLow};
11616   SDValue VecCstLow = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
11617                                   makeArrayRef(&CstLowArray[0], NumElts));
11618   // Create the splat vector for 0x53000000.
11619   SDValue CstHigh = DAG.getConstant(0x53000000, MVT::i32);
11620   SDValue CstHighArray[] = {CstHigh, CstHigh, CstHigh, CstHigh,
11621                             CstHigh, CstHigh, CstHigh, CstHigh};
11622   SDValue VecCstHigh = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
11623                                    makeArrayRef(&CstHighArray[0], NumElts));
11624
11625   // Create the right shift.
11626   SDValue CstShift = DAG.getConstant(16, MVT::i32);
11627   SDValue CstShiftArray[] = {CstShift, CstShift, CstShift, CstShift,
11628                              CstShift, CstShift, CstShift, CstShift};
11629   SDValue VecCstShift = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
11630                                     makeArrayRef(&CstShiftArray[0], NumElts));
11631   SDValue HighShift = DAG.getNode(ISD::SRL, DL, VecIntVT, V, VecCstShift);
11632
11633   SDValue Low, High;
11634   if (Subtarget.hasSSE41()) {
11635     EVT VecI16VT = Is128 ? MVT::v8i16 : MVT::v16i16;
11636     //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
11637     SDValue VecCstLowBitcast =
11638         DAG.getNode(ISD::BITCAST, DL, VecI16VT, VecCstLow);
11639     SDValue VecBitcast = DAG.getNode(ISD::BITCAST, DL, VecI16VT, V);
11640     // Low will be bitcasted right away, so do not bother bitcasting back to its
11641     // original type.
11642     Low = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecBitcast,
11643                       VecCstLowBitcast, DAG.getConstant(0xaa, MVT::i32));
11644     //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
11645     //                                 (uint4) 0x53000000, 0xaa);
11646     SDValue VecCstHighBitcast =
11647         DAG.getNode(ISD::BITCAST, DL, VecI16VT, VecCstHigh);
11648     SDValue VecShiftBitcast =
11649         DAG.getNode(ISD::BITCAST, DL, VecI16VT, HighShift);
11650     // High will be bitcasted right away, so do not bother bitcasting back to
11651     // its original type.
11652     High = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecShiftBitcast,
11653                        VecCstHighBitcast, DAG.getConstant(0xaa, MVT::i32));
11654   } else {
11655     SDValue CstMask = DAG.getConstant(0xffff, MVT::i32);
11656     SDValue VecCstMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT, CstMask,
11657                                      CstMask, CstMask, CstMask);
11658     //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
11659     SDValue LowAnd = DAG.getNode(ISD::AND, DL, VecIntVT, V, VecCstMask);
11660     Low = DAG.getNode(ISD::OR, DL, VecIntVT, LowAnd, VecCstLow);
11661
11662     //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
11663     High = DAG.getNode(ISD::OR, DL, VecIntVT, HighShift, VecCstHigh);
11664   }
11665
11666   // Create the vector constant for -(0x1.0p39f + 0x1.0p23f).
11667   SDValue CstFAdd = DAG.getConstantFP(
11668       APFloat(APFloat::IEEEsingle, APInt(32, 0xD3000080)), MVT::f32);
11669   SDValue CstFAddArray[] = {CstFAdd, CstFAdd, CstFAdd, CstFAdd,
11670                             CstFAdd, CstFAdd, CstFAdd, CstFAdd};
11671   SDValue VecCstFAdd = DAG.getNode(ISD::BUILD_VECTOR, DL, VecFloatVT,
11672                                    makeArrayRef(&CstFAddArray[0], NumElts));
11673
11674   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
11675   SDValue HighBitcast = DAG.getNode(ISD::BITCAST, DL, VecFloatVT, High);
11676   SDValue FHigh =
11677       DAG.getNode(ISD::FADD, DL, VecFloatVT, HighBitcast, VecCstFAdd);
11678   //     return (float4) lo + fhi;
11679   SDValue LowBitcast = DAG.getNode(ISD::BITCAST, DL, VecFloatVT, Low);
11680   return DAG.getNode(ISD::FADD, DL, VecFloatVT, LowBitcast, FHigh);
11681 }
11682
11683 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
11684                                                SelectionDAG &DAG) const {
11685   SDValue N0 = Op.getOperand(0);
11686   MVT SVT = N0.getSimpleValueType();
11687   SDLoc dl(Op);
11688
11689   switch (SVT.SimpleTy) {
11690   default:
11691     llvm_unreachable("Custom UINT_TO_FP is not supported!");
11692   case MVT::v4i8:
11693   case MVT::v4i16:
11694   case MVT::v8i8:
11695   case MVT::v8i16: {
11696     MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
11697     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
11698                        DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
11699   }
11700   case MVT::v4i32:
11701   case MVT::v8i32:
11702     return lowerUINT_TO_FP_vXi32(Op, DAG, *Subtarget);
11703   }
11704   llvm_unreachable(nullptr);
11705 }
11706
11707 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
11708                                            SelectionDAG &DAG) const {
11709   SDValue N0 = Op.getOperand(0);
11710   SDLoc dl(Op);
11711
11712   if (Op.getValueType().isVector())
11713     return lowerUINT_TO_FP_vec(Op, DAG);
11714
11715   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
11716   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
11717   // the optimization here.
11718   if (DAG.SignBitIsZero(N0))
11719     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
11720
11721   MVT SrcVT = N0.getSimpleValueType();
11722   MVT DstVT = Op.getSimpleValueType();
11723   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
11724     return LowerUINT_TO_FP_i64(Op, DAG);
11725   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
11726     return LowerUINT_TO_FP_i32(Op, DAG);
11727   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
11728     return SDValue();
11729
11730   // Make a 64-bit buffer, and use it to build an FILD.
11731   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
11732   if (SrcVT == MVT::i32) {
11733     SDValue WordOff = DAG.getConstant(4, getPointerTy());
11734     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
11735                                      getPointerTy(), StackSlot, WordOff);
11736     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11737                                   StackSlot, MachinePointerInfo(),
11738                                   false, false, 0);
11739     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
11740                                   OffsetSlot, MachinePointerInfo(),
11741                                   false, false, 0);
11742     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
11743     return Fild;
11744   }
11745
11746   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
11747   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11748                                StackSlot, MachinePointerInfo(),
11749                                false, false, 0);
11750   // For i64 source, we need to add the appropriate power of 2 if the input
11751   // was negative.  This is the same as the optimization in
11752   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
11753   // we must be careful to do the computation in x87 extended precision, not
11754   // in SSE. (The generic code can't know it's OK to do this, or how to.)
11755   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
11756   MachineMemOperand *MMO =
11757     DAG.getMachineFunction()
11758     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11759                           MachineMemOperand::MOLoad, 8, 8);
11760
11761   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
11762   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
11763   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
11764                                          MVT::i64, MMO);
11765
11766   APInt FF(32, 0x5F800000ULL);
11767
11768   // Check whether the sign bit is set.
11769   SDValue SignSet = DAG.getSetCC(dl,
11770                                  getSetCCResultType(*DAG.getContext(), MVT::i64),
11771                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
11772                                  ISD::SETLT);
11773
11774   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
11775   SDValue FudgePtr = DAG.getConstantPool(
11776                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
11777                                          getPointerTy());
11778
11779   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
11780   SDValue Zero = DAG.getIntPtrConstant(0);
11781   SDValue Four = DAG.getIntPtrConstant(4);
11782   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
11783                                Zero, Four);
11784   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
11785
11786   // Load the value out, extending it from f32 to f80.
11787   // FIXME: Avoid the extend by constructing the right constant pool?
11788   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
11789                                  FudgePtr, MachinePointerInfo::getConstantPool(),
11790                                  MVT::f32, false, false, false, 4);
11791   // Extend everything to 80 bits to force it to be done on x87.
11792   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
11793   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
11794 }
11795
11796 std::pair<SDValue,SDValue>
11797 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
11798                                     bool IsSigned, bool IsReplace) const {
11799   SDLoc DL(Op);
11800
11801   EVT DstTy = Op.getValueType();
11802
11803   if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
11804     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
11805     DstTy = MVT::i64;
11806   }
11807
11808   assert(DstTy.getSimpleVT() <= MVT::i64 &&
11809          DstTy.getSimpleVT() >= MVT::i16 &&
11810          "Unknown FP_TO_INT to lower!");
11811
11812   // These are really Legal.
11813   if (DstTy == MVT::i32 &&
11814       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
11815     return std::make_pair(SDValue(), SDValue());
11816   if (Subtarget->is64Bit() &&
11817       DstTy == MVT::i64 &&
11818       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
11819     return std::make_pair(SDValue(), SDValue());
11820
11821   // We lower FP->int64 either into FISTP64 followed by a load from a temporary
11822   // stack slot, or into the FTOL runtime function.
11823   MachineFunction &MF = DAG.getMachineFunction();
11824   unsigned MemSize = DstTy.getSizeInBits()/8;
11825   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
11826   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11827
11828   unsigned Opc;
11829   if (!IsSigned && isIntegerTypeFTOL(DstTy))
11830     Opc = X86ISD::WIN_FTOL;
11831   else
11832     switch (DstTy.getSimpleVT().SimpleTy) {
11833     default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
11834     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
11835     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
11836     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
11837     }
11838
11839   SDValue Chain = DAG.getEntryNode();
11840   SDValue Value = Op.getOperand(0);
11841   EVT TheVT = Op.getOperand(0).getValueType();
11842   // FIXME This causes a redundant load/store if the SSE-class value is already
11843   // in memory, such as if it is on the callstack.
11844   if (isScalarFPTypeInSSEReg(TheVT)) {
11845     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
11846     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
11847                          MachinePointerInfo::getFixedStack(SSFI),
11848                          false, false, 0);
11849     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
11850     SDValue Ops[] = {
11851       Chain, StackSlot, DAG.getValueType(TheVT)
11852     };
11853
11854     MachineMemOperand *MMO =
11855       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11856                               MachineMemOperand::MOLoad, MemSize, MemSize);
11857     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
11858     Chain = Value.getValue(1);
11859     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
11860     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11861   }
11862
11863   MachineMemOperand *MMO =
11864     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11865                             MachineMemOperand::MOStore, MemSize, MemSize);
11866
11867   if (Opc != X86ISD::WIN_FTOL) {
11868     // Build the FP_TO_INT*_IN_MEM
11869     SDValue Ops[] = { Chain, Value, StackSlot };
11870     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
11871                                            Ops, DstTy, MMO);
11872     return std::make_pair(FIST, StackSlot);
11873   } else {
11874     SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
11875       DAG.getVTList(MVT::Other, MVT::Glue),
11876       Chain, Value);
11877     SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
11878       MVT::i32, ftol.getValue(1));
11879     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
11880       MVT::i32, eax.getValue(2));
11881     SDValue Ops[] = { eax, edx };
11882     SDValue pair = IsReplace
11883       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops)
11884       : DAG.getMergeValues(Ops, DL);
11885     return std::make_pair(pair, SDValue());
11886   }
11887 }
11888
11889 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
11890                               const X86Subtarget *Subtarget) {
11891   MVT VT = Op->getSimpleValueType(0);
11892   SDValue In = Op->getOperand(0);
11893   MVT InVT = In.getSimpleValueType();
11894   SDLoc dl(Op);
11895
11896   // Optimize vectors in AVX mode:
11897   //
11898   //   v8i16 -> v8i32
11899   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
11900   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
11901   //   Concat upper and lower parts.
11902   //
11903   //   v4i32 -> v4i64
11904   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
11905   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
11906   //   Concat upper and lower parts.
11907   //
11908
11909   if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
11910       ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
11911       ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
11912     return SDValue();
11913
11914   if (Subtarget->hasInt256())
11915     return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
11916
11917   SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
11918   SDValue Undef = DAG.getUNDEF(InVT);
11919   bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
11920   SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
11921   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
11922
11923   MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
11924                              VT.getVectorNumElements()/2);
11925
11926   OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
11927   OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
11928
11929   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
11930 }
11931
11932 static  SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
11933                                         SelectionDAG &DAG) {
11934   MVT VT = Op->getSimpleValueType(0);
11935   SDValue In = Op->getOperand(0);
11936   MVT InVT = In.getSimpleValueType();
11937   SDLoc DL(Op);
11938   unsigned int NumElts = VT.getVectorNumElements();
11939   if (NumElts != 8 && NumElts != 16)
11940     return SDValue();
11941
11942   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
11943     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
11944
11945   EVT ExtVT = (NumElts == 8)? MVT::v8i64 : MVT::v16i32;
11946   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11947   // Now we have only mask extension
11948   assert(InVT.getVectorElementType() == MVT::i1);
11949   SDValue Cst = DAG.getTargetConstant(1, ExtVT.getScalarType());
11950   const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
11951   SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
11952   unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
11953   SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
11954                            MachinePointerInfo::getConstantPool(),
11955                            false, false, false, Alignment);
11956
11957   SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, DL, ExtVT, In, Ld);
11958   if (VT.is512BitVector())
11959     return Brcst;
11960   return DAG.getNode(X86ISD::VTRUNC, DL, VT, Brcst);
11961 }
11962
11963 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
11964                                SelectionDAG &DAG) {
11965   if (Subtarget->hasFp256()) {
11966     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
11967     if (Res.getNode())
11968       return Res;
11969   }
11970
11971   return SDValue();
11972 }
11973
11974 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
11975                                 SelectionDAG &DAG) {
11976   SDLoc DL(Op);
11977   MVT VT = Op.getSimpleValueType();
11978   SDValue In = Op.getOperand(0);
11979   MVT SVT = In.getSimpleValueType();
11980
11981   if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
11982     return LowerZERO_EXTEND_AVX512(Op, DAG);
11983
11984   if (Subtarget->hasFp256()) {
11985     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
11986     if (Res.getNode())
11987       return Res;
11988   }
11989
11990   assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
11991          VT.getVectorNumElements() != SVT.getVectorNumElements());
11992   return SDValue();
11993 }
11994
11995 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
11996   SDLoc DL(Op);
11997   MVT VT = Op.getSimpleValueType();
11998   SDValue In = Op.getOperand(0);
11999   MVT InVT = In.getSimpleValueType();
12000
12001   if (VT == MVT::i1) {
12002     assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
12003            "Invalid scalar TRUNCATE operation");
12004     if (InVT.getSizeInBits() >= 32)
12005       return SDValue();
12006     In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
12007     return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
12008   }
12009   assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
12010          "Invalid TRUNCATE operation");
12011
12012   if (InVT.is512BitVector() || VT.getVectorElementType() == MVT::i1) {
12013     if (VT.getVectorElementType().getSizeInBits() >=8)
12014       return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
12015
12016     assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
12017     unsigned NumElts = InVT.getVectorNumElements();
12018     assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
12019     if (InVT.getSizeInBits() < 512) {
12020       MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
12021       In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
12022       InVT = ExtVT;
12023     }
12024
12025     SDValue Cst = DAG.getTargetConstant(1, InVT.getVectorElementType());
12026     const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
12027     SDValue CP = DAG.getConstantPool(C, getPointerTy());
12028     unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
12029     SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
12030                            MachinePointerInfo::getConstantPool(),
12031                            false, false, false, Alignment);
12032     SDValue OneV = DAG.getNode(X86ISD::VBROADCAST, DL, InVT, Ld);
12033     SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
12034     return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
12035   }
12036
12037   if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
12038     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
12039     if (Subtarget->hasInt256()) {
12040       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
12041       In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
12042       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
12043                                 ShufMask);
12044       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
12045                          DAG.getIntPtrConstant(0));
12046     }
12047
12048     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12049                                DAG.getIntPtrConstant(0));
12050     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12051                                DAG.getIntPtrConstant(2));
12052     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
12053     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
12054     static const int ShufMask[] = {0, 2, 4, 6};
12055     return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
12056   }
12057
12058   if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
12059     // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
12060     if (Subtarget->hasInt256()) {
12061       In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
12062
12063       SmallVector<SDValue,32> pshufbMask;
12064       for (unsigned i = 0; i < 2; ++i) {
12065         pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
12066         pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
12067         pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
12068         pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
12069         pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
12070         pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
12071         pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
12072         pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
12073         for (unsigned j = 0; j < 8; ++j)
12074           pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
12075       }
12076       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
12077       In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
12078       In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
12079
12080       static const int ShufMask[] = {0,  2,  -1,  -1};
12081       In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, DAG.getUNDEF(MVT::v4i64),
12082                                 &ShufMask[0]);
12083       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12084                        DAG.getIntPtrConstant(0));
12085       return DAG.getNode(ISD::BITCAST, DL, VT, In);
12086     }
12087
12088     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
12089                                DAG.getIntPtrConstant(0));
12090
12091     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
12092                                DAG.getIntPtrConstant(4));
12093
12094     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
12095     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
12096
12097     // The PSHUFB mask:
12098     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
12099                                    -1, -1, -1, -1, -1, -1, -1, -1};
12100
12101     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
12102     OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
12103     OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
12104
12105     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
12106     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
12107
12108     // The MOVLHPS Mask:
12109     static const int ShufMask2[] = {0, 1, 4, 5};
12110     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
12111     return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
12112   }
12113
12114   // Handle truncation of V256 to V128 using shuffles.
12115   if (!VT.is128BitVector() || !InVT.is256BitVector())
12116     return SDValue();
12117
12118   assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
12119
12120   unsigned NumElems = VT.getVectorNumElements();
12121   MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
12122
12123   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
12124   // Prepare truncation shuffle mask
12125   for (unsigned i = 0; i != NumElems; ++i)
12126     MaskVec[i] = i * 2;
12127   SDValue V = DAG.getVectorShuffle(NVT, DL,
12128                                    DAG.getNode(ISD::BITCAST, DL, NVT, In),
12129                                    DAG.getUNDEF(NVT), &MaskVec[0]);
12130   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
12131                      DAG.getIntPtrConstant(0));
12132 }
12133
12134 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
12135                                            SelectionDAG &DAG) const {
12136   assert(!Op.getSimpleValueType().isVector());
12137
12138   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
12139     /*IsSigned=*/ true, /*IsReplace=*/ false);
12140   SDValue FIST = Vals.first, StackSlot = Vals.second;
12141   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
12142   if (!FIST.getNode()) return Op;
12143
12144   if (StackSlot.getNode())
12145     // Load the result.
12146     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
12147                        FIST, StackSlot, MachinePointerInfo(),
12148                        false, false, false, 0);
12149
12150   // The node is the result.
12151   return FIST;
12152 }
12153
12154 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
12155                                            SelectionDAG &DAG) const {
12156   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
12157     /*IsSigned=*/ false, /*IsReplace=*/ false);
12158   SDValue FIST = Vals.first, StackSlot = Vals.second;
12159   assert(FIST.getNode() && "Unexpected failure");
12160
12161   if (StackSlot.getNode())
12162     // Load the result.
12163     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
12164                        FIST, StackSlot, MachinePointerInfo(),
12165                        false, false, false, 0);
12166
12167   // The node is the result.
12168   return FIST;
12169 }
12170
12171 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
12172   SDLoc DL(Op);
12173   MVT VT = Op.getSimpleValueType();
12174   SDValue In = Op.getOperand(0);
12175   MVT SVT = In.getSimpleValueType();
12176
12177   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
12178
12179   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
12180                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
12181                                  In, DAG.getUNDEF(SVT)));
12182 }
12183
12184 /// The only differences between FABS and FNEG are the mask and the logic op.
12185 /// FNEG also has a folding opportunity for FNEG(FABS(x)).
12186 static SDValue LowerFABSorFNEG(SDValue Op, SelectionDAG &DAG) {
12187   assert((Op.getOpcode() == ISD::FABS || Op.getOpcode() == ISD::FNEG) &&
12188          "Wrong opcode for lowering FABS or FNEG.");
12189
12190   bool IsFABS = (Op.getOpcode() == ISD::FABS);
12191
12192   // If this is a FABS and it has an FNEG user, bail out to fold the combination
12193   // into an FNABS. We'll lower the FABS after that if it is still in use.
12194   if (IsFABS)
12195     for (SDNode *User : Op->uses())
12196       if (User->getOpcode() == ISD::FNEG)
12197         return Op;
12198
12199   SDValue Op0 = Op.getOperand(0);
12200   bool IsFNABS = !IsFABS && (Op0.getOpcode() == ISD::FABS);
12201
12202   SDLoc dl(Op);
12203   MVT VT = Op.getSimpleValueType();
12204   // Assume scalar op for initialization; update for vector if needed.
12205   // Note that there are no scalar bitwise logical SSE/AVX instructions, so we
12206   // generate a 16-byte vector constant and logic op even for the scalar case.
12207   // Using a 16-byte mask allows folding the load of the mask with
12208   // the logic op, so it can save (~4 bytes) on code size.
12209   MVT EltVT = VT;
12210   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
12211   // FIXME: Use function attribute "OptimizeForSize" and/or CodeGenOpt::Level to
12212   // decide if we should generate a 16-byte constant mask when we only need 4 or
12213   // 8 bytes for the scalar case.
12214   if (VT.isVector()) {
12215     EltVT = VT.getVectorElementType();
12216     NumElts = VT.getVectorNumElements();
12217   }
12218
12219   unsigned EltBits = EltVT.getSizeInBits();
12220   LLVMContext *Context = DAG.getContext();
12221   // For FABS, mask is 0x7f...; for FNEG, mask is 0x80...
12222   APInt MaskElt =
12223     IsFABS ? APInt::getSignedMaxValue(EltBits) : APInt::getSignBit(EltBits);
12224   Constant *C = ConstantInt::get(*Context, MaskElt);
12225   C = ConstantVector::getSplat(NumElts, C);
12226   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12227   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
12228   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
12229   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
12230                              MachinePointerInfo::getConstantPool(),
12231                              false, false, false, Alignment);
12232
12233   if (VT.isVector()) {
12234     // For a vector, cast operands to a vector type, perform the logic op,
12235     // and cast the result back to the original value type.
12236     MVT VecVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
12237     SDValue MaskCasted = DAG.getNode(ISD::BITCAST, dl, VecVT, Mask);
12238     SDValue Operand = IsFNABS ?
12239       DAG.getNode(ISD::BITCAST, dl, VecVT, Op0.getOperand(0)) :
12240       DAG.getNode(ISD::BITCAST, dl, VecVT, Op0);
12241     unsigned BitOp = IsFABS ? ISD::AND : IsFNABS ? ISD::OR : ISD::XOR;
12242     return DAG.getNode(ISD::BITCAST, dl, VT,
12243                        DAG.getNode(BitOp, dl, VecVT, Operand, MaskCasted));
12244   }
12245
12246   // If not vector, then scalar.
12247   unsigned BitOp = IsFABS ? X86ISD::FAND : IsFNABS ? X86ISD::FOR : X86ISD::FXOR;
12248   SDValue Operand = IsFNABS ? Op0.getOperand(0) : Op0;
12249   return DAG.getNode(BitOp, dl, VT, Operand, Mask);
12250 }
12251
12252 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
12253   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12254   LLVMContext *Context = DAG.getContext();
12255   SDValue Op0 = Op.getOperand(0);
12256   SDValue Op1 = Op.getOperand(1);
12257   SDLoc dl(Op);
12258   MVT VT = Op.getSimpleValueType();
12259   MVT SrcVT = Op1.getSimpleValueType();
12260
12261   // If second operand is smaller, extend it first.
12262   if (SrcVT.bitsLT(VT)) {
12263     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
12264     SrcVT = VT;
12265   }
12266   // And if it is bigger, shrink it first.
12267   if (SrcVT.bitsGT(VT)) {
12268     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
12269     SrcVT = VT;
12270   }
12271
12272   // At this point the operands and the result should have the same
12273   // type, and that won't be f80 since that is not custom lowered.
12274
12275   const fltSemantics &Sem =
12276       VT == MVT::f64 ? APFloat::IEEEdouble : APFloat::IEEEsingle;
12277   const unsigned SizeInBits = VT.getSizeInBits();
12278
12279   SmallVector<Constant *, 4> CV(
12280       VT == MVT::f64 ? 2 : 4,
12281       ConstantFP::get(*Context, APFloat(Sem, APInt(SizeInBits, 0))));
12282
12283   // First, clear all bits but the sign bit from the second operand (sign).
12284   CV[0] = ConstantFP::get(*Context,
12285                           APFloat(Sem, APInt::getHighBitsSet(SizeInBits, 1)));
12286   Constant *C = ConstantVector::get(CV);
12287   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
12288   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
12289                               MachinePointerInfo::getConstantPool(),
12290                               false, false, false, 16);
12291   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
12292
12293   // Next, clear the sign bit from the first operand (magnitude).
12294   // If it's a constant, we can clear it here.
12295   if (ConstantFPSDNode *Op0CN = dyn_cast<ConstantFPSDNode>(Op0)) {
12296     APFloat APF = Op0CN->getValueAPF();
12297     // If the magnitude is a positive zero, the sign bit alone is enough.
12298     if (APF.isPosZero())
12299       return SignBit;
12300     APF.clearSign();
12301     CV[0] = ConstantFP::get(*Context, APF);
12302   } else {
12303     CV[0] = ConstantFP::get(
12304         *Context,
12305         APFloat(Sem, APInt::getLowBitsSet(SizeInBits, SizeInBits - 1)));
12306   }
12307   C = ConstantVector::get(CV);
12308   CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
12309   SDValue Val = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
12310                             MachinePointerInfo::getConstantPool(),
12311                             false, false, false, 16);
12312   // If the magnitude operand wasn't a constant, we need to AND out the sign.
12313   if (!isa<ConstantFPSDNode>(Op0))
12314     Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Val);
12315
12316   // OR the magnitude value with the sign bit.
12317   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
12318 }
12319
12320 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
12321   SDValue N0 = Op.getOperand(0);
12322   SDLoc dl(Op);
12323   MVT VT = Op.getSimpleValueType();
12324
12325   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
12326   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
12327                                   DAG.getConstant(1, VT));
12328   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
12329 }
12330
12331 // Check whether an OR'd tree is PTEST-able.
12332 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
12333                                       SelectionDAG &DAG) {
12334   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
12335
12336   if (!Subtarget->hasSSE41())
12337     return SDValue();
12338
12339   if (!Op->hasOneUse())
12340     return SDValue();
12341
12342   SDNode *N = Op.getNode();
12343   SDLoc DL(N);
12344
12345   SmallVector<SDValue, 8> Opnds;
12346   DenseMap<SDValue, unsigned> VecInMap;
12347   SmallVector<SDValue, 8> VecIns;
12348   EVT VT = MVT::Other;
12349
12350   // Recognize a special case where a vector is casted into wide integer to
12351   // test all 0s.
12352   Opnds.push_back(N->getOperand(0));
12353   Opnds.push_back(N->getOperand(1));
12354
12355   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
12356     SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
12357     // BFS traverse all OR'd operands.
12358     if (I->getOpcode() == ISD::OR) {
12359       Opnds.push_back(I->getOperand(0));
12360       Opnds.push_back(I->getOperand(1));
12361       // Re-evaluate the number of nodes to be traversed.
12362       e += 2; // 2 more nodes (LHS and RHS) are pushed.
12363       continue;
12364     }
12365
12366     // Quit if a non-EXTRACT_VECTOR_ELT
12367     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
12368       return SDValue();
12369
12370     // Quit if without a constant index.
12371     SDValue Idx = I->getOperand(1);
12372     if (!isa<ConstantSDNode>(Idx))
12373       return SDValue();
12374
12375     SDValue ExtractedFromVec = I->getOperand(0);
12376     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
12377     if (M == VecInMap.end()) {
12378       VT = ExtractedFromVec.getValueType();
12379       // Quit if not 128/256-bit vector.
12380       if (!VT.is128BitVector() && !VT.is256BitVector())
12381         return SDValue();
12382       // Quit if not the same type.
12383       if (VecInMap.begin() != VecInMap.end() &&
12384           VT != VecInMap.begin()->first.getValueType())
12385         return SDValue();
12386       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
12387       VecIns.push_back(ExtractedFromVec);
12388     }
12389     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
12390   }
12391
12392   assert((VT.is128BitVector() || VT.is256BitVector()) &&
12393          "Not extracted from 128-/256-bit vector.");
12394
12395   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
12396
12397   for (DenseMap<SDValue, unsigned>::const_iterator
12398         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
12399     // Quit if not all elements are used.
12400     if (I->second != FullMask)
12401       return SDValue();
12402   }
12403
12404   EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
12405
12406   // Cast all vectors into TestVT for PTEST.
12407   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
12408     VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
12409
12410   // If more than one full vectors are evaluated, OR them first before PTEST.
12411   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
12412     // Each iteration will OR 2 nodes and append the result until there is only
12413     // 1 node left, i.e. the final OR'd value of all vectors.
12414     SDValue LHS = VecIns[Slot];
12415     SDValue RHS = VecIns[Slot + 1];
12416     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
12417   }
12418
12419   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
12420                      VecIns.back(), VecIns.back());
12421 }
12422
12423 /// \brief return true if \c Op has a use that doesn't just read flags.
12424 static bool hasNonFlagsUse(SDValue Op) {
12425   for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
12426        ++UI) {
12427     SDNode *User = *UI;
12428     unsigned UOpNo = UI.getOperandNo();
12429     if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
12430       // Look pass truncate.
12431       UOpNo = User->use_begin().getOperandNo();
12432       User = *User->use_begin();
12433     }
12434
12435     if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
12436         !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
12437       return true;
12438   }
12439   return false;
12440 }
12441
12442 /// Emit nodes that will be selected as "test Op0,Op0", or something
12443 /// equivalent.
12444 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
12445                                     SelectionDAG &DAG) const {
12446   if (Op.getValueType() == MVT::i1) {
12447     SDValue ExtOp = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i8, Op);
12448     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, ExtOp,
12449                        DAG.getConstant(0, MVT::i8));
12450   }
12451   // CF and OF aren't always set the way we want. Determine which
12452   // of these we need.
12453   bool NeedCF = false;
12454   bool NeedOF = false;
12455   switch (X86CC) {
12456   default: break;
12457   case X86::COND_A: case X86::COND_AE:
12458   case X86::COND_B: case X86::COND_BE:
12459     NeedCF = true;
12460     break;
12461   case X86::COND_G: case X86::COND_GE:
12462   case X86::COND_L: case X86::COND_LE:
12463   case X86::COND_O: case X86::COND_NO: {
12464     // Check if we really need to set the
12465     // Overflow flag. If NoSignedWrap is present
12466     // that is not actually needed.
12467     switch (Op->getOpcode()) {
12468     case ISD::ADD:
12469     case ISD::SUB:
12470     case ISD::MUL:
12471     case ISD::SHL: {
12472       const BinaryWithFlagsSDNode *BinNode =
12473           cast<BinaryWithFlagsSDNode>(Op.getNode());
12474       if (BinNode->hasNoSignedWrap())
12475         break;
12476     }
12477     default:
12478       NeedOF = true;
12479       break;
12480     }
12481     break;
12482   }
12483   }
12484   // See if we can use the EFLAGS value from the operand instead of
12485   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
12486   // we prove that the arithmetic won't overflow, we can't use OF or CF.
12487   if (Op.getResNo() != 0 || NeedOF || NeedCF) {
12488     // Emit a CMP with 0, which is the TEST pattern.
12489     //if (Op.getValueType() == MVT::i1)
12490     //  return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
12491     //                     DAG.getConstant(0, MVT::i1));
12492     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
12493                        DAG.getConstant(0, Op.getValueType()));
12494   }
12495   unsigned Opcode = 0;
12496   unsigned NumOperands = 0;
12497
12498   // Truncate operations may prevent the merge of the SETCC instruction
12499   // and the arithmetic instruction before it. Attempt to truncate the operands
12500   // of the arithmetic instruction and use a reduced bit-width instruction.
12501   bool NeedTruncation = false;
12502   SDValue ArithOp = Op;
12503   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
12504     SDValue Arith = Op->getOperand(0);
12505     // Both the trunc and the arithmetic op need to have one user each.
12506     if (Arith->hasOneUse())
12507       switch (Arith.getOpcode()) {
12508         default: break;
12509         case ISD::ADD:
12510         case ISD::SUB:
12511         case ISD::AND:
12512         case ISD::OR:
12513         case ISD::XOR: {
12514           NeedTruncation = true;
12515           ArithOp = Arith;
12516         }
12517       }
12518   }
12519
12520   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
12521   // which may be the result of a CAST.  We use the variable 'Op', which is the
12522   // non-casted variable when we check for possible users.
12523   switch (ArithOp.getOpcode()) {
12524   case ISD::ADD:
12525     // Due to an isel shortcoming, be conservative if this add is likely to be
12526     // selected as part of a load-modify-store instruction. When the root node
12527     // in a match is a store, isel doesn't know how to remap non-chain non-flag
12528     // uses of other nodes in the match, such as the ADD in this case. This
12529     // leads to the ADD being left around and reselected, with the result being
12530     // two adds in the output.  Alas, even if none our users are stores, that
12531     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
12532     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
12533     // climbing the DAG back to the root, and it doesn't seem to be worth the
12534     // effort.
12535     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
12536          UE = Op.getNode()->use_end(); UI != UE; ++UI)
12537       if (UI->getOpcode() != ISD::CopyToReg &&
12538           UI->getOpcode() != ISD::SETCC &&
12539           UI->getOpcode() != ISD::STORE)
12540         goto default_case;
12541
12542     if (ConstantSDNode *C =
12543         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
12544       // An add of one will be selected as an INC.
12545       if (C->getAPIntValue() == 1 && !Subtarget->slowIncDec()) {
12546         Opcode = X86ISD::INC;
12547         NumOperands = 1;
12548         break;
12549       }
12550
12551       // An add of negative one (subtract of one) will be selected as a DEC.
12552       if (C->getAPIntValue().isAllOnesValue() && !Subtarget->slowIncDec()) {
12553         Opcode = X86ISD::DEC;
12554         NumOperands = 1;
12555         break;
12556       }
12557     }
12558
12559     // Otherwise use a regular EFLAGS-setting add.
12560     Opcode = X86ISD::ADD;
12561     NumOperands = 2;
12562     break;
12563   case ISD::SHL:
12564   case ISD::SRL:
12565     // If we have a constant logical shift that's only used in a comparison
12566     // against zero turn it into an equivalent AND. This allows turning it into
12567     // a TEST instruction later.
12568     if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
12569         isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
12570       EVT VT = Op.getValueType();
12571       unsigned BitWidth = VT.getSizeInBits();
12572       unsigned ShAmt = Op->getConstantOperandVal(1);
12573       if (ShAmt >= BitWidth) // Avoid undefined shifts.
12574         break;
12575       APInt Mask = ArithOp.getOpcode() == ISD::SRL
12576                        ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
12577                        : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
12578       if (!Mask.isSignedIntN(32)) // Avoid large immediates.
12579         break;
12580       SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
12581                                 DAG.getConstant(Mask, VT));
12582       DAG.ReplaceAllUsesWith(Op, New);
12583       Op = New;
12584     }
12585     break;
12586
12587   case ISD::AND:
12588     // If the primary and result isn't used, don't bother using X86ISD::AND,
12589     // because a TEST instruction will be better.
12590     if (!hasNonFlagsUse(Op))
12591       break;
12592     // FALL THROUGH
12593   case ISD::SUB:
12594   case ISD::OR:
12595   case ISD::XOR:
12596     // Due to the ISEL shortcoming noted above, be conservative if this op is
12597     // likely to be selected as part of a load-modify-store instruction.
12598     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
12599            UE = Op.getNode()->use_end(); UI != UE; ++UI)
12600       if (UI->getOpcode() == ISD::STORE)
12601         goto default_case;
12602
12603     // Otherwise use a regular EFLAGS-setting instruction.
12604     switch (ArithOp.getOpcode()) {
12605     default: llvm_unreachable("unexpected operator!");
12606     case ISD::SUB: Opcode = X86ISD::SUB; break;
12607     case ISD::XOR: Opcode = X86ISD::XOR; break;
12608     case ISD::AND: Opcode = X86ISD::AND; break;
12609     case ISD::OR: {
12610       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
12611         SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
12612         if (EFLAGS.getNode())
12613           return EFLAGS;
12614       }
12615       Opcode = X86ISD::OR;
12616       break;
12617     }
12618     }
12619
12620     NumOperands = 2;
12621     break;
12622   case X86ISD::ADD:
12623   case X86ISD::SUB:
12624   case X86ISD::INC:
12625   case X86ISD::DEC:
12626   case X86ISD::OR:
12627   case X86ISD::XOR:
12628   case X86ISD::AND:
12629     return SDValue(Op.getNode(), 1);
12630   default:
12631   default_case:
12632     break;
12633   }
12634
12635   // If we found that truncation is beneficial, perform the truncation and
12636   // update 'Op'.
12637   if (NeedTruncation) {
12638     EVT VT = Op.getValueType();
12639     SDValue WideVal = Op->getOperand(0);
12640     EVT WideVT = WideVal.getValueType();
12641     unsigned ConvertedOp = 0;
12642     // Use a target machine opcode to prevent further DAGCombine
12643     // optimizations that may separate the arithmetic operations
12644     // from the setcc node.
12645     switch (WideVal.getOpcode()) {
12646       default: break;
12647       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
12648       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
12649       case ISD::AND: ConvertedOp = X86ISD::AND; break;
12650       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
12651       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
12652     }
12653
12654     if (ConvertedOp) {
12655       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12656       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
12657         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
12658         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
12659         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
12660       }
12661     }
12662   }
12663
12664   if (Opcode == 0)
12665     // Emit a CMP with 0, which is the TEST pattern.
12666     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
12667                        DAG.getConstant(0, Op.getValueType()));
12668
12669   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
12670   SmallVector<SDValue, 4> Ops(Op->op_begin(), Op->op_begin() + NumOperands);
12671
12672   SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
12673   DAG.ReplaceAllUsesWith(Op, New);
12674   return SDValue(New.getNode(), 1);
12675 }
12676
12677 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
12678 /// equivalent.
12679 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
12680                                    SDLoc dl, SelectionDAG &DAG) const {
12681   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
12682     if (C->getAPIntValue() == 0)
12683       return EmitTest(Op0, X86CC, dl, DAG);
12684
12685      if (Op0.getValueType() == MVT::i1)
12686        llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
12687   }
12688
12689   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
12690        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
12691     // Do the comparison at i32 if it's smaller, besides the Atom case.
12692     // This avoids subregister aliasing issues. Keep the smaller reference
12693     // if we're optimizing for size, however, as that'll allow better folding
12694     // of memory operations.
12695     if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
12696         !DAG.getMachineFunction().getFunction()->hasFnAttribute(
12697             Attribute::MinSize) &&
12698         !Subtarget->isAtom()) {
12699       unsigned ExtendOp =
12700           isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
12701       Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
12702       Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
12703     }
12704     // Use SUB instead of CMP to enable CSE between SUB and CMP.
12705     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
12706     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
12707                               Op0, Op1);
12708     return SDValue(Sub.getNode(), 1);
12709   }
12710   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
12711 }
12712
12713 /// Convert a comparison if required by the subtarget.
12714 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
12715                                                  SelectionDAG &DAG) const {
12716   // If the subtarget does not support the FUCOMI instruction, floating-point
12717   // comparisons have to be converted.
12718   if (Subtarget->hasCMov() ||
12719       Cmp.getOpcode() != X86ISD::CMP ||
12720       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
12721       !Cmp.getOperand(1).getValueType().isFloatingPoint())
12722     return Cmp;
12723
12724   // The instruction selector will select an FUCOM instruction instead of
12725   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
12726   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
12727   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
12728   SDLoc dl(Cmp);
12729   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
12730   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
12731   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
12732                             DAG.getConstant(8, MVT::i8));
12733   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
12734   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
12735 }
12736
12737 /// The minimum architected relative accuracy is 2^-12. We need one
12738 /// Newton-Raphson step to have a good float result (24 bits of precision).
12739 SDValue X86TargetLowering::getRsqrtEstimate(SDValue Op,
12740                                             DAGCombinerInfo &DCI,
12741                                             unsigned &RefinementSteps,
12742                                             bool &UseOneConstNR) const {
12743   // FIXME: We should use instruction latency models to calculate the cost of
12744   // each potential sequence, but this is very hard to do reliably because
12745   // at least Intel's Core* chips have variable timing based on the number of
12746   // significant digits in the divisor and/or sqrt operand.
12747   if (!Subtarget->useSqrtEst())
12748     return SDValue();
12749
12750   EVT VT = Op.getValueType();
12751
12752   // SSE1 has rsqrtss and rsqrtps.
12753   // TODO: Add support for AVX512 (v16f32).
12754   // It is likely not profitable to do this for f64 because a double-precision
12755   // rsqrt estimate with refinement on x86 prior to FMA requires at least 16
12756   // instructions: convert to single, rsqrtss, convert back to double, refine
12757   // (3 steps = at least 13 insts). If an 'rsqrtsd' variant was added to the ISA
12758   // along with FMA, this could be a throughput win.
12759   if ((Subtarget->hasSSE1() && (VT == MVT::f32 || VT == MVT::v4f32)) ||
12760       (Subtarget->hasAVX() && VT == MVT::v8f32)) {
12761     RefinementSteps = 1;
12762     UseOneConstNR = false;
12763     return DCI.DAG.getNode(X86ISD::FRSQRT, SDLoc(Op), VT, Op);
12764   }
12765   return SDValue();
12766 }
12767
12768 /// The minimum architected relative accuracy is 2^-12. We need one
12769 /// Newton-Raphson step to have a good float result (24 bits of precision).
12770 SDValue X86TargetLowering::getRecipEstimate(SDValue Op,
12771                                             DAGCombinerInfo &DCI,
12772                                             unsigned &RefinementSteps) const {
12773   // FIXME: We should use instruction latency models to calculate the cost of
12774   // each potential sequence, but this is very hard to do reliably because
12775   // at least Intel's Core* chips have variable timing based on the number of
12776   // significant digits in the divisor.
12777   if (!Subtarget->useReciprocalEst())
12778     return SDValue();
12779
12780   EVT VT = Op.getValueType();
12781
12782   // SSE1 has rcpss and rcpps. AVX adds a 256-bit variant for rcpps.
12783   // TODO: Add support for AVX512 (v16f32).
12784   // It is likely not profitable to do this for f64 because a double-precision
12785   // reciprocal estimate with refinement on x86 prior to FMA requires
12786   // 15 instructions: convert to single, rcpss, convert back to double, refine
12787   // (3 steps = 12 insts). If an 'rcpsd' variant was added to the ISA
12788   // along with FMA, this could be a throughput win.
12789   if ((Subtarget->hasSSE1() && (VT == MVT::f32 || VT == MVT::v4f32)) ||
12790       (Subtarget->hasAVX() && VT == MVT::v8f32)) {
12791     RefinementSteps = ReciprocalEstimateRefinementSteps;
12792     return DCI.DAG.getNode(X86ISD::FRCP, SDLoc(Op), VT, Op);
12793   }
12794   return SDValue();
12795 }
12796
12797 static bool isAllOnes(SDValue V) {
12798   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
12799   return C && C->isAllOnesValue();
12800 }
12801
12802 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
12803 /// if it's possible.
12804 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
12805                                      SDLoc dl, SelectionDAG &DAG) const {
12806   SDValue Op0 = And.getOperand(0);
12807   SDValue Op1 = And.getOperand(1);
12808   if (Op0.getOpcode() == ISD::TRUNCATE)
12809     Op0 = Op0.getOperand(0);
12810   if (Op1.getOpcode() == ISD::TRUNCATE)
12811     Op1 = Op1.getOperand(0);
12812
12813   SDValue LHS, RHS;
12814   if (Op1.getOpcode() == ISD::SHL)
12815     std::swap(Op0, Op1);
12816   if (Op0.getOpcode() == ISD::SHL) {
12817     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
12818       if (And00C->getZExtValue() == 1) {
12819         // If we looked past a truncate, check that it's only truncating away
12820         // known zeros.
12821         unsigned BitWidth = Op0.getValueSizeInBits();
12822         unsigned AndBitWidth = And.getValueSizeInBits();
12823         if (BitWidth > AndBitWidth) {
12824           APInt Zeros, Ones;
12825           DAG.computeKnownBits(Op0, Zeros, Ones);
12826           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
12827             return SDValue();
12828         }
12829         LHS = Op1;
12830         RHS = Op0.getOperand(1);
12831       }
12832   } else if (Op1.getOpcode() == ISD::Constant) {
12833     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
12834     uint64_t AndRHSVal = AndRHS->getZExtValue();
12835     SDValue AndLHS = Op0;
12836
12837     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
12838       LHS = AndLHS.getOperand(0);
12839       RHS = AndLHS.getOperand(1);
12840     }
12841
12842     // Use BT if the immediate can't be encoded in a TEST instruction.
12843     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
12844       LHS = AndLHS;
12845       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
12846     }
12847   }
12848
12849   if (LHS.getNode()) {
12850     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
12851     // instruction.  Since the shift amount is in-range-or-undefined, we know
12852     // that doing a bittest on the i32 value is ok.  We extend to i32 because
12853     // the encoding for the i16 version is larger than the i32 version.
12854     // Also promote i16 to i32 for performance / code size reason.
12855     if (LHS.getValueType() == MVT::i8 ||
12856         LHS.getValueType() == MVT::i16)
12857       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
12858
12859     // If the operand types disagree, extend the shift amount to match.  Since
12860     // BT ignores high bits (like shifts) we can use anyextend.
12861     if (LHS.getValueType() != RHS.getValueType())
12862       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
12863
12864     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
12865     X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
12866     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12867                        DAG.getConstant(Cond, MVT::i8), BT);
12868   }
12869
12870   return SDValue();
12871 }
12872
12873 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
12874 /// mask CMPs.
12875 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
12876                               SDValue &Op1) {
12877   unsigned SSECC;
12878   bool Swap = false;
12879
12880   // SSE Condition code mapping:
12881   //  0 - EQ
12882   //  1 - LT
12883   //  2 - LE
12884   //  3 - UNORD
12885   //  4 - NEQ
12886   //  5 - NLT
12887   //  6 - NLE
12888   //  7 - ORD
12889   switch (SetCCOpcode) {
12890   default: llvm_unreachable("Unexpected SETCC condition");
12891   case ISD::SETOEQ:
12892   case ISD::SETEQ:  SSECC = 0; break;
12893   case ISD::SETOGT:
12894   case ISD::SETGT:  Swap = true; // Fallthrough
12895   case ISD::SETLT:
12896   case ISD::SETOLT: SSECC = 1; break;
12897   case ISD::SETOGE:
12898   case ISD::SETGE:  Swap = true; // Fallthrough
12899   case ISD::SETLE:
12900   case ISD::SETOLE: SSECC = 2; break;
12901   case ISD::SETUO:  SSECC = 3; break;
12902   case ISD::SETUNE:
12903   case ISD::SETNE:  SSECC = 4; break;
12904   case ISD::SETULE: Swap = true; // Fallthrough
12905   case ISD::SETUGE: SSECC = 5; break;
12906   case ISD::SETULT: Swap = true; // Fallthrough
12907   case ISD::SETUGT: SSECC = 6; break;
12908   case ISD::SETO:   SSECC = 7; break;
12909   case ISD::SETUEQ:
12910   case ISD::SETONE: SSECC = 8; break;
12911   }
12912   if (Swap)
12913     std::swap(Op0, Op1);
12914
12915   return SSECC;
12916 }
12917
12918 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
12919 // ones, and then concatenate the result back.
12920 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
12921   MVT VT = Op.getSimpleValueType();
12922
12923   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
12924          "Unsupported value type for operation");
12925
12926   unsigned NumElems = VT.getVectorNumElements();
12927   SDLoc dl(Op);
12928   SDValue CC = Op.getOperand(2);
12929
12930   // Extract the LHS vectors
12931   SDValue LHS = Op.getOperand(0);
12932   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
12933   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
12934
12935   // Extract the RHS vectors
12936   SDValue RHS = Op.getOperand(1);
12937   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
12938   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
12939
12940   // Issue the operation on the smaller types and concatenate the result back
12941   MVT EltVT = VT.getVectorElementType();
12942   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
12943   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
12944                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
12945                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
12946 }
12947
12948 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
12949                                      const X86Subtarget *Subtarget) {
12950   SDValue Op0 = Op.getOperand(0);
12951   SDValue Op1 = Op.getOperand(1);
12952   SDValue CC = Op.getOperand(2);
12953   MVT VT = Op.getSimpleValueType();
12954   SDLoc dl(Op);
12955
12956   assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 8 &&
12957          Op.getValueType().getScalarType() == MVT::i1 &&
12958          "Cannot set masked compare for this operation");
12959
12960   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
12961   unsigned  Opc = 0;
12962   bool Unsigned = false;
12963   bool Swap = false;
12964   unsigned SSECC;
12965   switch (SetCCOpcode) {
12966   default: llvm_unreachable("Unexpected SETCC condition");
12967   case ISD::SETNE:  SSECC = 4; break;
12968   case ISD::SETEQ:  Opc = X86ISD::PCMPEQM; break;
12969   case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
12970   case ISD::SETLT:  Swap = true; //fall-through
12971   case ISD::SETGT:  Opc = X86ISD::PCMPGTM; break;
12972   case ISD::SETULT: SSECC = 1; Unsigned = true; break;
12973   case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
12974   case ISD::SETGE:  Swap = true; SSECC = 2; break; // LE + swap
12975   case ISD::SETULE: Unsigned = true; //fall-through
12976   case ISD::SETLE:  SSECC = 2; break;
12977   }
12978
12979   if (Swap)
12980     std::swap(Op0, Op1);
12981   if (Opc)
12982     return DAG.getNode(Opc, dl, VT, Op0, Op1);
12983   Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
12984   return DAG.getNode(Opc, dl, VT, Op0, Op1,
12985                      DAG.getConstant(SSECC, MVT::i8));
12986 }
12987
12988 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
12989 /// operand \p Op1.  If non-trivial (for example because it's not constant)
12990 /// return an empty value.
12991 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
12992 {
12993   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
12994   if (!BV)
12995     return SDValue();
12996
12997   MVT VT = Op1.getSimpleValueType();
12998   MVT EVT = VT.getVectorElementType();
12999   unsigned n = VT.getVectorNumElements();
13000   SmallVector<SDValue, 8> ULTOp1;
13001
13002   for (unsigned i = 0; i < n; ++i) {
13003     ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
13004     if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
13005       return SDValue();
13006
13007     // Avoid underflow.
13008     APInt Val = Elt->getAPIntValue();
13009     if (Val == 0)
13010       return SDValue();
13011
13012     ULTOp1.push_back(DAG.getConstant(Val - 1, EVT));
13013   }
13014
13015   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
13016 }
13017
13018 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
13019                            SelectionDAG &DAG) {
13020   SDValue Op0 = Op.getOperand(0);
13021   SDValue Op1 = Op.getOperand(1);
13022   SDValue CC = Op.getOperand(2);
13023   MVT VT = Op.getSimpleValueType();
13024   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13025   bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
13026   SDLoc dl(Op);
13027
13028   if (isFP) {
13029 #ifndef NDEBUG
13030     MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
13031     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
13032 #endif
13033
13034     unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
13035     unsigned Opc = X86ISD::CMPP;
13036     if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
13037       assert(VT.getVectorNumElements() <= 16);
13038       Opc = X86ISD::CMPM;
13039     }
13040     // In the two special cases we can't handle, emit two comparisons.
13041     if (SSECC == 8) {
13042       unsigned CC0, CC1;
13043       unsigned CombineOpc;
13044       if (SetCCOpcode == ISD::SETUEQ) {
13045         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
13046       } else {
13047         assert(SetCCOpcode == ISD::SETONE);
13048         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
13049       }
13050
13051       SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
13052                                  DAG.getConstant(CC0, MVT::i8));
13053       SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
13054                                  DAG.getConstant(CC1, MVT::i8));
13055       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
13056     }
13057     // Handle all other FP comparisons here.
13058     return DAG.getNode(Opc, dl, VT, Op0, Op1,
13059                        DAG.getConstant(SSECC, MVT::i8));
13060   }
13061
13062   // Break 256-bit integer vector compare into smaller ones.
13063   if (VT.is256BitVector() && !Subtarget->hasInt256())
13064     return Lower256IntVSETCC(Op, DAG);
13065
13066   bool MaskResult = (VT.getVectorElementType() == MVT::i1);
13067   EVT OpVT = Op1.getValueType();
13068   if (Subtarget->hasAVX512()) {
13069     if (Op1.getValueType().is512BitVector() ||
13070         (Subtarget->hasBWI() && Subtarget->hasVLX()) ||
13071         (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
13072       return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
13073
13074     // In AVX-512 architecture setcc returns mask with i1 elements,
13075     // But there is no compare instruction for i8 and i16 elements in KNL.
13076     // We are not talking about 512-bit operands in this case, these
13077     // types are illegal.
13078     if (MaskResult &&
13079         (OpVT.getVectorElementType().getSizeInBits() < 32 &&
13080          OpVT.getVectorElementType().getSizeInBits() >= 8))
13081       return DAG.getNode(ISD::TRUNCATE, dl, VT,
13082                          DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
13083   }
13084
13085   // We are handling one of the integer comparisons here.  Since SSE only has
13086   // GT and EQ comparisons for integer, swapping operands and multiple
13087   // operations may be required for some comparisons.
13088   unsigned Opc;
13089   bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
13090   bool Subus = false;
13091
13092   switch (SetCCOpcode) {
13093   default: llvm_unreachable("Unexpected SETCC condition");
13094   case ISD::SETNE:  Invert = true;
13095   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
13096   case ISD::SETLT:  Swap = true;
13097   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
13098   case ISD::SETGE:  Swap = true;
13099   case ISD::SETLE:  Opc = X86ISD::PCMPGT;
13100                     Invert = true; break;
13101   case ISD::SETULT: Swap = true;
13102   case ISD::SETUGT: Opc = X86ISD::PCMPGT;
13103                     FlipSigns = true; break;
13104   case ISD::SETUGE: Swap = true;
13105   case ISD::SETULE: Opc = X86ISD::PCMPGT;
13106                     FlipSigns = true; Invert = true; break;
13107   }
13108
13109   // Special case: Use min/max operations for SETULE/SETUGE
13110   MVT VET = VT.getVectorElementType();
13111   bool hasMinMax =
13112        (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
13113     || (Subtarget->hasSSE2()  && (VET == MVT::i8));
13114
13115   if (hasMinMax) {
13116     switch (SetCCOpcode) {
13117     default: break;
13118     case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
13119     case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
13120     }
13121
13122     if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
13123   }
13124
13125   bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
13126   if (!MinMax && hasSubus) {
13127     // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
13128     // Op0 u<= Op1:
13129     //   t = psubus Op0, Op1
13130     //   pcmpeq t, <0..0>
13131     switch (SetCCOpcode) {
13132     default: break;
13133     case ISD::SETULT: {
13134       // If the comparison is against a constant we can turn this into a
13135       // setule.  With psubus, setule does not require a swap.  This is
13136       // beneficial because the constant in the register is no longer
13137       // destructed as the destination so it can be hoisted out of a loop.
13138       // Only do this pre-AVX since vpcmp* is no longer destructive.
13139       if (Subtarget->hasAVX())
13140         break;
13141       SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
13142       if (ULEOp1.getNode()) {
13143         Op1 = ULEOp1;
13144         Subus = true; Invert = false; Swap = false;
13145       }
13146       break;
13147     }
13148     // Psubus is better than flip-sign because it requires no inversion.
13149     case ISD::SETUGE: Subus = true; Invert = false; Swap = true;  break;
13150     case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
13151     }
13152
13153     if (Subus) {
13154       Opc = X86ISD::SUBUS;
13155       FlipSigns = false;
13156     }
13157   }
13158
13159   if (Swap)
13160     std::swap(Op0, Op1);
13161
13162   // Check that the operation in question is available (most are plain SSE2,
13163   // but PCMPGTQ and PCMPEQQ have different requirements).
13164   if (VT == MVT::v2i64) {
13165     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
13166       assert(Subtarget->hasSSE2() && "Don't know how to lower!");
13167
13168       // First cast everything to the right type.
13169       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
13170       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
13171
13172       // Since SSE has no unsigned integer comparisons, we need to flip the sign
13173       // bits of the inputs before performing those operations. The lower
13174       // compare is always unsigned.
13175       SDValue SB;
13176       if (FlipSigns) {
13177         SB = DAG.getConstant(0x80000000U, MVT::v4i32);
13178       } else {
13179         SDValue Sign = DAG.getConstant(0x80000000U, MVT::i32);
13180         SDValue Zero = DAG.getConstant(0x00000000U, MVT::i32);
13181         SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
13182                          Sign, Zero, Sign, Zero);
13183       }
13184       Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
13185       Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
13186
13187       // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
13188       SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
13189       SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
13190
13191       // Create masks for only the low parts/high parts of the 64 bit integers.
13192       static const int MaskHi[] = { 1, 1, 3, 3 };
13193       static const int MaskLo[] = { 0, 0, 2, 2 };
13194       SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
13195       SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
13196       SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
13197
13198       SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
13199       Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
13200
13201       if (Invert)
13202         Result = DAG.getNOT(dl, Result, MVT::v4i32);
13203
13204       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
13205     }
13206
13207     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
13208       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
13209       // pcmpeqd + pshufd + pand.
13210       assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
13211
13212       // First cast everything to the right type.
13213       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
13214       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
13215
13216       // Do the compare.
13217       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
13218
13219       // Make sure the lower and upper halves are both all-ones.
13220       static const int Mask[] = { 1, 0, 3, 2 };
13221       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
13222       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
13223
13224       if (Invert)
13225         Result = DAG.getNOT(dl, Result, MVT::v4i32);
13226
13227       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
13228     }
13229   }
13230
13231   // Since SSE has no unsigned integer comparisons, we need to flip the sign
13232   // bits of the inputs before performing those operations.
13233   if (FlipSigns) {
13234     EVT EltVT = VT.getVectorElementType();
13235     SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), VT);
13236     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
13237     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
13238   }
13239
13240   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
13241
13242   // If the logical-not of the result is required, perform that now.
13243   if (Invert)
13244     Result = DAG.getNOT(dl, Result, VT);
13245
13246   if (MinMax)
13247     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
13248
13249   if (Subus)
13250     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
13251                          getZeroVector(VT, Subtarget, DAG, dl));
13252
13253   return Result;
13254 }
13255
13256 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
13257
13258   MVT VT = Op.getSimpleValueType();
13259
13260   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
13261
13262   assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
13263          && "SetCC type must be 8-bit or 1-bit integer");
13264   SDValue Op0 = Op.getOperand(0);
13265   SDValue Op1 = Op.getOperand(1);
13266   SDLoc dl(Op);
13267   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
13268
13269   // Optimize to BT if possible.
13270   // Lower (X & (1 << N)) == 0 to BT(X, N).
13271   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
13272   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
13273   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
13274       Op1.getOpcode() == ISD::Constant &&
13275       cast<ConstantSDNode>(Op1)->isNullValue() &&
13276       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13277     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
13278     if (NewSetCC.getNode()) {
13279       if (VT == MVT::i1)
13280         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewSetCC);
13281       return NewSetCC;
13282     }
13283   }
13284
13285   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
13286   // these.
13287   if (Op1.getOpcode() == ISD::Constant &&
13288       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
13289        cast<ConstantSDNode>(Op1)->isNullValue()) &&
13290       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13291
13292     // If the input is a setcc, then reuse the input setcc or use a new one with
13293     // the inverted condition.
13294     if (Op0.getOpcode() == X86ISD::SETCC) {
13295       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
13296       bool Invert = (CC == ISD::SETNE) ^
13297         cast<ConstantSDNode>(Op1)->isNullValue();
13298       if (!Invert)
13299         return Op0;
13300
13301       CCode = X86::GetOppositeBranchCondition(CCode);
13302       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13303                                   DAG.getConstant(CCode, MVT::i8),
13304                                   Op0.getOperand(1));
13305       if (VT == MVT::i1)
13306         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
13307       return SetCC;
13308     }
13309   }
13310   if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
13311       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
13312       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13313
13314     ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
13315     return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, MVT::i1), NewCC);
13316   }
13317
13318   bool isFP = Op1.getSimpleValueType().isFloatingPoint();
13319   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
13320   if (X86CC == X86::COND_INVALID)
13321     return SDValue();
13322
13323   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
13324   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
13325   SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13326                               DAG.getConstant(X86CC, MVT::i8), EFLAGS);
13327   if (VT == MVT::i1)
13328     return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
13329   return SetCC;
13330 }
13331
13332 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
13333 static bool isX86LogicalCmp(SDValue Op) {
13334   unsigned Opc = Op.getNode()->getOpcode();
13335   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
13336       Opc == X86ISD::SAHF)
13337     return true;
13338   if (Op.getResNo() == 1 &&
13339       (Opc == X86ISD::ADD ||
13340        Opc == X86ISD::SUB ||
13341        Opc == X86ISD::ADC ||
13342        Opc == X86ISD::SBB ||
13343        Opc == X86ISD::SMUL ||
13344        Opc == X86ISD::UMUL ||
13345        Opc == X86ISD::INC ||
13346        Opc == X86ISD::DEC ||
13347        Opc == X86ISD::OR ||
13348        Opc == X86ISD::XOR ||
13349        Opc == X86ISD::AND))
13350     return true;
13351
13352   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
13353     return true;
13354
13355   return false;
13356 }
13357
13358 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
13359   if (V.getOpcode() != ISD::TRUNCATE)
13360     return false;
13361
13362   SDValue VOp0 = V.getOperand(0);
13363   unsigned InBits = VOp0.getValueSizeInBits();
13364   unsigned Bits = V.getValueSizeInBits();
13365   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
13366 }
13367
13368 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
13369   bool addTest = true;
13370   SDValue Cond  = Op.getOperand(0);
13371   SDValue Op1 = Op.getOperand(1);
13372   SDValue Op2 = Op.getOperand(2);
13373   SDLoc DL(Op);
13374   EVT VT = Op1.getValueType();
13375   SDValue CC;
13376
13377   // Lower FP selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
13378   // are available or VBLENDV if AVX is available.
13379   // Otherwise FP cmovs get lowered into a less efficient branch sequence later.
13380   if (Cond.getOpcode() == ISD::SETCC &&
13381       ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
13382        (Subtarget->hasSSE1() && VT == MVT::f32)) &&
13383       VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
13384     SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
13385     int SSECC = translateX86FSETCC(
13386         cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
13387
13388     if (SSECC != 8) {
13389       if (Subtarget->hasAVX512()) {
13390         SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
13391                                   DAG.getConstant(SSECC, MVT::i8));
13392         return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
13393       }
13394
13395       SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
13396                                 DAG.getConstant(SSECC, MVT::i8));
13397
13398       // If we have AVX, we can use a variable vector select (VBLENDV) instead
13399       // of 3 logic instructions for size savings and potentially speed.
13400       // Unfortunately, there is no scalar form of VBLENDV.
13401
13402       // If either operand is a constant, don't try this. We can expect to
13403       // optimize away at least one of the logic instructions later in that
13404       // case, so that sequence would be faster than a variable blend.
13405
13406       // BLENDV was introduced with SSE 4.1, but the 2 register form implicitly
13407       // uses XMM0 as the selection register. That may need just as many
13408       // instructions as the AND/ANDN/OR sequence due to register moves, so
13409       // don't bother.
13410
13411       if (Subtarget->hasAVX() &&
13412           !isa<ConstantFPSDNode>(Op1) && !isa<ConstantFPSDNode>(Op2)) {
13413
13414         // Convert to vectors, do a VSELECT, and convert back to scalar.
13415         // All of the conversions should be optimized away.
13416
13417         EVT VecVT = VT == MVT::f32 ? MVT::v4f32 : MVT::v2f64;
13418         SDValue VOp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op1);
13419         SDValue VOp2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op2);
13420         SDValue VCmp = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Cmp);
13421
13422         EVT VCmpVT = VT == MVT::f32 ? MVT::v4i32 : MVT::v2i64;
13423         VCmp = DAG.getNode(ISD::BITCAST, DL, VCmpVT, VCmp);
13424
13425         SDValue VSel = DAG.getNode(ISD::VSELECT, DL, VecVT, VCmp, VOp1, VOp2);
13426
13427         return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
13428                            VSel, DAG.getIntPtrConstant(0));
13429       }
13430       SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
13431       SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
13432       return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
13433     }
13434   }
13435
13436   if (Cond.getOpcode() == ISD::SETCC) {
13437     SDValue NewCond = LowerSETCC(Cond, DAG);
13438     if (NewCond.getNode())
13439       Cond = NewCond;
13440   }
13441
13442   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
13443   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
13444   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
13445   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
13446   if (Cond.getOpcode() == X86ISD::SETCC &&
13447       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
13448       isZero(Cond.getOperand(1).getOperand(1))) {
13449     SDValue Cmp = Cond.getOperand(1);
13450
13451     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
13452
13453     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
13454         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
13455       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
13456
13457       SDValue CmpOp0 = Cmp.getOperand(0);
13458       // Apply further optimizations for special cases
13459       // (select (x != 0), -1, 0) -> neg & sbb
13460       // (select (x == 0), 0, -1) -> neg & sbb
13461       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
13462         if (YC->isNullValue() &&
13463             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
13464           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
13465           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
13466                                     DAG.getConstant(0, CmpOp0.getValueType()),
13467                                     CmpOp0);
13468           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
13469                                     DAG.getConstant(X86::COND_B, MVT::i8),
13470                                     SDValue(Neg.getNode(), 1));
13471           return Res;
13472         }
13473
13474       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
13475                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
13476       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
13477
13478       SDValue Res =   // Res = 0 or -1.
13479         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
13480                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
13481
13482       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
13483         Res = DAG.getNOT(DL, Res, Res.getValueType());
13484
13485       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
13486       if (!N2C || !N2C->isNullValue())
13487         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
13488       return Res;
13489     }
13490   }
13491
13492   // Look past (and (setcc_carry (cmp ...)), 1).
13493   if (Cond.getOpcode() == ISD::AND &&
13494       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
13495     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
13496     if (C && C->getAPIntValue() == 1)
13497       Cond = Cond.getOperand(0);
13498   }
13499
13500   // If condition flag is set by a X86ISD::CMP, then use it as the condition
13501   // setting operand in place of the X86ISD::SETCC.
13502   unsigned CondOpcode = Cond.getOpcode();
13503   if (CondOpcode == X86ISD::SETCC ||
13504       CondOpcode == X86ISD::SETCC_CARRY) {
13505     CC = Cond.getOperand(0);
13506
13507     SDValue Cmp = Cond.getOperand(1);
13508     unsigned Opc = Cmp.getOpcode();
13509     MVT VT = Op.getSimpleValueType();
13510
13511     bool IllegalFPCMov = false;
13512     if (VT.isFloatingPoint() && !VT.isVector() &&
13513         !isScalarFPTypeInSSEReg(VT))  // FPStack?
13514       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
13515
13516     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
13517         Opc == X86ISD::BT) { // FIXME
13518       Cond = Cmp;
13519       addTest = false;
13520     }
13521   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
13522              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
13523              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
13524               Cond.getOperand(0).getValueType() != MVT::i8)) {
13525     SDValue LHS = Cond.getOperand(0);
13526     SDValue RHS = Cond.getOperand(1);
13527     unsigned X86Opcode;
13528     unsigned X86Cond;
13529     SDVTList VTs;
13530     switch (CondOpcode) {
13531     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
13532     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
13533     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
13534     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
13535     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
13536     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
13537     default: llvm_unreachable("unexpected overflowing operator");
13538     }
13539     if (CondOpcode == ISD::UMULO)
13540       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
13541                           MVT::i32);
13542     else
13543       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
13544
13545     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
13546
13547     if (CondOpcode == ISD::UMULO)
13548       Cond = X86Op.getValue(2);
13549     else
13550       Cond = X86Op.getValue(1);
13551
13552     CC = DAG.getConstant(X86Cond, MVT::i8);
13553     addTest = false;
13554   }
13555
13556   if (addTest) {
13557     // Look pass the truncate if the high bits are known zero.
13558     if (isTruncWithZeroHighBitsInput(Cond, DAG))
13559         Cond = Cond.getOperand(0);
13560
13561     // We know the result of AND is compared against zero. Try to match
13562     // it to BT.
13563     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
13564       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
13565       if (NewSetCC.getNode()) {
13566         CC = NewSetCC.getOperand(0);
13567         Cond = NewSetCC.getOperand(1);
13568         addTest = false;
13569       }
13570     }
13571   }
13572
13573   if (addTest) {
13574     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
13575     Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
13576   }
13577
13578   // a <  b ? -1 :  0 -> RES = ~setcc_carry
13579   // a <  b ?  0 : -1 -> RES = setcc_carry
13580   // a >= b ? -1 :  0 -> RES = setcc_carry
13581   // a >= b ?  0 : -1 -> RES = ~setcc_carry
13582   if (Cond.getOpcode() == X86ISD::SUB) {
13583     Cond = ConvertCmpIfNecessary(Cond, DAG);
13584     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
13585
13586     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
13587         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
13588       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
13589                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
13590       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
13591         return DAG.getNOT(DL, Res, Res.getValueType());
13592       return Res;
13593     }
13594   }
13595
13596   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
13597   // widen the cmov and push the truncate through. This avoids introducing a new
13598   // branch during isel and doesn't add any extensions.
13599   if (Op.getValueType() == MVT::i8 &&
13600       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
13601     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
13602     if (T1.getValueType() == T2.getValueType() &&
13603         // Blacklist CopyFromReg to avoid partial register stalls.
13604         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
13605       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
13606       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
13607       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
13608     }
13609   }
13610
13611   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
13612   // condition is true.
13613   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
13614   SDValue Ops[] = { Op2, Op1, CC, Cond };
13615   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
13616 }
13617
13618 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op, const X86Subtarget *Subtarget,
13619                                        SelectionDAG &DAG) {
13620   MVT VT = Op->getSimpleValueType(0);
13621   SDValue In = Op->getOperand(0);
13622   MVT InVT = In.getSimpleValueType();
13623   MVT VTElt = VT.getVectorElementType();
13624   MVT InVTElt = InVT.getVectorElementType();
13625   SDLoc dl(Op);
13626
13627   // SKX processor
13628   if ((InVTElt == MVT::i1) &&
13629       (((Subtarget->hasBWI() && Subtarget->hasVLX() &&
13630         VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() <= 16)) ||
13631
13632        ((Subtarget->hasBWI() && VT.is512BitVector() &&
13633         VTElt.getSizeInBits() <= 16)) ||
13634
13635        ((Subtarget->hasDQI() && Subtarget->hasVLX() &&
13636         VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() >= 32)) ||
13637
13638        ((Subtarget->hasDQI() && VT.is512BitVector() &&
13639         VTElt.getSizeInBits() >= 32))))
13640     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
13641
13642   unsigned int NumElts = VT.getVectorNumElements();
13643
13644   if (NumElts != 8 && NumElts != 16)
13645     return SDValue();
13646
13647   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1) {
13648     if (In.getOpcode() == X86ISD::VSEXT || In.getOpcode() == X86ISD::VZEXT)
13649       return DAG.getNode(In.getOpcode(), dl, VT, In.getOperand(0));
13650     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
13651   }
13652
13653   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13654   assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
13655
13656   MVT ExtVT = (NumElts == 8) ? MVT::v8i64 : MVT::v16i32;
13657   Constant *C = ConstantInt::get(*DAG.getContext(),
13658     APInt::getAllOnesValue(ExtVT.getScalarType().getSizeInBits()));
13659
13660   SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
13661   unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
13662   SDValue Ld = DAG.getLoad(ExtVT.getScalarType(), dl, DAG.getEntryNode(), CP,
13663                           MachinePointerInfo::getConstantPool(),
13664                           false, false, false, Alignment);
13665   SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, dl, ExtVT, In, Ld);
13666   if (VT.is512BitVector())
13667     return Brcst;
13668   return DAG.getNode(X86ISD::VTRUNC, dl, VT, Brcst);
13669 }
13670
13671 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
13672                                 SelectionDAG &DAG) {
13673   MVT VT = Op->getSimpleValueType(0);
13674   SDValue In = Op->getOperand(0);
13675   MVT InVT = In.getSimpleValueType();
13676   SDLoc dl(Op);
13677
13678   if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
13679     return LowerSIGN_EXTEND_AVX512(Op, Subtarget, DAG);
13680
13681   if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
13682       (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
13683       (VT != MVT::v16i16 || InVT != MVT::v16i8))
13684     return SDValue();
13685
13686   if (Subtarget->hasInt256())
13687     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
13688
13689   // Optimize vectors in AVX mode
13690   // Sign extend  v8i16 to v8i32 and
13691   //              v4i32 to v4i64
13692   //
13693   // Divide input vector into two parts
13694   // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
13695   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
13696   // concat the vectors to original VT
13697
13698   unsigned NumElems = InVT.getVectorNumElements();
13699   SDValue Undef = DAG.getUNDEF(InVT);
13700
13701   SmallVector<int,8> ShufMask1(NumElems, -1);
13702   for (unsigned i = 0; i != NumElems/2; ++i)
13703     ShufMask1[i] = i;
13704
13705   SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
13706
13707   SmallVector<int,8> ShufMask2(NumElems, -1);
13708   for (unsigned i = 0; i != NumElems/2; ++i)
13709     ShufMask2[i] = i + NumElems/2;
13710
13711   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
13712
13713   MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
13714                                 VT.getVectorNumElements()/2);
13715
13716   OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
13717   OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
13718
13719   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
13720 }
13721
13722 // Lower vector extended loads using a shuffle. If SSSE3 is not available we
13723 // may emit an illegal shuffle but the expansion is still better than scalar
13724 // code. We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise
13725 // we'll emit a shuffle and a arithmetic shift.
13726 // FIXME: Is the expansion actually better than scalar code? It doesn't seem so.
13727 // TODO: It is possible to support ZExt by zeroing the undef values during
13728 // the shuffle phase or after the shuffle.
13729 static SDValue LowerExtendedLoad(SDValue Op, const X86Subtarget *Subtarget,
13730                                  SelectionDAG &DAG) {
13731   MVT RegVT = Op.getSimpleValueType();
13732   assert(RegVT.isVector() && "We only custom lower vector sext loads.");
13733   assert(RegVT.isInteger() &&
13734          "We only custom lower integer vector sext loads.");
13735
13736   // Nothing useful we can do without SSE2 shuffles.
13737   assert(Subtarget->hasSSE2() && "We only custom lower sext loads with SSE2.");
13738
13739   LoadSDNode *Ld = cast<LoadSDNode>(Op.getNode());
13740   SDLoc dl(Ld);
13741   EVT MemVT = Ld->getMemoryVT();
13742   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13743   unsigned RegSz = RegVT.getSizeInBits();
13744
13745   ISD::LoadExtType Ext = Ld->getExtensionType();
13746
13747   assert((Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)
13748          && "Only anyext and sext are currently implemented.");
13749   assert(MemVT != RegVT && "Cannot extend to the same type");
13750   assert(MemVT.isVector() && "Must load a vector from memory");
13751
13752   unsigned NumElems = RegVT.getVectorNumElements();
13753   unsigned MemSz = MemVT.getSizeInBits();
13754   assert(RegSz > MemSz && "Register size must be greater than the mem size");
13755
13756   if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256()) {
13757     // The only way in which we have a legal 256-bit vector result but not the
13758     // integer 256-bit operations needed to directly lower a sextload is if we
13759     // have AVX1 but not AVX2. In that case, we can always emit a sextload to
13760     // a 128-bit vector and a normal sign_extend to 256-bits that should get
13761     // correctly legalized. We do this late to allow the canonical form of
13762     // sextload to persist throughout the rest of the DAG combiner -- it wants
13763     // to fold together any extensions it can, and so will fuse a sign_extend
13764     // of an sextload into a sextload targeting a wider value.
13765     SDValue Load;
13766     if (MemSz == 128) {
13767       // Just switch this to a normal load.
13768       assert(TLI.isTypeLegal(MemVT) && "If the memory type is a 128-bit type, "
13769                                        "it must be a legal 128-bit vector "
13770                                        "type!");
13771       Load = DAG.getLoad(MemVT, dl, Ld->getChain(), Ld->getBasePtr(),
13772                   Ld->getPointerInfo(), Ld->isVolatile(), Ld->isNonTemporal(),
13773                   Ld->isInvariant(), Ld->getAlignment());
13774     } else {
13775       assert(MemSz < 128 &&
13776              "Can't extend a type wider than 128 bits to a 256 bit vector!");
13777       // Do an sext load to a 128-bit vector type. We want to use the same
13778       // number of elements, but elements half as wide. This will end up being
13779       // recursively lowered by this routine, but will succeed as we definitely
13780       // have all the necessary features if we're using AVX1.
13781       EVT HalfEltVT =
13782           EVT::getIntegerVT(*DAG.getContext(), RegVT.getScalarSizeInBits() / 2);
13783       EVT HalfVecVT = EVT::getVectorVT(*DAG.getContext(), HalfEltVT, NumElems);
13784       Load =
13785           DAG.getExtLoad(Ext, dl, HalfVecVT, Ld->getChain(), Ld->getBasePtr(),
13786                          Ld->getPointerInfo(), MemVT, Ld->isVolatile(),
13787                          Ld->isNonTemporal(), Ld->isInvariant(),
13788                          Ld->getAlignment());
13789     }
13790
13791     // Replace chain users with the new chain.
13792     assert(Load->getNumValues() == 2 && "Loads must carry a chain!");
13793     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Load.getValue(1));
13794
13795     // Finally, do a normal sign-extend to the desired register.
13796     return DAG.getSExtOrTrunc(Load, dl, RegVT);
13797   }
13798
13799   // All sizes must be a power of two.
13800   assert(isPowerOf2_32(RegSz * MemSz * NumElems) &&
13801          "Non-power-of-two elements are not custom lowered!");
13802
13803   // Attempt to load the original value using scalar loads.
13804   // Find the largest scalar type that divides the total loaded size.
13805   MVT SclrLoadTy = MVT::i8;
13806   for (MVT Tp : MVT::integer_valuetypes()) {
13807     if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
13808       SclrLoadTy = Tp;
13809     }
13810   }
13811
13812   // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
13813   if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
13814       (64 <= MemSz))
13815     SclrLoadTy = MVT::f64;
13816
13817   // Calculate the number of scalar loads that we need to perform
13818   // in order to load our vector from memory.
13819   unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
13820
13821   assert((Ext != ISD::SEXTLOAD || NumLoads == 1) &&
13822          "Can only lower sext loads with a single scalar load!");
13823
13824   unsigned loadRegZize = RegSz;
13825   if (Ext == ISD::SEXTLOAD && RegSz == 256)
13826     loadRegZize /= 2;
13827
13828   // Represent our vector as a sequence of elements which are the
13829   // largest scalar that we can load.
13830   EVT LoadUnitVecVT = EVT::getVectorVT(
13831       *DAG.getContext(), SclrLoadTy, loadRegZize / SclrLoadTy.getSizeInBits());
13832
13833   // Represent the data using the same element type that is stored in
13834   // memory. In practice, we ''widen'' MemVT.
13835   EVT WideVecVT =
13836       EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
13837                        loadRegZize / MemVT.getScalarType().getSizeInBits());
13838
13839   assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
13840          "Invalid vector type");
13841
13842   // We can't shuffle using an illegal type.
13843   assert(TLI.isTypeLegal(WideVecVT) &&
13844          "We only lower types that form legal widened vector types");
13845
13846   SmallVector<SDValue, 8> Chains;
13847   SDValue Ptr = Ld->getBasePtr();
13848   SDValue Increment =
13849       DAG.getConstant(SclrLoadTy.getSizeInBits() / 8, TLI.getPointerTy());
13850   SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
13851
13852   for (unsigned i = 0; i < NumLoads; ++i) {
13853     // Perform a single load.
13854     SDValue ScalarLoad =
13855         DAG.getLoad(SclrLoadTy, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
13856                     Ld->isVolatile(), Ld->isNonTemporal(), Ld->isInvariant(),
13857                     Ld->getAlignment());
13858     Chains.push_back(ScalarLoad.getValue(1));
13859     // Create the first element type using SCALAR_TO_VECTOR in order to avoid
13860     // another round of DAGCombining.
13861     if (i == 0)
13862       Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
13863     else
13864       Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
13865                         ScalarLoad, DAG.getIntPtrConstant(i));
13866
13867     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
13868   }
13869
13870   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
13871
13872   // Bitcast the loaded value to a vector of the original element type, in
13873   // the size of the target vector type.
13874   SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
13875   unsigned SizeRatio = RegSz / MemSz;
13876
13877   if (Ext == ISD::SEXTLOAD) {
13878     // If we have SSE4.1, we can directly emit a VSEXT node.
13879     if (Subtarget->hasSSE41()) {
13880       SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
13881       DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
13882       return Sext;
13883     }
13884
13885     // Otherwise we'll shuffle the small elements in the high bits of the
13886     // larger type and perform an arithmetic shift. If the shift is not legal
13887     // it's better to scalarize.
13888     assert(TLI.isOperationLegalOrCustom(ISD::SRA, RegVT) &&
13889            "We can't implement a sext load without an arithmetic right shift!");
13890
13891     // Redistribute the loaded elements into the different locations.
13892     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
13893     for (unsigned i = 0; i != NumElems; ++i)
13894       ShuffleVec[i * SizeRatio + SizeRatio - 1] = i;
13895
13896     SDValue Shuff = DAG.getVectorShuffle(
13897         WideVecVT, dl, SlicedVec, DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
13898
13899     Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
13900
13901     // Build the arithmetic shift.
13902     unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
13903                    MemVT.getVectorElementType().getSizeInBits();
13904     Shuff =
13905         DAG.getNode(ISD::SRA, dl, RegVT, Shuff, DAG.getConstant(Amt, RegVT));
13906
13907     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
13908     return Shuff;
13909   }
13910
13911   // Redistribute the loaded elements into the different locations.
13912   SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
13913   for (unsigned i = 0; i != NumElems; ++i)
13914     ShuffleVec[i * SizeRatio] = i;
13915
13916   SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
13917                                        DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
13918
13919   // Bitcast to the requested type.
13920   Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
13921   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
13922   return Shuff;
13923 }
13924
13925 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
13926 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
13927 // from the AND / OR.
13928 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
13929   Opc = Op.getOpcode();
13930   if (Opc != ISD::OR && Opc != ISD::AND)
13931     return false;
13932   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
13933           Op.getOperand(0).hasOneUse() &&
13934           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
13935           Op.getOperand(1).hasOneUse());
13936 }
13937
13938 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
13939 // 1 and that the SETCC node has a single use.
13940 static bool isXor1OfSetCC(SDValue Op) {
13941   if (Op.getOpcode() != ISD::XOR)
13942     return false;
13943   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
13944   if (N1C && N1C->getAPIntValue() == 1) {
13945     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
13946       Op.getOperand(0).hasOneUse();
13947   }
13948   return false;
13949 }
13950
13951 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
13952   bool addTest = true;
13953   SDValue Chain = Op.getOperand(0);
13954   SDValue Cond  = Op.getOperand(1);
13955   SDValue Dest  = Op.getOperand(2);
13956   SDLoc dl(Op);
13957   SDValue CC;
13958   bool Inverted = false;
13959
13960   if (Cond.getOpcode() == ISD::SETCC) {
13961     // Check for setcc([su]{add,sub,mul}o == 0).
13962     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
13963         isa<ConstantSDNode>(Cond.getOperand(1)) &&
13964         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
13965         Cond.getOperand(0).getResNo() == 1 &&
13966         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
13967          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
13968          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
13969          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
13970          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
13971          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
13972       Inverted = true;
13973       Cond = Cond.getOperand(0);
13974     } else {
13975       SDValue NewCond = LowerSETCC(Cond, DAG);
13976       if (NewCond.getNode())
13977         Cond = NewCond;
13978     }
13979   }
13980 #if 0
13981   // FIXME: LowerXALUO doesn't handle these!!
13982   else if (Cond.getOpcode() == X86ISD::ADD  ||
13983            Cond.getOpcode() == X86ISD::SUB  ||
13984            Cond.getOpcode() == X86ISD::SMUL ||
13985            Cond.getOpcode() == X86ISD::UMUL)
13986     Cond = LowerXALUO(Cond, DAG);
13987 #endif
13988
13989   // Look pass (and (setcc_carry (cmp ...)), 1).
13990   if (Cond.getOpcode() == ISD::AND &&
13991       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
13992     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
13993     if (C && C->getAPIntValue() == 1)
13994       Cond = Cond.getOperand(0);
13995   }
13996
13997   // If condition flag is set by a X86ISD::CMP, then use it as the condition
13998   // setting operand in place of the X86ISD::SETCC.
13999   unsigned CondOpcode = Cond.getOpcode();
14000   if (CondOpcode == X86ISD::SETCC ||
14001       CondOpcode == X86ISD::SETCC_CARRY) {
14002     CC = Cond.getOperand(0);
14003
14004     SDValue Cmp = Cond.getOperand(1);
14005     unsigned Opc = Cmp.getOpcode();
14006     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
14007     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
14008       Cond = Cmp;
14009       addTest = false;
14010     } else {
14011       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
14012       default: break;
14013       case X86::COND_O:
14014       case X86::COND_B:
14015         // These can only come from an arithmetic instruction with overflow,
14016         // e.g. SADDO, UADDO.
14017         Cond = Cond.getNode()->getOperand(1);
14018         addTest = false;
14019         break;
14020       }
14021     }
14022   }
14023   CondOpcode = Cond.getOpcode();
14024   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
14025       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
14026       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
14027        Cond.getOperand(0).getValueType() != MVT::i8)) {
14028     SDValue LHS = Cond.getOperand(0);
14029     SDValue RHS = Cond.getOperand(1);
14030     unsigned X86Opcode;
14031     unsigned X86Cond;
14032     SDVTList VTs;
14033     // Keep this in sync with LowerXALUO, otherwise we might create redundant
14034     // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
14035     // X86ISD::INC).
14036     switch (CondOpcode) {
14037     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
14038     case ISD::SADDO:
14039       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
14040         if (C->isOne()) {
14041           X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
14042           break;
14043         }
14044       X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
14045     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
14046     case ISD::SSUBO:
14047       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
14048         if (C->isOne()) {
14049           X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
14050           break;
14051         }
14052       X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
14053     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
14054     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
14055     default: llvm_unreachable("unexpected overflowing operator");
14056     }
14057     if (Inverted)
14058       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
14059     if (CondOpcode == ISD::UMULO)
14060       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
14061                           MVT::i32);
14062     else
14063       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
14064
14065     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
14066
14067     if (CondOpcode == ISD::UMULO)
14068       Cond = X86Op.getValue(2);
14069     else
14070       Cond = X86Op.getValue(1);
14071
14072     CC = DAG.getConstant(X86Cond, MVT::i8);
14073     addTest = false;
14074   } else {
14075     unsigned CondOpc;
14076     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
14077       SDValue Cmp = Cond.getOperand(0).getOperand(1);
14078       if (CondOpc == ISD::OR) {
14079         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
14080         // two branches instead of an explicit OR instruction with a
14081         // separate test.
14082         if (Cmp == Cond.getOperand(1).getOperand(1) &&
14083             isX86LogicalCmp(Cmp)) {
14084           CC = Cond.getOperand(0).getOperand(0);
14085           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14086                               Chain, Dest, CC, Cmp);
14087           CC = Cond.getOperand(1).getOperand(0);
14088           Cond = Cmp;
14089           addTest = false;
14090         }
14091       } else { // ISD::AND
14092         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
14093         // two branches instead of an explicit AND instruction with a
14094         // separate test. However, we only do this if this block doesn't
14095         // have a fall-through edge, because this requires an explicit
14096         // jmp when the condition is false.
14097         if (Cmp == Cond.getOperand(1).getOperand(1) &&
14098             isX86LogicalCmp(Cmp) &&
14099             Op.getNode()->hasOneUse()) {
14100           X86::CondCode CCode =
14101             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
14102           CCode = X86::GetOppositeBranchCondition(CCode);
14103           CC = DAG.getConstant(CCode, MVT::i8);
14104           SDNode *User = *Op.getNode()->use_begin();
14105           // Look for an unconditional branch following this conditional branch.
14106           // We need this because we need to reverse the successors in order
14107           // to implement FCMP_OEQ.
14108           if (User->getOpcode() == ISD::BR) {
14109             SDValue FalseBB = User->getOperand(1);
14110             SDNode *NewBR =
14111               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14112             assert(NewBR == User);
14113             (void)NewBR;
14114             Dest = FalseBB;
14115
14116             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14117                                 Chain, Dest, CC, Cmp);
14118             X86::CondCode CCode =
14119               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
14120             CCode = X86::GetOppositeBranchCondition(CCode);
14121             CC = DAG.getConstant(CCode, MVT::i8);
14122             Cond = Cmp;
14123             addTest = false;
14124           }
14125         }
14126       }
14127     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
14128       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
14129       // It should be transformed during dag combiner except when the condition
14130       // is set by a arithmetics with overflow node.
14131       X86::CondCode CCode =
14132         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
14133       CCode = X86::GetOppositeBranchCondition(CCode);
14134       CC = DAG.getConstant(CCode, MVT::i8);
14135       Cond = Cond.getOperand(0).getOperand(1);
14136       addTest = false;
14137     } else if (Cond.getOpcode() == ISD::SETCC &&
14138                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
14139       // For FCMP_OEQ, we can emit
14140       // two branches instead of an explicit AND instruction with a
14141       // separate test. However, we only do this if this block doesn't
14142       // have a fall-through edge, because this requires an explicit
14143       // jmp when the condition is false.
14144       if (Op.getNode()->hasOneUse()) {
14145         SDNode *User = *Op.getNode()->use_begin();
14146         // Look for an unconditional branch following this conditional branch.
14147         // We need this because we need to reverse the successors in order
14148         // to implement FCMP_OEQ.
14149         if (User->getOpcode() == ISD::BR) {
14150           SDValue FalseBB = User->getOperand(1);
14151           SDNode *NewBR =
14152             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14153           assert(NewBR == User);
14154           (void)NewBR;
14155           Dest = FalseBB;
14156
14157           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
14158                                     Cond.getOperand(0), Cond.getOperand(1));
14159           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14160           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
14161           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14162                               Chain, Dest, CC, Cmp);
14163           CC = DAG.getConstant(X86::COND_P, MVT::i8);
14164           Cond = Cmp;
14165           addTest = false;
14166         }
14167       }
14168     } else if (Cond.getOpcode() == ISD::SETCC &&
14169                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
14170       // For FCMP_UNE, we can emit
14171       // two branches instead of an explicit AND instruction with a
14172       // separate test. However, we only do this if this block doesn't
14173       // have a fall-through edge, because this requires an explicit
14174       // jmp when the condition is false.
14175       if (Op.getNode()->hasOneUse()) {
14176         SDNode *User = *Op.getNode()->use_begin();
14177         // Look for an unconditional branch following this conditional branch.
14178         // We need this because we need to reverse the successors in order
14179         // to implement FCMP_UNE.
14180         if (User->getOpcode() == ISD::BR) {
14181           SDValue FalseBB = User->getOperand(1);
14182           SDNode *NewBR =
14183             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14184           assert(NewBR == User);
14185           (void)NewBR;
14186
14187           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
14188                                     Cond.getOperand(0), Cond.getOperand(1));
14189           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14190           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
14191           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14192                               Chain, Dest, CC, Cmp);
14193           CC = DAG.getConstant(X86::COND_NP, MVT::i8);
14194           Cond = Cmp;
14195           addTest = false;
14196           Dest = FalseBB;
14197         }
14198       }
14199     }
14200   }
14201
14202   if (addTest) {
14203     // Look pass the truncate if the high bits are known zero.
14204     if (isTruncWithZeroHighBitsInput(Cond, DAG))
14205         Cond = Cond.getOperand(0);
14206
14207     // We know the result of AND is compared against zero. Try to match
14208     // it to BT.
14209     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
14210       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
14211       if (NewSetCC.getNode()) {
14212         CC = NewSetCC.getOperand(0);
14213         Cond = NewSetCC.getOperand(1);
14214         addTest = false;
14215       }
14216     }
14217   }
14218
14219   if (addTest) {
14220     X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
14221     CC = DAG.getConstant(X86Cond, MVT::i8);
14222     Cond = EmitTest(Cond, X86Cond, dl, DAG);
14223   }
14224   Cond = ConvertCmpIfNecessary(Cond, DAG);
14225   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14226                      Chain, Dest, CC, Cond);
14227 }
14228
14229 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
14230 // Calls to _alloca are needed to probe the stack when allocating more than 4k
14231 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
14232 // that the guard pages used by the OS virtual memory manager are allocated in
14233 // correct sequence.
14234 SDValue
14235 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
14236                                            SelectionDAG &DAG) const {
14237   MachineFunction &MF = DAG.getMachineFunction();
14238   bool SplitStack = MF.shouldSplitStack();
14239   bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMachO()) ||
14240                SplitStack;
14241   SDLoc dl(Op);
14242
14243   if (!Lower) {
14244     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14245     SDNode* Node = Op.getNode();
14246
14247     unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
14248     assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
14249         " not tell us which reg is the stack pointer!");
14250     EVT VT = Node->getValueType(0);
14251     SDValue Tmp1 = SDValue(Node, 0);
14252     SDValue Tmp2 = SDValue(Node, 1);
14253     SDValue Tmp3 = Node->getOperand(2);
14254     SDValue Chain = Tmp1.getOperand(0);
14255
14256     // Chain the dynamic stack allocation so that it doesn't modify the stack
14257     // pointer when other instructions are using the stack.
14258     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true),
14259         SDLoc(Node));
14260
14261     SDValue Size = Tmp2.getOperand(1);
14262     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
14263     Chain = SP.getValue(1);
14264     unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
14265     const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
14266     unsigned StackAlign = TFI.getStackAlignment();
14267     Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
14268     if (Align > StackAlign)
14269       Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
14270           DAG.getConstant(-(uint64_t)Align, VT));
14271     Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
14272
14273     Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, true),
14274         DAG.getIntPtrConstant(0, true), SDValue(),
14275         SDLoc(Node));
14276
14277     SDValue Ops[2] = { Tmp1, Tmp2 };
14278     return DAG.getMergeValues(Ops, dl);
14279   }
14280
14281   // Get the inputs.
14282   SDValue Chain = Op.getOperand(0);
14283   SDValue Size  = Op.getOperand(1);
14284   unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
14285   EVT VT = Op.getNode()->getValueType(0);
14286
14287   bool Is64Bit = Subtarget->is64Bit();
14288   EVT SPTy = getPointerTy();
14289
14290   if (SplitStack) {
14291     MachineRegisterInfo &MRI = MF.getRegInfo();
14292
14293     if (Is64Bit) {
14294       // The 64 bit implementation of segmented stacks needs to clobber both r10
14295       // r11. This makes it impossible to use it along with nested parameters.
14296       const Function *F = MF.getFunction();
14297
14298       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
14299            I != E; ++I)
14300         if (I->hasNestAttr())
14301           report_fatal_error("Cannot use segmented stacks with functions that "
14302                              "have nested arguments.");
14303     }
14304
14305     const TargetRegisterClass *AddrRegClass =
14306       getRegClassFor(getPointerTy());
14307     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
14308     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
14309     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
14310                                 DAG.getRegister(Vreg, SPTy));
14311     SDValue Ops1[2] = { Value, Chain };
14312     return DAG.getMergeValues(Ops1, dl);
14313   } else {
14314     SDValue Flag;
14315     const unsigned Reg = (Subtarget->isTarget64BitLP64() ? X86::RAX : X86::EAX);
14316
14317     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
14318     Flag = Chain.getValue(1);
14319     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
14320
14321     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
14322
14323     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
14324     unsigned SPReg = RegInfo->getStackRegister();
14325     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
14326     Chain = SP.getValue(1);
14327
14328     if (Align) {
14329       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
14330                        DAG.getConstant(-(uint64_t)Align, VT));
14331       Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
14332     }
14333
14334     SDValue Ops1[2] = { SP, Chain };
14335     return DAG.getMergeValues(Ops1, dl);
14336   }
14337 }
14338
14339 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
14340   MachineFunction &MF = DAG.getMachineFunction();
14341   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
14342
14343   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
14344   SDLoc DL(Op);
14345
14346   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
14347     // vastart just stores the address of the VarArgsFrameIndex slot into the
14348     // memory location argument.
14349     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
14350                                    getPointerTy());
14351     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
14352                         MachinePointerInfo(SV), false, false, 0);
14353   }
14354
14355   // __va_list_tag:
14356   //   gp_offset         (0 - 6 * 8)
14357   //   fp_offset         (48 - 48 + 8 * 16)
14358   //   overflow_arg_area (point to parameters coming in memory).
14359   //   reg_save_area
14360   SmallVector<SDValue, 8> MemOps;
14361   SDValue FIN = Op.getOperand(1);
14362   // Store gp_offset
14363   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
14364                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
14365                                                MVT::i32),
14366                                FIN, MachinePointerInfo(SV), false, false, 0);
14367   MemOps.push_back(Store);
14368
14369   // Store fp_offset
14370   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
14371                     FIN, DAG.getIntPtrConstant(4));
14372   Store = DAG.getStore(Op.getOperand(0), DL,
14373                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
14374                                        MVT::i32),
14375                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
14376   MemOps.push_back(Store);
14377
14378   // Store ptr to overflow_arg_area
14379   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
14380                     FIN, DAG.getIntPtrConstant(4));
14381   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
14382                                     getPointerTy());
14383   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
14384                        MachinePointerInfo(SV, 8),
14385                        false, false, 0);
14386   MemOps.push_back(Store);
14387
14388   // Store ptr to reg_save_area.
14389   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
14390                     FIN, DAG.getIntPtrConstant(8));
14391   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
14392                                     getPointerTy());
14393   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
14394                        MachinePointerInfo(SV, 16), false, false, 0);
14395   MemOps.push_back(Store);
14396   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
14397 }
14398
14399 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
14400   assert(Subtarget->is64Bit() &&
14401          "LowerVAARG only handles 64-bit va_arg!");
14402   assert((Subtarget->isTargetLinux() ||
14403           Subtarget->isTargetDarwin()) &&
14404           "Unhandled target in LowerVAARG");
14405   assert(Op.getNode()->getNumOperands() == 4);
14406   SDValue Chain = Op.getOperand(0);
14407   SDValue SrcPtr = Op.getOperand(1);
14408   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
14409   unsigned Align = Op.getConstantOperandVal(3);
14410   SDLoc dl(Op);
14411
14412   EVT ArgVT = Op.getNode()->getValueType(0);
14413   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
14414   uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
14415   uint8_t ArgMode;
14416
14417   // Decide which area this value should be read from.
14418   // TODO: Implement the AMD64 ABI in its entirety. This simple
14419   // selection mechanism works only for the basic types.
14420   if (ArgVT == MVT::f80) {
14421     llvm_unreachable("va_arg for f80 not yet implemented");
14422   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
14423     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
14424   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
14425     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
14426   } else {
14427     llvm_unreachable("Unhandled argument type in LowerVAARG");
14428   }
14429
14430   if (ArgMode == 2) {
14431     // Sanity Check: Make sure using fp_offset makes sense.
14432     assert(!DAG.getTarget().Options.UseSoftFloat &&
14433            !(DAG.getMachineFunction().getFunction()->hasFnAttribute(
14434                Attribute::NoImplicitFloat)) &&
14435            Subtarget->hasSSE1());
14436   }
14437
14438   // Insert VAARG_64 node into the DAG
14439   // VAARG_64 returns two values: Variable Argument Address, Chain
14440   SDValue InstOps[] = {Chain, SrcPtr, DAG.getConstant(ArgSize, MVT::i32),
14441                        DAG.getConstant(ArgMode, MVT::i8),
14442                        DAG.getConstant(Align, MVT::i32)};
14443   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
14444   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
14445                                           VTs, InstOps, MVT::i64,
14446                                           MachinePointerInfo(SV),
14447                                           /*Align=*/0,
14448                                           /*Volatile=*/false,
14449                                           /*ReadMem=*/true,
14450                                           /*WriteMem=*/true);
14451   Chain = VAARG.getValue(1);
14452
14453   // Load the next argument and return it
14454   return DAG.getLoad(ArgVT, dl,
14455                      Chain,
14456                      VAARG,
14457                      MachinePointerInfo(),
14458                      false, false, false, 0);
14459 }
14460
14461 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
14462                            SelectionDAG &DAG) {
14463   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
14464   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
14465   SDValue Chain = Op.getOperand(0);
14466   SDValue DstPtr = Op.getOperand(1);
14467   SDValue SrcPtr = Op.getOperand(2);
14468   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
14469   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
14470   SDLoc DL(Op);
14471
14472   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
14473                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
14474                        false,
14475                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
14476 }
14477
14478 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
14479 // amount is a constant. Takes immediate version of shift as input.
14480 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
14481                                           SDValue SrcOp, uint64_t ShiftAmt,
14482                                           SelectionDAG &DAG) {
14483   MVT ElementType = VT.getVectorElementType();
14484
14485   // Fold this packed shift into its first operand if ShiftAmt is 0.
14486   if (ShiftAmt == 0)
14487     return SrcOp;
14488
14489   // Check for ShiftAmt >= element width
14490   if (ShiftAmt >= ElementType.getSizeInBits()) {
14491     if (Opc == X86ISD::VSRAI)
14492       ShiftAmt = ElementType.getSizeInBits() - 1;
14493     else
14494       return DAG.getConstant(0, VT);
14495   }
14496
14497   assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
14498          && "Unknown target vector shift-by-constant node");
14499
14500   // Fold this packed vector shift into a build vector if SrcOp is a
14501   // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
14502   if (VT == SrcOp.getSimpleValueType() &&
14503       ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
14504     SmallVector<SDValue, 8> Elts;
14505     unsigned NumElts = SrcOp->getNumOperands();
14506     ConstantSDNode *ND;
14507
14508     switch(Opc) {
14509     default: llvm_unreachable(nullptr);
14510     case X86ISD::VSHLI:
14511       for (unsigned i=0; i!=NumElts; ++i) {
14512         SDValue CurrentOp = SrcOp->getOperand(i);
14513         if (CurrentOp->getOpcode() == ISD::UNDEF) {
14514           Elts.push_back(CurrentOp);
14515           continue;
14516         }
14517         ND = cast<ConstantSDNode>(CurrentOp);
14518         const APInt &C = ND->getAPIntValue();
14519         Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), ElementType));
14520       }
14521       break;
14522     case X86ISD::VSRLI:
14523       for (unsigned i=0; i!=NumElts; ++i) {
14524         SDValue CurrentOp = SrcOp->getOperand(i);
14525         if (CurrentOp->getOpcode() == ISD::UNDEF) {
14526           Elts.push_back(CurrentOp);
14527           continue;
14528         }
14529         ND = cast<ConstantSDNode>(CurrentOp);
14530         const APInt &C = ND->getAPIntValue();
14531         Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), ElementType));
14532       }
14533       break;
14534     case X86ISD::VSRAI:
14535       for (unsigned i=0; i!=NumElts; ++i) {
14536         SDValue CurrentOp = SrcOp->getOperand(i);
14537         if (CurrentOp->getOpcode() == ISD::UNDEF) {
14538           Elts.push_back(CurrentOp);
14539           continue;
14540         }
14541         ND = cast<ConstantSDNode>(CurrentOp);
14542         const APInt &C = ND->getAPIntValue();
14543         Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), ElementType));
14544       }
14545       break;
14546     }
14547
14548     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
14549   }
14550
14551   return DAG.getNode(Opc, dl, VT, SrcOp, DAG.getConstant(ShiftAmt, MVT::i8));
14552 }
14553
14554 // getTargetVShiftNode - Handle vector element shifts where the shift amount
14555 // may or may not be a constant. Takes immediate version of shift as input.
14556 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
14557                                    SDValue SrcOp, SDValue ShAmt,
14558                                    SelectionDAG &DAG) {
14559   MVT SVT = ShAmt.getSimpleValueType();
14560   assert((SVT == MVT::i32 || SVT == MVT::i64) && "Unexpected value type!");
14561
14562   // Catch shift-by-constant.
14563   if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
14564     return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
14565                                       CShAmt->getZExtValue(), DAG);
14566
14567   // Change opcode to non-immediate version
14568   switch (Opc) {
14569     default: llvm_unreachable("Unknown target vector shift node");
14570     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
14571     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
14572     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
14573   }
14574
14575   const X86Subtarget &Subtarget =
14576       static_cast<const X86Subtarget &>(DAG.getSubtarget());
14577   if (Subtarget.hasSSE41() && ShAmt.getOpcode() == ISD::ZERO_EXTEND &&
14578       ShAmt.getOperand(0).getSimpleValueType() == MVT::i16) {
14579     // Let the shuffle legalizer expand this shift amount node.
14580     SDValue Op0 = ShAmt.getOperand(0);
14581     Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(Op0), MVT::v8i16, Op0);
14582     ShAmt = getShuffleVectorZeroOrUndef(Op0, 0, true, &Subtarget, DAG);
14583   } else {
14584     // Need to build a vector containing shift amount.
14585     // SSE/AVX packed shifts only use the lower 64-bit of the shift count.
14586     SmallVector<SDValue, 4> ShOps;
14587     ShOps.push_back(ShAmt);
14588     if (SVT == MVT::i32) {
14589       ShOps.push_back(DAG.getConstant(0, SVT));
14590       ShOps.push_back(DAG.getUNDEF(SVT));
14591     }
14592     ShOps.push_back(DAG.getUNDEF(SVT));
14593
14594     MVT BVT = SVT == MVT::i32 ? MVT::v4i32 : MVT::v2i64;
14595     ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, BVT, ShOps);
14596   }
14597
14598   // The return type has to be a 128-bit type with the same element
14599   // type as the input type.
14600   MVT EltVT = VT.getVectorElementType();
14601   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
14602
14603   ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
14604   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
14605 }
14606
14607 /// \brief Return (and \p Op, \p Mask) for compare instructions or
14608 /// (vselect \p Mask, \p Op, \p PreservedSrc) for others along with the
14609 /// necessary casting for \p Mask when lowering masking intrinsics.
14610 static SDValue getVectorMaskingNode(SDValue Op, SDValue Mask,
14611                                     SDValue PreservedSrc,
14612                                     const X86Subtarget *Subtarget,
14613                                     SelectionDAG &DAG) {
14614     EVT VT = Op.getValueType();
14615     EVT MaskVT = EVT::getVectorVT(*DAG.getContext(),
14616                                   MVT::i1, VT.getVectorNumElements());
14617     EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
14618                                      Mask.getValueType().getSizeInBits());
14619     SDLoc dl(Op);
14620
14621     assert(MaskVT.isSimple() && "invalid mask type");
14622
14623     if (isAllOnes(Mask))
14624       return Op;
14625
14626     // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
14627     // are extracted by EXTRACT_SUBVECTOR.
14628     SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
14629                               DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
14630                               DAG.getIntPtrConstant(0));
14631
14632     switch (Op.getOpcode()) {
14633       default: break;
14634       case X86ISD::PCMPEQM:
14635       case X86ISD::PCMPGTM:
14636       case X86ISD::CMPM:
14637       case X86ISD::CMPMU:
14638         return DAG.getNode(ISD::AND, dl, VT, Op, VMask);
14639     }
14640     if (PreservedSrc.getOpcode() == ISD::UNDEF)
14641       PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
14642     return DAG.getNode(ISD::VSELECT, dl, VT, VMask, Op, PreservedSrc);
14643 }
14644
14645 /// \brief Creates an SDNode for a predicated scalar operation.
14646 /// \returns (X86vselect \p Mask, \p Op, \p PreservedSrc).
14647 /// The mask is comming as MVT::i8 and it should be truncated
14648 /// to MVT::i1 while lowering masking intrinsics.
14649 /// The main difference between ScalarMaskingNode and VectorMaskingNode is using
14650 /// "X86select" instead of "vselect". We just can't create the "vselect" node for
14651 /// a scalar instruction.
14652 static SDValue getScalarMaskingNode(SDValue Op, SDValue Mask,
14653                                     SDValue PreservedSrc,
14654                                     const X86Subtarget *Subtarget,
14655                                     SelectionDAG &DAG) {
14656     if (isAllOnes(Mask))
14657       return Op;
14658
14659     EVT VT = Op.getValueType();
14660     SDLoc dl(Op);
14661     // The mask should be of type MVT::i1
14662     SDValue IMask = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Mask);
14663
14664     if (PreservedSrc.getOpcode() == ISD::UNDEF)
14665       PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
14666     return DAG.getNode(X86ISD::SELECT, dl, VT, IMask, Op, PreservedSrc);
14667 }
14668
14669 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
14670                                        SelectionDAG &DAG) {
14671   SDLoc dl(Op);
14672   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
14673   EVT VT = Op.getValueType();
14674   const IntrinsicData* IntrData = getIntrinsicWithoutChain(IntNo);
14675   if (IntrData) {
14676     switch(IntrData->Type) {
14677     case INTR_TYPE_1OP:
14678       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1));
14679     case INTR_TYPE_2OP:
14680       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
14681         Op.getOperand(2));
14682     case INTR_TYPE_3OP:
14683       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
14684         Op.getOperand(2), Op.getOperand(3));
14685     case INTR_TYPE_1OP_MASK_RM: {
14686       SDValue Src = Op.getOperand(1);
14687       SDValue Src0 = Op.getOperand(2);
14688       SDValue Mask = Op.getOperand(3);
14689       SDValue RoundingMode = Op.getOperand(4);
14690       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src,
14691                                               RoundingMode),
14692                                   Mask, Src0, Subtarget, DAG);
14693     }
14694     case INTR_TYPE_SCALAR_MASK_RM: {
14695       SDValue Src1 = Op.getOperand(1);
14696       SDValue Src2 = Op.getOperand(2);
14697       SDValue Src0 = Op.getOperand(3);
14698       SDValue Mask = Op.getOperand(4);
14699       // There are 2 kinds of intrinsics in this group:
14700       // (1) With supress-all-exceptions (sae) - 6 operands
14701       // (2) With rounding mode and sae - 7 operands.
14702       if (Op.getNumOperands() == 6) {
14703         SDValue Sae  = Op.getOperand(5);
14704         return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2,
14705                                                 Sae),
14706                                     Mask, Src0, Subtarget, DAG);
14707       }
14708       assert(Op.getNumOperands() == 7 && "Unexpected intrinsic form");
14709       SDValue RoundingMode  = Op.getOperand(5);
14710       SDValue Sae  = Op.getOperand(6);
14711       return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2,
14712                                               RoundingMode, Sae),
14713                                   Mask, Src0, Subtarget, DAG);
14714     }
14715     case INTR_TYPE_2OP_MASK: {
14716       SDValue Src1 = Op.getOperand(1);
14717       SDValue Src2 = Op.getOperand(2);
14718       SDValue PassThru = Op.getOperand(3);
14719       SDValue Mask = Op.getOperand(4);
14720       // We specify 2 possible opcodes for intrinsics with rounding modes.
14721       // First, we check if the intrinsic may have non-default rounding mode,
14722       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
14723       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
14724       if (IntrWithRoundingModeOpcode != 0) {
14725         SDValue Rnd = Op.getOperand(5);
14726         unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
14727         if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
14728           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
14729                                       dl, Op.getValueType(),
14730                                       Src1, Src2, Rnd),
14731                                       Mask, PassThru, Subtarget, DAG);
14732         }
14733       }
14734       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
14735                                               Src1,Src2),
14736                                   Mask, PassThru, Subtarget, DAG);
14737     }
14738     case FMA_OP_MASK: {
14739       SDValue Src1 = Op.getOperand(1);
14740       SDValue Src2 = Op.getOperand(2);
14741       SDValue Src3 = Op.getOperand(3);
14742       SDValue Mask = Op.getOperand(4);
14743       // We specify 2 possible opcodes for intrinsics with rounding modes.
14744       // First, we check if the intrinsic may have non-default rounding mode,
14745       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
14746       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
14747       if (IntrWithRoundingModeOpcode != 0) {
14748         SDValue Rnd = Op.getOperand(5);
14749         if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
14750             X86::STATIC_ROUNDING::CUR_DIRECTION)
14751           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
14752                                                   dl, Op.getValueType(),
14753                                                   Src1, Src2, Src3, Rnd),
14754                                       Mask, Src1, Subtarget, DAG);
14755       }
14756       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0,
14757                                               dl, Op.getValueType(),
14758                                               Src1, Src2, Src3),
14759                                   Mask, Src1, Subtarget, DAG);
14760     }
14761     case CMP_MASK:
14762     case CMP_MASK_CC: {
14763       // Comparison intrinsics with masks.
14764       // Example of transformation:
14765       // (i8 (int_x86_avx512_mask_pcmpeq_q_128
14766       //             (v2i64 %a), (v2i64 %b), (i8 %mask))) ->
14767       // (i8 (bitcast
14768       //   (v8i1 (insert_subvector undef,
14769       //           (v2i1 (and (PCMPEQM %a, %b),
14770       //                      (extract_subvector
14771       //                         (v8i1 (bitcast %mask)), 0))), 0))))
14772       EVT VT = Op.getOperand(1).getValueType();
14773       EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
14774                                     VT.getVectorNumElements());
14775       SDValue Mask = Op.getOperand((IntrData->Type == CMP_MASK_CC) ? 4 : 3);
14776       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
14777                                        Mask.getValueType().getSizeInBits());
14778       SDValue Cmp;
14779       if (IntrData->Type == CMP_MASK_CC) {
14780         Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
14781                     Op.getOperand(2), Op.getOperand(3));
14782       } else {
14783         assert(IntrData->Type == CMP_MASK && "Unexpected intrinsic type!");
14784         Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
14785                     Op.getOperand(2));
14786       }
14787       SDValue CmpMask = getVectorMaskingNode(Cmp, Mask,
14788                                              DAG.getTargetConstant(0, MaskVT),
14789                                              Subtarget, DAG);
14790       SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, BitcastVT,
14791                                 DAG.getUNDEF(BitcastVT), CmpMask,
14792                                 DAG.getIntPtrConstant(0));
14793       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
14794     }
14795     case COMI: { // Comparison intrinsics
14796       ISD::CondCode CC = (ISD::CondCode)IntrData->Opc1;
14797       SDValue LHS = Op.getOperand(1);
14798       SDValue RHS = Op.getOperand(2);
14799       unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
14800       assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
14801       SDValue Cond = DAG.getNode(IntrData->Opc0, dl, MVT::i32, LHS, RHS);
14802       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14803                                   DAG.getConstant(X86CC, MVT::i8), Cond);
14804       return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
14805     }
14806     case VSHIFT:
14807       return getTargetVShiftNode(IntrData->Opc0, dl, Op.getSimpleValueType(),
14808                                  Op.getOperand(1), Op.getOperand(2), DAG);
14809     case VSHIFT_MASK:
14810       return getVectorMaskingNode(getTargetVShiftNode(IntrData->Opc0, dl,
14811                                                       Op.getSimpleValueType(),
14812                                                       Op.getOperand(1),
14813                                                       Op.getOperand(2), DAG),
14814                                   Op.getOperand(4), Op.getOperand(3), Subtarget,
14815                                   DAG);
14816     case COMPRESS_EXPAND_IN_REG: {
14817       SDValue Mask = Op.getOperand(3);
14818       SDValue DataToCompress = Op.getOperand(1);
14819       SDValue PassThru = Op.getOperand(2);
14820       if (isAllOnes(Mask)) // return data as is
14821         return Op.getOperand(1);
14822       EVT VT = Op.getValueType();
14823       EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
14824                                     VT.getVectorNumElements());
14825       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
14826                                        Mask.getValueType().getSizeInBits());
14827       SDLoc dl(Op);
14828       SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
14829                                   DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
14830                                   DAG.getIntPtrConstant(0));
14831
14832       return DAG.getNode(IntrData->Opc0, dl, VT, VMask, DataToCompress,
14833                          PassThru);
14834     }
14835     case BLEND: {
14836       SDValue Mask = Op.getOperand(3);
14837       EVT VT = Op.getValueType();
14838       EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
14839                                     VT.getVectorNumElements());
14840       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
14841                                        Mask.getValueType().getSizeInBits());
14842       SDLoc dl(Op);
14843       SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
14844                                   DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
14845                                   DAG.getIntPtrConstant(0));
14846       return DAG.getNode(IntrData->Opc0, dl, VT, VMask, Op.getOperand(1),
14847                          Op.getOperand(2));
14848     }
14849     default:
14850       break;
14851     }
14852   }
14853
14854   switch (IntNo) {
14855   default: return SDValue();    // Don't custom lower most intrinsics.
14856
14857   case Intrinsic::x86_avx2_permd:
14858   case Intrinsic::x86_avx2_permps:
14859     // Operands intentionally swapped. Mask is last operand to intrinsic,
14860     // but second operand for node/instruction.
14861     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
14862                        Op.getOperand(2), Op.getOperand(1));
14863
14864   case Intrinsic::x86_avx512_mask_valign_q_512:
14865   case Intrinsic::x86_avx512_mask_valign_d_512:
14866     // Vector source operands are swapped.
14867     return getVectorMaskingNode(DAG.getNode(X86ISD::VALIGN, dl,
14868                                             Op.getValueType(), Op.getOperand(2),
14869                                             Op.getOperand(1),
14870                                             Op.getOperand(3)),
14871                                 Op.getOperand(5), Op.getOperand(4),
14872                                 Subtarget, DAG);
14873
14874   // ptest and testp intrinsics. The intrinsic these come from are designed to
14875   // return an integer value, not just an instruction so lower it to the ptest
14876   // or testp pattern and a setcc for the result.
14877   case Intrinsic::x86_sse41_ptestz:
14878   case Intrinsic::x86_sse41_ptestc:
14879   case Intrinsic::x86_sse41_ptestnzc:
14880   case Intrinsic::x86_avx_ptestz_256:
14881   case Intrinsic::x86_avx_ptestc_256:
14882   case Intrinsic::x86_avx_ptestnzc_256:
14883   case Intrinsic::x86_avx_vtestz_ps:
14884   case Intrinsic::x86_avx_vtestc_ps:
14885   case Intrinsic::x86_avx_vtestnzc_ps:
14886   case Intrinsic::x86_avx_vtestz_pd:
14887   case Intrinsic::x86_avx_vtestc_pd:
14888   case Intrinsic::x86_avx_vtestnzc_pd:
14889   case Intrinsic::x86_avx_vtestz_ps_256:
14890   case Intrinsic::x86_avx_vtestc_ps_256:
14891   case Intrinsic::x86_avx_vtestnzc_ps_256:
14892   case Intrinsic::x86_avx_vtestz_pd_256:
14893   case Intrinsic::x86_avx_vtestc_pd_256:
14894   case Intrinsic::x86_avx_vtestnzc_pd_256: {
14895     bool IsTestPacked = false;
14896     unsigned X86CC;
14897     switch (IntNo) {
14898     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
14899     case Intrinsic::x86_avx_vtestz_ps:
14900     case Intrinsic::x86_avx_vtestz_pd:
14901     case Intrinsic::x86_avx_vtestz_ps_256:
14902     case Intrinsic::x86_avx_vtestz_pd_256:
14903       IsTestPacked = true; // Fallthrough
14904     case Intrinsic::x86_sse41_ptestz:
14905     case Intrinsic::x86_avx_ptestz_256:
14906       // ZF = 1
14907       X86CC = X86::COND_E;
14908       break;
14909     case Intrinsic::x86_avx_vtestc_ps:
14910     case Intrinsic::x86_avx_vtestc_pd:
14911     case Intrinsic::x86_avx_vtestc_ps_256:
14912     case Intrinsic::x86_avx_vtestc_pd_256:
14913       IsTestPacked = true; // Fallthrough
14914     case Intrinsic::x86_sse41_ptestc:
14915     case Intrinsic::x86_avx_ptestc_256:
14916       // CF = 1
14917       X86CC = X86::COND_B;
14918       break;
14919     case Intrinsic::x86_avx_vtestnzc_ps:
14920     case Intrinsic::x86_avx_vtestnzc_pd:
14921     case Intrinsic::x86_avx_vtestnzc_ps_256:
14922     case Intrinsic::x86_avx_vtestnzc_pd_256:
14923       IsTestPacked = true; // Fallthrough
14924     case Intrinsic::x86_sse41_ptestnzc:
14925     case Intrinsic::x86_avx_ptestnzc_256:
14926       // ZF and CF = 0
14927       X86CC = X86::COND_A;
14928       break;
14929     }
14930
14931     SDValue LHS = Op.getOperand(1);
14932     SDValue RHS = Op.getOperand(2);
14933     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
14934     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
14935     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
14936     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
14937     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
14938   }
14939   case Intrinsic::x86_avx512_kortestz_w:
14940   case Intrinsic::x86_avx512_kortestc_w: {
14941     unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
14942     SDValue LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(1));
14943     SDValue RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(2));
14944     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
14945     SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
14946     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
14947     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
14948   }
14949
14950   case Intrinsic::x86_sse42_pcmpistria128:
14951   case Intrinsic::x86_sse42_pcmpestria128:
14952   case Intrinsic::x86_sse42_pcmpistric128:
14953   case Intrinsic::x86_sse42_pcmpestric128:
14954   case Intrinsic::x86_sse42_pcmpistrio128:
14955   case Intrinsic::x86_sse42_pcmpestrio128:
14956   case Intrinsic::x86_sse42_pcmpistris128:
14957   case Intrinsic::x86_sse42_pcmpestris128:
14958   case Intrinsic::x86_sse42_pcmpistriz128:
14959   case Intrinsic::x86_sse42_pcmpestriz128: {
14960     unsigned Opcode;
14961     unsigned X86CC;
14962     switch (IntNo) {
14963     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
14964     case Intrinsic::x86_sse42_pcmpistria128:
14965       Opcode = X86ISD::PCMPISTRI;
14966       X86CC = X86::COND_A;
14967       break;
14968     case Intrinsic::x86_sse42_pcmpestria128:
14969       Opcode = X86ISD::PCMPESTRI;
14970       X86CC = X86::COND_A;
14971       break;
14972     case Intrinsic::x86_sse42_pcmpistric128:
14973       Opcode = X86ISD::PCMPISTRI;
14974       X86CC = X86::COND_B;
14975       break;
14976     case Intrinsic::x86_sse42_pcmpestric128:
14977       Opcode = X86ISD::PCMPESTRI;
14978       X86CC = X86::COND_B;
14979       break;
14980     case Intrinsic::x86_sse42_pcmpistrio128:
14981       Opcode = X86ISD::PCMPISTRI;
14982       X86CC = X86::COND_O;
14983       break;
14984     case Intrinsic::x86_sse42_pcmpestrio128:
14985       Opcode = X86ISD::PCMPESTRI;
14986       X86CC = X86::COND_O;
14987       break;
14988     case Intrinsic::x86_sse42_pcmpistris128:
14989       Opcode = X86ISD::PCMPISTRI;
14990       X86CC = X86::COND_S;
14991       break;
14992     case Intrinsic::x86_sse42_pcmpestris128:
14993       Opcode = X86ISD::PCMPESTRI;
14994       X86CC = X86::COND_S;
14995       break;
14996     case Intrinsic::x86_sse42_pcmpistriz128:
14997       Opcode = X86ISD::PCMPISTRI;
14998       X86CC = X86::COND_E;
14999       break;
15000     case Intrinsic::x86_sse42_pcmpestriz128:
15001       Opcode = X86ISD::PCMPESTRI;
15002       X86CC = X86::COND_E;
15003       break;
15004     }
15005     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
15006     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
15007     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
15008     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15009                                 DAG.getConstant(X86CC, MVT::i8),
15010                                 SDValue(PCMP.getNode(), 1));
15011     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15012   }
15013
15014   case Intrinsic::x86_sse42_pcmpistri128:
15015   case Intrinsic::x86_sse42_pcmpestri128: {
15016     unsigned Opcode;
15017     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
15018       Opcode = X86ISD::PCMPISTRI;
15019     else
15020       Opcode = X86ISD::PCMPESTRI;
15021
15022     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
15023     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
15024     return DAG.getNode(Opcode, dl, VTs, NewOps);
15025   }
15026   }
15027 }
15028
15029 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15030                               SDValue Src, SDValue Mask, SDValue Base,
15031                               SDValue Index, SDValue ScaleOp, SDValue Chain,
15032                               const X86Subtarget * Subtarget) {
15033   SDLoc dl(Op);
15034   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15035   assert(C && "Invalid scale type");
15036   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
15037   EVT MaskVT = MVT::getVectorVT(MVT::i1,
15038                              Index.getSimpleValueType().getVectorNumElements());
15039   SDValue MaskInReg;
15040   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15041   if (MaskC)
15042     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
15043   else
15044     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
15045   SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
15046   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
15047   SDValue Segment = DAG.getRegister(0, MVT::i32);
15048   if (Src.getOpcode() == ISD::UNDEF)
15049     Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
15050   SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
15051   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
15052   SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
15053   return DAG.getMergeValues(RetOps, dl);
15054 }
15055
15056 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15057                                SDValue Src, SDValue Mask, SDValue Base,
15058                                SDValue Index, SDValue ScaleOp, SDValue Chain) {
15059   SDLoc dl(Op);
15060   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15061   assert(C && "Invalid scale type");
15062   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
15063   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
15064   SDValue Segment = DAG.getRegister(0, MVT::i32);
15065   EVT MaskVT = MVT::getVectorVT(MVT::i1,
15066                              Index.getSimpleValueType().getVectorNumElements());
15067   SDValue MaskInReg;
15068   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15069   if (MaskC)
15070     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
15071   else
15072     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
15073   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
15074   SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
15075   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
15076   return SDValue(Res, 1);
15077 }
15078
15079 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15080                                SDValue Mask, SDValue Base, SDValue Index,
15081                                SDValue ScaleOp, SDValue Chain) {
15082   SDLoc dl(Op);
15083   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15084   assert(C && "Invalid scale type");
15085   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
15086   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
15087   SDValue Segment = DAG.getRegister(0, MVT::i32);
15088   EVT MaskVT =
15089     MVT::getVectorVT(MVT::i1, 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(MVT::Other);
15097   SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
15098   SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
15099   return SDValue(Res, 0);
15100 }
15101
15102 // getReadPerformanceCounter - Handles the lowering of builtin intrinsics that
15103 // read performance monitor counters (x86_rdpmc).
15104 static void getReadPerformanceCounter(SDNode *N, SDLoc DL,
15105                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
15106                               SmallVectorImpl<SDValue> &Results) {
15107   assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
15108   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
15109   SDValue LO, HI;
15110
15111   // The ECX register is used to select the index of the performance counter
15112   // to read.
15113   SDValue Chain = DAG.getCopyToReg(N->getOperand(0), DL, X86::ECX,
15114                                    N->getOperand(2));
15115   SDValue rd = DAG.getNode(X86ISD::RDPMC_DAG, DL, Tys, Chain);
15116
15117   // Reads the content of a 64-bit performance counter and returns it in the
15118   // registers EDX:EAX.
15119   if (Subtarget->is64Bit()) {
15120     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
15121     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
15122                             LO.getValue(2));
15123   } else {
15124     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
15125     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
15126                             LO.getValue(2));
15127   }
15128   Chain = HI.getValue(1);
15129
15130   if (Subtarget->is64Bit()) {
15131     // The EAX register is loaded with the low-order 32 bits. The EDX register
15132     // is loaded with the supported high-order bits of the counter.
15133     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
15134                               DAG.getConstant(32, MVT::i8));
15135     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
15136     Results.push_back(Chain);
15137     return;
15138   }
15139
15140   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
15141   SDValue Ops[] = { LO, HI };
15142   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
15143   Results.push_back(Pair);
15144   Results.push_back(Chain);
15145 }
15146
15147 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
15148 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
15149 // also used to custom lower READCYCLECOUNTER nodes.
15150 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
15151                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
15152                               SmallVectorImpl<SDValue> &Results) {
15153   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
15154   SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
15155   SDValue LO, HI;
15156
15157   // The processor's time-stamp counter (a 64-bit MSR) is stored into the
15158   // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
15159   // and the EAX register is loaded with the low-order 32 bits.
15160   if (Subtarget->is64Bit()) {
15161     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
15162     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
15163                             LO.getValue(2));
15164   } else {
15165     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
15166     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
15167                             LO.getValue(2));
15168   }
15169   SDValue Chain = HI.getValue(1);
15170
15171   if (Opcode == X86ISD::RDTSCP_DAG) {
15172     assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
15173
15174     // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
15175     // the ECX register. Add 'ecx' explicitly to the chain.
15176     SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
15177                                      HI.getValue(2));
15178     // Explicitly store the content of ECX at the location passed in input
15179     // to the 'rdtscp' intrinsic.
15180     Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
15181                          MachinePointerInfo(), false, false, 0);
15182   }
15183
15184   if (Subtarget->is64Bit()) {
15185     // The EDX register is loaded with the high-order 32 bits of the MSR, and
15186     // the EAX register is loaded with the low-order 32 bits.
15187     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
15188                               DAG.getConstant(32, MVT::i8));
15189     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
15190     Results.push_back(Chain);
15191     return;
15192   }
15193
15194   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
15195   SDValue Ops[] = { LO, HI };
15196   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
15197   Results.push_back(Pair);
15198   Results.push_back(Chain);
15199 }
15200
15201 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
15202                                      SelectionDAG &DAG) {
15203   SmallVector<SDValue, 2> Results;
15204   SDLoc DL(Op);
15205   getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
15206                           Results);
15207   return DAG.getMergeValues(Results, DL);
15208 }
15209
15210
15211 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
15212                                       SelectionDAG &DAG) {
15213   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
15214
15215   const IntrinsicData* IntrData = getIntrinsicWithChain(IntNo);
15216   if (!IntrData)
15217     return SDValue();
15218
15219   SDLoc dl(Op);
15220   switch(IntrData->Type) {
15221   default:
15222     llvm_unreachable("Unknown Intrinsic Type");
15223     break;
15224   case RDSEED:
15225   case RDRAND: {
15226     // Emit the node with the right value type.
15227     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
15228     SDValue Result = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
15229
15230     // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
15231     // Otherwise return the value from Rand, which is always 0, casted to i32.
15232     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
15233                       DAG.getConstant(1, Op->getValueType(1)),
15234                       DAG.getConstant(X86::COND_B, MVT::i32),
15235                       SDValue(Result.getNode(), 1) };
15236     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
15237                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
15238                                   Ops);
15239
15240     // Return { result, isValid, chain }.
15241     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
15242                        SDValue(Result.getNode(), 2));
15243   }
15244   case GATHER: {
15245   //gather(v1, mask, index, base, scale);
15246     SDValue Chain = Op.getOperand(0);
15247     SDValue Src   = Op.getOperand(2);
15248     SDValue Base  = Op.getOperand(3);
15249     SDValue Index = Op.getOperand(4);
15250     SDValue Mask  = Op.getOperand(5);
15251     SDValue Scale = Op.getOperand(6);
15252     return getGatherNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain,
15253                           Subtarget);
15254   }
15255   case SCATTER: {
15256   //scatter(base, mask, index, v1, scale);
15257     SDValue Chain = Op.getOperand(0);
15258     SDValue Base  = Op.getOperand(2);
15259     SDValue Mask  = Op.getOperand(3);
15260     SDValue Index = Op.getOperand(4);
15261     SDValue Src   = Op.getOperand(5);
15262     SDValue Scale = Op.getOperand(6);
15263     return getScatterNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain);
15264   }
15265   case PREFETCH: {
15266     SDValue Hint = Op.getOperand(6);
15267     unsigned HintVal;
15268     if (dyn_cast<ConstantSDNode> (Hint) == nullptr ||
15269         (HintVal = dyn_cast<ConstantSDNode> (Hint)->getZExtValue()) > 1)
15270       llvm_unreachable("Wrong prefetch hint in intrinsic: should be 0 or 1");
15271     unsigned Opcode = (HintVal ? IntrData->Opc1 : IntrData->Opc0);
15272     SDValue Chain = Op.getOperand(0);
15273     SDValue Mask  = Op.getOperand(2);
15274     SDValue Index = Op.getOperand(3);
15275     SDValue Base  = Op.getOperand(4);
15276     SDValue Scale = Op.getOperand(5);
15277     return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
15278   }
15279   // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
15280   case RDTSC: {
15281     SmallVector<SDValue, 2> Results;
15282     getReadTimeStampCounter(Op.getNode(), dl, IntrData->Opc0, DAG, Subtarget, Results);
15283     return DAG.getMergeValues(Results, dl);
15284   }
15285   // Read Performance Monitoring Counters.
15286   case RDPMC: {
15287     SmallVector<SDValue, 2> Results;
15288     getReadPerformanceCounter(Op.getNode(), dl, DAG, Subtarget, Results);
15289     return DAG.getMergeValues(Results, dl);
15290   }
15291   // XTEST intrinsics.
15292   case XTEST: {
15293     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
15294     SDValue InTrans = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
15295     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15296                                 DAG.getConstant(X86::COND_NE, MVT::i8),
15297                                 InTrans);
15298     SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
15299     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
15300                        Ret, SDValue(InTrans.getNode(), 1));
15301   }
15302   // ADC/ADCX/SBB
15303   case ADX: {
15304     SmallVector<SDValue, 2> Results;
15305     SDVTList CFVTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
15306     SDVTList VTs = DAG.getVTList(Op.getOperand(3)->getValueType(0), MVT::Other);
15307     SDValue GenCF = DAG.getNode(X86ISD::ADD, dl, CFVTs, Op.getOperand(2),
15308                                 DAG.getConstant(-1, MVT::i8));
15309     SDValue Res = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(3),
15310                               Op.getOperand(4), GenCF.getValue(1));
15311     SDValue Store = DAG.getStore(Op.getOperand(0), dl, Res.getValue(0),
15312                                  Op.getOperand(5), MachinePointerInfo(),
15313                                  false, false, 0);
15314     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15315                                 DAG.getConstant(X86::COND_B, MVT::i8),
15316                                 Res.getValue(1));
15317     Results.push_back(SetCC);
15318     Results.push_back(Store);
15319     return DAG.getMergeValues(Results, dl);
15320   }
15321   case COMPRESS_TO_MEM: {
15322     SDLoc dl(Op);
15323     SDValue Mask = Op.getOperand(4);
15324     SDValue DataToCompress = Op.getOperand(3);
15325     SDValue Addr = Op.getOperand(2);
15326     SDValue Chain = Op.getOperand(0);
15327
15328     if (isAllOnes(Mask)) // return just a store
15329       return DAG.getStore(Chain, dl, DataToCompress, Addr,
15330                           MachinePointerInfo(), false, false, 0);
15331
15332     EVT VT = DataToCompress.getValueType();
15333     EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15334                                   VT.getVectorNumElements());
15335     EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15336                                      Mask.getValueType().getSizeInBits());
15337     SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15338                                 DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
15339                                 DAG.getIntPtrConstant(0));
15340
15341     SDValue Compressed =  DAG.getNode(IntrData->Opc0, dl, VT, VMask,
15342                                       DataToCompress, DAG.getUNDEF(VT));
15343     return DAG.getStore(Chain, dl, Compressed, Addr,
15344                         MachinePointerInfo(), false, false, 0);
15345   }
15346   case EXPAND_FROM_MEM: {
15347     SDLoc dl(Op);
15348     SDValue Mask = Op.getOperand(4);
15349     SDValue PathThru = Op.getOperand(3);
15350     SDValue Addr = Op.getOperand(2);
15351     SDValue Chain = Op.getOperand(0);
15352     EVT VT = Op.getValueType();
15353
15354     if (isAllOnes(Mask)) // return just a load
15355       return DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(), false, false,
15356                          false, 0);
15357     EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15358                                   VT.getVectorNumElements());
15359     EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15360                                      Mask.getValueType().getSizeInBits());
15361     SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15362                                 DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
15363                                 DAG.getIntPtrConstant(0));
15364
15365     SDValue DataToExpand = DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(),
15366                                    false, false, false, 0);
15367
15368     SDValue Results[] = {
15369         DAG.getNode(IntrData->Opc0, dl, VT, VMask, DataToExpand, PathThru),
15370         Chain};
15371     return DAG.getMergeValues(Results, dl);
15372   }
15373   }
15374 }
15375
15376 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
15377                                            SelectionDAG &DAG) const {
15378   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
15379   MFI->setReturnAddressIsTaken(true);
15380
15381   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
15382     return SDValue();
15383
15384   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15385   SDLoc dl(Op);
15386   EVT PtrVT = getPointerTy();
15387
15388   if (Depth > 0) {
15389     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
15390     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15391     SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
15392     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
15393                        DAG.getNode(ISD::ADD, dl, PtrVT,
15394                                    FrameAddr, Offset),
15395                        MachinePointerInfo(), false, false, false, 0);
15396   }
15397
15398   // Just load the return address.
15399   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
15400   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
15401                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
15402 }
15403
15404 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
15405   MachineFunction &MF = DAG.getMachineFunction();
15406   MachineFrameInfo *MFI = MF.getFrameInfo();
15407   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
15408   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15409   EVT VT = Op.getValueType();
15410
15411   MFI->setFrameAddressIsTaken(true);
15412
15413   if (MF.getTarget().getMCAsmInfo()->usesWindowsCFI()) {
15414     // Depth > 0 makes no sense on targets which use Windows unwind codes.  It
15415     // is not possible to crawl up the stack without looking at the unwind codes
15416     // simultaneously.
15417     int FrameAddrIndex = FuncInfo->getFAIndex();
15418     if (!FrameAddrIndex) {
15419       // Set up a frame object for the return address.
15420       unsigned SlotSize = RegInfo->getSlotSize();
15421       FrameAddrIndex = MF.getFrameInfo()->CreateFixedObject(
15422           SlotSize, /*Offset=*/INT64_MIN, /*IsImmutable=*/false);
15423       FuncInfo->setFAIndex(FrameAddrIndex);
15424     }
15425     return DAG.getFrameIndex(FrameAddrIndex, VT);
15426   }
15427
15428   unsigned FrameReg =
15429       RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
15430   SDLoc dl(Op);  // FIXME probably not meaningful
15431   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15432   assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
15433           (FrameReg == X86::EBP && VT == MVT::i32)) &&
15434          "Invalid Frame Register!");
15435   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
15436   while (Depth--)
15437     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
15438                             MachinePointerInfo(),
15439                             false, false, false, 0);
15440   return FrameAddr;
15441 }
15442
15443 // FIXME? Maybe this could be a TableGen attribute on some registers and
15444 // this table could be generated automatically from RegInfo.
15445 unsigned X86TargetLowering::getRegisterByName(const char* RegName,
15446                                               EVT VT) const {
15447   unsigned Reg = StringSwitch<unsigned>(RegName)
15448                        .Case("esp", X86::ESP)
15449                        .Case("rsp", X86::RSP)
15450                        .Default(0);
15451   if (Reg)
15452     return Reg;
15453   report_fatal_error("Invalid register name global variable");
15454 }
15455
15456 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
15457                                                      SelectionDAG &DAG) const {
15458   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15459   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
15460 }
15461
15462 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
15463   SDValue Chain     = Op.getOperand(0);
15464   SDValue Offset    = Op.getOperand(1);
15465   SDValue Handler   = Op.getOperand(2);
15466   SDLoc dl      (Op);
15467
15468   EVT PtrVT = getPointerTy();
15469   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15470   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
15471   assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
15472           (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
15473          "Invalid Frame Register!");
15474   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
15475   unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
15476
15477   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
15478                                  DAG.getIntPtrConstant(RegInfo->getSlotSize()));
15479   StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
15480   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
15481                        false, false, 0);
15482   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
15483
15484   return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
15485                      DAG.getRegister(StoreAddrReg, PtrVT));
15486 }
15487
15488 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
15489                                                SelectionDAG &DAG) const {
15490   SDLoc DL(Op);
15491   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
15492                      DAG.getVTList(MVT::i32, MVT::Other),
15493                      Op.getOperand(0), Op.getOperand(1));
15494 }
15495
15496 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
15497                                                 SelectionDAG &DAG) const {
15498   SDLoc DL(Op);
15499   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
15500                      Op.getOperand(0), Op.getOperand(1));
15501 }
15502
15503 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
15504   return Op.getOperand(0);
15505 }
15506
15507 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
15508                                                 SelectionDAG &DAG) const {
15509   SDValue Root = Op.getOperand(0);
15510   SDValue Trmp = Op.getOperand(1); // trampoline
15511   SDValue FPtr = Op.getOperand(2); // nested function
15512   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
15513   SDLoc dl (Op);
15514
15515   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
15516   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
15517
15518   if (Subtarget->is64Bit()) {
15519     SDValue OutChains[6];
15520
15521     // Large code-model.
15522     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
15523     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
15524
15525     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
15526     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
15527
15528     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
15529
15530     // Load the pointer to the nested function into R11.
15531     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
15532     SDValue Addr = Trmp;
15533     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
15534                                 Addr, MachinePointerInfo(TrmpAddr),
15535                                 false, false, 0);
15536
15537     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15538                        DAG.getConstant(2, MVT::i64));
15539     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
15540                                 MachinePointerInfo(TrmpAddr, 2),
15541                                 false, false, 2);
15542
15543     // Load the 'nest' parameter value into R10.
15544     // R10 is specified in X86CallingConv.td
15545     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
15546     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15547                        DAG.getConstant(10, MVT::i64));
15548     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
15549                                 Addr, MachinePointerInfo(TrmpAddr, 10),
15550                                 false, false, 0);
15551
15552     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15553                        DAG.getConstant(12, MVT::i64));
15554     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
15555                                 MachinePointerInfo(TrmpAddr, 12),
15556                                 false, false, 2);
15557
15558     // Jump to the nested function.
15559     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
15560     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15561                        DAG.getConstant(20, MVT::i64));
15562     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
15563                                 Addr, MachinePointerInfo(TrmpAddr, 20),
15564                                 false, false, 0);
15565
15566     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
15567     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15568                        DAG.getConstant(22, MVT::i64));
15569     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
15570                                 MachinePointerInfo(TrmpAddr, 22),
15571                                 false, false, 0);
15572
15573     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
15574   } else {
15575     const Function *Func =
15576       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
15577     CallingConv::ID CC = Func->getCallingConv();
15578     unsigned NestReg;
15579
15580     switch (CC) {
15581     default:
15582       llvm_unreachable("Unsupported calling convention");
15583     case CallingConv::C:
15584     case CallingConv::X86_StdCall: {
15585       // Pass 'nest' parameter in ECX.
15586       // Must be kept in sync with X86CallingConv.td
15587       NestReg = X86::ECX;
15588
15589       // Check that ECX wasn't needed by an 'inreg' parameter.
15590       FunctionType *FTy = Func->getFunctionType();
15591       const AttributeSet &Attrs = Func->getAttributes();
15592
15593       if (!Attrs.isEmpty() && !Func->isVarArg()) {
15594         unsigned InRegCount = 0;
15595         unsigned Idx = 1;
15596
15597         for (FunctionType::param_iterator I = FTy->param_begin(),
15598              E = FTy->param_end(); I != E; ++I, ++Idx)
15599           if (Attrs.hasAttribute(Idx, Attribute::InReg))
15600             // FIXME: should only count parameters that are lowered to integers.
15601             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
15602
15603         if (InRegCount > 2) {
15604           report_fatal_error("Nest register in use - reduce number of inreg"
15605                              " parameters!");
15606         }
15607       }
15608       break;
15609     }
15610     case CallingConv::X86_FastCall:
15611     case CallingConv::X86_ThisCall:
15612     case CallingConv::Fast:
15613       // Pass 'nest' parameter in EAX.
15614       // Must be kept in sync with X86CallingConv.td
15615       NestReg = X86::EAX;
15616       break;
15617     }
15618
15619     SDValue OutChains[4];
15620     SDValue Addr, Disp;
15621
15622     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15623                        DAG.getConstant(10, MVT::i32));
15624     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
15625
15626     // This is storing the opcode for MOV32ri.
15627     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
15628     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
15629     OutChains[0] = DAG.getStore(Root, dl,
15630                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
15631                                 Trmp, MachinePointerInfo(TrmpAddr),
15632                                 false, false, 0);
15633
15634     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15635                        DAG.getConstant(1, MVT::i32));
15636     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
15637                                 MachinePointerInfo(TrmpAddr, 1),
15638                                 false, false, 1);
15639
15640     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
15641     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15642                        DAG.getConstant(5, MVT::i32));
15643     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
15644                                 MachinePointerInfo(TrmpAddr, 5),
15645                                 false, false, 1);
15646
15647     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15648                        DAG.getConstant(6, MVT::i32));
15649     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
15650                                 MachinePointerInfo(TrmpAddr, 6),
15651                                 false, false, 1);
15652
15653     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
15654   }
15655 }
15656
15657 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
15658                                             SelectionDAG &DAG) const {
15659   /*
15660    The rounding mode is in bits 11:10 of FPSR, and has the following
15661    settings:
15662      00 Round to nearest
15663      01 Round to -inf
15664      10 Round to +inf
15665      11 Round to 0
15666
15667   FLT_ROUNDS, on the other hand, expects the following:
15668     -1 Undefined
15669      0 Round to 0
15670      1 Round to nearest
15671      2 Round to +inf
15672      3 Round to -inf
15673
15674   To perform the conversion, we do:
15675     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
15676   */
15677
15678   MachineFunction &MF = DAG.getMachineFunction();
15679   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
15680   unsigned StackAlignment = TFI.getStackAlignment();
15681   MVT VT = Op.getSimpleValueType();
15682   SDLoc DL(Op);
15683
15684   // Save FP Control Word to stack slot
15685   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
15686   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
15687
15688   MachineMemOperand *MMO =
15689    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
15690                            MachineMemOperand::MOStore, 2, 2);
15691
15692   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
15693   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
15694                                           DAG.getVTList(MVT::Other),
15695                                           Ops, MVT::i16, MMO);
15696
15697   // Load FP Control Word from stack slot
15698   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
15699                             MachinePointerInfo(), false, false, false, 0);
15700
15701   // Transform as necessary
15702   SDValue CWD1 =
15703     DAG.getNode(ISD::SRL, DL, MVT::i16,
15704                 DAG.getNode(ISD::AND, DL, MVT::i16,
15705                             CWD, DAG.getConstant(0x800, MVT::i16)),
15706                 DAG.getConstant(11, MVT::i8));
15707   SDValue CWD2 =
15708     DAG.getNode(ISD::SRL, DL, MVT::i16,
15709                 DAG.getNode(ISD::AND, DL, MVT::i16,
15710                             CWD, DAG.getConstant(0x400, MVT::i16)),
15711                 DAG.getConstant(9, MVT::i8));
15712
15713   SDValue RetVal =
15714     DAG.getNode(ISD::AND, DL, MVT::i16,
15715                 DAG.getNode(ISD::ADD, DL, MVT::i16,
15716                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
15717                             DAG.getConstant(1, MVT::i16)),
15718                 DAG.getConstant(3, MVT::i16));
15719
15720   return DAG.getNode((VT.getSizeInBits() < 16 ?
15721                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
15722 }
15723
15724 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
15725   MVT VT = Op.getSimpleValueType();
15726   EVT OpVT = VT;
15727   unsigned NumBits = VT.getSizeInBits();
15728   SDLoc dl(Op);
15729
15730   Op = Op.getOperand(0);
15731   if (VT == MVT::i8) {
15732     // Zero extend to i32 since there is not an i8 bsr.
15733     OpVT = MVT::i32;
15734     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
15735   }
15736
15737   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
15738   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
15739   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
15740
15741   // If src is zero (i.e. bsr sets ZF), returns NumBits.
15742   SDValue Ops[] = {
15743     Op,
15744     DAG.getConstant(NumBits+NumBits-1, OpVT),
15745     DAG.getConstant(X86::COND_E, MVT::i8),
15746     Op.getValue(1)
15747   };
15748   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
15749
15750   // Finally xor with NumBits-1.
15751   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
15752
15753   if (VT == MVT::i8)
15754     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
15755   return Op;
15756 }
15757
15758 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
15759   MVT VT = Op.getSimpleValueType();
15760   EVT OpVT = VT;
15761   unsigned NumBits = VT.getSizeInBits();
15762   SDLoc dl(Op);
15763
15764   Op = Op.getOperand(0);
15765   if (VT == MVT::i8) {
15766     // Zero extend to i32 since there is not an i8 bsr.
15767     OpVT = MVT::i32;
15768     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
15769   }
15770
15771   // Issue a bsr (scan bits in reverse).
15772   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
15773   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
15774
15775   // And xor with NumBits-1.
15776   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
15777
15778   if (VT == MVT::i8)
15779     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
15780   return Op;
15781 }
15782
15783 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
15784   MVT VT = Op.getSimpleValueType();
15785   unsigned NumBits = VT.getSizeInBits();
15786   SDLoc dl(Op);
15787   Op = Op.getOperand(0);
15788
15789   // Issue a bsf (scan bits forward) which also sets EFLAGS.
15790   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
15791   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
15792
15793   // If src is zero (i.e. bsf sets ZF), returns NumBits.
15794   SDValue Ops[] = {
15795     Op,
15796     DAG.getConstant(NumBits, VT),
15797     DAG.getConstant(X86::COND_E, MVT::i8),
15798     Op.getValue(1)
15799   };
15800   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
15801 }
15802
15803 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
15804 // ones, and then concatenate the result back.
15805 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
15806   MVT VT = Op.getSimpleValueType();
15807
15808   assert(VT.is256BitVector() && VT.isInteger() &&
15809          "Unsupported value type for operation");
15810
15811   unsigned NumElems = VT.getVectorNumElements();
15812   SDLoc dl(Op);
15813
15814   // Extract the LHS vectors
15815   SDValue LHS = Op.getOperand(0);
15816   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
15817   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
15818
15819   // Extract the RHS vectors
15820   SDValue RHS = Op.getOperand(1);
15821   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
15822   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
15823
15824   MVT EltVT = VT.getVectorElementType();
15825   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
15826
15827   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
15828                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
15829                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
15830 }
15831
15832 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
15833   assert(Op.getSimpleValueType().is256BitVector() &&
15834          Op.getSimpleValueType().isInteger() &&
15835          "Only handle AVX 256-bit vector integer operation");
15836   return Lower256IntArith(Op, DAG);
15837 }
15838
15839 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
15840   assert(Op.getSimpleValueType().is256BitVector() &&
15841          Op.getSimpleValueType().isInteger() &&
15842          "Only handle AVX 256-bit vector integer operation");
15843   return Lower256IntArith(Op, DAG);
15844 }
15845
15846 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
15847                         SelectionDAG &DAG) {
15848   SDLoc dl(Op);
15849   MVT VT = Op.getSimpleValueType();
15850
15851   // Decompose 256-bit ops into smaller 128-bit ops.
15852   if (VT.is256BitVector() && !Subtarget->hasInt256())
15853     return Lower256IntArith(Op, DAG);
15854
15855   SDValue A = Op.getOperand(0);
15856   SDValue B = Op.getOperand(1);
15857
15858   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
15859   if (VT == MVT::v4i32) {
15860     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
15861            "Should not custom lower when pmuldq is available!");
15862
15863     // Extract the odd parts.
15864     static const int UnpackMask[] = { 1, -1, 3, -1 };
15865     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
15866     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
15867
15868     // Multiply the even parts.
15869     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
15870     // Now multiply odd parts.
15871     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
15872
15873     Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
15874     Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
15875
15876     // Merge the two vectors back together with a shuffle. This expands into 2
15877     // shuffles.
15878     static const int ShufMask[] = { 0, 4, 2, 6 };
15879     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
15880   }
15881
15882   assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
15883          "Only know how to lower V2I64/V4I64/V8I64 multiply");
15884
15885   //  Ahi = psrlqi(a, 32);
15886   //  Bhi = psrlqi(b, 32);
15887   //
15888   //  AloBlo = pmuludq(a, b);
15889   //  AloBhi = pmuludq(a, Bhi);
15890   //  AhiBlo = pmuludq(Ahi, b);
15891
15892   //  AloBhi = psllqi(AloBhi, 32);
15893   //  AhiBlo = psllqi(AhiBlo, 32);
15894   //  return AloBlo + AloBhi + AhiBlo;
15895
15896   SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
15897   SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
15898
15899   // Bit cast to 32-bit vectors for MULUDQ
15900   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
15901                                   (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
15902   A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
15903   B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
15904   Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
15905   Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
15906
15907   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
15908   SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
15909   SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
15910
15911   AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
15912   AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
15913
15914   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
15915   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
15916 }
15917
15918 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
15919   assert(Subtarget->isTargetWin64() && "Unexpected target");
15920   EVT VT = Op.getValueType();
15921   assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
15922          "Unexpected return type for lowering");
15923
15924   RTLIB::Libcall LC;
15925   bool isSigned;
15926   switch (Op->getOpcode()) {
15927   default: llvm_unreachable("Unexpected request for libcall!");
15928   case ISD::SDIV:      isSigned = true;  LC = RTLIB::SDIV_I128;    break;
15929   case ISD::UDIV:      isSigned = false; LC = RTLIB::UDIV_I128;    break;
15930   case ISD::SREM:      isSigned = true;  LC = RTLIB::SREM_I128;    break;
15931   case ISD::UREM:      isSigned = false; LC = RTLIB::UREM_I128;    break;
15932   case ISD::SDIVREM:   isSigned = true;  LC = RTLIB::SDIVREM_I128; break;
15933   case ISD::UDIVREM:   isSigned = false; LC = RTLIB::UDIVREM_I128; break;
15934   }
15935
15936   SDLoc dl(Op);
15937   SDValue InChain = DAG.getEntryNode();
15938
15939   TargetLowering::ArgListTy Args;
15940   TargetLowering::ArgListEntry Entry;
15941   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
15942     EVT ArgVT = Op->getOperand(i).getValueType();
15943     assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
15944            "Unexpected argument type for lowering");
15945     SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
15946     Entry.Node = StackPtr;
15947     InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
15948                            false, false, 16);
15949     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
15950     Entry.Ty = PointerType::get(ArgTy,0);
15951     Entry.isSExt = false;
15952     Entry.isZExt = false;
15953     Args.push_back(Entry);
15954   }
15955
15956   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
15957                                          getPointerTy());
15958
15959   TargetLowering::CallLoweringInfo CLI(DAG);
15960   CLI.setDebugLoc(dl).setChain(InChain)
15961     .setCallee(getLibcallCallingConv(LC),
15962                static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
15963                Callee, std::move(Args), 0)
15964     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
15965
15966   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
15967   return DAG.getNode(ISD::BITCAST, dl, VT, CallInfo.first);
15968 }
15969
15970 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
15971                              SelectionDAG &DAG) {
15972   SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
15973   EVT VT = Op0.getValueType();
15974   SDLoc dl(Op);
15975
15976   assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
15977          (VT == MVT::v8i32 && Subtarget->hasInt256()));
15978
15979   // PMULxD operations multiply each even value (starting at 0) of LHS with
15980   // the related value of RHS and produce a widen result.
15981   // E.g., PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
15982   // => <2 x i64> <ae|cg>
15983   //
15984   // In other word, to have all the results, we need to perform two PMULxD:
15985   // 1. one with the even values.
15986   // 2. one with the odd values.
15987   // To achieve #2, with need to place the odd values at an even position.
15988   //
15989   // Place the odd value at an even position (basically, shift all values 1
15990   // step to the left):
15991   const int Mask[] = {1, -1, 3, -1, 5, -1, 7, -1};
15992   // <a|b|c|d> => <b|undef|d|undef>
15993   SDValue Odd0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
15994   // <e|f|g|h> => <f|undef|h|undef>
15995   SDValue Odd1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
15996
15997   // Emit two multiplies, one for the lower 2 ints and one for the higher 2
15998   // ints.
15999   MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
16000   bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
16001   unsigned Opcode =
16002       (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
16003   // PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
16004   // => <2 x i64> <ae|cg>
16005   SDValue Mul1 = DAG.getNode(ISD::BITCAST, dl, VT,
16006                              DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
16007   // PMULUDQ <4 x i32> <b|undef|d|undef>, <4 x i32> <f|undef|h|undef>
16008   // => <2 x i64> <bf|dh>
16009   SDValue Mul2 = DAG.getNode(ISD::BITCAST, dl, VT,
16010                              DAG.getNode(Opcode, dl, MulVT, Odd0, Odd1));
16011
16012   // Shuffle it back into the right order.
16013   SDValue Highs, Lows;
16014   if (VT == MVT::v8i32) {
16015     const int HighMask[] = {1, 9, 3, 11, 5, 13, 7, 15};
16016     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
16017     const int LowMask[] = {0, 8, 2, 10, 4, 12, 6, 14};
16018     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
16019   } else {
16020     const int HighMask[] = {1, 5, 3, 7};
16021     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
16022     const int LowMask[] = {0, 4, 2, 6};
16023     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
16024   }
16025
16026   // If we have a signed multiply but no PMULDQ fix up the high parts of a
16027   // unsigned multiply.
16028   if (IsSigned && !Subtarget->hasSSE41()) {
16029     SDValue ShAmt =
16030         DAG.getConstant(31, DAG.getTargetLoweringInfo().getShiftAmountTy(VT));
16031     SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
16032                              DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
16033     SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
16034                              DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
16035
16036     SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
16037     Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
16038   }
16039
16040   // The first result of MUL_LOHI is actually the low value, followed by the
16041   // high value.
16042   SDValue Ops[] = {Lows, Highs};
16043   return DAG.getMergeValues(Ops, dl);
16044 }
16045
16046 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
16047                                          const X86Subtarget *Subtarget) {
16048   MVT VT = Op.getSimpleValueType();
16049   SDLoc dl(Op);
16050   SDValue R = Op.getOperand(0);
16051   SDValue Amt = Op.getOperand(1);
16052
16053   // Optimize shl/srl/sra with constant shift amount.
16054   if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
16055     if (auto *ShiftConst = BVAmt->getConstantSplatNode()) {
16056       uint64_t ShiftAmt = ShiftConst->getZExtValue();
16057
16058       if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
16059           (Subtarget->hasInt256() &&
16060            (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16)) ||
16061           (Subtarget->hasAVX512() &&
16062            (VT == MVT::v8i64 || VT == MVT::v16i32))) {
16063         if (Op.getOpcode() == ISD::SHL)
16064           return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
16065                                             DAG);
16066         if (Op.getOpcode() == ISD::SRL)
16067           return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
16068                                             DAG);
16069         if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
16070           return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
16071                                             DAG);
16072       }
16073
16074       if (VT == MVT::v16i8 || (Subtarget->hasInt256() && VT == MVT::v32i8)) {
16075         unsigned NumElts = VT.getVectorNumElements();
16076         MVT ShiftVT = MVT::getVectorVT(MVT::i16, NumElts / 2);
16077
16078         if (Op.getOpcode() == ISD::SHL) {
16079           // Make a large shift.
16080           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, ShiftVT,
16081                                                    R, ShiftAmt, DAG);
16082           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
16083           // Zero out the rightmost bits.
16084           SmallVector<SDValue, 32> V(
16085               NumElts, DAG.getConstant(uint8_t(-1U << ShiftAmt), MVT::i8));
16086           return DAG.getNode(ISD::AND, dl, VT, SHL,
16087                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
16088         }
16089         if (Op.getOpcode() == ISD::SRL) {
16090           // Make a large shift.
16091           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ShiftVT,
16092                                                    R, ShiftAmt, DAG);
16093           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
16094           // Zero out the leftmost bits.
16095           SmallVector<SDValue, 32> V(
16096               NumElts, DAG.getConstant(uint8_t(-1U) >> ShiftAmt, MVT::i8));
16097           return DAG.getNode(ISD::AND, dl, VT, SRL,
16098                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
16099         }
16100         if (Op.getOpcode() == ISD::SRA) {
16101           if (ShiftAmt == 7) {
16102             // R s>> 7  ===  R s< 0
16103             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
16104             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
16105           }
16106
16107           // R s>> a === ((R u>> a) ^ m) - m
16108           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
16109           SmallVector<SDValue, 32> V(NumElts,
16110                                      DAG.getConstant(128 >> ShiftAmt, MVT::i8));
16111           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
16112           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
16113           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
16114           return Res;
16115         }
16116         llvm_unreachable("Unknown shift opcode.");
16117       }
16118     }
16119   }
16120
16121   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
16122   if (!Subtarget->is64Bit() &&
16123       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
16124       Amt.getOpcode() == ISD::BITCAST &&
16125       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
16126     Amt = Amt.getOperand(0);
16127     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
16128                      VT.getVectorNumElements();
16129     unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
16130     uint64_t ShiftAmt = 0;
16131     for (unsigned i = 0; i != Ratio; ++i) {
16132       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
16133       if (!C)
16134         return SDValue();
16135       // 6 == Log2(64)
16136       ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
16137     }
16138     // Check remaining shift amounts.
16139     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
16140       uint64_t ShAmt = 0;
16141       for (unsigned j = 0; j != Ratio; ++j) {
16142         ConstantSDNode *C =
16143           dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
16144         if (!C)
16145           return SDValue();
16146         // 6 == Log2(64)
16147         ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
16148       }
16149       if (ShAmt != ShiftAmt)
16150         return SDValue();
16151     }
16152     switch (Op.getOpcode()) {
16153     default:
16154       llvm_unreachable("Unknown shift opcode!");
16155     case ISD::SHL:
16156       return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
16157                                         DAG);
16158     case ISD::SRL:
16159       return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
16160                                         DAG);
16161     case ISD::SRA:
16162       return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
16163                                         DAG);
16164     }
16165   }
16166
16167   return SDValue();
16168 }
16169
16170 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
16171                                         const X86Subtarget* Subtarget) {
16172   MVT VT = Op.getSimpleValueType();
16173   SDLoc dl(Op);
16174   SDValue R = Op.getOperand(0);
16175   SDValue Amt = Op.getOperand(1);
16176
16177   if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
16178       VT == MVT::v4i32 || VT == MVT::v8i16 ||
16179       (Subtarget->hasInt256() &&
16180        ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
16181         VT == MVT::v8i32 || VT == MVT::v16i16)) ||
16182        (Subtarget->hasAVX512() && (VT == MVT::v8i64 || VT == MVT::v16i32))) {
16183     SDValue BaseShAmt;
16184     EVT EltVT = VT.getVectorElementType();
16185
16186     if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Amt)) {
16187       // Check if this build_vector node is doing a splat.
16188       // If so, then set BaseShAmt equal to the splat value.
16189       BaseShAmt = BV->getSplatValue();
16190       if (BaseShAmt && BaseShAmt.getOpcode() == ISD::UNDEF)
16191         BaseShAmt = SDValue();
16192     } else {
16193       if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
16194         Amt = Amt.getOperand(0);
16195
16196       ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(Amt);
16197       if (SVN && SVN->isSplat()) {
16198         unsigned SplatIdx = (unsigned)SVN->getSplatIndex();
16199         SDValue InVec = Amt.getOperand(0);
16200         if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
16201           assert((SplatIdx < InVec.getValueType().getVectorNumElements()) &&
16202                  "Unexpected shuffle index found!");
16203           BaseShAmt = InVec.getOperand(SplatIdx);
16204         } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
16205            if (ConstantSDNode *C =
16206                dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
16207              if (C->getZExtValue() == SplatIdx)
16208                BaseShAmt = InVec.getOperand(1);
16209            }
16210         }
16211
16212         if (!BaseShAmt)
16213           // Avoid introducing an extract element from a shuffle.
16214           BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, InVec,
16215                                     DAG.getIntPtrConstant(SplatIdx));
16216       }
16217     }
16218
16219     if (BaseShAmt.getNode()) {
16220       assert(EltVT.bitsLE(MVT::i64) && "Unexpected element type!");
16221       if (EltVT != MVT::i64 && EltVT.bitsGT(MVT::i32))
16222         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, BaseShAmt);
16223       else if (EltVT.bitsLT(MVT::i32))
16224         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
16225
16226       switch (Op.getOpcode()) {
16227       default:
16228         llvm_unreachable("Unknown shift opcode!");
16229       case ISD::SHL:
16230         switch (VT.SimpleTy) {
16231         default: return SDValue();
16232         case MVT::v2i64:
16233         case MVT::v4i32:
16234         case MVT::v8i16:
16235         case MVT::v4i64:
16236         case MVT::v8i32:
16237         case MVT::v16i16:
16238         case MVT::v16i32:
16239         case MVT::v8i64:
16240           return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
16241         }
16242       case ISD::SRA:
16243         switch (VT.SimpleTy) {
16244         default: return SDValue();
16245         case MVT::v4i32:
16246         case MVT::v8i16:
16247         case MVT::v8i32:
16248         case MVT::v16i16:
16249         case MVT::v16i32:
16250         case MVT::v8i64:
16251           return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
16252         }
16253       case ISD::SRL:
16254         switch (VT.SimpleTy) {
16255         default: return SDValue();
16256         case MVT::v2i64:
16257         case MVT::v4i32:
16258         case MVT::v8i16:
16259         case MVT::v4i64:
16260         case MVT::v8i32:
16261         case MVT::v16i16:
16262         case MVT::v16i32:
16263         case MVT::v8i64:
16264           return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
16265         }
16266       }
16267     }
16268   }
16269
16270   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
16271   if (!Subtarget->is64Bit() &&
16272       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64) ||
16273       (Subtarget->hasAVX512() && VT == MVT::v8i64)) &&
16274       Amt.getOpcode() == ISD::BITCAST &&
16275       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
16276     Amt = Amt.getOperand(0);
16277     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
16278                      VT.getVectorNumElements();
16279     std::vector<SDValue> Vals(Ratio);
16280     for (unsigned i = 0; i != Ratio; ++i)
16281       Vals[i] = Amt.getOperand(i);
16282     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
16283       for (unsigned j = 0; j != Ratio; ++j)
16284         if (Vals[j] != Amt.getOperand(i + j))
16285           return SDValue();
16286     }
16287     switch (Op.getOpcode()) {
16288     default:
16289       llvm_unreachable("Unknown shift opcode!");
16290     case ISD::SHL:
16291       return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
16292     case ISD::SRL:
16293       return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
16294     case ISD::SRA:
16295       return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
16296     }
16297   }
16298
16299   return SDValue();
16300 }
16301
16302 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
16303                           SelectionDAG &DAG) {
16304   MVT VT = Op.getSimpleValueType();
16305   SDLoc dl(Op);
16306   SDValue R = Op.getOperand(0);
16307   SDValue Amt = Op.getOperand(1);
16308
16309   assert(VT.isVector() && "Custom lowering only for vector shifts!");
16310   assert(Subtarget->hasSSE2() && "Only custom lower when we have SSE2!");
16311
16312   if (SDValue V = LowerScalarImmediateShift(Op, DAG, Subtarget))
16313     return V;
16314
16315   if (SDValue V = LowerScalarVariableShift(Op, DAG, Subtarget))
16316       return V;
16317
16318   if (Subtarget->hasAVX512() && (VT == MVT::v16i32 || VT == MVT::v8i64))
16319     return Op;
16320
16321   // AVX2 has VPSLLV/VPSRAV/VPSRLV.
16322   if (Subtarget->hasInt256()) {
16323     if (Op.getOpcode() == ISD::SRL &&
16324         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
16325          VT == MVT::v4i64 || VT == MVT::v8i32))
16326       return Op;
16327     if (Op.getOpcode() == ISD::SHL &&
16328         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
16329          VT == MVT::v4i64 || VT == MVT::v8i32))
16330       return Op;
16331     if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
16332       return Op;
16333   }
16334
16335   // 2i64 vector logical shifts can efficiently avoid scalarization - do the
16336   // shifts per-lane and then shuffle the partial results back together.
16337   if (VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) {
16338     // Splat the shift amounts so the scalar shifts above will catch it.
16339     SDValue Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {0, 0});
16340     SDValue Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {1, 1});
16341     SDValue R0 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt0);
16342     SDValue R1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt1);
16343     return DAG.getVectorShuffle(VT, dl, R0, R1, {0, 3});
16344   }
16345
16346   // If possible, lower this packed shift into a vector multiply instead of
16347   // expanding it into a sequence of scalar shifts.
16348   // Do this only if the vector shift count is a constant build_vector.
16349   if (Op.getOpcode() == ISD::SHL &&
16350       (VT == MVT::v8i16 || VT == MVT::v4i32 ||
16351        (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
16352       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
16353     SmallVector<SDValue, 8> Elts;
16354     EVT SVT = VT.getScalarType();
16355     unsigned SVTBits = SVT.getSizeInBits();
16356     const APInt &One = APInt(SVTBits, 1);
16357     unsigned NumElems = VT.getVectorNumElements();
16358
16359     for (unsigned i=0; i !=NumElems; ++i) {
16360       SDValue Op = Amt->getOperand(i);
16361       if (Op->getOpcode() == ISD::UNDEF) {
16362         Elts.push_back(Op);
16363         continue;
16364       }
16365
16366       ConstantSDNode *ND = cast<ConstantSDNode>(Op);
16367       const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
16368       uint64_t ShAmt = C.getZExtValue();
16369       if (ShAmt >= SVTBits) {
16370         Elts.push_back(DAG.getUNDEF(SVT));
16371         continue;
16372       }
16373       Elts.push_back(DAG.getConstant(One.shl(ShAmt), SVT));
16374     }
16375     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
16376     return DAG.getNode(ISD::MUL, dl, VT, R, BV);
16377   }
16378
16379   // Lower SHL with variable shift amount.
16380   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
16381     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
16382
16383     Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
16384     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
16385     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
16386     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
16387   }
16388
16389   // If possible, lower this shift as a sequence of two shifts by
16390   // constant plus a MOVSS/MOVSD instead of scalarizing it.
16391   // Example:
16392   //   (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
16393   //
16394   // Could be rewritten as:
16395   //   (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
16396   //
16397   // The advantage is that the two shifts from the example would be
16398   // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
16399   // the vector shift into four scalar shifts plus four pairs of vector
16400   // insert/extract.
16401   if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
16402       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
16403     unsigned TargetOpcode = X86ISD::MOVSS;
16404     bool CanBeSimplified;
16405     // The splat value for the first packed shift (the 'X' from the example).
16406     SDValue Amt1 = Amt->getOperand(0);
16407     // The splat value for the second packed shift (the 'Y' from the example).
16408     SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
16409                                         Amt->getOperand(2);
16410
16411     // See if it is possible to replace this node with a sequence of
16412     // two shifts followed by a MOVSS/MOVSD
16413     if (VT == MVT::v4i32) {
16414       // Check if it is legal to use a MOVSS.
16415       CanBeSimplified = Amt2 == Amt->getOperand(2) &&
16416                         Amt2 == Amt->getOperand(3);
16417       if (!CanBeSimplified) {
16418         // Otherwise, check if we can still simplify this node using a MOVSD.
16419         CanBeSimplified = Amt1 == Amt->getOperand(1) &&
16420                           Amt->getOperand(2) == Amt->getOperand(3);
16421         TargetOpcode = X86ISD::MOVSD;
16422         Amt2 = Amt->getOperand(2);
16423       }
16424     } else {
16425       // Do similar checks for the case where the machine value type
16426       // is MVT::v8i16.
16427       CanBeSimplified = Amt1 == Amt->getOperand(1);
16428       for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
16429         CanBeSimplified = Amt2 == Amt->getOperand(i);
16430
16431       if (!CanBeSimplified) {
16432         TargetOpcode = X86ISD::MOVSD;
16433         CanBeSimplified = true;
16434         Amt2 = Amt->getOperand(4);
16435         for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
16436           CanBeSimplified = Amt1 == Amt->getOperand(i);
16437         for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
16438           CanBeSimplified = Amt2 == Amt->getOperand(j);
16439       }
16440     }
16441
16442     if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
16443         isa<ConstantSDNode>(Amt2)) {
16444       // Replace this node with two shifts followed by a MOVSS/MOVSD.
16445       EVT CastVT = MVT::v4i32;
16446       SDValue Splat1 =
16447         DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), VT);
16448       SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
16449       SDValue Splat2 =
16450         DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), VT);
16451       SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
16452       if (TargetOpcode == X86ISD::MOVSD)
16453         CastVT = MVT::v2i64;
16454       SDValue BitCast1 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift1);
16455       SDValue BitCast2 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift2);
16456       SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
16457                                             BitCast1, DAG);
16458       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
16459     }
16460   }
16461
16462   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
16463     assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
16464
16465     // a = a << 5;
16466     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
16467     Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
16468
16469     // Turn 'a' into a mask suitable for VSELECT
16470     SDValue VSelM = DAG.getConstant(0x80, VT);
16471     SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
16472     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
16473
16474     SDValue CM1 = DAG.getConstant(0x0f, VT);
16475     SDValue CM2 = DAG.getConstant(0x3f, VT);
16476
16477     // r = VSELECT(r, psllw(r & (char16)15, 4), a);
16478     SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
16479     M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 4, DAG);
16480     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
16481     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
16482
16483     // a += a
16484     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
16485     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
16486     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
16487
16488     // r = VSELECT(r, psllw(r & (char16)63, 2), a);
16489     M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
16490     M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 2, DAG);
16491     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
16492     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
16493
16494     // a += a
16495     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
16496     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
16497     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
16498
16499     // return VSELECT(r, r+r, a);
16500     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
16501                     DAG.getNode(ISD::ADD, dl, VT, R, R), R);
16502     return R;
16503   }
16504
16505   // It's worth extending once and using the v8i32 shifts for 16-bit types, but
16506   // the extra overheads to get from v16i8 to v8i32 make the existing SSE
16507   // solution better.
16508   if (Subtarget->hasInt256() && VT == MVT::v8i16) {
16509     MVT NewVT = VT == MVT::v8i16 ? MVT::v8i32 : MVT::v16i16;
16510     unsigned ExtOpc =
16511         Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
16512     R = DAG.getNode(ExtOpc, dl, NewVT, R);
16513     Amt = DAG.getNode(ISD::ANY_EXTEND, dl, NewVT, Amt);
16514     return DAG.getNode(ISD::TRUNCATE, dl, VT,
16515                        DAG.getNode(Op.getOpcode(), dl, NewVT, R, Amt));
16516   }
16517
16518   // Decompose 256-bit shifts into smaller 128-bit shifts.
16519   if (VT.is256BitVector()) {
16520     unsigned NumElems = VT.getVectorNumElements();
16521     MVT EltVT = VT.getVectorElementType();
16522     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
16523
16524     // Extract the two vectors
16525     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
16526     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
16527
16528     // Recreate the shift amount vectors
16529     SDValue Amt1, Amt2;
16530     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
16531       // Constant shift amount
16532       SmallVector<SDValue, 8> Ops(Amt->op_begin(), Amt->op_begin() + NumElems);
16533       ArrayRef<SDValue> Amt1Csts = makeArrayRef(Ops).slice(0, NumElems / 2);
16534       ArrayRef<SDValue> Amt2Csts = makeArrayRef(Ops).slice(NumElems / 2);
16535
16536       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
16537       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
16538     } else {
16539       // Variable shift amount
16540       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
16541       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
16542     }
16543
16544     // Issue new vector shifts for the smaller types
16545     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
16546     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
16547
16548     // Concatenate the result back
16549     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
16550   }
16551
16552   return SDValue();
16553 }
16554
16555 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
16556   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
16557   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
16558   // looks for this combo and may remove the "setcc" instruction if the "setcc"
16559   // has only one use.
16560   SDNode *N = Op.getNode();
16561   SDValue LHS = N->getOperand(0);
16562   SDValue RHS = N->getOperand(1);
16563   unsigned BaseOp = 0;
16564   unsigned Cond = 0;
16565   SDLoc DL(Op);
16566   switch (Op.getOpcode()) {
16567   default: llvm_unreachable("Unknown ovf instruction!");
16568   case ISD::SADDO:
16569     // A subtract of one will be selected as a INC. Note that INC doesn't
16570     // set CF, so we can't do this for UADDO.
16571     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
16572       if (C->isOne()) {
16573         BaseOp = X86ISD::INC;
16574         Cond = X86::COND_O;
16575         break;
16576       }
16577     BaseOp = X86ISD::ADD;
16578     Cond = X86::COND_O;
16579     break;
16580   case ISD::UADDO:
16581     BaseOp = X86ISD::ADD;
16582     Cond = X86::COND_B;
16583     break;
16584   case ISD::SSUBO:
16585     // A subtract of one will be selected as a DEC. Note that DEC doesn't
16586     // set CF, so we can't do this for USUBO.
16587     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
16588       if (C->isOne()) {
16589         BaseOp = X86ISD::DEC;
16590         Cond = X86::COND_O;
16591         break;
16592       }
16593     BaseOp = X86ISD::SUB;
16594     Cond = X86::COND_O;
16595     break;
16596   case ISD::USUBO:
16597     BaseOp = X86ISD::SUB;
16598     Cond = X86::COND_B;
16599     break;
16600   case ISD::SMULO:
16601     BaseOp = N->getValueType(0) == MVT::i8 ? X86ISD::SMUL8 : X86ISD::SMUL;
16602     Cond = X86::COND_O;
16603     break;
16604   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
16605     if (N->getValueType(0) == MVT::i8) {
16606       BaseOp = X86ISD::UMUL8;
16607       Cond = X86::COND_O;
16608       break;
16609     }
16610     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
16611                                  MVT::i32);
16612     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
16613
16614     SDValue SetCC =
16615       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
16616                   DAG.getConstant(X86::COND_O, MVT::i32),
16617                   SDValue(Sum.getNode(), 2));
16618
16619     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
16620   }
16621   }
16622
16623   // Also sets EFLAGS.
16624   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
16625   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
16626
16627   SDValue SetCC =
16628     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
16629                 DAG.getConstant(Cond, MVT::i32),
16630                 SDValue(Sum.getNode(), 1));
16631
16632   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
16633 }
16634
16635 /// Returns true if the operand type is exactly twice the native width, and
16636 /// the corresponding cmpxchg8b or cmpxchg16b instruction is available.
16637 /// Used to know whether to use cmpxchg8/16b when expanding atomic operations
16638 /// (otherwise we leave them alone to become __sync_fetch_and_... calls).
16639 bool X86TargetLowering::needsCmpXchgNb(const Type *MemType) const {
16640   unsigned OpWidth = MemType->getPrimitiveSizeInBits();
16641
16642   if (OpWidth == 64)
16643     return !Subtarget->is64Bit(); // FIXME this should be Subtarget.hasCmpxchg8b
16644   else if (OpWidth == 128)
16645     return Subtarget->hasCmpxchg16b();
16646   else
16647     return false;
16648 }
16649
16650 bool X86TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
16651   return needsCmpXchgNb(SI->getValueOperand()->getType());
16652 }
16653
16654 // Note: this turns large loads into lock cmpxchg8b/16b.
16655 // FIXME: On 32 bits x86, fild/movq might be faster than lock cmpxchg8b.
16656 bool X86TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
16657   auto PTy = cast<PointerType>(LI->getPointerOperand()->getType());
16658   return needsCmpXchgNb(PTy->getElementType());
16659 }
16660
16661 TargetLoweringBase::AtomicRMWExpansionKind
16662 X86TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
16663   unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
16664   const Type *MemType = AI->getType();
16665
16666   // If the operand is too big, we must see if cmpxchg8/16b is available
16667   // and default to library calls otherwise.
16668   if (MemType->getPrimitiveSizeInBits() > NativeWidth) {
16669     return needsCmpXchgNb(MemType) ? AtomicRMWExpansionKind::CmpXChg
16670                                    : AtomicRMWExpansionKind::None;
16671   }
16672
16673   AtomicRMWInst::BinOp Op = AI->getOperation();
16674   switch (Op) {
16675   default:
16676     llvm_unreachable("Unknown atomic operation");
16677   case AtomicRMWInst::Xchg:
16678   case AtomicRMWInst::Add:
16679   case AtomicRMWInst::Sub:
16680     // It's better to use xadd, xsub or xchg for these in all cases.
16681     return AtomicRMWExpansionKind::None;
16682   case AtomicRMWInst::Or:
16683   case AtomicRMWInst::And:
16684   case AtomicRMWInst::Xor:
16685     // If the atomicrmw's result isn't actually used, we can just add a "lock"
16686     // prefix to a normal instruction for these operations.
16687     return !AI->use_empty() ? AtomicRMWExpansionKind::CmpXChg
16688                             : AtomicRMWExpansionKind::None;
16689   case AtomicRMWInst::Nand:
16690   case AtomicRMWInst::Max:
16691   case AtomicRMWInst::Min:
16692   case AtomicRMWInst::UMax:
16693   case AtomicRMWInst::UMin:
16694     // These always require a non-trivial set of data operations on x86. We must
16695     // use a cmpxchg loop.
16696     return AtomicRMWExpansionKind::CmpXChg;
16697   }
16698 }
16699
16700 static bool hasMFENCE(const X86Subtarget& Subtarget) {
16701   // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
16702   // no-sse2). There isn't any reason to disable it if the target processor
16703   // supports it.
16704   return Subtarget.hasSSE2() || Subtarget.is64Bit();
16705 }
16706
16707 LoadInst *
16708 X86TargetLowering::lowerIdempotentRMWIntoFencedLoad(AtomicRMWInst *AI) const {
16709   unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
16710   const Type *MemType = AI->getType();
16711   // Accesses larger than the native width are turned into cmpxchg/libcalls, so
16712   // there is no benefit in turning such RMWs into loads, and it is actually
16713   // harmful as it introduces a mfence.
16714   if (MemType->getPrimitiveSizeInBits() > NativeWidth)
16715     return nullptr;
16716
16717   auto Builder = IRBuilder<>(AI);
16718   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
16719   auto SynchScope = AI->getSynchScope();
16720   // We must restrict the ordering to avoid generating loads with Release or
16721   // ReleaseAcquire orderings.
16722   auto Order = AtomicCmpXchgInst::getStrongestFailureOrdering(AI->getOrdering());
16723   auto Ptr = AI->getPointerOperand();
16724
16725   // Before the load we need a fence. Here is an example lifted from
16726   // http://www.hpl.hp.com/techreports/2012/HPL-2012-68.pdf showing why a fence
16727   // is required:
16728   // Thread 0:
16729   //   x.store(1, relaxed);
16730   //   r1 = y.fetch_add(0, release);
16731   // Thread 1:
16732   //   y.fetch_add(42, acquire);
16733   //   r2 = x.load(relaxed);
16734   // r1 = r2 = 0 is impossible, but becomes possible if the idempotent rmw is
16735   // lowered to just a load without a fence. A mfence flushes the store buffer,
16736   // making the optimization clearly correct.
16737   // FIXME: it is required if isAtLeastRelease(Order) but it is not clear
16738   // otherwise, we might be able to be more agressive on relaxed idempotent
16739   // rmw. In practice, they do not look useful, so we don't try to be
16740   // especially clever.
16741   if (SynchScope == SingleThread) {
16742     // FIXME: we could just insert an X86ISD::MEMBARRIER here, except we are at
16743     // the IR level, so we must wrap it in an intrinsic.
16744     return nullptr;
16745   } else if (hasMFENCE(*Subtarget)) {
16746     Function *MFence = llvm::Intrinsic::getDeclaration(M,
16747             Intrinsic::x86_sse2_mfence);
16748     Builder.CreateCall(MFence);
16749   } else {
16750     // FIXME: it might make sense to use a locked operation here but on a
16751     // different cache-line to prevent cache-line bouncing. In practice it
16752     // is probably a small win, and x86 processors without mfence are rare
16753     // enough that we do not bother.
16754     return nullptr;
16755   }
16756
16757   // Finally we can emit the atomic load.
16758   LoadInst *Loaded = Builder.CreateAlignedLoad(Ptr,
16759           AI->getType()->getPrimitiveSizeInBits());
16760   Loaded->setAtomic(Order, SynchScope);
16761   AI->replaceAllUsesWith(Loaded);
16762   AI->eraseFromParent();
16763   return Loaded;
16764 }
16765
16766 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
16767                                  SelectionDAG &DAG) {
16768   SDLoc dl(Op);
16769   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
16770     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
16771   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
16772     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
16773
16774   // The only fence that needs an instruction is a sequentially-consistent
16775   // cross-thread fence.
16776   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
16777     if (hasMFENCE(*Subtarget))
16778       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
16779
16780     SDValue Chain = Op.getOperand(0);
16781     SDValue Zero = DAG.getConstant(0, MVT::i32);
16782     SDValue Ops[] = {
16783       DAG.getRegister(X86::ESP, MVT::i32), // Base
16784       DAG.getTargetConstant(1, MVT::i8),   // Scale
16785       DAG.getRegister(0, MVT::i32),        // Index
16786       DAG.getTargetConstant(0, MVT::i32),  // Disp
16787       DAG.getRegister(0, MVT::i32),        // Segment.
16788       Zero,
16789       Chain
16790     };
16791     SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
16792     return SDValue(Res, 0);
16793   }
16794
16795   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
16796   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
16797 }
16798
16799 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
16800                              SelectionDAG &DAG) {
16801   MVT T = Op.getSimpleValueType();
16802   SDLoc DL(Op);
16803   unsigned Reg = 0;
16804   unsigned size = 0;
16805   switch(T.SimpleTy) {
16806   default: llvm_unreachable("Invalid value type!");
16807   case MVT::i8:  Reg = X86::AL;  size = 1; break;
16808   case MVT::i16: Reg = X86::AX;  size = 2; break;
16809   case MVT::i32: Reg = X86::EAX; size = 4; break;
16810   case MVT::i64:
16811     assert(Subtarget->is64Bit() && "Node not type legal!");
16812     Reg = X86::RAX; size = 8;
16813     break;
16814   }
16815   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
16816                                   Op.getOperand(2), SDValue());
16817   SDValue Ops[] = { cpIn.getValue(0),
16818                     Op.getOperand(1),
16819                     Op.getOperand(3),
16820                     DAG.getTargetConstant(size, MVT::i8),
16821                     cpIn.getValue(1) };
16822   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
16823   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
16824   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
16825                                            Ops, T, MMO);
16826
16827   SDValue cpOut =
16828     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
16829   SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
16830                                       MVT::i32, cpOut.getValue(2));
16831   SDValue Success = DAG.getNode(X86ISD::SETCC, DL, Op->getValueType(1),
16832                                 DAG.getConstant(X86::COND_E, MVT::i8), EFLAGS);
16833
16834   DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), cpOut);
16835   DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
16836   DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), EFLAGS.getValue(1));
16837   return SDValue();
16838 }
16839
16840 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
16841                             SelectionDAG &DAG) {
16842   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
16843   MVT DstVT = Op.getSimpleValueType();
16844
16845   if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
16846     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
16847     if (DstVT != MVT::f64)
16848       // This conversion needs to be expanded.
16849       return SDValue();
16850
16851     SDValue InVec = Op->getOperand(0);
16852     SDLoc dl(Op);
16853     unsigned NumElts = SrcVT.getVectorNumElements();
16854     EVT SVT = SrcVT.getVectorElementType();
16855
16856     // Widen the vector in input in the case of MVT::v2i32.
16857     // Example: from MVT::v2i32 to MVT::v4i32.
16858     SmallVector<SDValue, 16> Elts;
16859     for (unsigned i = 0, e = NumElts; i != e; ++i)
16860       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
16861                                  DAG.getIntPtrConstant(i)));
16862
16863     // Explicitly mark the extra elements as Undef.
16864     Elts.append(NumElts, DAG.getUNDEF(SVT));
16865
16866     EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
16867     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
16868     SDValue ToV2F64 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, BV);
16869     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
16870                        DAG.getIntPtrConstant(0));
16871   }
16872
16873   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
16874          Subtarget->hasMMX() && "Unexpected custom BITCAST");
16875   assert((DstVT == MVT::i64 ||
16876           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
16877          "Unexpected custom BITCAST");
16878   // i64 <=> MMX conversions are Legal.
16879   if (SrcVT==MVT::i64 && DstVT.isVector())
16880     return Op;
16881   if (DstVT==MVT::i64 && SrcVT.isVector())
16882     return Op;
16883   // MMX <=> MMX conversions are Legal.
16884   if (SrcVT.isVector() && DstVT.isVector())
16885     return Op;
16886   // All other conversions need to be expanded.
16887   return SDValue();
16888 }
16889
16890 static SDValue LowerCTPOP(SDValue Op, const X86Subtarget *Subtarget,
16891                           SelectionDAG &DAG) {
16892   SDNode *Node = Op.getNode();
16893   SDLoc dl(Node);
16894
16895   Op = Op.getOperand(0);
16896   EVT VT = Op.getValueType();
16897   assert((VT.is128BitVector() || VT.is256BitVector()) &&
16898          "CTPOP lowering only implemented for 128/256-bit wide vector types");
16899
16900   unsigned NumElts = VT.getVectorNumElements();
16901   EVT EltVT = VT.getVectorElementType();
16902   unsigned Len = EltVT.getSizeInBits();
16903
16904   // This is the vectorized version of the "best" algorithm from
16905   // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
16906   // with a minor tweak to use a series of adds + shifts instead of vector
16907   // multiplications. Implemented for the v2i64, v4i64, v4i32, v8i32 types:
16908   //
16909   //  v2i64, v4i64, v4i32 => Only profitable w/ popcnt disabled
16910   //  v8i32 => Always profitable
16911   //
16912   // FIXME: There a couple of possible improvements:
16913   //
16914   // 1) Support for i8 and i16 vectors (needs measurements if popcnt enabled).
16915   // 2) Use strategies from http://wm.ite.pl/articles/sse-popcount.html
16916   //
16917   assert(EltVT.isInteger() && (Len == 32 || Len == 64) && Len % 8 == 0 &&
16918          "CTPOP not implemented for this vector element type.");
16919
16920   // X86 canonicalize ANDs to vXi64, generate the appropriate bitcasts to avoid
16921   // extra legalization.
16922   bool NeedsBitcast = EltVT == MVT::i32;
16923   MVT BitcastVT = VT.is256BitVector() ? MVT::v4i64 : MVT::v2i64;
16924
16925   SDValue Cst55 = DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x55)), EltVT);
16926   SDValue Cst33 = DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x33)), EltVT);
16927   SDValue Cst0F = DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x0F)), EltVT);
16928
16929   // v = v - ((v >> 1) & 0x55555555...)
16930   SmallVector<SDValue, 8> Ones(NumElts, DAG.getConstant(1, EltVT));
16931   SDValue OnesV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ones);
16932   SDValue Srl = DAG.getNode(ISD::SRL, dl, VT, Op, OnesV);
16933   if (NeedsBitcast)
16934     Srl = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Srl);
16935
16936   SmallVector<SDValue, 8> Mask55(NumElts, Cst55);
16937   SDValue M55 = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Mask55);
16938   if (NeedsBitcast)
16939     M55 = DAG.getNode(ISD::BITCAST, dl, BitcastVT, M55);
16940
16941   SDValue And = DAG.getNode(ISD::AND, dl, Srl.getValueType(), Srl, M55);
16942   if (VT != And.getValueType())
16943     And = DAG.getNode(ISD::BITCAST, dl, VT, And);
16944   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, Op, And);
16945
16946   // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...)
16947   SmallVector<SDValue, 8> Mask33(NumElts, Cst33);
16948   SDValue M33 = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Mask33);
16949   SmallVector<SDValue, 8> Twos(NumElts, DAG.getConstant(2, EltVT));
16950   SDValue TwosV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Twos);
16951
16952   Srl = DAG.getNode(ISD::SRL, dl, VT, Sub, TwosV);
16953   if (NeedsBitcast) {
16954     Srl = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Srl);
16955     M33 = DAG.getNode(ISD::BITCAST, dl, BitcastVT, M33);
16956     Sub = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Sub);
16957   }
16958
16959   SDValue AndRHS = DAG.getNode(ISD::AND, dl, M33.getValueType(), Srl, M33);
16960   SDValue AndLHS = DAG.getNode(ISD::AND, dl, M33.getValueType(), Sub, M33);
16961   if (VT != AndRHS.getValueType()) {
16962     AndRHS = DAG.getNode(ISD::BITCAST, dl, VT, AndRHS);
16963     AndLHS = DAG.getNode(ISD::BITCAST, dl, VT, AndLHS);
16964   }
16965   SDValue Add = DAG.getNode(ISD::ADD, dl, VT, AndLHS, AndRHS);
16966
16967   // v = (v + (v >> 4)) & 0x0F0F0F0F...
16968   SmallVector<SDValue, 8> Fours(NumElts, DAG.getConstant(4, EltVT));
16969   SDValue FoursV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Fours);
16970   Srl = DAG.getNode(ISD::SRL, dl, VT, Add, FoursV);
16971   Add = DAG.getNode(ISD::ADD, dl, VT, Add, Srl);
16972
16973   SmallVector<SDValue, 8> Mask0F(NumElts, Cst0F);
16974   SDValue M0F = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Mask0F);
16975   if (NeedsBitcast) {
16976     Add = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Add);
16977     M0F = DAG.getNode(ISD::BITCAST, dl, BitcastVT, M0F);
16978   }
16979   And = DAG.getNode(ISD::AND, dl, M0F.getValueType(), Add, M0F);
16980   if (VT != And.getValueType())
16981     And = DAG.getNode(ISD::BITCAST, dl, VT, And);
16982
16983   // The algorithm mentioned above uses:
16984   //    v = (v * 0x01010101...) >> (Len - 8)
16985   //
16986   // Change it to use vector adds + vector shifts which yield faster results on
16987   // Haswell than using vector integer multiplication.
16988   //
16989   // For i32 elements:
16990   //    v = v + (v >> 8)
16991   //    v = v + (v >> 16)
16992   //
16993   // For i64 elements:
16994   //    v = v + (v >> 8)
16995   //    v = v + (v >> 16)
16996   //    v = v + (v >> 32)
16997   //
16998   Add = And;
16999   SmallVector<SDValue, 8> Csts;
17000   for (unsigned i = 8; i <= Len/2; i *= 2) {
17001     Csts.assign(NumElts, DAG.getConstant(i, EltVT));
17002     SDValue CstsV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Csts);
17003     Srl = DAG.getNode(ISD::SRL, dl, VT, Add, CstsV);
17004     Add = DAG.getNode(ISD::ADD, dl, VT, Add, Srl);
17005     Csts.clear();
17006   }
17007
17008   // The result is on the least significant 6-bits on i32 and 7-bits on i64.
17009   SDValue Cst3F = DAG.getConstant(APInt(Len, Len == 32 ? 0x3F : 0x7F), EltVT);
17010   SmallVector<SDValue, 8> Cst3FV(NumElts, Cst3F);
17011   SDValue M3F = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Cst3FV);
17012   if (NeedsBitcast) {
17013     Add = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Add);
17014     M3F = DAG.getNode(ISD::BITCAST, dl, BitcastVT, M3F);
17015   }
17016   And = DAG.getNode(ISD::AND, dl, M3F.getValueType(), Add, M3F);
17017   if (VT != And.getValueType())
17018     And = DAG.getNode(ISD::BITCAST, dl, VT, And);
17019
17020   return And;
17021 }
17022
17023 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
17024   SDNode *Node = Op.getNode();
17025   SDLoc dl(Node);
17026   EVT T = Node->getValueType(0);
17027   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
17028                               DAG.getConstant(0, T), Node->getOperand(2));
17029   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
17030                        cast<AtomicSDNode>(Node)->getMemoryVT(),
17031                        Node->getOperand(0),
17032                        Node->getOperand(1), negOp,
17033                        cast<AtomicSDNode>(Node)->getMemOperand(),
17034                        cast<AtomicSDNode>(Node)->getOrdering(),
17035                        cast<AtomicSDNode>(Node)->getSynchScope());
17036 }
17037
17038 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
17039   SDNode *Node = Op.getNode();
17040   SDLoc dl(Node);
17041   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
17042
17043   // Convert seq_cst store -> xchg
17044   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
17045   // FIXME: On 32-bit, store -> fist or movq would be more efficient
17046   //        (The only way to get a 16-byte store is cmpxchg16b)
17047   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
17048   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
17049       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
17050     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
17051                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
17052                                  Node->getOperand(0),
17053                                  Node->getOperand(1), Node->getOperand(2),
17054                                  cast<AtomicSDNode>(Node)->getMemOperand(),
17055                                  cast<AtomicSDNode>(Node)->getOrdering(),
17056                                  cast<AtomicSDNode>(Node)->getSynchScope());
17057     return Swap.getValue(1);
17058   }
17059   // Other atomic stores have a simple pattern.
17060   return Op;
17061 }
17062
17063 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
17064   EVT VT = Op.getNode()->getSimpleValueType(0);
17065
17066   // Let legalize expand this if it isn't a legal type yet.
17067   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
17068     return SDValue();
17069
17070   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
17071
17072   unsigned Opc;
17073   bool ExtraOp = false;
17074   switch (Op.getOpcode()) {
17075   default: llvm_unreachable("Invalid code");
17076   case ISD::ADDC: Opc = X86ISD::ADD; break;
17077   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
17078   case ISD::SUBC: Opc = X86ISD::SUB; break;
17079   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
17080   }
17081
17082   if (!ExtraOp)
17083     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
17084                        Op.getOperand(1));
17085   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
17086                      Op.getOperand(1), Op.getOperand(2));
17087 }
17088
17089 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
17090                             SelectionDAG &DAG) {
17091   assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
17092
17093   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
17094   // which returns the values as { float, float } (in XMM0) or
17095   // { double, double } (which is returned in XMM0, XMM1).
17096   SDLoc dl(Op);
17097   SDValue Arg = Op.getOperand(0);
17098   EVT ArgVT = Arg.getValueType();
17099   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
17100
17101   TargetLowering::ArgListTy Args;
17102   TargetLowering::ArgListEntry Entry;
17103
17104   Entry.Node = Arg;
17105   Entry.Ty = ArgTy;
17106   Entry.isSExt = false;
17107   Entry.isZExt = false;
17108   Args.push_back(Entry);
17109
17110   bool isF64 = ArgVT == MVT::f64;
17111   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
17112   // the small struct {f32, f32} is returned in (eax, edx). For f64,
17113   // the results are returned via SRet in memory.
17114   const char *LibcallName =  isF64 ? "__sincos_stret" : "__sincosf_stret";
17115   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17116   SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy());
17117
17118   Type *RetTy = isF64
17119     ? (Type*)StructType::get(ArgTy, ArgTy, nullptr)
17120     : (Type*)VectorType::get(ArgTy, 4);
17121
17122   TargetLowering::CallLoweringInfo CLI(DAG);
17123   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
17124     .setCallee(CallingConv::C, RetTy, Callee, std::move(Args), 0);
17125
17126   std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
17127
17128   if (isF64)
17129     // Returned in xmm0 and xmm1.
17130     return CallResult.first;
17131
17132   // Returned in bits 0:31 and 32:64 xmm0.
17133   SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
17134                                CallResult.first, DAG.getIntPtrConstant(0));
17135   SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
17136                                CallResult.first, DAG.getIntPtrConstant(1));
17137   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
17138   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
17139 }
17140
17141 /// LowerOperation - Provide custom lowering hooks for some operations.
17142 ///
17143 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
17144   switch (Op.getOpcode()) {
17145   default: llvm_unreachable("Should not custom lower this!");
17146   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
17147   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
17148     return LowerCMP_SWAP(Op, Subtarget, DAG);
17149   case ISD::CTPOP:              return LowerCTPOP(Op, Subtarget, DAG);
17150   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
17151   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
17152   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
17153   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, Subtarget, DAG);
17154   case ISD::VECTOR_SHUFFLE:     return lowerVectorShuffle(Op, Subtarget, DAG);
17155   case ISD::VSELECT:            return LowerVSELECT(Op, DAG);
17156   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
17157   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
17158   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
17159   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
17160   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
17161   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
17162   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
17163   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
17164   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
17165   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
17166   case ISD::SHL_PARTS:
17167   case ISD::SRA_PARTS:
17168   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
17169   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
17170   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
17171   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
17172   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, Subtarget, DAG);
17173   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, Subtarget, DAG);
17174   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, Subtarget, DAG);
17175   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
17176   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
17177   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
17178   case ISD::LOAD:               return LowerExtendedLoad(Op, Subtarget, DAG);
17179   case ISD::FABS:
17180   case ISD::FNEG:               return LowerFABSorFNEG(Op, DAG);
17181   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
17182   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
17183   case ISD::SETCC:              return LowerSETCC(Op, DAG);
17184   case ISD::SELECT:             return LowerSELECT(Op, DAG);
17185   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
17186   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
17187   case ISD::VASTART:            return LowerVASTART(Op, DAG);
17188   case ISD::VAARG:              return LowerVAARG(Op, DAG);
17189   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
17190   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, Subtarget, DAG);
17191   case ISD::INTRINSIC_VOID:
17192   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
17193   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
17194   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
17195   case ISD::FRAME_TO_ARGS_OFFSET:
17196                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
17197   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
17198   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
17199   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
17200   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
17201   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
17202   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
17203   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
17204   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
17205   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
17206   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
17207   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
17208   case ISD::UMUL_LOHI:
17209   case ISD::SMUL_LOHI:          return LowerMUL_LOHI(Op, Subtarget, DAG);
17210   case ISD::SRA:
17211   case ISD::SRL:
17212   case ISD::SHL:                return LowerShift(Op, Subtarget, DAG);
17213   case ISD::SADDO:
17214   case ISD::UADDO:
17215   case ISD::SSUBO:
17216   case ISD::USUBO:
17217   case ISD::SMULO:
17218   case ISD::UMULO:              return LowerXALUO(Op, DAG);
17219   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
17220   case ISD::BITCAST:            return LowerBITCAST(Op, Subtarget, DAG);
17221   case ISD::ADDC:
17222   case ISD::ADDE:
17223   case ISD::SUBC:
17224   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
17225   case ISD::ADD:                return LowerADD(Op, DAG);
17226   case ISD::SUB:                return LowerSUB(Op, DAG);
17227   case ISD::FSINCOS:            return LowerFSINCOS(Op, Subtarget, DAG);
17228   }
17229 }
17230
17231 /// ReplaceNodeResults - Replace a node with an illegal result type
17232 /// with a new node built out of custom code.
17233 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
17234                                            SmallVectorImpl<SDValue>&Results,
17235                                            SelectionDAG &DAG) const {
17236   SDLoc dl(N);
17237   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17238   switch (N->getOpcode()) {
17239   default:
17240     llvm_unreachable("Do not know how to custom type legalize this operation!");
17241   // We might have generated v2f32 FMIN/FMAX operations. Widen them to v4f32.
17242   case X86ISD::FMINC:
17243   case X86ISD::FMIN:
17244   case X86ISD::FMAXC:
17245   case X86ISD::FMAX: {
17246     EVT VT = N->getValueType(0);
17247     if (VT != MVT::v2f32)
17248       llvm_unreachable("Unexpected type (!= v2f32) on FMIN/FMAX.");
17249     SDValue UNDEF = DAG.getUNDEF(VT);
17250     SDValue LHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
17251                               N->getOperand(0), UNDEF);
17252     SDValue RHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
17253                               N->getOperand(1), UNDEF);
17254     Results.push_back(DAG.getNode(N->getOpcode(), dl, MVT::v4f32, LHS, RHS));
17255     return;
17256   }
17257   case ISD::SIGN_EXTEND_INREG:
17258   case ISD::ADDC:
17259   case ISD::ADDE:
17260   case ISD::SUBC:
17261   case ISD::SUBE:
17262     // We don't want to expand or promote these.
17263     return;
17264   case ISD::SDIV:
17265   case ISD::UDIV:
17266   case ISD::SREM:
17267   case ISD::UREM:
17268   case ISD::SDIVREM:
17269   case ISD::UDIVREM: {
17270     SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
17271     Results.push_back(V);
17272     return;
17273   }
17274   case ISD::FP_TO_SINT:
17275   case ISD::FP_TO_UINT: {
17276     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
17277
17278     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
17279       return;
17280
17281     std::pair<SDValue,SDValue> Vals =
17282         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
17283     SDValue FIST = Vals.first, StackSlot = Vals.second;
17284     if (FIST.getNode()) {
17285       EVT VT = N->getValueType(0);
17286       // Return a load from the stack slot.
17287       if (StackSlot.getNode())
17288         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
17289                                       MachinePointerInfo(),
17290                                       false, false, false, 0));
17291       else
17292         Results.push_back(FIST);
17293     }
17294     return;
17295   }
17296   case ISD::UINT_TO_FP: {
17297     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
17298     if (N->getOperand(0).getValueType() != MVT::v2i32 ||
17299         N->getValueType(0) != MVT::v2f32)
17300       return;
17301     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
17302                                  N->getOperand(0));
17303     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
17304                                      MVT::f64);
17305     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
17306     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
17307                              DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
17308     Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
17309     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
17310     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
17311     return;
17312   }
17313   case ISD::FP_ROUND: {
17314     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
17315         return;
17316     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
17317     Results.push_back(V);
17318     return;
17319   }
17320   case ISD::INTRINSIC_W_CHAIN: {
17321     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
17322     switch (IntNo) {
17323     default : llvm_unreachable("Do not know how to custom type "
17324                                "legalize this intrinsic operation!");
17325     case Intrinsic::x86_rdtsc:
17326       return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
17327                                      Results);
17328     case Intrinsic::x86_rdtscp:
17329       return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
17330                                      Results);
17331     case Intrinsic::x86_rdpmc:
17332       return getReadPerformanceCounter(N, dl, DAG, Subtarget, Results);
17333     }
17334   }
17335   case ISD::READCYCLECOUNTER: {
17336     return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
17337                                    Results);
17338   }
17339   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
17340     EVT T = N->getValueType(0);
17341     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
17342     bool Regs64bit = T == MVT::i128;
17343     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
17344     SDValue cpInL, cpInH;
17345     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
17346                         DAG.getConstant(0, HalfT));
17347     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
17348                         DAG.getConstant(1, HalfT));
17349     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
17350                              Regs64bit ? X86::RAX : X86::EAX,
17351                              cpInL, SDValue());
17352     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
17353                              Regs64bit ? X86::RDX : X86::EDX,
17354                              cpInH, cpInL.getValue(1));
17355     SDValue swapInL, swapInH;
17356     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
17357                           DAG.getConstant(0, HalfT));
17358     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
17359                           DAG.getConstant(1, HalfT));
17360     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
17361                                Regs64bit ? X86::RBX : X86::EBX,
17362                                swapInL, cpInH.getValue(1));
17363     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
17364                                Regs64bit ? X86::RCX : X86::ECX,
17365                                swapInH, swapInL.getValue(1));
17366     SDValue Ops[] = { swapInH.getValue(0),
17367                       N->getOperand(1),
17368                       swapInH.getValue(1) };
17369     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
17370     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
17371     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
17372                                   X86ISD::LCMPXCHG8_DAG;
17373     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
17374     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
17375                                         Regs64bit ? X86::RAX : X86::EAX,
17376                                         HalfT, Result.getValue(1));
17377     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
17378                                         Regs64bit ? X86::RDX : X86::EDX,
17379                                         HalfT, cpOutL.getValue(2));
17380     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
17381
17382     SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
17383                                         MVT::i32, cpOutH.getValue(2));
17384     SDValue Success =
17385         DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
17386                     DAG.getConstant(X86::COND_E, MVT::i8), EFLAGS);
17387     Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
17388
17389     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
17390     Results.push_back(Success);
17391     Results.push_back(EFLAGS.getValue(1));
17392     return;
17393   }
17394   case ISD::ATOMIC_SWAP:
17395   case ISD::ATOMIC_LOAD_ADD:
17396   case ISD::ATOMIC_LOAD_SUB:
17397   case ISD::ATOMIC_LOAD_AND:
17398   case ISD::ATOMIC_LOAD_OR:
17399   case ISD::ATOMIC_LOAD_XOR:
17400   case ISD::ATOMIC_LOAD_NAND:
17401   case ISD::ATOMIC_LOAD_MIN:
17402   case ISD::ATOMIC_LOAD_MAX:
17403   case ISD::ATOMIC_LOAD_UMIN:
17404   case ISD::ATOMIC_LOAD_UMAX:
17405   case ISD::ATOMIC_LOAD: {
17406     // Delegate to generic TypeLegalization. Situations we can really handle
17407     // should have already been dealt with by AtomicExpandPass.cpp.
17408     break;
17409   }
17410   case ISD::BITCAST: {
17411     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
17412     EVT DstVT = N->getValueType(0);
17413     EVT SrcVT = N->getOperand(0)->getValueType(0);
17414
17415     if (SrcVT != MVT::f64 ||
17416         (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
17417       return;
17418
17419     unsigned NumElts = DstVT.getVectorNumElements();
17420     EVT SVT = DstVT.getVectorElementType();
17421     EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
17422     SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
17423                                    MVT::v2f64, N->getOperand(0));
17424     SDValue ToVecInt = DAG.getNode(ISD::BITCAST, dl, WiderVT, Expanded);
17425
17426     if (ExperimentalVectorWideningLegalization) {
17427       // If we are legalizing vectors by widening, we already have the desired
17428       // legal vector type, just return it.
17429       Results.push_back(ToVecInt);
17430       return;
17431     }
17432
17433     SmallVector<SDValue, 8> Elts;
17434     for (unsigned i = 0, e = NumElts; i != e; ++i)
17435       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
17436                                    ToVecInt, DAG.getIntPtrConstant(i)));
17437
17438     Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
17439   }
17440   }
17441 }
17442
17443 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
17444   switch (Opcode) {
17445   default: return nullptr;
17446   case X86ISD::BSF:                return "X86ISD::BSF";
17447   case X86ISD::BSR:                return "X86ISD::BSR";
17448   case X86ISD::SHLD:               return "X86ISD::SHLD";
17449   case X86ISD::SHRD:               return "X86ISD::SHRD";
17450   case X86ISD::FAND:               return "X86ISD::FAND";
17451   case X86ISD::FANDN:              return "X86ISD::FANDN";
17452   case X86ISD::FOR:                return "X86ISD::FOR";
17453   case X86ISD::FXOR:               return "X86ISD::FXOR";
17454   case X86ISD::FSRL:               return "X86ISD::FSRL";
17455   case X86ISD::FILD:               return "X86ISD::FILD";
17456   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
17457   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
17458   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
17459   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
17460   case X86ISD::FLD:                return "X86ISD::FLD";
17461   case X86ISD::FST:                return "X86ISD::FST";
17462   case X86ISD::CALL:               return "X86ISD::CALL";
17463   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
17464   case X86ISD::RDTSCP_DAG:         return "X86ISD::RDTSCP_DAG";
17465   case X86ISD::RDPMC_DAG:          return "X86ISD::RDPMC_DAG";
17466   case X86ISD::BT:                 return "X86ISD::BT";
17467   case X86ISD::CMP:                return "X86ISD::CMP";
17468   case X86ISD::COMI:               return "X86ISD::COMI";
17469   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
17470   case X86ISD::CMPM:               return "X86ISD::CMPM";
17471   case X86ISD::CMPMU:              return "X86ISD::CMPMU";
17472   case X86ISD::SETCC:              return "X86ISD::SETCC";
17473   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
17474   case X86ISD::FSETCC:             return "X86ISD::FSETCC";
17475   case X86ISD::CMOV:               return "X86ISD::CMOV";
17476   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
17477   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
17478   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
17479   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
17480   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
17481   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
17482   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
17483   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
17484   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
17485   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
17486   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
17487   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
17488   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
17489   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
17490   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
17491   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
17492   case X86ISD::SHRUNKBLEND:        return "X86ISD::SHRUNKBLEND";
17493   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
17494   case X86ISD::HADD:               return "X86ISD::HADD";
17495   case X86ISD::HSUB:               return "X86ISD::HSUB";
17496   case X86ISD::FHADD:              return "X86ISD::FHADD";
17497   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
17498   case X86ISD::UMAX:               return "X86ISD::UMAX";
17499   case X86ISD::UMIN:               return "X86ISD::UMIN";
17500   case X86ISD::SMAX:               return "X86ISD::SMAX";
17501   case X86ISD::SMIN:               return "X86ISD::SMIN";
17502   case X86ISD::FMAX:               return "X86ISD::FMAX";
17503   case X86ISD::FMIN:               return "X86ISD::FMIN";
17504   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
17505   case X86ISD::FMINC:              return "X86ISD::FMINC";
17506   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
17507   case X86ISD::FRCP:               return "X86ISD::FRCP";
17508   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
17509   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
17510   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
17511   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
17512   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
17513   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
17514   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
17515   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
17516   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
17517   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
17518   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
17519   case X86ISD::LCMPXCHG16_DAG:     return "X86ISD::LCMPXCHG16_DAG";
17520   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
17521   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
17522   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
17523   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
17524   case X86ISD::VTRUNC:             return "X86ISD::VTRUNC";
17525   case X86ISD::VTRUNCM:            return "X86ISD::VTRUNCM";
17526   case X86ISD::VINSERT:            return "X86ISD::VINSERT";
17527   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
17528   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
17529   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
17530   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
17531   case X86ISD::VSHL:               return "X86ISD::VSHL";
17532   case X86ISD::VSRL:               return "X86ISD::VSRL";
17533   case X86ISD::VSRA:               return "X86ISD::VSRA";
17534   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
17535   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
17536   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
17537   case X86ISD::CMPP:               return "X86ISD::CMPP";
17538   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
17539   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
17540   case X86ISD::PCMPEQM:            return "X86ISD::PCMPEQM";
17541   case X86ISD::PCMPGTM:            return "X86ISD::PCMPGTM";
17542   case X86ISD::ADD:                return "X86ISD::ADD";
17543   case X86ISD::SUB:                return "X86ISD::SUB";
17544   case X86ISD::ADC:                return "X86ISD::ADC";
17545   case X86ISD::SBB:                return "X86ISD::SBB";
17546   case X86ISD::SMUL:               return "X86ISD::SMUL";
17547   case X86ISD::UMUL:               return "X86ISD::UMUL";
17548   case X86ISD::SMUL8:              return "X86ISD::SMUL8";
17549   case X86ISD::UMUL8:              return "X86ISD::UMUL8";
17550   case X86ISD::SDIVREM8_SEXT_HREG: return "X86ISD::SDIVREM8_SEXT_HREG";
17551   case X86ISD::UDIVREM8_ZEXT_HREG: return "X86ISD::UDIVREM8_ZEXT_HREG";
17552   case X86ISD::INC:                return "X86ISD::INC";
17553   case X86ISD::DEC:                return "X86ISD::DEC";
17554   case X86ISD::OR:                 return "X86ISD::OR";
17555   case X86ISD::XOR:                return "X86ISD::XOR";
17556   case X86ISD::AND:                return "X86ISD::AND";
17557   case X86ISD::BEXTR:              return "X86ISD::BEXTR";
17558   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
17559   case X86ISD::PTEST:              return "X86ISD::PTEST";
17560   case X86ISD::TESTP:              return "X86ISD::TESTP";
17561   case X86ISD::TESTM:              return "X86ISD::TESTM";
17562   case X86ISD::TESTNM:             return "X86ISD::TESTNM";
17563   case X86ISD::KORTEST:            return "X86ISD::KORTEST";
17564   case X86ISD::PACKSS:             return "X86ISD::PACKSS";
17565   case X86ISD::PACKUS:             return "X86ISD::PACKUS";
17566   case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
17567   case X86ISD::VALIGN:             return "X86ISD::VALIGN";
17568   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
17569   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
17570   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
17571   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
17572   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
17573   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
17574   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
17575   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
17576   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
17577   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
17578   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
17579   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
17580   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
17581   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
17582   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
17583   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
17584   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
17585   case X86ISD::VBROADCASTM:        return "X86ISD::VBROADCASTM";
17586   case X86ISD::VEXTRACT:           return "X86ISD::VEXTRACT";
17587   case X86ISD::VPERMILPI:          return "X86ISD::VPERMILPI";
17588   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
17589   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
17590   case X86ISD::VPERMV3:            return "X86ISD::VPERMV3";
17591   case X86ISD::VPERMIV3:           return "X86ISD::VPERMIV3";
17592   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
17593   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
17594   case X86ISD::PMULDQ:             return "X86ISD::PMULDQ";
17595   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
17596   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
17597   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
17598   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
17599   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
17600   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
17601   case X86ISD::SAHF:               return "X86ISD::SAHF";
17602   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
17603   case X86ISD::RDSEED:             return "X86ISD::RDSEED";
17604   case X86ISD::FMADD:              return "X86ISD::FMADD";
17605   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
17606   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
17607   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
17608   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
17609   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
17610   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
17611   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
17612   case X86ISD::XTEST:              return "X86ISD::XTEST";
17613   case X86ISD::COMPRESS:           return "X86ISD::COMPRESS";
17614   case X86ISD::EXPAND:             return "X86ISD::EXPAND";
17615   case X86ISD::SELECT:             return "X86ISD::SELECT";
17616   case X86ISD::ADDSUB:             return "X86ISD::ADDSUB";
17617   case X86ISD::RCP28:              return "X86ISD::RCP28";
17618   case X86ISD::RSQRT28:            return "X86ISD::RSQRT28";
17619   case X86ISD::FADD_RND:           return "X86ISD::FADD_RND";
17620   case X86ISD::FSUB_RND:           return "X86ISD::FSUB_RND";
17621   case X86ISD::FMUL_RND:           return "X86ISD::FMUL_RND";
17622   case X86ISD::FDIV_RND:           return "X86ISD::FDIV_RND";
17623   }
17624 }
17625
17626 // isLegalAddressingMode - Return true if the addressing mode represented
17627 // by AM is legal for this target, for a load/store of the specified type.
17628 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
17629                                               Type *Ty) const {
17630   // X86 supports extremely general addressing modes.
17631   CodeModel::Model M = getTargetMachine().getCodeModel();
17632   Reloc::Model R = getTargetMachine().getRelocationModel();
17633
17634   // X86 allows a sign-extended 32-bit immediate field as a displacement.
17635   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
17636     return false;
17637
17638   if (AM.BaseGV) {
17639     unsigned GVFlags =
17640       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
17641
17642     // If a reference to this global requires an extra load, we can't fold it.
17643     if (isGlobalStubReference(GVFlags))
17644       return false;
17645
17646     // If BaseGV requires a register for the PIC base, we cannot also have a
17647     // BaseReg specified.
17648     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
17649       return false;
17650
17651     // If lower 4G is not available, then we must use rip-relative addressing.
17652     if ((M != CodeModel::Small || R != Reloc::Static) &&
17653         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
17654       return false;
17655   }
17656
17657   switch (AM.Scale) {
17658   case 0:
17659   case 1:
17660   case 2:
17661   case 4:
17662   case 8:
17663     // These scales always work.
17664     break;
17665   case 3:
17666   case 5:
17667   case 9:
17668     // These scales are formed with basereg+scalereg.  Only accept if there is
17669     // no basereg yet.
17670     if (AM.HasBaseReg)
17671       return false;
17672     break;
17673   default:  // Other stuff never works.
17674     return false;
17675   }
17676
17677   return true;
17678 }
17679
17680 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
17681   unsigned Bits = Ty->getScalarSizeInBits();
17682
17683   // 8-bit shifts are always expensive, but versions with a scalar amount aren't
17684   // particularly cheaper than those without.
17685   if (Bits == 8)
17686     return false;
17687
17688   // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
17689   // variable shifts just as cheap as scalar ones.
17690   if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
17691     return false;
17692
17693   // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
17694   // fully general vector.
17695   return true;
17696 }
17697
17698 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
17699   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
17700     return false;
17701   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
17702   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
17703   return NumBits1 > NumBits2;
17704 }
17705
17706 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
17707   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
17708     return false;
17709
17710   if (!isTypeLegal(EVT::getEVT(Ty1)))
17711     return false;
17712
17713   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
17714
17715   // Assuming the caller doesn't have a zeroext or signext return parameter,
17716   // truncation all the way down to i1 is valid.
17717   return true;
17718 }
17719
17720 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
17721   return isInt<32>(Imm);
17722 }
17723
17724 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
17725   // Can also use sub to handle negated immediates.
17726   return isInt<32>(Imm);
17727 }
17728
17729 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
17730   if (!VT1.isInteger() || !VT2.isInteger())
17731     return false;
17732   unsigned NumBits1 = VT1.getSizeInBits();
17733   unsigned NumBits2 = VT2.getSizeInBits();
17734   return NumBits1 > NumBits2;
17735 }
17736
17737 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
17738   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
17739   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
17740 }
17741
17742 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
17743   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
17744   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
17745 }
17746
17747 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
17748   EVT VT1 = Val.getValueType();
17749   if (isZExtFree(VT1, VT2))
17750     return true;
17751
17752   if (Val.getOpcode() != ISD::LOAD)
17753     return false;
17754
17755   if (!VT1.isSimple() || !VT1.isInteger() ||
17756       !VT2.isSimple() || !VT2.isInteger())
17757     return false;
17758
17759   switch (VT1.getSimpleVT().SimpleTy) {
17760   default: break;
17761   case MVT::i8:
17762   case MVT::i16:
17763   case MVT::i32:
17764     // X86 has 8, 16, and 32-bit zero-extending loads.
17765     return true;
17766   }
17767
17768   return false;
17769 }
17770
17771 bool X86TargetLowering::isVectorLoadExtDesirable(SDValue) const { return true; }
17772
17773 bool
17774 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
17775   if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
17776     return false;
17777
17778   VT = VT.getScalarType();
17779
17780   if (!VT.isSimple())
17781     return false;
17782
17783   switch (VT.getSimpleVT().SimpleTy) {
17784   case MVT::f32:
17785   case MVT::f64:
17786     return true;
17787   default:
17788     break;
17789   }
17790
17791   return false;
17792 }
17793
17794 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
17795   // i16 instructions are longer (0x66 prefix) and potentially slower.
17796   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
17797 }
17798
17799 /// isShuffleMaskLegal - Targets can use this to indicate that they only
17800 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
17801 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
17802 /// are assumed to be legal.
17803 bool
17804 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
17805                                       EVT VT) const {
17806   if (!VT.isSimple())
17807     return false;
17808
17809   // Very little shuffling can be done for 64-bit vectors right now.
17810   if (VT.getSizeInBits() == 64)
17811     return false;
17812
17813   // We only care that the types being shuffled are legal. The lowering can
17814   // handle any possible shuffle mask that results.
17815   return isTypeLegal(VT.getSimpleVT());
17816 }
17817
17818 bool
17819 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
17820                                           EVT VT) const {
17821   // Just delegate to the generic legality, clear masks aren't special.
17822   return isShuffleMaskLegal(Mask, VT);
17823 }
17824
17825 //===----------------------------------------------------------------------===//
17826 //                           X86 Scheduler Hooks
17827 //===----------------------------------------------------------------------===//
17828
17829 /// Utility function to emit xbegin specifying the start of an RTM region.
17830 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
17831                                      const TargetInstrInfo *TII) {
17832   DebugLoc DL = MI->getDebugLoc();
17833
17834   const BasicBlock *BB = MBB->getBasicBlock();
17835   MachineFunction::iterator I = MBB;
17836   ++I;
17837
17838   // For the v = xbegin(), we generate
17839   //
17840   // thisMBB:
17841   //  xbegin sinkMBB
17842   //
17843   // mainMBB:
17844   //  eax = -1
17845   //
17846   // sinkMBB:
17847   //  v = eax
17848
17849   MachineBasicBlock *thisMBB = MBB;
17850   MachineFunction *MF = MBB->getParent();
17851   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
17852   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
17853   MF->insert(I, mainMBB);
17854   MF->insert(I, sinkMBB);
17855
17856   // Transfer the remainder of BB and its successor edges to sinkMBB.
17857   sinkMBB->splice(sinkMBB->begin(), MBB,
17858                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
17859   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
17860
17861   // thisMBB:
17862   //  xbegin sinkMBB
17863   //  # fallthrough to mainMBB
17864   //  # abortion to sinkMBB
17865   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
17866   thisMBB->addSuccessor(mainMBB);
17867   thisMBB->addSuccessor(sinkMBB);
17868
17869   // mainMBB:
17870   //  EAX = -1
17871   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
17872   mainMBB->addSuccessor(sinkMBB);
17873
17874   // sinkMBB:
17875   // EAX is live into the sinkMBB
17876   sinkMBB->addLiveIn(X86::EAX);
17877   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
17878           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
17879     .addReg(X86::EAX);
17880
17881   MI->eraseFromParent();
17882   return sinkMBB;
17883 }
17884
17885 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
17886 // or XMM0_V32I8 in AVX all of this code can be replaced with that
17887 // in the .td file.
17888 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
17889                                        const TargetInstrInfo *TII) {
17890   unsigned Opc;
17891   switch (MI->getOpcode()) {
17892   default: llvm_unreachable("illegal opcode!");
17893   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
17894   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
17895   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
17896   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
17897   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
17898   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
17899   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
17900   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
17901   }
17902
17903   DebugLoc dl = MI->getDebugLoc();
17904   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
17905
17906   unsigned NumArgs = MI->getNumOperands();
17907   for (unsigned i = 1; i < NumArgs; ++i) {
17908     MachineOperand &Op = MI->getOperand(i);
17909     if (!(Op.isReg() && Op.isImplicit()))
17910       MIB.addOperand(Op);
17911   }
17912   if (MI->hasOneMemOperand())
17913     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
17914
17915   BuildMI(*BB, MI, dl,
17916     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
17917     .addReg(X86::XMM0);
17918
17919   MI->eraseFromParent();
17920   return BB;
17921 }
17922
17923 // FIXME: Custom handling because TableGen doesn't support multiple implicit
17924 // defs in an instruction pattern
17925 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
17926                                        const TargetInstrInfo *TII) {
17927   unsigned Opc;
17928   switch (MI->getOpcode()) {
17929   default: llvm_unreachable("illegal opcode!");
17930   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
17931   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
17932   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
17933   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
17934   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
17935   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
17936   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
17937   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
17938   }
17939
17940   DebugLoc dl = MI->getDebugLoc();
17941   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
17942
17943   unsigned NumArgs = MI->getNumOperands(); // remove the results
17944   for (unsigned i = 1; i < NumArgs; ++i) {
17945     MachineOperand &Op = MI->getOperand(i);
17946     if (!(Op.isReg() && Op.isImplicit()))
17947       MIB.addOperand(Op);
17948   }
17949   if (MI->hasOneMemOperand())
17950     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
17951
17952   BuildMI(*BB, MI, dl,
17953     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
17954     .addReg(X86::ECX);
17955
17956   MI->eraseFromParent();
17957   return BB;
17958 }
17959
17960 static MachineBasicBlock *EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
17961                                       const X86Subtarget *Subtarget) {
17962   DebugLoc dl = MI->getDebugLoc();
17963   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
17964   // Address into RAX/EAX, other two args into ECX, EDX.
17965   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
17966   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
17967   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
17968   for (int i = 0; i < X86::AddrNumOperands; ++i)
17969     MIB.addOperand(MI->getOperand(i));
17970
17971   unsigned ValOps = X86::AddrNumOperands;
17972   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
17973     .addReg(MI->getOperand(ValOps).getReg());
17974   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
17975     .addReg(MI->getOperand(ValOps+1).getReg());
17976
17977   // The instruction doesn't actually take any operands though.
17978   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
17979
17980   MI->eraseFromParent(); // The pseudo is gone now.
17981   return BB;
17982 }
17983
17984 MachineBasicBlock *
17985 X86TargetLowering::EmitVAARG64WithCustomInserter(MachineInstr *MI,
17986                                                  MachineBasicBlock *MBB) const {
17987   // Emit va_arg instruction on X86-64.
17988
17989   // Operands to this pseudo-instruction:
17990   // 0  ) Output        : destination address (reg)
17991   // 1-5) Input         : va_list address (addr, i64mem)
17992   // 6  ) ArgSize       : Size (in bytes) of vararg type
17993   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
17994   // 8  ) Align         : Alignment of type
17995   // 9  ) EFLAGS (implicit-def)
17996
17997   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
17998   static_assert(X86::AddrNumOperands == 5,
17999                 "VAARG_64 assumes 5 address operands");
18000
18001   unsigned DestReg = MI->getOperand(0).getReg();
18002   MachineOperand &Base = MI->getOperand(1);
18003   MachineOperand &Scale = MI->getOperand(2);
18004   MachineOperand &Index = MI->getOperand(3);
18005   MachineOperand &Disp = MI->getOperand(4);
18006   MachineOperand &Segment = MI->getOperand(5);
18007   unsigned ArgSize = MI->getOperand(6).getImm();
18008   unsigned ArgMode = MI->getOperand(7).getImm();
18009   unsigned Align = MI->getOperand(8).getImm();
18010
18011   // Memory Reference
18012   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
18013   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
18014   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
18015
18016   // Machine Information
18017   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18018   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
18019   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
18020   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
18021   DebugLoc DL = MI->getDebugLoc();
18022
18023   // struct va_list {
18024   //   i32   gp_offset
18025   //   i32   fp_offset
18026   //   i64   overflow_area (address)
18027   //   i64   reg_save_area (address)
18028   // }
18029   // sizeof(va_list) = 24
18030   // alignment(va_list) = 8
18031
18032   unsigned TotalNumIntRegs = 6;
18033   unsigned TotalNumXMMRegs = 8;
18034   bool UseGPOffset = (ArgMode == 1);
18035   bool UseFPOffset = (ArgMode == 2);
18036   unsigned MaxOffset = TotalNumIntRegs * 8 +
18037                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
18038
18039   /* Align ArgSize to a multiple of 8 */
18040   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
18041   bool NeedsAlign = (Align > 8);
18042
18043   MachineBasicBlock *thisMBB = MBB;
18044   MachineBasicBlock *overflowMBB;
18045   MachineBasicBlock *offsetMBB;
18046   MachineBasicBlock *endMBB;
18047
18048   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
18049   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
18050   unsigned OffsetReg = 0;
18051
18052   if (!UseGPOffset && !UseFPOffset) {
18053     // If we only pull from the overflow region, we don't create a branch.
18054     // We don't need to alter control flow.
18055     OffsetDestReg = 0; // unused
18056     OverflowDestReg = DestReg;
18057
18058     offsetMBB = nullptr;
18059     overflowMBB = thisMBB;
18060     endMBB = thisMBB;
18061   } else {
18062     // First emit code to check if gp_offset (or fp_offset) is below the bound.
18063     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
18064     // If not, pull from overflow_area. (branch to overflowMBB)
18065     //
18066     //       thisMBB
18067     //         |     .
18068     //         |        .
18069     //     offsetMBB   overflowMBB
18070     //         |        .
18071     //         |     .
18072     //        endMBB
18073
18074     // Registers for the PHI in endMBB
18075     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
18076     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
18077
18078     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
18079     MachineFunction *MF = MBB->getParent();
18080     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18081     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18082     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18083
18084     MachineFunction::iterator MBBIter = MBB;
18085     ++MBBIter;
18086
18087     // Insert the new basic blocks
18088     MF->insert(MBBIter, offsetMBB);
18089     MF->insert(MBBIter, overflowMBB);
18090     MF->insert(MBBIter, endMBB);
18091
18092     // Transfer the remainder of MBB and its successor edges to endMBB.
18093     endMBB->splice(endMBB->begin(), thisMBB,
18094                    std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
18095     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
18096
18097     // Make offsetMBB and overflowMBB successors of thisMBB
18098     thisMBB->addSuccessor(offsetMBB);
18099     thisMBB->addSuccessor(overflowMBB);
18100
18101     // endMBB is a successor of both offsetMBB and overflowMBB
18102     offsetMBB->addSuccessor(endMBB);
18103     overflowMBB->addSuccessor(endMBB);
18104
18105     // Load the offset value into a register
18106     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
18107     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
18108       .addOperand(Base)
18109       .addOperand(Scale)
18110       .addOperand(Index)
18111       .addDisp(Disp, UseFPOffset ? 4 : 0)
18112       .addOperand(Segment)
18113       .setMemRefs(MMOBegin, MMOEnd);
18114
18115     // Check if there is enough room left to pull this argument.
18116     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
18117       .addReg(OffsetReg)
18118       .addImm(MaxOffset + 8 - ArgSizeA8);
18119
18120     // Branch to "overflowMBB" if offset >= max
18121     // Fall through to "offsetMBB" otherwise
18122     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
18123       .addMBB(overflowMBB);
18124   }
18125
18126   // In offsetMBB, emit code to use the reg_save_area.
18127   if (offsetMBB) {
18128     assert(OffsetReg != 0);
18129
18130     // Read the reg_save_area address.
18131     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
18132     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
18133       .addOperand(Base)
18134       .addOperand(Scale)
18135       .addOperand(Index)
18136       .addDisp(Disp, 16)
18137       .addOperand(Segment)
18138       .setMemRefs(MMOBegin, MMOEnd);
18139
18140     // Zero-extend the offset
18141     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
18142       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
18143         .addImm(0)
18144         .addReg(OffsetReg)
18145         .addImm(X86::sub_32bit);
18146
18147     // Add the offset to the reg_save_area to get the final address.
18148     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
18149       .addReg(OffsetReg64)
18150       .addReg(RegSaveReg);
18151
18152     // Compute the offset for the next argument
18153     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
18154     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
18155       .addReg(OffsetReg)
18156       .addImm(UseFPOffset ? 16 : 8);
18157
18158     // Store it back into the va_list.
18159     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
18160       .addOperand(Base)
18161       .addOperand(Scale)
18162       .addOperand(Index)
18163       .addDisp(Disp, UseFPOffset ? 4 : 0)
18164       .addOperand(Segment)
18165       .addReg(NextOffsetReg)
18166       .setMemRefs(MMOBegin, MMOEnd);
18167
18168     // Jump to endMBB
18169     BuildMI(offsetMBB, DL, TII->get(X86::JMP_1))
18170       .addMBB(endMBB);
18171   }
18172
18173   //
18174   // Emit code to use overflow area
18175   //
18176
18177   // Load the overflow_area address into a register.
18178   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
18179   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
18180     .addOperand(Base)
18181     .addOperand(Scale)
18182     .addOperand(Index)
18183     .addDisp(Disp, 8)
18184     .addOperand(Segment)
18185     .setMemRefs(MMOBegin, MMOEnd);
18186
18187   // If we need to align it, do so. Otherwise, just copy the address
18188   // to OverflowDestReg.
18189   if (NeedsAlign) {
18190     // Align the overflow address
18191     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
18192     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
18193
18194     // aligned_addr = (addr + (align-1)) & ~(align-1)
18195     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
18196       .addReg(OverflowAddrReg)
18197       .addImm(Align-1);
18198
18199     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
18200       .addReg(TmpReg)
18201       .addImm(~(uint64_t)(Align-1));
18202   } else {
18203     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
18204       .addReg(OverflowAddrReg);
18205   }
18206
18207   // Compute the next overflow address after this argument.
18208   // (the overflow address should be kept 8-byte aligned)
18209   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
18210   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
18211     .addReg(OverflowDestReg)
18212     .addImm(ArgSizeA8);
18213
18214   // Store the new overflow address.
18215   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
18216     .addOperand(Base)
18217     .addOperand(Scale)
18218     .addOperand(Index)
18219     .addDisp(Disp, 8)
18220     .addOperand(Segment)
18221     .addReg(NextAddrReg)
18222     .setMemRefs(MMOBegin, MMOEnd);
18223
18224   // If we branched, emit the PHI to the front of endMBB.
18225   if (offsetMBB) {
18226     BuildMI(*endMBB, endMBB->begin(), DL,
18227             TII->get(X86::PHI), DestReg)
18228       .addReg(OffsetDestReg).addMBB(offsetMBB)
18229       .addReg(OverflowDestReg).addMBB(overflowMBB);
18230   }
18231
18232   // Erase the pseudo instruction
18233   MI->eraseFromParent();
18234
18235   return endMBB;
18236 }
18237
18238 MachineBasicBlock *
18239 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
18240                                                  MachineInstr *MI,
18241                                                  MachineBasicBlock *MBB) const {
18242   // Emit code to save XMM registers to the stack. The ABI says that the
18243   // number of registers to save is given in %al, so it's theoretically
18244   // possible to do an indirect jump trick to avoid saving all of them,
18245   // however this code takes a simpler approach and just executes all
18246   // of the stores if %al is non-zero. It's less code, and it's probably
18247   // easier on the hardware branch predictor, and stores aren't all that
18248   // expensive anyway.
18249
18250   // Create the new basic blocks. One block contains all the XMM stores,
18251   // and one block is the final destination regardless of whether any
18252   // stores were performed.
18253   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
18254   MachineFunction *F = MBB->getParent();
18255   MachineFunction::iterator MBBIter = MBB;
18256   ++MBBIter;
18257   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
18258   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
18259   F->insert(MBBIter, XMMSaveMBB);
18260   F->insert(MBBIter, EndMBB);
18261
18262   // Transfer the remainder of MBB and its successor edges to EndMBB.
18263   EndMBB->splice(EndMBB->begin(), MBB,
18264                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
18265   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
18266
18267   // The original block will now fall through to the XMM save block.
18268   MBB->addSuccessor(XMMSaveMBB);
18269   // The XMMSaveMBB will fall through to the end block.
18270   XMMSaveMBB->addSuccessor(EndMBB);
18271
18272   // Now add the instructions.
18273   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18274   DebugLoc DL = MI->getDebugLoc();
18275
18276   unsigned CountReg = MI->getOperand(0).getReg();
18277   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
18278   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
18279
18280   if (!Subtarget->isTargetWin64()) {
18281     // If %al is 0, branch around the XMM save block.
18282     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
18283     BuildMI(MBB, DL, TII->get(X86::JE_1)).addMBB(EndMBB);
18284     MBB->addSuccessor(EndMBB);
18285   }
18286
18287   // Make sure the last operand is EFLAGS, which gets clobbered by the branch
18288   // that was just emitted, but clearly shouldn't be "saved".
18289   assert((MI->getNumOperands() <= 3 ||
18290           !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
18291           MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
18292          && "Expected last argument to be EFLAGS");
18293   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
18294   // In the XMM save block, save all the XMM argument registers.
18295   for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
18296     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
18297     MachineMemOperand *MMO =
18298       F->getMachineMemOperand(
18299           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
18300         MachineMemOperand::MOStore,
18301         /*Size=*/16, /*Align=*/16);
18302     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
18303       .addFrameIndex(RegSaveFrameIndex)
18304       .addImm(/*Scale=*/1)
18305       .addReg(/*IndexReg=*/0)
18306       .addImm(/*Disp=*/Offset)
18307       .addReg(/*Segment=*/0)
18308       .addReg(MI->getOperand(i).getReg())
18309       .addMemOperand(MMO);
18310   }
18311
18312   MI->eraseFromParent();   // The pseudo instruction is gone now.
18313
18314   return EndMBB;
18315 }
18316
18317 // The EFLAGS operand of SelectItr might be missing a kill marker
18318 // because there were multiple uses of EFLAGS, and ISel didn't know
18319 // which to mark. Figure out whether SelectItr should have had a
18320 // kill marker, and set it if it should. Returns the correct kill
18321 // marker value.
18322 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
18323                                      MachineBasicBlock* BB,
18324                                      const TargetRegisterInfo* TRI) {
18325   // Scan forward through BB for a use/def of EFLAGS.
18326   MachineBasicBlock::iterator miI(std::next(SelectItr));
18327   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
18328     const MachineInstr& mi = *miI;
18329     if (mi.readsRegister(X86::EFLAGS))
18330       return false;
18331     if (mi.definesRegister(X86::EFLAGS))
18332       break; // Should have kill-flag - update below.
18333   }
18334
18335   // If we hit the end of the block, check whether EFLAGS is live into a
18336   // successor.
18337   if (miI == BB->end()) {
18338     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
18339                                           sEnd = BB->succ_end();
18340          sItr != sEnd; ++sItr) {
18341       MachineBasicBlock* succ = *sItr;
18342       if (succ->isLiveIn(X86::EFLAGS))
18343         return false;
18344     }
18345   }
18346
18347   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
18348   // out. SelectMI should have a kill flag on EFLAGS.
18349   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
18350   return true;
18351 }
18352
18353 MachineBasicBlock *
18354 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
18355                                      MachineBasicBlock *BB) const {
18356   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18357   DebugLoc DL = MI->getDebugLoc();
18358
18359   // To "insert" a SELECT_CC instruction, we actually have to insert the
18360   // diamond control-flow pattern.  The incoming instruction knows the
18361   // destination vreg to set, the condition code register to branch on, the
18362   // true/false values to select between, and a branch opcode to use.
18363   const BasicBlock *LLVM_BB = BB->getBasicBlock();
18364   MachineFunction::iterator It = BB;
18365   ++It;
18366
18367   //  thisMBB:
18368   //  ...
18369   //   TrueVal = ...
18370   //   cmpTY ccX, r1, r2
18371   //   bCC copy1MBB
18372   //   fallthrough --> copy0MBB
18373   MachineBasicBlock *thisMBB = BB;
18374   MachineFunction *F = BB->getParent();
18375
18376   // We also lower double CMOVs:
18377   //   (CMOV (CMOV F, T, cc1), T, cc2)
18378   // to two successives branches.  For that, we look for another CMOV as the
18379   // following instruction.
18380   //
18381   // Without this, we would add a PHI between the two jumps, which ends up
18382   // creating a few copies all around. For instance, for
18383   //
18384   //    (sitofp (zext (fcmp une)))
18385   //
18386   // we would generate:
18387   //
18388   //         ucomiss %xmm1, %xmm0
18389   //         movss  <1.0f>, %xmm0
18390   //         movaps  %xmm0, %xmm1
18391   //         jne     .LBB5_2
18392   //         xorps   %xmm1, %xmm1
18393   // .LBB5_2:
18394   //         jp      .LBB5_4
18395   //         movaps  %xmm1, %xmm0
18396   // .LBB5_4:
18397   //         retq
18398   //
18399   // because this custom-inserter would have generated:
18400   //
18401   //   A
18402   //   | \
18403   //   |  B
18404   //   | /
18405   //   C
18406   //   | \
18407   //   |  D
18408   //   | /
18409   //   E
18410   //
18411   // A: X = ...; Y = ...
18412   // B: empty
18413   // C: Z = PHI [X, A], [Y, B]
18414   // D: empty
18415   // E: PHI [X, C], [Z, D]
18416   //
18417   // If we lower both CMOVs in a single step, we can instead generate:
18418   //
18419   //   A
18420   //   | \
18421   //   |  C
18422   //   | /|
18423   //   |/ |
18424   //   |  |
18425   //   |  D
18426   //   | /
18427   //   E
18428   //
18429   // A: X = ...; Y = ...
18430   // D: empty
18431   // E: PHI [X, A], [X, C], [Y, D]
18432   //
18433   // Which, in our sitofp/fcmp example, gives us something like:
18434   //
18435   //         ucomiss %xmm1, %xmm0
18436   //         movss  <1.0f>, %xmm0
18437   //         jne     .LBB5_4
18438   //         jp      .LBB5_4
18439   //         xorps   %xmm0, %xmm0
18440   // .LBB5_4:
18441   //         retq
18442   //
18443   MachineInstr *NextCMOV = nullptr;
18444   MachineBasicBlock::iterator NextMIIt =
18445       std::next(MachineBasicBlock::iterator(MI));
18446   if (NextMIIt != BB->end() && NextMIIt->getOpcode() == MI->getOpcode() &&
18447       NextMIIt->getOperand(2).getReg() == MI->getOperand(2).getReg() &&
18448       NextMIIt->getOperand(1).getReg() == MI->getOperand(0).getReg())
18449     NextCMOV = &*NextMIIt;
18450
18451   MachineBasicBlock *jcc1MBB = nullptr;
18452
18453   // If we have a double CMOV, we lower it to two successive branches to
18454   // the same block.  EFLAGS is used by both, so mark it as live in the second.
18455   if (NextCMOV) {
18456     jcc1MBB = F->CreateMachineBasicBlock(LLVM_BB);
18457     F->insert(It, jcc1MBB);
18458     jcc1MBB->addLiveIn(X86::EFLAGS);
18459   }
18460
18461   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
18462   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
18463   F->insert(It, copy0MBB);
18464   F->insert(It, sinkMBB);
18465
18466   // If the EFLAGS register isn't dead in the terminator, then claim that it's
18467   // live into the sink and copy blocks.
18468   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
18469
18470   MachineInstr *LastEFLAGSUser = NextCMOV ? NextCMOV : MI;
18471   if (!LastEFLAGSUser->killsRegister(X86::EFLAGS) &&
18472       !checkAndUpdateEFLAGSKill(LastEFLAGSUser, BB, TRI)) {
18473     copy0MBB->addLiveIn(X86::EFLAGS);
18474     sinkMBB->addLiveIn(X86::EFLAGS);
18475   }
18476
18477   // Transfer the remainder of BB and its successor edges to sinkMBB.
18478   sinkMBB->splice(sinkMBB->begin(), BB,
18479                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
18480   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
18481
18482   // Add the true and fallthrough blocks as its successors.
18483   if (NextCMOV) {
18484     // The fallthrough block may be jcc1MBB, if we have a double CMOV.
18485     BB->addSuccessor(jcc1MBB);
18486
18487     // In that case, jcc1MBB will itself fallthrough the copy0MBB, and
18488     // jump to the sinkMBB.
18489     jcc1MBB->addSuccessor(copy0MBB);
18490     jcc1MBB->addSuccessor(sinkMBB);
18491   } else {
18492     BB->addSuccessor(copy0MBB);
18493   }
18494
18495   // The true block target of the first (or only) branch is always sinkMBB.
18496   BB->addSuccessor(sinkMBB);
18497
18498   // Create the conditional branch instruction.
18499   unsigned Opc =
18500     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
18501   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
18502
18503   if (NextCMOV) {
18504     unsigned Opc2 = X86::GetCondBranchFromCond(
18505         (X86::CondCode)NextCMOV->getOperand(3).getImm());
18506     BuildMI(jcc1MBB, DL, TII->get(Opc2)).addMBB(sinkMBB);
18507   }
18508
18509   //  copy0MBB:
18510   //   %FalseValue = ...
18511   //   # fallthrough to sinkMBB
18512   copy0MBB->addSuccessor(sinkMBB);
18513
18514   //  sinkMBB:
18515   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
18516   //  ...
18517   MachineInstrBuilder MIB =
18518       BuildMI(*sinkMBB, sinkMBB->begin(), DL, TII->get(X86::PHI),
18519               MI->getOperand(0).getReg())
18520           .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
18521           .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
18522
18523   // If we have a double CMOV, the second Jcc provides the same incoming
18524   // value as the first Jcc (the True operand of the SELECT_CC/CMOV nodes).
18525   if (NextCMOV) {
18526     MIB.addReg(MI->getOperand(2).getReg()).addMBB(jcc1MBB);
18527     // Copy the PHI result to the register defined by the second CMOV.
18528     BuildMI(*sinkMBB, std::next(MachineBasicBlock::iterator(MIB.getInstr())),
18529             DL, TII->get(TargetOpcode::COPY), NextCMOV->getOperand(0).getReg())
18530         .addReg(MI->getOperand(0).getReg());
18531     NextCMOV->eraseFromParent();
18532   }
18533
18534   MI->eraseFromParent();   // The pseudo instruction is gone now.
18535   return sinkMBB;
18536 }
18537
18538 MachineBasicBlock *
18539 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI,
18540                                         MachineBasicBlock *BB) const {
18541   MachineFunction *MF = BB->getParent();
18542   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18543   DebugLoc DL = MI->getDebugLoc();
18544   const BasicBlock *LLVM_BB = BB->getBasicBlock();
18545
18546   assert(MF->shouldSplitStack());
18547
18548   const bool Is64Bit = Subtarget->is64Bit();
18549   const bool IsLP64 = Subtarget->isTarget64BitLP64();
18550
18551   const unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
18552   const unsigned TlsOffset = IsLP64 ? 0x70 : Is64Bit ? 0x40 : 0x30;
18553
18554   // BB:
18555   //  ... [Till the alloca]
18556   // If stacklet is not large enough, jump to mallocMBB
18557   //
18558   // bumpMBB:
18559   //  Allocate by subtracting from RSP
18560   //  Jump to continueMBB
18561   //
18562   // mallocMBB:
18563   //  Allocate by call to runtime
18564   //
18565   // continueMBB:
18566   //  ...
18567   //  [rest of original BB]
18568   //
18569
18570   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18571   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18572   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18573
18574   MachineRegisterInfo &MRI = MF->getRegInfo();
18575   const TargetRegisterClass *AddrRegClass =
18576     getRegClassFor(getPointerTy());
18577
18578   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
18579     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
18580     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
18581     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
18582     sizeVReg = MI->getOperand(1).getReg(),
18583     physSPReg = IsLP64 || Subtarget->isTargetNaCl64() ? X86::RSP : X86::ESP;
18584
18585   MachineFunction::iterator MBBIter = BB;
18586   ++MBBIter;
18587
18588   MF->insert(MBBIter, bumpMBB);
18589   MF->insert(MBBIter, mallocMBB);
18590   MF->insert(MBBIter, continueMBB);
18591
18592   continueMBB->splice(continueMBB->begin(), BB,
18593                       std::next(MachineBasicBlock::iterator(MI)), BB->end());
18594   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
18595
18596   // Add code to the main basic block to check if the stack limit has been hit,
18597   // and if so, jump to mallocMBB otherwise to bumpMBB.
18598   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
18599   BuildMI(BB, DL, TII->get(IsLP64 ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
18600     .addReg(tmpSPVReg).addReg(sizeVReg);
18601   BuildMI(BB, DL, TII->get(IsLP64 ? X86::CMP64mr:X86::CMP32mr))
18602     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
18603     .addReg(SPLimitVReg);
18604   BuildMI(BB, DL, TII->get(X86::JG_1)).addMBB(mallocMBB);
18605
18606   // bumpMBB simply decreases the stack pointer, since we know the current
18607   // stacklet has enough space.
18608   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
18609     .addReg(SPLimitVReg);
18610   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
18611     .addReg(SPLimitVReg);
18612   BuildMI(bumpMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
18613
18614   // Calls into a routine in libgcc to allocate more space from the heap.
18615   const uint32_t *RegMask =
18616       Subtarget->getRegisterInfo()->getCallPreservedMask(*MF, CallingConv::C);
18617   if (IsLP64) {
18618     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
18619       .addReg(sizeVReg);
18620     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
18621       .addExternalSymbol("__morestack_allocate_stack_space")
18622       .addRegMask(RegMask)
18623       .addReg(X86::RDI, RegState::Implicit)
18624       .addReg(X86::RAX, RegState::ImplicitDefine);
18625   } else if (Is64Bit) {
18626     BuildMI(mallocMBB, DL, TII->get(X86::MOV32rr), X86::EDI)
18627       .addReg(sizeVReg);
18628     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
18629       .addExternalSymbol("__morestack_allocate_stack_space")
18630       .addRegMask(RegMask)
18631       .addReg(X86::EDI, RegState::Implicit)
18632       .addReg(X86::EAX, RegState::ImplicitDefine);
18633   } else {
18634     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
18635       .addImm(12);
18636     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
18637     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
18638       .addExternalSymbol("__morestack_allocate_stack_space")
18639       .addRegMask(RegMask)
18640       .addReg(X86::EAX, RegState::ImplicitDefine);
18641   }
18642
18643   if (!Is64Bit)
18644     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
18645       .addImm(16);
18646
18647   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
18648     .addReg(IsLP64 ? X86::RAX : X86::EAX);
18649   BuildMI(mallocMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
18650
18651   // Set up the CFG correctly.
18652   BB->addSuccessor(bumpMBB);
18653   BB->addSuccessor(mallocMBB);
18654   mallocMBB->addSuccessor(continueMBB);
18655   bumpMBB->addSuccessor(continueMBB);
18656
18657   // Take care of the PHI nodes.
18658   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
18659           MI->getOperand(0).getReg())
18660     .addReg(mallocPtrVReg).addMBB(mallocMBB)
18661     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
18662
18663   // Delete the original pseudo instruction.
18664   MI->eraseFromParent();
18665
18666   // And we're done.
18667   return continueMBB;
18668 }
18669
18670 MachineBasicBlock *
18671 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
18672                                         MachineBasicBlock *BB) const {
18673   DebugLoc DL = MI->getDebugLoc();
18674
18675   assert(!Subtarget->isTargetMachO());
18676
18677   X86FrameLowering::emitStackProbeCall(*BB->getParent(), *BB, MI, DL);
18678
18679   MI->eraseFromParent();   // The pseudo instruction is gone now.
18680   return BB;
18681 }
18682
18683 MachineBasicBlock *
18684 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
18685                                       MachineBasicBlock *BB) const {
18686   // This is pretty easy.  We're taking the value that we received from
18687   // our load from the relocation, sticking it in either RDI (x86-64)
18688   // or EAX and doing an indirect call.  The return value will then
18689   // be in the normal return register.
18690   MachineFunction *F = BB->getParent();
18691   const X86InstrInfo *TII = Subtarget->getInstrInfo();
18692   DebugLoc DL = MI->getDebugLoc();
18693
18694   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
18695   assert(MI->getOperand(3).isGlobal() && "This should be a global");
18696
18697   // Get a register mask for the lowered call.
18698   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
18699   // proper register mask.
18700   const uint32_t *RegMask =
18701       Subtarget->getRegisterInfo()->getCallPreservedMask(*F, CallingConv::C);
18702   if (Subtarget->is64Bit()) {
18703     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
18704                                       TII->get(X86::MOV64rm), X86::RDI)
18705     .addReg(X86::RIP)
18706     .addImm(0).addReg(0)
18707     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
18708                       MI->getOperand(3).getTargetFlags())
18709     .addReg(0);
18710     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
18711     addDirectMem(MIB, X86::RDI);
18712     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
18713   } else if (F->getTarget().getRelocationModel() != Reloc::PIC_) {
18714     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
18715                                       TII->get(X86::MOV32rm), X86::EAX)
18716     .addReg(0)
18717     .addImm(0).addReg(0)
18718     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
18719                       MI->getOperand(3).getTargetFlags())
18720     .addReg(0);
18721     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
18722     addDirectMem(MIB, X86::EAX);
18723     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
18724   } else {
18725     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
18726                                       TII->get(X86::MOV32rm), X86::EAX)
18727     .addReg(TII->getGlobalBaseReg(F))
18728     .addImm(0).addReg(0)
18729     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
18730                       MI->getOperand(3).getTargetFlags())
18731     .addReg(0);
18732     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
18733     addDirectMem(MIB, X86::EAX);
18734     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
18735   }
18736
18737   MI->eraseFromParent(); // The pseudo instruction is gone now.
18738   return BB;
18739 }
18740
18741 MachineBasicBlock *
18742 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
18743                                     MachineBasicBlock *MBB) const {
18744   DebugLoc DL = MI->getDebugLoc();
18745   MachineFunction *MF = MBB->getParent();
18746   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18747   MachineRegisterInfo &MRI = MF->getRegInfo();
18748
18749   const BasicBlock *BB = MBB->getBasicBlock();
18750   MachineFunction::iterator I = MBB;
18751   ++I;
18752
18753   // Memory Reference
18754   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
18755   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
18756
18757   unsigned DstReg;
18758   unsigned MemOpndSlot = 0;
18759
18760   unsigned CurOp = 0;
18761
18762   DstReg = MI->getOperand(CurOp++).getReg();
18763   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
18764   assert(RC->hasType(MVT::i32) && "Invalid destination!");
18765   unsigned mainDstReg = MRI.createVirtualRegister(RC);
18766   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
18767
18768   MemOpndSlot = CurOp;
18769
18770   MVT PVT = getPointerTy();
18771   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
18772          "Invalid Pointer Size!");
18773
18774   // For v = setjmp(buf), we generate
18775   //
18776   // thisMBB:
18777   //  buf[LabelOffset] = restoreMBB
18778   //  SjLjSetup restoreMBB
18779   //
18780   // mainMBB:
18781   //  v_main = 0
18782   //
18783   // sinkMBB:
18784   //  v = phi(main, restore)
18785   //
18786   // restoreMBB:
18787   //  if base pointer being used, load it from frame
18788   //  v_restore = 1
18789
18790   MachineBasicBlock *thisMBB = MBB;
18791   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
18792   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
18793   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
18794   MF->insert(I, mainMBB);
18795   MF->insert(I, sinkMBB);
18796   MF->push_back(restoreMBB);
18797
18798   MachineInstrBuilder MIB;
18799
18800   // Transfer the remainder of BB and its successor edges to sinkMBB.
18801   sinkMBB->splice(sinkMBB->begin(), MBB,
18802                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
18803   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
18804
18805   // thisMBB:
18806   unsigned PtrStoreOpc = 0;
18807   unsigned LabelReg = 0;
18808   const int64_t LabelOffset = 1 * PVT.getStoreSize();
18809   Reloc::Model RM = MF->getTarget().getRelocationModel();
18810   bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
18811                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
18812
18813   // Prepare IP either in reg or imm.
18814   if (!UseImmLabel) {
18815     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
18816     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
18817     LabelReg = MRI.createVirtualRegister(PtrRC);
18818     if (Subtarget->is64Bit()) {
18819       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
18820               .addReg(X86::RIP)
18821               .addImm(0)
18822               .addReg(0)
18823               .addMBB(restoreMBB)
18824               .addReg(0);
18825     } else {
18826       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
18827       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
18828               .addReg(XII->getGlobalBaseReg(MF))
18829               .addImm(0)
18830               .addReg(0)
18831               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
18832               .addReg(0);
18833     }
18834   } else
18835     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
18836   // Store IP
18837   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
18838   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
18839     if (i == X86::AddrDisp)
18840       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
18841     else
18842       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
18843   }
18844   if (!UseImmLabel)
18845     MIB.addReg(LabelReg);
18846   else
18847     MIB.addMBB(restoreMBB);
18848   MIB.setMemRefs(MMOBegin, MMOEnd);
18849   // Setup
18850   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
18851           .addMBB(restoreMBB);
18852
18853   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
18854   MIB.addRegMask(RegInfo->getNoPreservedMask());
18855   thisMBB->addSuccessor(mainMBB);
18856   thisMBB->addSuccessor(restoreMBB);
18857
18858   // mainMBB:
18859   //  EAX = 0
18860   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
18861   mainMBB->addSuccessor(sinkMBB);
18862
18863   // sinkMBB:
18864   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
18865           TII->get(X86::PHI), DstReg)
18866     .addReg(mainDstReg).addMBB(mainMBB)
18867     .addReg(restoreDstReg).addMBB(restoreMBB);
18868
18869   // restoreMBB:
18870   if (RegInfo->hasBasePointer(*MF)) {
18871     const bool Uses64BitFramePtr =
18872         Subtarget->isTarget64BitLP64() || Subtarget->isTargetNaCl64();
18873     X86MachineFunctionInfo *X86FI = MF->getInfo<X86MachineFunctionInfo>();
18874     X86FI->setRestoreBasePointer(MF);
18875     unsigned FramePtr = RegInfo->getFrameRegister(*MF);
18876     unsigned BasePtr = RegInfo->getBaseRegister();
18877     unsigned Opm = Uses64BitFramePtr ? X86::MOV64rm : X86::MOV32rm;
18878     addRegOffset(BuildMI(restoreMBB, DL, TII->get(Opm), BasePtr),
18879                  FramePtr, true, X86FI->getRestoreBasePointerOffset())
18880       .setMIFlag(MachineInstr::FrameSetup);
18881   }
18882   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
18883   BuildMI(restoreMBB, DL, TII->get(X86::JMP_1)).addMBB(sinkMBB);
18884   restoreMBB->addSuccessor(sinkMBB);
18885
18886   MI->eraseFromParent();
18887   return sinkMBB;
18888 }
18889
18890 MachineBasicBlock *
18891 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
18892                                      MachineBasicBlock *MBB) const {
18893   DebugLoc DL = MI->getDebugLoc();
18894   MachineFunction *MF = MBB->getParent();
18895   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18896   MachineRegisterInfo &MRI = MF->getRegInfo();
18897
18898   // Memory Reference
18899   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
18900   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
18901
18902   MVT PVT = getPointerTy();
18903   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
18904          "Invalid Pointer Size!");
18905
18906   const TargetRegisterClass *RC =
18907     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
18908   unsigned Tmp = MRI.createVirtualRegister(RC);
18909   // Since FP is only updated here but NOT referenced, it's treated as GPR.
18910   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
18911   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
18912   unsigned SP = RegInfo->getStackRegister();
18913
18914   MachineInstrBuilder MIB;
18915
18916   const int64_t LabelOffset = 1 * PVT.getStoreSize();
18917   const int64_t SPOffset = 2 * PVT.getStoreSize();
18918
18919   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
18920   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
18921
18922   // Reload FP
18923   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
18924   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
18925     MIB.addOperand(MI->getOperand(i));
18926   MIB.setMemRefs(MMOBegin, MMOEnd);
18927   // Reload IP
18928   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
18929   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
18930     if (i == X86::AddrDisp)
18931       MIB.addDisp(MI->getOperand(i), LabelOffset);
18932     else
18933       MIB.addOperand(MI->getOperand(i));
18934   }
18935   MIB.setMemRefs(MMOBegin, MMOEnd);
18936   // Reload SP
18937   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
18938   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
18939     if (i == X86::AddrDisp)
18940       MIB.addDisp(MI->getOperand(i), SPOffset);
18941     else
18942       MIB.addOperand(MI->getOperand(i));
18943   }
18944   MIB.setMemRefs(MMOBegin, MMOEnd);
18945   // Jump
18946   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
18947
18948   MI->eraseFromParent();
18949   return MBB;
18950 }
18951
18952 // Replace 213-type (isel default) FMA3 instructions with 231-type for
18953 // accumulator loops. Writing back to the accumulator allows the coalescer
18954 // to remove extra copies in the loop.
18955 MachineBasicBlock *
18956 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
18957                                  MachineBasicBlock *MBB) const {
18958   MachineOperand &AddendOp = MI->getOperand(3);
18959
18960   // Bail out early if the addend isn't a register - we can't switch these.
18961   if (!AddendOp.isReg())
18962     return MBB;
18963
18964   MachineFunction &MF = *MBB->getParent();
18965   MachineRegisterInfo &MRI = MF.getRegInfo();
18966
18967   // Check whether the addend is defined by a PHI:
18968   assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
18969   MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
18970   if (!AddendDef.isPHI())
18971     return MBB;
18972
18973   // Look for the following pattern:
18974   // loop:
18975   //   %addend = phi [%entry, 0], [%loop, %result]
18976   //   ...
18977   //   %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
18978
18979   // Replace with:
18980   //   loop:
18981   //   %addend = phi [%entry, 0], [%loop, %result]
18982   //   ...
18983   //   %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
18984
18985   for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
18986     assert(AddendDef.getOperand(i).isReg());
18987     MachineOperand PHISrcOp = AddendDef.getOperand(i);
18988     MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
18989     if (&PHISrcInst == MI) {
18990       // Found a matching instruction.
18991       unsigned NewFMAOpc = 0;
18992       switch (MI->getOpcode()) {
18993         case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
18994         case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
18995         case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
18996         case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
18997         case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
18998         case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
18999         case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
19000         case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
19001         case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
19002         case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
19003         case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
19004         case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
19005         case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
19006         case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
19007         case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
19008         case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
19009         case X86::VFMADDSUBPDr213r: NewFMAOpc = X86::VFMADDSUBPDr231r; break;
19010         case X86::VFMADDSUBPSr213r: NewFMAOpc = X86::VFMADDSUBPSr231r; break;
19011         case X86::VFMSUBADDPDr213r: NewFMAOpc = X86::VFMSUBADDPDr231r; break;
19012         case X86::VFMSUBADDPSr213r: NewFMAOpc = X86::VFMSUBADDPSr231r; break;
19013
19014         case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
19015         case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
19016         case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
19017         case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
19018         case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
19019         case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
19020         case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
19021         case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
19022         case X86::VFMADDSUBPDr213rY: NewFMAOpc = X86::VFMADDSUBPDr231rY; break;
19023         case X86::VFMADDSUBPSr213rY: NewFMAOpc = X86::VFMADDSUBPSr231rY; break;
19024         case X86::VFMSUBADDPDr213rY: NewFMAOpc = X86::VFMSUBADDPDr231rY; break;
19025         case X86::VFMSUBADDPSr213rY: NewFMAOpc = X86::VFMSUBADDPSr231rY; break;
19026         default: llvm_unreachable("Unrecognized FMA variant.");
19027       }
19028
19029       const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
19030       MachineInstrBuilder MIB =
19031         BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
19032         .addOperand(MI->getOperand(0))
19033         .addOperand(MI->getOperand(3))
19034         .addOperand(MI->getOperand(2))
19035         .addOperand(MI->getOperand(1));
19036       MBB->insert(MachineBasicBlock::iterator(MI), MIB);
19037       MI->eraseFromParent();
19038     }
19039   }
19040
19041   return MBB;
19042 }
19043
19044 MachineBasicBlock *
19045 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
19046                                                MachineBasicBlock *BB) const {
19047   switch (MI->getOpcode()) {
19048   default: llvm_unreachable("Unexpected instr type to insert");
19049   case X86::TAILJMPd64:
19050   case X86::TAILJMPr64:
19051   case X86::TAILJMPm64:
19052   case X86::TAILJMPd64_REX:
19053   case X86::TAILJMPr64_REX:
19054   case X86::TAILJMPm64_REX:
19055     llvm_unreachable("TAILJMP64 would not be touched here.");
19056   case X86::TCRETURNdi64:
19057   case X86::TCRETURNri64:
19058   case X86::TCRETURNmi64:
19059     return BB;
19060   case X86::WIN_ALLOCA:
19061     return EmitLoweredWinAlloca(MI, BB);
19062   case X86::SEG_ALLOCA_32:
19063   case X86::SEG_ALLOCA_64:
19064     return EmitLoweredSegAlloca(MI, BB);
19065   case X86::TLSCall_32:
19066   case X86::TLSCall_64:
19067     return EmitLoweredTLSCall(MI, BB);
19068   case X86::CMOV_GR8:
19069   case X86::CMOV_FR32:
19070   case X86::CMOV_FR64:
19071   case X86::CMOV_V4F32:
19072   case X86::CMOV_V2F64:
19073   case X86::CMOV_V2I64:
19074   case X86::CMOV_V8F32:
19075   case X86::CMOV_V4F64:
19076   case X86::CMOV_V4I64:
19077   case X86::CMOV_V16F32:
19078   case X86::CMOV_V8F64:
19079   case X86::CMOV_V8I64:
19080   case X86::CMOV_GR16:
19081   case X86::CMOV_GR32:
19082   case X86::CMOV_RFP32:
19083   case X86::CMOV_RFP64:
19084   case X86::CMOV_RFP80:
19085     return EmitLoweredSelect(MI, BB);
19086
19087   case X86::FP32_TO_INT16_IN_MEM:
19088   case X86::FP32_TO_INT32_IN_MEM:
19089   case X86::FP32_TO_INT64_IN_MEM:
19090   case X86::FP64_TO_INT16_IN_MEM:
19091   case X86::FP64_TO_INT32_IN_MEM:
19092   case X86::FP64_TO_INT64_IN_MEM:
19093   case X86::FP80_TO_INT16_IN_MEM:
19094   case X86::FP80_TO_INT32_IN_MEM:
19095   case X86::FP80_TO_INT64_IN_MEM: {
19096     MachineFunction *F = BB->getParent();
19097     const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19098     DebugLoc DL = MI->getDebugLoc();
19099
19100     // Change the floating point control register to use "round towards zero"
19101     // mode when truncating to an integer value.
19102     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
19103     addFrameReference(BuildMI(*BB, MI, DL,
19104                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
19105
19106     // Load the old value of the high byte of the control word...
19107     unsigned OldCW =
19108       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
19109     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
19110                       CWFrameIdx);
19111
19112     // Set the high part to be round to zero...
19113     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
19114       .addImm(0xC7F);
19115
19116     // Reload the modified control word now...
19117     addFrameReference(BuildMI(*BB, MI, DL,
19118                               TII->get(X86::FLDCW16m)), CWFrameIdx);
19119
19120     // Restore the memory image of control word to original value
19121     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
19122       .addReg(OldCW);
19123
19124     // Get the X86 opcode to use.
19125     unsigned Opc;
19126     switch (MI->getOpcode()) {
19127     default: llvm_unreachable("illegal opcode!");
19128     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
19129     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
19130     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
19131     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
19132     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
19133     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
19134     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
19135     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
19136     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
19137     }
19138
19139     X86AddressMode AM;
19140     MachineOperand &Op = MI->getOperand(0);
19141     if (Op.isReg()) {
19142       AM.BaseType = X86AddressMode::RegBase;
19143       AM.Base.Reg = Op.getReg();
19144     } else {
19145       AM.BaseType = X86AddressMode::FrameIndexBase;
19146       AM.Base.FrameIndex = Op.getIndex();
19147     }
19148     Op = MI->getOperand(1);
19149     if (Op.isImm())
19150       AM.Scale = Op.getImm();
19151     Op = MI->getOperand(2);
19152     if (Op.isImm())
19153       AM.IndexReg = Op.getImm();
19154     Op = MI->getOperand(3);
19155     if (Op.isGlobal()) {
19156       AM.GV = Op.getGlobal();
19157     } else {
19158       AM.Disp = Op.getImm();
19159     }
19160     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
19161                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
19162
19163     // Reload the original control word now.
19164     addFrameReference(BuildMI(*BB, MI, DL,
19165                               TII->get(X86::FLDCW16m)), CWFrameIdx);
19166
19167     MI->eraseFromParent();   // The pseudo instruction is gone now.
19168     return BB;
19169   }
19170     // String/text processing lowering.
19171   case X86::PCMPISTRM128REG:
19172   case X86::VPCMPISTRM128REG:
19173   case X86::PCMPISTRM128MEM:
19174   case X86::VPCMPISTRM128MEM:
19175   case X86::PCMPESTRM128REG:
19176   case X86::VPCMPESTRM128REG:
19177   case X86::PCMPESTRM128MEM:
19178   case X86::VPCMPESTRM128MEM:
19179     assert(Subtarget->hasSSE42() &&
19180            "Target must have SSE4.2 or AVX features enabled");
19181     return EmitPCMPSTRM(MI, BB, Subtarget->getInstrInfo());
19182
19183   // String/text processing lowering.
19184   case X86::PCMPISTRIREG:
19185   case X86::VPCMPISTRIREG:
19186   case X86::PCMPISTRIMEM:
19187   case X86::VPCMPISTRIMEM:
19188   case X86::PCMPESTRIREG:
19189   case X86::VPCMPESTRIREG:
19190   case X86::PCMPESTRIMEM:
19191   case X86::VPCMPESTRIMEM:
19192     assert(Subtarget->hasSSE42() &&
19193            "Target must have SSE4.2 or AVX features enabled");
19194     return EmitPCMPSTRI(MI, BB, Subtarget->getInstrInfo());
19195
19196   // Thread synchronization.
19197   case X86::MONITOR:
19198     return EmitMonitor(MI, BB, Subtarget);
19199
19200   // xbegin
19201   case X86::XBEGIN:
19202     return EmitXBegin(MI, BB, Subtarget->getInstrInfo());
19203
19204   case X86::VASTART_SAVE_XMM_REGS:
19205     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
19206
19207   case X86::VAARG_64:
19208     return EmitVAARG64WithCustomInserter(MI, BB);
19209
19210   case X86::EH_SjLj_SetJmp32:
19211   case X86::EH_SjLj_SetJmp64:
19212     return emitEHSjLjSetJmp(MI, BB);
19213
19214   case X86::EH_SjLj_LongJmp32:
19215   case X86::EH_SjLj_LongJmp64:
19216     return emitEHSjLjLongJmp(MI, BB);
19217
19218   case TargetOpcode::STATEPOINT:
19219     // As an implementation detail, STATEPOINT shares the STACKMAP format at
19220     // this point in the process.  We diverge later.
19221     return emitPatchPoint(MI, BB);
19222
19223   case TargetOpcode::STACKMAP:
19224   case TargetOpcode::PATCHPOINT:
19225     return emitPatchPoint(MI, BB);
19226
19227   case X86::VFMADDPDr213r:
19228   case X86::VFMADDPSr213r:
19229   case X86::VFMADDSDr213r:
19230   case X86::VFMADDSSr213r:
19231   case X86::VFMSUBPDr213r:
19232   case X86::VFMSUBPSr213r:
19233   case X86::VFMSUBSDr213r:
19234   case X86::VFMSUBSSr213r:
19235   case X86::VFNMADDPDr213r:
19236   case X86::VFNMADDPSr213r:
19237   case X86::VFNMADDSDr213r:
19238   case X86::VFNMADDSSr213r:
19239   case X86::VFNMSUBPDr213r:
19240   case X86::VFNMSUBPSr213r:
19241   case X86::VFNMSUBSDr213r:
19242   case X86::VFNMSUBSSr213r:
19243   case X86::VFMADDSUBPDr213r:
19244   case X86::VFMADDSUBPSr213r:
19245   case X86::VFMSUBADDPDr213r:
19246   case X86::VFMSUBADDPSr213r:
19247   case X86::VFMADDPDr213rY:
19248   case X86::VFMADDPSr213rY:
19249   case X86::VFMSUBPDr213rY:
19250   case X86::VFMSUBPSr213rY:
19251   case X86::VFNMADDPDr213rY:
19252   case X86::VFNMADDPSr213rY:
19253   case X86::VFNMSUBPDr213rY:
19254   case X86::VFNMSUBPSr213rY:
19255   case X86::VFMADDSUBPDr213rY:
19256   case X86::VFMADDSUBPSr213rY:
19257   case X86::VFMSUBADDPDr213rY:
19258   case X86::VFMSUBADDPSr213rY:
19259     return emitFMA3Instr(MI, BB);
19260   }
19261 }
19262
19263 //===----------------------------------------------------------------------===//
19264 //                           X86 Optimization Hooks
19265 //===----------------------------------------------------------------------===//
19266
19267 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
19268                                                       APInt &KnownZero,
19269                                                       APInt &KnownOne,
19270                                                       const SelectionDAG &DAG,
19271                                                       unsigned Depth) const {
19272   unsigned BitWidth = KnownZero.getBitWidth();
19273   unsigned Opc = Op.getOpcode();
19274   assert((Opc >= ISD::BUILTIN_OP_END ||
19275           Opc == ISD::INTRINSIC_WO_CHAIN ||
19276           Opc == ISD::INTRINSIC_W_CHAIN ||
19277           Opc == ISD::INTRINSIC_VOID) &&
19278          "Should use MaskedValueIsZero if you don't know whether Op"
19279          " is a target node!");
19280
19281   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
19282   switch (Opc) {
19283   default: break;
19284   case X86ISD::ADD:
19285   case X86ISD::SUB:
19286   case X86ISD::ADC:
19287   case X86ISD::SBB:
19288   case X86ISD::SMUL:
19289   case X86ISD::UMUL:
19290   case X86ISD::INC:
19291   case X86ISD::DEC:
19292   case X86ISD::OR:
19293   case X86ISD::XOR:
19294   case X86ISD::AND:
19295     // These nodes' second result is a boolean.
19296     if (Op.getResNo() == 0)
19297       break;
19298     // Fallthrough
19299   case X86ISD::SETCC:
19300     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
19301     break;
19302   case ISD::INTRINSIC_WO_CHAIN: {
19303     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
19304     unsigned NumLoBits = 0;
19305     switch (IntId) {
19306     default: break;
19307     case Intrinsic::x86_sse_movmsk_ps:
19308     case Intrinsic::x86_avx_movmsk_ps_256:
19309     case Intrinsic::x86_sse2_movmsk_pd:
19310     case Intrinsic::x86_avx_movmsk_pd_256:
19311     case Intrinsic::x86_mmx_pmovmskb:
19312     case Intrinsic::x86_sse2_pmovmskb_128:
19313     case Intrinsic::x86_avx2_pmovmskb: {
19314       // High bits of movmskp{s|d}, pmovmskb are known zero.
19315       switch (IntId) {
19316         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
19317         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
19318         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
19319         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
19320         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
19321         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
19322         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
19323         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
19324       }
19325       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
19326       break;
19327     }
19328     }
19329     break;
19330   }
19331   }
19332 }
19333
19334 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
19335   SDValue Op,
19336   const SelectionDAG &,
19337   unsigned Depth) const {
19338   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
19339   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
19340     return Op.getValueType().getScalarType().getSizeInBits();
19341
19342   // Fallback case.
19343   return 1;
19344 }
19345
19346 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
19347 /// node is a GlobalAddress + offset.
19348 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
19349                                        const GlobalValue* &GA,
19350                                        int64_t &Offset) const {
19351   if (N->getOpcode() == X86ISD::Wrapper) {
19352     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
19353       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
19354       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
19355       return true;
19356     }
19357   }
19358   return TargetLowering::isGAPlusOffset(N, GA, Offset);
19359 }
19360
19361 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
19362 /// same as extracting the high 128-bit part of 256-bit vector and then
19363 /// inserting the result into the low part of a new 256-bit vector
19364 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
19365   EVT VT = SVOp->getValueType(0);
19366   unsigned NumElems = VT.getVectorNumElements();
19367
19368   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
19369   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
19370     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
19371         SVOp->getMaskElt(j) >= 0)
19372       return false;
19373
19374   return true;
19375 }
19376
19377 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
19378 /// same as extracting the low 128-bit part of 256-bit vector and then
19379 /// inserting the result into the high part of a new 256-bit vector
19380 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
19381   EVT VT = SVOp->getValueType(0);
19382   unsigned NumElems = VT.getVectorNumElements();
19383
19384   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
19385   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
19386     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
19387         SVOp->getMaskElt(j) >= 0)
19388       return false;
19389
19390   return true;
19391 }
19392
19393 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
19394 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
19395                                         TargetLowering::DAGCombinerInfo &DCI,
19396                                         const X86Subtarget* Subtarget) {
19397   SDLoc dl(N);
19398   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
19399   SDValue V1 = SVOp->getOperand(0);
19400   SDValue V2 = SVOp->getOperand(1);
19401   EVT VT = SVOp->getValueType(0);
19402   unsigned NumElems = VT.getVectorNumElements();
19403
19404   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
19405       V2.getOpcode() == ISD::CONCAT_VECTORS) {
19406     //
19407     //                   0,0,0,...
19408     //                      |
19409     //    V      UNDEF    BUILD_VECTOR    UNDEF
19410     //     \      /           \           /
19411     //  CONCAT_VECTOR         CONCAT_VECTOR
19412     //         \                  /
19413     //          \                /
19414     //          RESULT: V + zero extended
19415     //
19416     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
19417         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
19418         V1.getOperand(1).getOpcode() != ISD::UNDEF)
19419       return SDValue();
19420
19421     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
19422       return SDValue();
19423
19424     // To match the shuffle mask, the first half of the mask should
19425     // be exactly the first vector, and all the rest a splat with the
19426     // first element of the second one.
19427     for (unsigned i = 0; i != NumElems/2; ++i)
19428       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
19429           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
19430         return SDValue();
19431
19432     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
19433     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
19434       if (Ld->hasNUsesOfValue(1, 0)) {
19435         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
19436         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
19437         SDValue ResNode =
19438           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
19439                                   Ld->getMemoryVT(),
19440                                   Ld->getPointerInfo(),
19441                                   Ld->getAlignment(),
19442                                   false/*isVolatile*/, true/*ReadMem*/,
19443                                   false/*WriteMem*/);
19444
19445         // Make sure the newly-created LOAD is in the same position as Ld in
19446         // terms of dependency. We create a TokenFactor for Ld and ResNode,
19447         // and update uses of Ld's output chain to use the TokenFactor.
19448         if (Ld->hasAnyUseOfValue(1)) {
19449           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
19450                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
19451           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
19452           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
19453                                  SDValue(ResNode.getNode(), 1));
19454         }
19455
19456         return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
19457       }
19458     }
19459
19460     // Emit a zeroed vector and insert the desired subvector on its
19461     // first half.
19462     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
19463     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
19464     return DCI.CombineTo(N, InsV);
19465   }
19466
19467   //===--------------------------------------------------------------------===//
19468   // Combine some shuffles into subvector extracts and inserts:
19469   //
19470
19471   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
19472   if (isShuffleHigh128VectorInsertLow(SVOp)) {
19473     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
19474     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
19475     return DCI.CombineTo(N, InsV);
19476   }
19477
19478   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
19479   if (isShuffleLow128VectorInsertHigh(SVOp)) {
19480     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
19481     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
19482     return DCI.CombineTo(N, InsV);
19483   }
19484
19485   return SDValue();
19486 }
19487
19488 /// \brief Combine an arbitrary chain of shuffles into a single instruction if
19489 /// possible.
19490 ///
19491 /// This is the leaf of the recursive combinine below. When we have found some
19492 /// chain of single-use x86 shuffle instructions and accumulated the combined
19493 /// shuffle mask represented by them, this will try to pattern match that mask
19494 /// into either a single instruction if there is a special purpose instruction
19495 /// for this operation, or into a PSHUFB instruction which is a fully general
19496 /// instruction but should only be used to replace chains over a certain depth.
19497 static bool combineX86ShuffleChain(SDValue Op, SDValue Root, ArrayRef<int> Mask,
19498                                    int Depth, bool HasPSHUFB, SelectionDAG &DAG,
19499                                    TargetLowering::DAGCombinerInfo &DCI,
19500                                    const X86Subtarget *Subtarget) {
19501   assert(!Mask.empty() && "Cannot combine an empty shuffle mask!");
19502
19503   // Find the operand that enters the chain. Note that multiple uses are OK
19504   // here, we're not going to remove the operand we find.
19505   SDValue Input = Op.getOperand(0);
19506   while (Input.getOpcode() == ISD::BITCAST)
19507     Input = Input.getOperand(0);
19508
19509   MVT VT = Input.getSimpleValueType();
19510   MVT RootVT = Root.getSimpleValueType();
19511   SDLoc DL(Root);
19512
19513   // Just remove no-op shuffle masks.
19514   if (Mask.size() == 1) {
19515     DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Input),
19516                   /*AddTo*/ true);
19517     return true;
19518   }
19519
19520   // Use the float domain if the operand type is a floating point type.
19521   bool FloatDomain = VT.isFloatingPoint();
19522
19523   // For floating point shuffles, we don't have free copies in the shuffle
19524   // instructions or the ability to load as part of the instruction, so
19525   // canonicalize their shuffles to UNPCK or MOV variants.
19526   //
19527   // Note that even with AVX we prefer the PSHUFD form of shuffle for integer
19528   // vectors because it can have a load folded into it that UNPCK cannot. This
19529   // doesn't preclude something switching to the shorter encoding post-RA.
19530   //
19531   // FIXME: Should teach these routines about AVX vector widths.
19532   if (FloatDomain && VT.getSizeInBits() == 128) {
19533     if (Mask.equals({0, 0}) || Mask.equals({1, 1})) {
19534       bool Lo = Mask.equals({0, 0});
19535       unsigned Shuffle;
19536       MVT ShuffleVT;
19537       // Check if we have SSE3 which will let us use MOVDDUP. That instruction
19538       // is no slower than UNPCKLPD but has the option to fold the input operand
19539       // into even an unaligned memory load.
19540       if (Lo && Subtarget->hasSSE3()) {
19541         Shuffle = X86ISD::MOVDDUP;
19542         ShuffleVT = MVT::v2f64;
19543       } else {
19544         // We have MOVLHPS and MOVHLPS throughout SSE and they encode smaller
19545         // than the UNPCK variants.
19546         Shuffle = Lo ? X86ISD::MOVLHPS : X86ISD::MOVHLPS;
19547         ShuffleVT = MVT::v4f32;
19548       }
19549       if (Depth == 1 && Root->getOpcode() == Shuffle)
19550         return false; // Nothing to do!
19551       Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
19552       DCI.AddToWorklist(Op.getNode());
19553       if (Shuffle == X86ISD::MOVDDUP)
19554         Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
19555       else
19556         Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
19557       DCI.AddToWorklist(Op.getNode());
19558       DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
19559                     /*AddTo*/ true);
19560       return true;
19561     }
19562     if (Subtarget->hasSSE3() &&
19563         (Mask.equals({0, 0, 2, 2}) || Mask.equals({1, 1, 3, 3}))) {
19564       bool Lo = Mask.equals({0, 0, 2, 2});
19565       unsigned Shuffle = Lo ? X86ISD::MOVSLDUP : X86ISD::MOVSHDUP;
19566       MVT ShuffleVT = MVT::v4f32;
19567       if (Depth == 1 && Root->getOpcode() == Shuffle)
19568         return false; // Nothing to do!
19569       Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
19570       DCI.AddToWorklist(Op.getNode());
19571       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
19572       DCI.AddToWorklist(Op.getNode());
19573       DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
19574                     /*AddTo*/ true);
19575       return true;
19576     }
19577     if (Mask.equals({0, 0, 1, 1}) || Mask.equals({2, 2, 3, 3})) {
19578       bool Lo = Mask.equals({0, 0, 1, 1});
19579       unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
19580       MVT ShuffleVT = MVT::v4f32;
19581       if (Depth == 1 && Root->getOpcode() == Shuffle)
19582         return false; // Nothing to do!
19583       Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
19584       DCI.AddToWorklist(Op.getNode());
19585       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
19586       DCI.AddToWorklist(Op.getNode());
19587       DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
19588                     /*AddTo*/ true);
19589       return true;
19590     }
19591   }
19592
19593   // We always canonicalize the 8 x i16 and 16 x i8 shuffles into their UNPCK
19594   // variants as none of these have single-instruction variants that are
19595   // superior to the UNPCK formulation.
19596   if (!FloatDomain && VT.getSizeInBits() == 128 &&
19597       (Mask.equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
19598        Mask.equals({4, 4, 5, 5, 6, 6, 7, 7}) ||
19599        Mask.equals({0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7}) ||
19600        Mask.equals(
19601            {8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15, 15}))) {
19602     bool Lo = Mask[0] == 0;
19603     unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
19604     if (Depth == 1 && Root->getOpcode() == Shuffle)
19605       return false; // Nothing to do!
19606     MVT ShuffleVT;
19607     switch (Mask.size()) {
19608     case 8:
19609       ShuffleVT = MVT::v8i16;
19610       break;
19611     case 16:
19612       ShuffleVT = MVT::v16i8;
19613       break;
19614     default:
19615       llvm_unreachable("Impossible mask size!");
19616     };
19617     Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
19618     DCI.AddToWorklist(Op.getNode());
19619     Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
19620     DCI.AddToWorklist(Op.getNode());
19621     DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
19622                   /*AddTo*/ true);
19623     return true;
19624   }
19625
19626   // Don't try to re-form single instruction chains under any circumstances now
19627   // that we've done encoding canonicalization for them.
19628   if (Depth < 2)
19629     return false;
19630
19631   // If we have 3 or more shuffle instructions or a chain involving PSHUFB, we
19632   // can replace them with a single PSHUFB instruction profitably. Intel's
19633   // manuals suggest only using PSHUFB if doing so replacing 5 instructions, but
19634   // in practice PSHUFB tends to be *very* fast so we're more aggressive.
19635   if ((Depth >= 3 || HasPSHUFB) && Subtarget->hasSSSE3()) {
19636     SmallVector<SDValue, 16> PSHUFBMask;
19637     int NumBytes = VT.getSizeInBits() / 8;
19638     int Ratio = NumBytes / Mask.size();
19639     for (int i = 0; i < NumBytes; ++i) {
19640       if (Mask[i / Ratio] == SM_SentinelUndef) {
19641         PSHUFBMask.push_back(DAG.getUNDEF(MVT::i8));
19642         continue;
19643       }
19644       int M = Mask[i / Ratio] != SM_SentinelZero
19645                   ? Ratio * Mask[i / Ratio] + i % Ratio
19646                   : 255;
19647       PSHUFBMask.push_back(DAG.getConstant(M, MVT::i8));
19648     }
19649     MVT ByteVT = MVT::getVectorVT(MVT::i8, NumBytes);
19650     Op = DAG.getNode(ISD::BITCAST, DL, ByteVT, Input);
19651     DCI.AddToWorklist(Op.getNode());
19652     SDValue PSHUFBMaskOp =
19653         DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVT, PSHUFBMask);
19654     DCI.AddToWorklist(PSHUFBMaskOp.getNode());
19655     Op = DAG.getNode(X86ISD::PSHUFB, DL, ByteVT, Op, PSHUFBMaskOp);
19656     DCI.AddToWorklist(Op.getNode());
19657     DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
19658                   /*AddTo*/ true);
19659     return true;
19660   }
19661
19662   // Failed to find any combines.
19663   return false;
19664 }
19665
19666 /// \brief Fully generic combining of x86 shuffle instructions.
19667 ///
19668 /// This should be the last combine run over the x86 shuffle instructions. Once
19669 /// they have been fully optimized, this will recursively consider all chains
19670 /// of single-use shuffle instructions, build a generic model of the cumulative
19671 /// shuffle operation, and check for simpler instructions which implement this
19672 /// operation. We use this primarily for two purposes:
19673 ///
19674 /// 1) Collapse generic shuffles to specialized single instructions when
19675 ///    equivalent. In most cases, this is just an encoding size win, but
19676 ///    sometimes we will collapse multiple generic shuffles into a single
19677 ///    special-purpose shuffle.
19678 /// 2) Look for sequences of shuffle instructions with 3 or more total
19679 ///    instructions, and replace them with the slightly more expensive SSSE3
19680 ///    PSHUFB instruction if available. We do this as the last combining step
19681 ///    to ensure we avoid using PSHUFB if we can implement the shuffle with
19682 ///    a suitable short sequence of other instructions. The PHUFB will either
19683 ///    use a register or have to read from memory and so is slightly (but only
19684 ///    slightly) more expensive than the other shuffle instructions.
19685 ///
19686 /// Because this is inherently a quadratic operation (for each shuffle in
19687 /// a chain, we recurse up the chain), the depth is limited to 8 instructions.
19688 /// This should never be an issue in practice as the shuffle lowering doesn't
19689 /// produce sequences of more than 8 instructions.
19690 ///
19691 /// FIXME: We will currently miss some cases where the redundant shuffling
19692 /// would simplify under the threshold for PSHUFB formation because of
19693 /// combine-ordering. To fix this, we should do the redundant instruction
19694 /// combining in this recursive walk.
19695 static bool combineX86ShufflesRecursively(SDValue Op, SDValue Root,
19696                                           ArrayRef<int> RootMask,
19697                                           int Depth, bool HasPSHUFB,
19698                                           SelectionDAG &DAG,
19699                                           TargetLowering::DAGCombinerInfo &DCI,
19700                                           const X86Subtarget *Subtarget) {
19701   // Bound the depth of our recursive combine because this is ultimately
19702   // quadratic in nature.
19703   if (Depth > 8)
19704     return false;
19705
19706   // Directly rip through bitcasts to find the underlying operand.
19707   while (Op.getOpcode() == ISD::BITCAST && Op.getOperand(0).hasOneUse())
19708     Op = Op.getOperand(0);
19709
19710   MVT VT = Op.getSimpleValueType();
19711   if (!VT.isVector())
19712     return false; // Bail if we hit a non-vector.
19713
19714   assert(Root.getSimpleValueType().isVector() &&
19715          "Shuffles operate on vector types!");
19716   assert(VT.getSizeInBits() == Root.getSimpleValueType().getSizeInBits() &&
19717          "Can only combine shuffles of the same vector register size.");
19718
19719   if (!isTargetShuffle(Op.getOpcode()))
19720     return false;
19721   SmallVector<int, 16> OpMask;
19722   bool IsUnary;
19723   bool HaveMask = getTargetShuffleMask(Op.getNode(), VT, OpMask, IsUnary);
19724   // We only can combine unary shuffles which we can decode the mask for.
19725   if (!HaveMask || !IsUnary)
19726     return false;
19727
19728   assert(VT.getVectorNumElements() == OpMask.size() &&
19729          "Different mask size from vector size!");
19730   assert(((RootMask.size() > OpMask.size() &&
19731            RootMask.size() % OpMask.size() == 0) ||
19732           (OpMask.size() > RootMask.size() &&
19733            OpMask.size() % RootMask.size() == 0) ||
19734           OpMask.size() == RootMask.size()) &&
19735          "The smaller number of elements must divide the larger.");
19736   int RootRatio = std::max<int>(1, OpMask.size() / RootMask.size());
19737   int OpRatio = std::max<int>(1, RootMask.size() / OpMask.size());
19738   assert(((RootRatio == 1 && OpRatio == 1) ||
19739           (RootRatio == 1) != (OpRatio == 1)) &&
19740          "Must not have a ratio for both incoming and op masks!");
19741
19742   SmallVector<int, 16> Mask;
19743   Mask.reserve(std::max(OpMask.size(), RootMask.size()));
19744
19745   // Merge this shuffle operation's mask into our accumulated mask. Note that
19746   // this shuffle's mask will be the first applied to the input, followed by the
19747   // root mask to get us all the way to the root value arrangement. The reason
19748   // for this order is that we are recursing up the operation chain.
19749   for (int i = 0, e = std::max(OpMask.size(), RootMask.size()); i < e; ++i) {
19750     int RootIdx = i / RootRatio;
19751     if (RootMask[RootIdx] < 0) {
19752       // This is a zero or undef lane, we're done.
19753       Mask.push_back(RootMask[RootIdx]);
19754       continue;
19755     }
19756
19757     int RootMaskedIdx = RootMask[RootIdx] * RootRatio + i % RootRatio;
19758     int OpIdx = RootMaskedIdx / OpRatio;
19759     if (OpMask[OpIdx] < 0) {
19760       // The incoming lanes are zero or undef, it doesn't matter which ones we
19761       // are using.
19762       Mask.push_back(OpMask[OpIdx]);
19763       continue;
19764     }
19765
19766     // Ok, we have non-zero lanes, map them through.
19767     Mask.push_back(OpMask[OpIdx] * OpRatio +
19768                    RootMaskedIdx % OpRatio);
19769   }
19770
19771   // See if we can recurse into the operand to combine more things.
19772   switch (Op.getOpcode()) {
19773     case X86ISD::PSHUFB:
19774       HasPSHUFB = true;
19775     case X86ISD::PSHUFD:
19776     case X86ISD::PSHUFHW:
19777     case X86ISD::PSHUFLW:
19778       if (Op.getOperand(0).hasOneUse() &&
19779           combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
19780                                         HasPSHUFB, DAG, DCI, Subtarget))
19781         return true;
19782       break;
19783
19784     case X86ISD::UNPCKL:
19785     case X86ISD::UNPCKH:
19786       assert(Op.getOperand(0) == Op.getOperand(1) && "We only combine unary shuffles!");
19787       // We can't check for single use, we have to check that this shuffle is the only user.
19788       if (Op->isOnlyUserOf(Op.getOperand(0).getNode()) &&
19789           combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
19790                                         HasPSHUFB, DAG, DCI, Subtarget))
19791           return true;
19792       break;
19793   }
19794
19795   // Minor canonicalization of the accumulated shuffle mask to make it easier
19796   // to match below. All this does is detect masks with squential pairs of
19797   // elements, and shrink them to the half-width mask. It does this in a loop
19798   // so it will reduce the size of the mask to the minimal width mask which
19799   // performs an equivalent shuffle.
19800   SmallVector<int, 16> WidenedMask;
19801   while (Mask.size() > 1 && canWidenShuffleElements(Mask, WidenedMask)) {
19802     Mask = std::move(WidenedMask);
19803     WidenedMask.clear();
19804   }
19805
19806   return combineX86ShuffleChain(Op, Root, Mask, Depth, HasPSHUFB, DAG, DCI,
19807                                 Subtarget);
19808 }
19809
19810 /// \brief Get the PSHUF-style mask from PSHUF node.
19811 ///
19812 /// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
19813 /// PSHUF-style masks that can be reused with such instructions.
19814 static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
19815   MVT VT = N.getSimpleValueType();
19816   SmallVector<int, 4> Mask;
19817   bool IsUnary;
19818   bool HaveMask = getTargetShuffleMask(N.getNode(), VT, Mask, IsUnary);
19819   (void)HaveMask;
19820   assert(HaveMask);
19821
19822   // If we have more than 128-bits, only the low 128-bits of shuffle mask
19823   // matter. Check that the upper masks are repeats and remove them.
19824   if (VT.getSizeInBits() > 128) {
19825     int LaneElts = 128 / VT.getScalarSizeInBits();
19826 #ifndef NDEBUG
19827     for (int i = 1, NumLanes = VT.getSizeInBits() / 128; i < NumLanes; ++i)
19828       for (int j = 0; j < LaneElts; ++j)
19829         assert(Mask[j] == Mask[i * LaneElts + j] - LaneElts &&
19830                "Mask doesn't repeat in high 128-bit lanes!");
19831 #endif
19832     Mask.resize(LaneElts);
19833   }
19834
19835   switch (N.getOpcode()) {
19836   case X86ISD::PSHUFD:
19837     return Mask;
19838   case X86ISD::PSHUFLW:
19839     Mask.resize(4);
19840     return Mask;
19841   case X86ISD::PSHUFHW:
19842     Mask.erase(Mask.begin(), Mask.begin() + 4);
19843     for (int &M : Mask)
19844       M -= 4;
19845     return Mask;
19846   default:
19847     llvm_unreachable("No valid shuffle instruction found!");
19848   }
19849 }
19850
19851 /// \brief Search for a combinable shuffle across a chain ending in pshufd.
19852 ///
19853 /// We walk up the chain and look for a combinable shuffle, skipping over
19854 /// shuffles that we could hoist this shuffle's transformation past without
19855 /// altering anything.
19856 static SDValue
19857 combineRedundantDWordShuffle(SDValue N, MutableArrayRef<int> Mask,
19858                              SelectionDAG &DAG,
19859                              TargetLowering::DAGCombinerInfo &DCI) {
19860   assert(N.getOpcode() == X86ISD::PSHUFD &&
19861          "Called with something other than an x86 128-bit half shuffle!");
19862   SDLoc DL(N);
19863
19864   // Walk up a single-use chain looking for a combinable shuffle. Keep a stack
19865   // of the shuffles in the chain so that we can form a fresh chain to replace
19866   // this one.
19867   SmallVector<SDValue, 8> Chain;
19868   SDValue V = N.getOperand(0);
19869   for (; V.hasOneUse(); V = V.getOperand(0)) {
19870     switch (V.getOpcode()) {
19871     default:
19872       return SDValue(); // Nothing combined!
19873
19874     case ISD::BITCAST:
19875       // Skip bitcasts as we always know the type for the target specific
19876       // instructions.
19877       continue;
19878
19879     case X86ISD::PSHUFD:
19880       // Found another dword shuffle.
19881       break;
19882
19883     case X86ISD::PSHUFLW:
19884       // Check that the low words (being shuffled) are the identity in the
19885       // dword shuffle, and the high words are self-contained.
19886       if (Mask[0] != 0 || Mask[1] != 1 ||
19887           !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
19888         return SDValue();
19889
19890       Chain.push_back(V);
19891       continue;
19892
19893     case X86ISD::PSHUFHW:
19894       // Check that the high words (being shuffled) are the identity in the
19895       // dword shuffle, and the low words are self-contained.
19896       if (Mask[2] != 2 || Mask[3] != 3 ||
19897           !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
19898         return SDValue();
19899
19900       Chain.push_back(V);
19901       continue;
19902
19903     case X86ISD::UNPCKL:
19904     case X86ISD::UNPCKH:
19905       // For either i8 -> i16 or i16 -> i32 unpacks, we can combine a dword
19906       // shuffle into a preceding word shuffle.
19907       if (V.getSimpleValueType().getScalarType() != MVT::i8 &&
19908           V.getSimpleValueType().getScalarType() != MVT::i16)
19909         return SDValue();
19910
19911       // Search for a half-shuffle which we can combine with.
19912       unsigned CombineOp =
19913           V.getOpcode() == X86ISD::UNPCKL ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
19914       if (V.getOperand(0) != V.getOperand(1) ||
19915           !V->isOnlyUserOf(V.getOperand(0).getNode()))
19916         return SDValue();
19917       Chain.push_back(V);
19918       V = V.getOperand(0);
19919       do {
19920         switch (V.getOpcode()) {
19921         default:
19922           return SDValue(); // Nothing to combine.
19923
19924         case X86ISD::PSHUFLW:
19925         case X86ISD::PSHUFHW:
19926           if (V.getOpcode() == CombineOp)
19927             break;
19928
19929           Chain.push_back(V);
19930
19931           // Fallthrough!
19932         case ISD::BITCAST:
19933           V = V.getOperand(0);
19934           continue;
19935         }
19936         break;
19937       } while (V.hasOneUse());
19938       break;
19939     }
19940     // Break out of the loop if we break out of the switch.
19941     break;
19942   }
19943
19944   if (!V.hasOneUse())
19945     // We fell out of the loop without finding a viable combining instruction.
19946     return SDValue();
19947
19948   // Merge this node's mask and our incoming mask.
19949   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
19950   for (int &M : Mask)
19951     M = VMask[M];
19952   V = DAG.getNode(V.getOpcode(), DL, V.getValueType(), V.getOperand(0),
19953                   getV4X86ShuffleImm8ForMask(Mask, DAG));
19954
19955   // Rebuild the chain around this new shuffle.
19956   while (!Chain.empty()) {
19957     SDValue W = Chain.pop_back_val();
19958
19959     if (V.getValueType() != W.getOperand(0).getValueType())
19960       V = DAG.getNode(ISD::BITCAST, DL, W.getOperand(0).getValueType(), V);
19961
19962     switch (W.getOpcode()) {
19963     default:
19964       llvm_unreachable("Only PSHUF and UNPCK instructions get here!");
19965
19966     case X86ISD::UNPCKL:
19967     case X86ISD::UNPCKH:
19968       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, V);
19969       break;
19970
19971     case X86ISD::PSHUFD:
19972     case X86ISD::PSHUFLW:
19973     case X86ISD::PSHUFHW:
19974       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, W.getOperand(1));
19975       break;
19976     }
19977   }
19978   if (V.getValueType() != N.getValueType())
19979     V = DAG.getNode(ISD::BITCAST, DL, N.getValueType(), V);
19980
19981   // Return the new chain to replace N.
19982   return V;
19983 }
19984
19985 /// \brief Search for a combinable shuffle across a chain ending in pshuflw or pshufhw.
19986 ///
19987 /// We walk up the chain, skipping shuffles of the other half and looking
19988 /// through shuffles which switch halves trying to find a shuffle of the same
19989 /// pair of dwords.
19990 static bool combineRedundantHalfShuffle(SDValue N, MutableArrayRef<int> Mask,
19991                                         SelectionDAG &DAG,
19992                                         TargetLowering::DAGCombinerInfo &DCI) {
19993   assert(
19994       (N.getOpcode() == X86ISD::PSHUFLW || N.getOpcode() == X86ISD::PSHUFHW) &&
19995       "Called with something other than an x86 128-bit half shuffle!");
19996   SDLoc DL(N);
19997   unsigned CombineOpcode = N.getOpcode();
19998
19999   // Walk up a single-use chain looking for a combinable shuffle.
20000   SDValue V = N.getOperand(0);
20001   for (; V.hasOneUse(); V = V.getOperand(0)) {
20002     switch (V.getOpcode()) {
20003     default:
20004       return false; // Nothing combined!
20005
20006     case ISD::BITCAST:
20007       // Skip bitcasts as we always know the type for the target specific
20008       // instructions.
20009       continue;
20010
20011     case X86ISD::PSHUFLW:
20012     case X86ISD::PSHUFHW:
20013       if (V.getOpcode() == CombineOpcode)
20014         break;
20015
20016       // Other-half shuffles are no-ops.
20017       continue;
20018     }
20019     // Break out of the loop if we break out of the switch.
20020     break;
20021   }
20022
20023   if (!V.hasOneUse())
20024     // We fell out of the loop without finding a viable combining instruction.
20025     return false;
20026
20027   // Combine away the bottom node as its shuffle will be accumulated into
20028   // a preceding shuffle.
20029   DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
20030
20031   // Record the old value.
20032   SDValue Old = V;
20033
20034   // Merge this node's mask and our incoming mask (adjusted to account for all
20035   // the pshufd instructions encountered).
20036   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
20037   for (int &M : Mask)
20038     M = VMask[M];
20039   V = DAG.getNode(V.getOpcode(), DL, MVT::v8i16, V.getOperand(0),
20040                   getV4X86ShuffleImm8ForMask(Mask, DAG));
20041
20042   // Check that the shuffles didn't cancel each other out. If not, we need to
20043   // combine to the new one.
20044   if (Old != V)
20045     // Replace the combinable shuffle with the combined one, updating all users
20046     // so that we re-evaluate the chain here.
20047     DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
20048
20049   return true;
20050 }
20051
20052 /// \brief Try to combine x86 target specific shuffles.
20053 static SDValue PerformTargetShuffleCombine(SDValue N, SelectionDAG &DAG,
20054                                            TargetLowering::DAGCombinerInfo &DCI,
20055                                            const X86Subtarget *Subtarget) {
20056   SDLoc DL(N);
20057   MVT VT = N.getSimpleValueType();
20058   SmallVector<int, 4> Mask;
20059
20060   switch (N.getOpcode()) {
20061   case X86ISD::PSHUFD:
20062   case X86ISD::PSHUFLW:
20063   case X86ISD::PSHUFHW:
20064     Mask = getPSHUFShuffleMask(N);
20065     assert(Mask.size() == 4);
20066     break;
20067   default:
20068     return SDValue();
20069   }
20070
20071   // Nuke no-op shuffles that show up after combining.
20072   if (isNoopShuffleMask(Mask))
20073     return DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
20074
20075   // Look for simplifications involving one or two shuffle instructions.
20076   SDValue V = N.getOperand(0);
20077   switch (N.getOpcode()) {
20078   default:
20079     break;
20080   case X86ISD::PSHUFLW:
20081   case X86ISD::PSHUFHW:
20082     assert(VT.getScalarType() == MVT::i16 && "Bad word shuffle type!");
20083
20084     if (combineRedundantHalfShuffle(N, Mask, DAG, DCI))
20085       return SDValue(); // We combined away this shuffle, so we're done.
20086
20087     // See if this reduces to a PSHUFD which is no more expensive and can
20088     // combine with more operations. Note that it has to at least flip the
20089     // dwords as otherwise it would have been removed as a no-op.
20090     if (makeArrayRef(Mask).equals({2, 3, 0, 1})) {
20091       int DMask[] = {0, 1, 2, 3};
20092       int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
20093       DMask[DOffset + 0] = DOffset + 1;
20094       DMask[DOffset + 1] = DOffset + 0;
20095       MVT DVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
20096       V = DAG.getNode(ISD::BITCAST, DL, DVT, V);
20097       DCI.AddToWorklist(V.getNode());
20098       V = DAG.getNode(X86ISD::PSHUFD, DL, DVT, V,
20099                       getV4X86ShuffleImm8ForMask(DMask, DAG));
20100       DCI.AddToWorklist(V.getNode());
20101       return DAG.getNode(ISD::BITCAST, DL, VT, V);
20102     }
20103
20104     // Look for shuffle patterns which can be implemented as a single unpack.
20105     // FIXME: This doesn't handle the location of the PSHUFD generically, and
20106     // only works when we have a PSHUFD followed by two half-shuffles.
20107     if (Mask[0] == Mask[1] && Mask[2] == Mask[3] &&
20108         (V.getOpcode() == X86ISD::PSHUFLW ||
20109          V.getOpcode() == X86ISD::PSHUFHW) &&
20110         V.getOpcode() != N.getOpcode() &&
20111         V.hasOneUse()) {
20112       SDValue D = V.getOperand(0);
20113       while (D.getOpcode() == ISD::BITCAST && D.hasOneUse())
20114         D = D.getOperand(0);
20115       if (D.getOpcode() == X86ISD::PSHUFD && D.hasOneUse()) {
20116         SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
20117         SmallVector<int, 4> DMask = getPSHUFShuffleMask(D);
20118         int NOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
20119         int VOffset = V.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
20120         int WordMask[8];
20121         for (int i = 0; i < 4; ++i) {
20122           WordMask[i + NOffset] = Mask[i] + NOffset;
20123           WordMask[i + VOffset] = VMask[i] + VOffset;
20124         }
20125         // Map the word mask through the DWord mask.
20126         int MappedMask[8];
20127         for (int i = 0; i < 8; ++i)
20128           MappedMask[i] = 2 * DMask[WordMask[i] / 2] + WordMask[i] % 2;
20129         if (makeArrayRef(MappedMask).equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
20130             makeArrayRef(MappedMask).equals({4, 4, 5, 5, 6, 6, 7, 7})) {
20131           // We can replace all three shuffles with an unpack.
20132           V = DAG.getNode(ISD::BITCAST, DL, VT, D.getOperand(0));
20133           DCI.AddToWorklist(V.getNode());
20134           return DAG.getNode(MappedMask[0] == 0 ? X86ISD::UNPCKL
20135                                                 : X86ISD::UNPCKH,
20136                              DL, VT, V, V);
20137         }
20138       }
20139     }
20140
20141     break;
20142
20143   case X86ISD::PSHUFD:
20144     if (SDValue NewN = combineRedundantDWordShuffle(N, Mask, DAG, DCI))
20145       return NewN;
20146
20147     break;
20148   }
20149
20150   return SDValue();
20151 }
20152
20153 /// \brief Try to combine a shuffle into a target-specific add-sub node.
20154 ///
20155 /// We combine this directly on the abstract vector shuffle nodes so it is
20156 /// easier to generically match. We also insert dummy vector shuffle nodes for
20157 /// the operands which explicitly discard the lanes which are unused by this
20158 /// operation to try to flow through the rest of the combiner the fact that
20159 /// they're unused.
20160 static SDValue combineShuffleToAddSub(SDNode *N, SelectionDAG &DAG) {
20161   SDLoc DL(N);
20162   EVT VT = N->getValueType(0);
20163
20164   // We only handle target-independent shuffles.
20165   // FIXME: It would be easy and harmless to use the target shuffle mask
20166   // extraction tool to support more.
20167   if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
20168     return SDValue();
20169
20170   auto *SVN = cast<ShuffleVectorSDNode>(N);
20171   ArrayRef<int> Mask = SVN->getMask();
20172   SDValue V1 = N->getOperand(0);
20173   SDValue V2 = N->getOperand(1);
20174
20175   // We require the first shuffle operand to be the SUB node, and the second to
20176   // be the ADD node.
20177   // FIXME: We should support the commuted patterns.
20178   if (V1->getOpcode() != ISD::FSUB || V2->getOpcode() != ISD::FADD)
20179     return SDValue();
20180
20181   // If there are other uses of these operations we can't fold them.
20182   if (!V1->hasOneUse() || !V2->hasOneUse())
20183     return SDValue();
20184
20185   // Ensure that both operations have the same operands. Note that we can
20186   // commute the FADD operands.
20187   SDValue LHS = V1->getOperand(0), RHS = V1->getOperand(1);
20188   if ((V2->getOperand(0) != LHS || V2->getOperand(1) != RHS) &&
20189       (V2->getOperand(0) != RHS || V2->getOperand(1) != LHS))
20190     return SDValue();
20191
20192   // We're looking for blends between FADD and FSUB nodes. We insist on these
20193   // nodes being lined up in a specific expected pattern.
20194   if (!(isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
20195         isShuffleEquivalent(V1, V2, Mask, {0, 5, 2, 7}) ||
20196         isShuffleEquivalent(V1, V2, Mask, {0, 9, 2, 11, 4, 13, 6, 15})))
20197     return SDValue();
20198
20199   // Only specific types are legal at this point, assert so we notice if and
20200   // when these change.
20201   assert((VT == MVT::v4f32 || VT == MVT::v2f64 || VT == MVT::v8f32 ||
20202           VT == MVT::v4f64) &&
20203          "Unknown vector type encountered!");
20204
20205   return DAG.getNode(X86ISD::ADDSUB, DL, VT, LHS, RHS);
20206 }
20207
20208 /// PerformShuffleCombine - Performs several different shuffle combines.
20209 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
20210                                      TargetLowering::DAGCombinerInfo &DCI,
20211                                      const X86Subtarget *Subtarget) {
20212   SDLoc dl(N);
20213   SDValue N0 = N->getOperand(0);
20214   SDValue N1 = N->getOperand(1);
20215   EVT VT = N->getValueType(0);
20216
20217   // Don't create instructions with illegal types after legalize types has run.
20218   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20219   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
20220     return SDValue();
20221
20222   // If we have legalized the vector types, look for blends of FADD and FSUB
20223   // nodes that we can fuse into an ADDSUB node.
20224   if (TLI.isTypeLegal(VT) && Subtarget->hasSSE3())
20225     if (SDValue AddSub = combineShuffleToAddSub(N, DAG))
20226       return AddSub;
20227
20228   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
20229   if (Subtarget->hasFp256() && VT.is256BitVector() &&
20230       N->getOpcode() == ISD::VECTOR_SHUFFLE)
20231     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
20232
20233   // During Type Legalization, when promoting illegal vector types,
20234   // the backend might introduce new shuffle dag nodes and bitcasts.
20235   //
20236   // This code performs the following transformation:
20237   // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
20238   //       (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
20239   //
20240   // We do this only if both the bitcast and the BINOP dag nodes have
20241   // one use. Also, perform this transformation only if the new binary
20242   // operation is legal. This is to avoid introducing dag nodes that
20243   // potentially need to be further expanded (or custom lowered) into a
20244   // less optimal sequence of dag nodes.
20245   if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
20246       N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
20247       N0.getOpcode() == ISD::BITCAST) {
20248     SDValue BC0 = N0.getOperand(0);
20249     EVT SVT = BC0.getValueType();
20250     unsigned Opcode = BC0.getOpcode();
20251     unsigned NumElts = VT.getVectorNumElements();
20252
20253     if (BC0.hasOneUse() && SVT.isVector() &&
20254         SVT.getVectorNumElements() * 2 == NumElts &&
20255         TLI.isOperationLegal(Opcode, VT)) {
20256       bool CanFold = false;
20257       switch (Opcode) {
20258       default : break;
20259       case ISD::ADD :
20260       case ISD::FADD :
20261       case ISD::SUB :
20262       case ISD::FSUB :
20263       case ISD::MUL :
20264       case ISD::FMUL :
20265         CanFold = true;
20266       }
20267
20268       unsigned SVTNumElts = SVT.getVectorNumElements();
20269       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
20270       for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
20271         CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
20272       for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
20273         CanFold = SVOp->getMaskElt(i) < 0;
20274
20275       if (CanFold) {
20276         SDValue BC00 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(0));
20277         SDValue BC01 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(1));
20278         SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
20279         return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
20280       }
20281     }
20282   }
20283
20284   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
20285   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
20286   // consecutive, non-overlapping, and in the right order.
20287   SmallVector<SDValue, 16> Elts;
20288   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
20289     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
20290
20291   SDValue LD = EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true);
20292   if (LD.getNode())
20293     return LD;
20294
20295   if (isTargetShuffle(N->getOpcode())) {
20296     SDValue Shuffle =
20297         PerformTargetShuffleCombine(SDValue(N, 0), DAG, DCI, Subtarget);
20298     if (Shuffle.getNode())
20299       return Shuffle;
20300
20301     // Try recursively combining arbitrary sequences of x86 shuffle
20302     // instructions into higher-order shuffles. We do this after combining
20303     // specific PSHUF instruction sequences into their minimal form so that we
20304     // can evaluate how many specialized shuffle instructions are involved in
20305     // a particular chain.
20306     SmallVector<int, 1> NonceMask; // Just a placeholder.
20307     NonceMask.push_back(0);
20308     if (combineX86ShufflesRecursively(SDValue(N, 0), SDValue(N, 0), NonceMask,
20309                                       /*Depth*/ 1, /*HasPSHUFB*/ false, DAG,
20310                                       DCI, Subtarget))
20311       return SDValue(); // This routine will use CombineTo to replace N.
20312   }
20313
20314   return SDValue();
20315 }
20316
20317 /// PerformTruncateCombine - Converts truncate operation to
20318 /// a sequence of vector shuffle operations.
20319 /// It is possible when we truncate 256-bit vector to 128-bit vector
20320 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
20321                                       TargetLowering::DAGCombinerInfo &DCI,
20322                                       const X86Subtarget *Subtarget)  {
20323   return SDValue();
20324 }
20325
20326 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
20327 /// specific shuffle of a load can be folded into a single element load.
20328 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
20329 /// shuffles have been custom lowered so we need to handle those here.
20330 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
20331                                          TargetLowering::DAGCombinerInfo &DCI) {
20332   if (DCI.isBeforeLegalizeOps())
20333     return SDValue();
20334
20335   SDValue InVec = N->getOperand(0);
20336   SDValue EltNo = N->getOperand(1);
20337
20338   if (!isa<ConstantSDNode>(EltNo))
20339     return SDValue();
20340
20341   EVT OriginalVT = InVec.getValueType();
20342
20343   if (InVec.getOpcode() == ISD::BITCAST) {
20344     // Don't duplicate a load with other uses.
20345     if (!InVec.hasOneUse())
20346       return SDValue();
20347     EVT BCVT = InVec.getOperand(0).getValueType();
20348     if (BCVT.getVectorNumElements() != OriginalVT.getVectorNumElements())
20349       return SDValue();
20350     InVec = InVec.getOperand(0);
20351   }
20352
20353   EVT CurrentVT = InVec.getValueType();
20354
20355   if (!isTargetShuffle(InVec.getOpcode()))
20356     return SDValue();
20357
20358   // Don't duplicate a load with other uses.
20359   if (!InVec.hasOneUse())
20360     return SDValue();
20361
20362   SmallVector<int, 16> ShuffleMask;
20363   bool UnaryShuffle;
20364   if (!getTargetShuffleMask(InVec.getNode(), CurrentVT.getSimpleVT(),
20365                             ShuffleMask, UnaryShuffle))
20366     return SDValue();
20367
20368   // Select the input vector, guarding against out of range extract vector.
20369   unsigned NumElems = CurrentVT.getVectorNumElements();
20370   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
20371   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
20372   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
20373                                          : InVec.getOperand(1);
20374
20375   // If inputs to shuffle are the same for both ops, then allow 2 uses
20376   unsigned AllowedUses = InVec.getNumOperands() > 1 &&
20377                          InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
20378
20379   if (LdNode.getOpcode() == ISD::BITCAST) {
20380     // Don't duplicate a load with other uses.
20381     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
20382       return SDValue();
20383
20384     AllowedUses = 1; // only allow 1 load use if we have a bitcast
20385     LdNode = LdNode.getOperand(0);
20386   }
20387
20388   if (!ISD::isNormalLoad(LdNode.getNode()))
20389     return SDValue();
20390
20391   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
20392
20393   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
20394     return SDValue();
20395
20396   EVT EltVT = N->getValueType(0);
20397   // If there's a bitcast before the shuffle, check if the load type and
20398   // alignment is valid.
20399   unsigned Align = LN0->getAlignment();
20400   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20401   unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment(
20402       EltVT.getTypeForEVT(*DAG.getContext()));
20403
20404   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, EltVT))
20405     return SDValue();
20406
20407   // All checks match so transform back to vector_shuffle so that DAG combiner
20408   // can finish the job
20409   SDLoc dl(N);
20410
20411   // Create shuffle node taking into account the case that its a unary shuffle
20412   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(CurrentVT)
20413                                    : InVec.getOperand(1);
20414   Shuffle = DAG.getVectorShuffle(CurrentVT, dl,
20415                                  InVec.getOperand(0), Shuffle,
20416                                  &ShuffleMask[0]);
20417   Shuffle = DAG.getNode(ISD::BITCAST, dl, OriginalVT, Shuffle);
20418   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
20419                      EltNo);
20420 }
20421
20422 /// \brief Detect bitcasts between i32 to x86mmx low word. Since MMX types are
20423 /// special and don't usually play with other vector types, it's better to
20424 /// handle them early to be sure we emit efficient code by avoiding
20425 /// store-load conversions.
20426 static SDValue PerformBITCASTCombine(SDNode *N, SelectionDAG &DAG) {
20427   if (N->getValueType(0) != MVT::x86mmx ||
20428       N->getOperand(0)->getOpcode() != ISD::BUILD_VECTOR ||
20429       N->getOperand(0)->getValueType(0) != MVT::v2i32)
20430     return SDValue();
20431
20432   SDValue V = N->getOperand(0);
20433   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V.getOperand(1));
20434   if (C && C->getZExtValue() == 0 && V.getOperand(0).getValueType() == MVT::i32)
20435     return DAG.getNode(X86ISD::MMX_MOVW2D, SDLoc(V.getOperand(0)),
20436                        N->getValueType(0), V.getOperand(0));
20437
20438   return SDValue();
20439 }
20440
20441 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
20442 /// generation and convert it from being a bunch of shuffles and extracts
20443 /// into a somewhat faster sequence. For i686, the best sequence is apparently
20444 /// storing the value and loading scalars back, while for x64 we should
20445 /// use 64-bit extracts and shifts.
20446 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
20447                                          TargetLowering::DAGCombinerInfo &DCI) {
20448   SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
20449   if (NewOp.getNode())
20450     return NewOp;
20451
20452   SDValue InputVector = N->getOperand(0);
20453
20454   // Detect mmx to i32 conversion through a v2i32 elt extract.
20455   if (InputVector.getOpcode() == ISD::BITCAST && InputVector.hasOneUse() &&
20456       N->getValueType(0) == MVT::i32 &&
20457       InputVector.getValueType() == MVT::v2i32) {
20458
20459     // The bitcast source is a direct mmx result.
20460     SDValue MMXSrc = InputVector.getNode()->getOperand(0);
20461     if (MMXSrc.getValueType() == MVT::x86mmx)
20462       return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
20463                          N->getValueType(0),
20464                          InputVector.getNode()->getOperand(0));
20465
20466     // The mmx is indirect: (i64 extract_elt (v1i64 bitcast (x86mmx ...))).
20467     SDValue MMXSrcOp = MMXSrc.getOperand(0);
20468     if (MMXSrc.getOpcode() == ISD::EXTRACT_VECTOR_ELT && MMXSrc.hasOneUse() &&
20469         MMXSrc.getValueType() == MVT::i64 && MMXSrcOp.hasOneUse() &&
20470         MMXSrcOp.getOpcode() == ISD::BITCAST &&
20471         MMXSrcOp.getValueType() == MVT::v1i64 &&
20472         MMXSrcOp.getOperand(0).getValueType() == MVT::x86mmx)
20473       return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
20474                          N->getValueType(0),
20475                          MMXSrcOp.getOperand(0));
20476   }
20477
20478   // Only operate on vectors of 4 elements, where the alternative shuffling
20479   // gets to be more expensive.
20480   if (InputVector.getValueType() != MVT::v4i32)
20481     return SDValue();
20482
20483   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
20484   // single use which is a sign-extend or zero-extend, and all elements are
20485   // used.
20486   SmallVector<SDNode *, 4> Uses;
20487   unsigned ExtractedElements = 0;
20488   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
20489        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
20490     if (UI.getUse().getResNo() != InputVector.getResNo())
20491       return SDValue();
20492
20493     SDNode *Extract = *UI;
20494     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
20495       return SDValue();
20496
20497     if (Extract->getValueType(0) != MVT::i32)
20498       return SDValue();
20499     if (!Extract->hasOneUse())
20500       return SDValue();
20501     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
20502         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
20503       return SDValue();
20504     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
20505       return SDValue();
20506
20507     // Record which element was extracted.
20508     ExtractedElements |=
20509       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
20510
20511     Uses.push_back(Extract);
20512   }
20513
20514   // If not all the elements were used, this may not be worthwhile.
20515   if (ExtractedElements != 15)
20516     return SDValue();
20517
20518   // Ok, we've now decided to do the transformation.
20519   // If 64-bit shifts are legal, use the extract-shift sequence,
20520   // otherwise bounce the vector off the cache.
20521   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20522   SDValue Vals[4];
20523   SDLoc dl(InputVector);
20524
20525   if (TLI.isOperationLegal(ISD::SRA, MVT::i64)) {
20526     SDValue Cst = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, InputVector);
20527     EVT VecIdxTy = DAG.getTargetLoweringInfo().getVectorIdxTy();
20528     SDValue BottomHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
20529       DAG.getConstant(0, VecIdxTy));
20530     SDValue TopHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
20531       DAG.getConstant(1, VecIdxTy));
20532
20533     SDValue ShAmt = DAG.getConstant(32,
20534       DAG.getTargetLoweringInfo().getShiftAmountTy(MVT::i64));
20535     Vals[0] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BottomHalf);
20536     Vals[1] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
20537       DAG.getNode(ISD::SRA, dl, MVT::i64, BottomHalf, ShAmt));
20538     Vals[2] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, TopHalf);
20539     Vals[3] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
20540       DAG.getNode(ISD::SRA, dl, MVT::i64, TopHalf, ShAmt));
20541   } else {
20542     // Store the value to a temporary stack slot.
20543     SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
20544     SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
20545       MachinePointerInfo(), false, false, 0);
20546
20547     EVT ElementType = InputVector.getValueType().getVectorElementType();
20548     unsigned EltSize = ElementType.getSizeInBits() / 8;
20549
20550     // Replace each use (extract) with a load of the appropriate element.
20551     for (unsigned i = 0; i < 4; ++i) {
20552       uint64_t Offset = EltSize * i;
20553       SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
20554
20555       SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
20556                                        StackPtr, OffsetVal);
20557
20558       // Load the scalar.
20559       Vals[i] = DAG.getLoad(ElementType, dl, Ch,
20560                             ScalarAddr, MachinePointerInfo(),
20561                             false, false, false, 0);
20562
20563     }
20564   }
20565
20566   // Replace the extracts
20567   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
20568     UE = Uses.end(); UI != UE; ++UI) {
20569     SDNode *Extract = *UI;
20570
20571     SDValue Idx = Extract->getOperand(1);
20572     uint64_t IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
20573     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), Vals[IdxVal]);
20574   }
20575
20576   // The replacement was made in place; don't return anything.
20577   return SDValue();
20578 }
20579
20580 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
20581 static std::pair<unsigned, bool>
20582 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
20583                    SelectionDAG &DAG, const X86Subtarget *Subtarget) {
20584   if (!VT.isVector())
20585     return std::make_pair(0, false);
20586
20587   bool NeedSplit = false;
20588   switch (VT.getSimpleVT().SimpleTy) {
20589   default: return std::make_pair(0, false);
20590   case MVT::v4i64:
20591   case MVT::v2i64:
20592     if (!Subtarget->hasVLX())
20593       return std::make_pair(0, false);
20594     break;
20595   case MVT::v64i8:
20596   case MVT::v32i16:
20597     if (!Subtarget->hasBWI())
20598       return std::make_pair(0, false);
20599     break;
20600   case MVT::v16i32:
20601   case MVT::v8i64:
20602     if (!Subtarget->hasAVX512())
20603       return std::make_pair(0, false);
20604     break;
20605   case MVT::v32i8:
20606   case MVT::v16i16:
20607   case MVT::v8i32:
20608     if (!Subtarget->hasAVX2())
20609       NeedSplit = true;
20610     if (!Subtarget->hasAVX())
20611       return std::make_pair(0, false);
20612     break;
20613   case MVT::v16i8:
20614   case MVT::v8i16:
20615   case MVT::v4i32:
20616     if (!Subtarget->hasSSE2())
20617       return std::make_pair(0, false);
20618   }
20619
20620   // SSE2 has only a small subset of the operations.
20621   bool hasUnsigned = Subtarget->hasSSE41() ||
20622                      (Subtarget->hasSSE2() && VT == MVT::v16i8);
20623   bool hasSigned = Subtarget->hasSSE41() ||
20624                    (Subtarget->hasSSE2() && VT == MVT::v8i16);
20625
20626   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
20627
20628   unsigned Opc = 0;
20629   // Check for x CC y ? x : y.
20630   if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
20631       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
20632     switch (CC) {
20633     default: break;
20634     case ISD::SETULT:
20635     case ISD::SETULE:
20636       Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
20637     case ISD::SETUGT:
20638     case ISD::SETUGE:
20639       Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
20640     case ISD::SETLT:
20641     case ISD::SETLE:
20642       Opc = hasSigned ? X86ISD::SMIN : 0; break;
20643     case ISD::SETGT:
20644     case ISD::SETGE:
20645       Opc = hasSigned ? X86ISD::SMAX : 0; break;
20646     }
20647   // Check for x CC y ? y : x -- a min/max with reversed arms.
20648   } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
20649              DAG.isEqualTo(RHS, Cond.getOperand(0))) {
20650     switch (CC) {
20651     default: break;
20652     case ISD::SETULT:
20653     case ISD::SETULE:
20654       Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
20655     case ISD::SETUGT:
20656     case ISD::SETUGE:
20657       Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
20658     case ISD::SETLT:
20659     case ISD::SETLE:
20660       Opc = hasSigned ? X86ISD::SMAX : 0; break;
20661     case ISD::SETGT:
20662     case ISD::SETGE:
20663       Opc = hasSigned ? X86ISD::SMIN : 0; break;
20664     }
20665   }
20666
20667   return std::make_pair(Opc, NeedSplit);
20668 }
20669
20670 static SDValue
20671 transformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
20672                                       const X86Subtarget *Subtarget) {
20673   SDLoc dl(N);
20674   SDValue Cond = N->getOperand(0);
20675   SDValue LHS = N->getOperand(1);
20676   SDValue RHS = N->getOperand(2);
20677
20678   if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
20679     SDValue CondSrc = Cond->getOperand(0);
20680     if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
20681       Cond = CondSrc->getOperand(0);
20682   }
20683
20684   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
20685     return SDValue();
20686
20687   // A vselect where all conditions and data are constants can be optimized into
20688   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
20689   if (ISD::isBuildVectorOfConstantSDNodes(LHS.getNode()) &&
20690       ISD::isBuildVectorOfConstantSDNodes(RHS.getNode()))
20691     return SDValue();
20692
20693   unsigned MaskValue = 0;
20694   if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
20695     return SDValue();
20696
20697   MVT VT = N->getSimpleValueType(0);
20698   unsigned NumElems = VT.getVectorNumElements();
20699   SmallVector<int, 8> ShuffleMask(NumElems, -1);
20700   for (unsigned i = 0; i < NumElems; ++i) {
20701     // Be sure we emit undef where we can.
20702     if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
20703       ShuffleMask[i] = -1;
20704     else
20705       ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
20706   }
20707
20708   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20709   if (!TLI.isShuffleMaskLegal(ShuffleMask, VT))
20710     return SDValue();
20711   return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
20712 }
20713
20714 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
20715 /// nodes.
20716 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
20717                                     TargetLowering::DAGCombinerInfo &DCI,
20718                                     const X86Subtarget *Subtarget) {
20719   SDLoc DL(N);
20720   SDValue Cond = N->getOperand(0);
20721   // Get the LHS/RHS of the select.
20722   SDValue LHS = N->getOperand(1);
20723   SDValue RHS = N->getOperand(2);
20724   EVT VT = LHS.getValueType();
20725   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20726
20727   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
20728   // instructions match the semantics of the common C idiom x<y?x:y but not
20729   // x<=y?x:y, because of how they handle negative zero (which can be
20730   // ignored in unsafe-math mode).
20731   // We also try to create v2f32 min/max nodes, which we later widen to v4f32.
20732   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
20733       VT != MVT::f80 && (TLI.isTypeLegal(VT) || VT == MVT::v2f32) &&
20734       (Subtarget->hasSSE2() ||
20735        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
20736     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
20737
20738     unsigned Opcode = 0;
20739     // Check for x CC y ? x : y.
20740     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
20741         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
20742       switch (CC) {
20743       default: break;
20744       case ISD::SETULT:
20745         // Converting this to a min would handle NaNs incorrectly, and swapping
20746         // the operands would cause it to handle comparisons between positive
20747         // and negative zero incorrectly.
20748         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
20749           if (!DAG.getTarget().Options.UnsafeFPMath &&
20750               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
20751             break;
20752           std::swap(LHS, RHS);
20753         }
20754         Opcode = X86ISD::FMIN;
20755         break;
20756       case ISD::SETOLE:
20757         // Converting this to a min would handle comparisons between positive
20758         // and negative zero incorrectly.
20759         if (!DAG.getTarget().Options.UnsafeFPMath &&
20760             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
20761           break;
20762         Opcode = X86ISD::FMIN;
20763         break;
20764       case ISD::SETULE:
20765         // Converting this to a min would handle both negative zeros and NaNs
20766         // incorrectly, but we can swap the operands to fix both.
20767         std::swap(LHS, RHS);
20768       case ISD::SETOLT:
20769       case ISD::SETLT:
20770       case ISD::SETLE:
20771         Opcode = X86ISD::FMIN;
20772         break;
20773
20774       case ISD::SETOGE:
20775         // Converting this to a max would handle comparisons between positive
20776         // and negative zero incorrectly.
20777         if (!DAG.getTarget().Options.UnsafeFPMath &&
20778             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
20779           break;
20780         Opcode = X86ISD::FMAX;
20781         break;
20782       case ISD::SETUGT:
20783         // Converting this to a max would handle NaNs incorrectly, and swapping
20784         // the operands would cause it to handle comparisons between positive
20785         // and negative zero incorrectly.
20786         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
20787           if (!DAG.getTarget().Options.UnsafeFPMath &&
20788               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
20789             break;
20790           std::swap(LHS, RHS);
20791         }
20792         Opcode = X86ISD::FMAX;
20793         break;
20794       case ISD::SETUGE:
20795         // Converting this to a max would handle both negative zeros and NaNs
20796         // incorrectly, but we can swap the operands to fix both.
20797         std::swap(LHS, RHS);
20798       case ISD::SETOGT:
20799       case ISD::SETGT:
20800       case ISD::SETGE:
20801         Opcode = X86ISD::FMAX;
20802         break;
20803       }
20804     // Check for x CC y ? y : x -- a min/max with reversed arms.
20805     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
20806                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
20807       switch (CC) {
20808       default: break;
20809       case ISD::SETOGE:
20810         // Converting this to a min would handle comparisons between positive
20811         // and negative zero incorrectly, and swapping the operands would
20812         // cause it to handle NaNs incorrectly.
20813         if (!DAG.getTarget().Options.UnsafeFPMath &&
20814             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
20815           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
20816             break;
20817           std::swap(LHS, RHS);
20818         }
20819         Opcode = X86ISD::FMIN;
20820         break;
20821       case ISD::SETUGT:
20822         // Converting this to a min would handle NaNs incorrectly.
20823         if (!DAG.getTarget().Options.UnsafeFPMath &&
20824             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
20825           break;
20826         Opcode = X86ISD::FMIN;
20827         break;
20828       case ISD::SETUGE:
20829         // Converting this to a min would handle both negative zeros and NaNs
20830         // incorrectly, but we can swap the operands to fix both.
20831         std::swap(LHS, RHS);
20832       case ISD::SETOGT:
20833       case ISD::SETGT:
20834       case ISD::SETGE:
20835         Opcode = X86ISD::FMIN;
20836         break;
20837
20838       case ISD::SETULT:
20839         // Converting this to a max would handle NaNs incorrectly.
20840         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
20841           break;
20842         Opcode = X86ISD::FMAX;
20843         break;
20844       case ISD::SETOLE:
20845         // Converting this to a max would handle comparisons between positive
20846         // and negative zero incorrectly, and swapping the operands would
20847         // cause it to handle NaNs incorrectly.
20848         if (!DAG.getTarget().Options.UnsafeFPMath &&
20849             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
20850           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
20851             break;
20852           std::swap(LHS, RHS);
20853         }
20854         Opcode = X86ISD::FMAX;
20855         break;
20856       case ISD::SETULE:
20857         // Converting this to a max would handle both negative zeros and NaNs
20858         // incorrectly, but we can swap the operands to fix both.
20859         std::swap(LHS, RHS);
20860       case ISD::SETOLT:
20861       case ISD::SETLT:
20862       case ISD::SETLE:
20863         Opcode = X86ISD::FMAX;
20864         break;
20865       }
20866     }
20867
20868     if (Opcode)
20869       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
20870   }
20871
20872   EVT CondVT = Cond.getValueType();
20873   if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
20874       CondVT.getVectorElementType() == MVT::i1) {
20875     // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
20876     // lowering on KNL. In this case we convert it to
20877     // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
20878     // The same situation for all 128 and 256-bit vectors of i8 and i16.
20879     // Since SKX these selects have a proper lowering.
20880     EVT OpVT = LHS.getValueType();
20881     if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
20882         (OpVT.getVectorElementType() == MVT::i8 ||
20883          OpVT.getVectorElementType() == MVT::i16) &&
20884         !(Subtarget->hasBWI() && Subtarget->hasVLX())) {
20885       Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
20886       DCI.AddToWorklist(Cond.getNode());
20887       return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
20888     }
20889   }
20890   // If this is a select between two integer constants, try to do some
20891   // optimizations.
20892   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
20893     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
20894       // Don't do this for crazy integer types.
20895       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
20896         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
20897         // so that TrueC (the true value) is larger than FalseC.
20898         bool NeedsCondInvert = false;
20899
20900         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
20901             // Efficiently invertible.
20902             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
20903              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
20904               isa<ConstantSDNode>(Cond.getOperand(1))))) {
20905           NeedsCondInvert = true;
20906           std::swap(TrueC, FalseC);
20907         }
20908
20909         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
20910         if (FalseC->getAPIntValue() == 0 &&
20911             TrueC->getAPIntValue().isPowerOf2()) {
20912           if (NeedsCondInvert) // Invert the condition if needed.
20913             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
20914                                DAG.getConstant(1, Cond.getValueType()));
20915
20916           // Zero extend the condition if needed.
20917           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
20918
20919           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
20920           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
20921                              DAG.getConstant(ShAmt, MVT::i8));
20922         }
20923
20924         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
20925         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
20926           if (NeedsCondInvert) // Invert the condition if needed.
20927             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
20928                                DAG.getConstant(1, Cond.getValueType()));
20929
20930           // Zero extend the condition if needed.
20931           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
20932                              FalseC->getValueType(0), Cond);
20933           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
20934                              SDValue(FalseC, 0));
20935         }
20936
20937         // Optimize cases that will turn into an LEA instruction.  This requires
20938         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
20939         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
20940           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
20941           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
20942
20943           bool isFastMultiplier = false;
20944           if (Diff < 10) {
20945             switch ((unsigned char)Diff) {
20946               default: break;
20947               case 1:  // result = add base, cond
20948               case 2:  // result = lea base(    , cond*2)
20949               case 3:  // result = lea base(cond, cond*2)
20950               case 4:  // result = lea base(    , cond*4)
20951               case 5:  // result = lea base(cond, cond*4)
20952               case 8:  // result = lea base(    , cond*8)
20953               case 9:  // result = lea base(cond, cond*8)
20954                 isFastMultiplier = true;
20955                 break;
20956             }
20957           }
20958
20959           if (isFastMultiplier) {
20960             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
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, FalseC->getValueType(0),
20967                                Cond);
20968             // Scale the condition by the difference.
20969             if (Diff != 1)
20970               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
20971                                  DAG.getConstant(Diff, Cond.getValueType()));
20972
20973             // Add the base if non-zero.
20974             if (FalseC->getAPIntValue() != 0)
20975               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
20976                                  SDValue(FalseC, 0));
20977             return Cond;
20978           }
20979         }
20980       }
20981   }
20982
20983   // Canonicalize max and min:
20984   // (x > y) ? x : y -> (x >= y) ? x : y
20985   // (x < y) ? x : y -> (x <= y) ? x : y
20986   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
20987   // the need for an extra compare
20988   // against zero. e.g.
20989   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
20990   // subl   %esi, %edi
20991   // testl  %edi, %edi
20992   // movl   $0, %eax
20993   // cmovgl %edi, %eax
20994   // =>
20995   // xorl   %eax, %eax
20996   // subl   %esi, $edi
20997   // cmovsl %eax, %edi
20998   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
20999       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
21000       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
21001     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
21002     switch (CC) {
21003     default: break;
21004     case ISD::SETLT:
21005     case ISD::SETGT: {
21006       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
21007       Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
21008                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
21009       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
21010     }
21011     }
21012   }
21013
21014   // Early exit check
21015   if (!TLI.isTypeLegal(VT))
21016     return SDValue();
21017
21018   // Match VSELECTs into subs with unsigned saturation.
21019   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
21020       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
21021       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
21022        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
21023     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
21024
21025     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
21026     // left side invert the predicate to simplify logic below.
21027     SDValue Other;
21028     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
21029       Other = RHS;
21030       CC = ISD::getSetCCInverse(CC, true);
21031     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
21032       Other = LHS;
21033     }
21034
21035     if (Other.getNode() && Other->getNumOperands() == 2 &&
21036         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
21037       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
21038       SDValue CondRHS = Cond->getOperand(1);
21039
21040       // Look for a general sub with unsigned saturation first.
21041       // x >= y ? x-y : 0 --> subus x, y
21042       // x >  y ? x-y : 0 --> subus x, y
21043       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
21044           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
21045         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
21046
21047       if (auto *OpRHSBV = dyn_cast<BuildVectorSDNode>(OpRHS))
21048         if (auto *OpRHSConst = OpRHSBV->getConstantSplatNode()) {
21049           if (auto *CondRHSBV = dyn_cast<BuildVectorSDNode>(CondRHS))
21050             if (auto *CondRHSConst = CondRHSBV->getConstantSplatNode())
21051               // If the RHS is a constant we have to reverse the const
21052               // canonicalization.
21053               // x > C-1 ? x+-C : 0 --> subus x, C
21054               if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
21055                   CondRHSConst->getAPIntValue() ==
21056                       (-OpRHSConst->getAPIntValue() - 1))
21057                 return DAG.getNode(
21058                     X86ISD::SUBUS, DL, VT, OpLHS,
21059                     DAG.getConstant(-OpRHSConst->getAPIntValue(), VT));
21060
21061           // Another special case: If C was a sign bit, the sub has been
21062           // canonicalized into a xor.
21063           // FIXME: Would it be better to use computeKnownBits to determine
21064           //        whether it's safe to decanonicalize the xor?
21065           // x s< 0 ? x^C : 0 --> subus x, C
21066           if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
21067               ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
21068               OpRHSConst->getAPIntValue().isSignBit())
21069             // Note that we have to rebuild the RHS constant here to ensure we
21070             // don't rely on particular values of undef lanes.
21071             return DAG.getNode(
21072                 X86ISD::SUBUS, DL, VT, OpLHS,
21073                 DAG.getConstant(OpRHSConst->getAPIntValue(), VT));
21074         }
21075     }
21076   }
21077
21078   // Try to match a min/max vector operation.
21079   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
21080     std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
21081     unsigned Opc = ret.first;
21082     bool NeedSplit = ret.second;
21083
21084     if (Opc && NeedSplit) {
21085       unsigned NumElems = VT.getVectorNumElements();
21086       // Extract the LHS vectors
21087       SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
21088       SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
21089
21090       // Extract the RHS vectors
21091       SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
21092       SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
21093
21094       // Create min/max for each subvector
21095       LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
21096       RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
21097
21098       // Merge the result
21099       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
21100     } else if (Opc)
21101       return DAG.getNode(Opc, DL, VT, LHS, RHS);
21102   }
21103
21104   // Simplify vector selection if condition value type matches vselect
21105   // operand type
21106   if (N->getOpcode() == ISD::VSELECT && CondVT == VT) {
21107     assert(Cond.getValueType().isVector() &&
21108            "vector select expects a vector selector!");
21109
21110     bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
21111     bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
21112
21113     // Try invert the condition if true value is not all 1s and false value
21114     // is not all 0s.
21115     if (!TValIsAllOnes && !FValIsAllZeros &&
21116         // Check if the selector will be produced by CMPP*/PCMP*
21117         Cond.getOpcode() == ISD::SETCC &&
21118         // Check if SETCC has already been promoted
21119         TLI.getSetCCResultType(*DAG.getContext(), VT) == CondVT) {
21120       bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
21121       bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
21122
21123       if (TValIsAllZeros || FValIsAllOnes) {
21124         SDValue CC = Cond.getOperand(2);
21125         ISD::CondCode NewCC =
21126           ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
21127                                Cond.getOperand(0).getValueType().isInteger());
21128         Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
21129         std::swap(LHS, RHS);
21130         TValIsAllOnes = FValIsAllOnes;
21131         FValIsAllZeros = TValIsAllZeros;
21132       }
21133     }
21134
21135     if (TValIsAllOnes || FValIsAllZeros) {
21136       SDValue Ret;
21137
21138       if (TValIsAllOnes && FValIsAllZeros)
21139         Ret = Cond;
21140       else if (TValIsAllOnes)
21141         Ret = DAG.getNode(ISD::OR, DL, CondVT, Cond,
21142                           DAG.getNode(ISD::BITCAST, DL, CondVT, RHS));
21143       else if (FValIsAllZeros)
21144         Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
21145                           DAG.getNode(ISD::BITCAST, DL, CondVT, LHS));
21146
21147       return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
21148     }
21149   }
21150
21151   // We should generate an X86ISD::BLENDI from a vselect if its argument
21152   // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
21153   // constants. This specific pattern gets generated when we split a
21154   // selector for a 512 bit vector in a machine without AVX512 (but with
21155   // 256-bit vectors), during legalization:
21156   //
21157   // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
21158   //
21159   // Iff we find this pattern and the build_vectors are built from
21160   // constants, we translate the vselect into a shuffle_vector that we
21161   // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
21162   if ((N->getOpcode() == ISD::VSELECT ||
21163        N->getOpcode() == X86ISD::SHRUNKBLEND) &&
21164       !DCI.isBeforeLegalize()) {
21165     SDValue Shuffle = transformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
21166     if (Shuffle.getNode())
21167       return Shuffle;
21168   }
21169
21170   // If this is a *dynamic* select (non-constant condition) and we can match
21171   // this node with one of the variable blend instructions, restructure the
21172   // condition so that the blends can use the high bit of each element and use
21173   // SimplifyDemandedBits to simplify the condition operand.
21174   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
21175       !DCI.isBeforeLegalize() &&
21176       !ISD::isBuildVectorOfConstantSDNodes(Cond.getNode())) {
21177     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
21178
21179     // Don't optimize vector selects that map to mask-registers.
21180     if (BitWidth == 1)
21181       return SDValue();
21182
21183     // We can only handle the cases where VSELECT is directly legal on the
21184     // subtarget. We custom lower VSELECT nodes with constant conditions and
21185     // this makes it hard to see whether a dynamic VSELECT will correctly
21186     // lower, so we both check the operation's status and explicitly handle the
21187     // cases where a *dynamic* blend will fail even though a constant-condition
21188     // blend could be custom lowered.
21189     // FIXME: We should find a better way to handle this class of problems.
21190     // Potentially, we should combine constant-condition vselect nodes
21191     // pre-legalization into shuffles and not mark as many types as custom
21192     // lowered.
21193     if (!TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
21194       return SDValue();
21195     // FIXME: We don't support i16-element blends currently. We could and
21196     // should support them by making *all* the bits in the condition be set
21197     // rather than just the high bit and using an i8-element blend.
21198     if (VT.getScalarType() == MVT::i16)
21199       return SDValue();
21200     // Dynamic blending was only available from SSE4.1 onward.
21201     if (VT.getSizeInBits() == 128 && !Subtarget->hasSSE41())
21202       return SDValue();
21203     // Byte blends are only available in AVX2
21204     if (VT.getSizeInBits() == 256 && VT.getScalarType() == MVT::i8 &&
21205         !Subtarget->hasAVX2())
21206       return SDValue();
21207
21208     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
21209     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
21210
21211     APInt KnownZero, KnownOne;
21212     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
21213                                           DCI.isBeforeLegalizeOps());
21214     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
21215         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne,
21216                                  TLO)) {
21217       // If we changed the computation somewhere in the DAG, this change
21218       // will affect all users of Cond.
21219       // Make sure it is fine and update all the nodes so that we do not
21220       // use the generic VSELECT anymore. Otherwise, we may perform
21221       // wrong optimizations as we messed up with the actual expectation
21222       // for the vector boolean values.
21223       if (Cond != TLO.Old) {
21224         // Check all uses of that condition operand to check whether it will be
21225         // consumed by non-BLEND instructions, which may depend on all bits are
21226         // set properly.
21227         for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
21228              I != E; ++I)
21229           if (I->getOpcode() != ISD::VSELECT)
21230             // TODO: Add other opcodes eventually lowered into BLEND.
21231             return SDValue();
21232
21233         // Update all the users of the condition, before committing the change,
21234         // so that the VSELECT optimizations that expect the correct vector
21235         // boolean value will not be triggered.
21236         for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
21237              I != E; ++I)
21238           DAG.ReplaceAllUsesOfValueWith(
21239               SDValue(*I, 0),
21240               DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(*I), I->getValueType(0),
21241                           Cond, I->getOperand(1), I->getOperand(2)));
21242         DCI.CommitTargetLoweringOpt(TLO);
21243         return SDValue();
21244       }
21245       // At this point, only Cond is changed. Change the condition
21246       // just for N to keep the opportunity to optimize all other
21247       // users their own way.
21248       DAG.ReplaceAllUsesOfValueWith(
21249           SDValue(N, 0),
21250           DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(N), N->getValueType(0),
21251                       TLO.New, N->getOperand(1), N->getOperand(2)));
21252       return SDValue();
21253     }
21254   }
21255
21256   return SDValue();
21257 }
21258
21259 // Check whether a boolean test is testing a boolean value generated by
21260 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
21261 // code.
21262 //
21263 // Simplify the following patterns:
21264 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
21265 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
21266 // to (Op EFLAGS Cond)
21267 //
21268 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
21269 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
21270 // to (Op EFLAGS !Cond)
21271 //
21272 // where Op could be BRCOND or CMOV.
21273 //
21274 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
21275   // Quit if not CMP and SUB with its value result used.
21276   if (Cmp.getOpcode() != X86ISD::CMP &&
21277       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
21278       return SDValue();
21279
21280   // Quit if not used as a boolean value.
21281   if (CC != X86::COND_E && CC != X86::COND_NE)
21282     return SDValue();
21283
21284   // Check CMP operands. One of them should be 0 or 1 and the other should be
21285   // an SetCC or extended from it.
21286   SDValue Op1 = Cmp.getOperand(0);
21287   SDValue Op2 = Cmp.getOperand(1);
21288
21289   SDValue SetCC;
21290   const ConstantSDNode* C = nullptr;
21291   bool needOppositeCond = (CC == X86::COND_E);
21292   bool checkAgainstTrue = false; // Is it a comparison against 1?
21293
21294   if ((C = dyn_cast<ConstantSDNode>(Op1)))
21295     SetCC = Op2;
21296   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
21297     SetCC = Op1;
21298   else // Quit if all operands are not constants.
21299     return SDValue();
21300
21301   if (C->getZExtValue() == 1) {
21302     needOppositeCond = !needOppositeCond;
21303     checkAgainstTrue = true;
21304   } else if (C->getZExtValue() != 0)
21305     // Quit if the constant is neither 0 or 1.
21306     return SDValue();
21307
21308   bool truncatedToBoolWithAnd = false;
21309   // Skip (zext $x), (trunc $x), or (and $x, 1) node.
21310   while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
21311          SetCC.getOpcode() == ISD::TRUNCATE ||
21312          SetCC.getOpcode() == ISD::AND) {
21313     if (SetCC.getOpcode() == ISD::AND) {
21314       int OpIdx = -1;
21315       ConstantSDNode *CS;
21316       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
21317           CS->getZExtValue() == 1)
21318         OpIdx = 1;
21319       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
21320           CS->getZExtValue() == 1)
21321         OpIdx = 0;
21322       if (OpIdx == -1)
21323         break;
21324       SetCC = SetCC.getOperand(OpIdx);
21325       truncatedToBoolWithAnd = true;
21326     } else
21327       SetCC = SetCC.getOperand(0);
21328   }
21329
21330   switch (SetCC.getOpcode()) {
21331   case X86ISD::SETCC_CARRY:
21332     // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
21333     // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
21334     // i.e. it's a comparison against true but the result of SETCC_CARRY is not
21335     // truncated to i1 using 'and'.
21336     if (checkAgainstTrue && !truncatedToBoolWithAnd)
21337       break;
21338     assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
21339            "Invalid use of SETCC_CARRY!");
21340     // FALL THROUGH
21341   case X86ISD::SETCC:
21342     // Set the condition code or opposite one if necessary.
21343     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
21344     if (needOppositeCond)
21345       CC = X86::GetOppositeBranchCondition(CC);
21346     return SetCC.getOperand(1);
21347   case X86ISD::CMOV: {
21348     // Check whether false/true value has canonical one, i.e. 0 or 1.
21349     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
21350     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
21351     // Quit if true value is not a constant.
21352     if (!TVal)
21353       return SDValue();
21354     // Quit if false value is not a constant.
21355     if (!FVal) {
21356       SDValue Op = SetCC.getOperand(0);
21357       // Skip 'zext' or 'trunc' node.
21358       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
21359           Op.getOpcode() == ISD::TRUNCATE)
21360         Op = Op.getOperand(0);
21361       // A special case for rdrand/rdseed, where 0 is set if false cond is
21362       // found.
21363       if ((Op.getOpcode() != X86ISD::RDRAND &&
21364            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
21365         return SDValue();
21366     }
21367     // Quit if false value is not the constant 0 or 1.
21368     bool FValIsFalse = true;
21369     if (FVal && FVal->getZExtValue() != 0) {
21370       if (FVal->getZExtValue() != 1)
21371         return SDValue();
21372       // If FVal is 1, opposite cond is needed.
21373       needOppositeCond = !needOppositeCond;
21374       FValIsFalse = false;
21375     }
21376     // Quit if TVal is not the constant opposite of FVal.
21377     if (FValIsFalse && TVal->getZExtValue() != 1)
21378       return SDValue();
21379     if (!FValIsFalse && TVal->getZExtValue() != 0)
21380       return SDValue();
21381     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
21382     if (needOppositeCond)
21383       CC = X86::GetOppositeBranchCondition(CC);
21384     return SetCC.getOperand(3);
21385   }
21386   }
21387
21388   return SDValue();
21389 }
21390
21391 /// Check whether Cond is an AND/OR of SETCCs off of the same EFLAGS.
21392 /// Match:
21393 ///   (X86or (X86setcc) (X86setcc))
21394 ///   (X86cmp (and (X86setcc) (X86setcc)), 0)
21395 static bool checkBoolTestAndOrSetCCCombine(SDValue Cond, X86::CondCode &CC0,
21396                                            X86::CondCode &CC1, SDValue &Flags,
21397                                            bool &isAnd) {
21398   if (Cond->getOpcode() == X86ISD::CMP) {
21399     ConstantSDNode *CondOp1C = dyn_cast<ConstantSDNode>(Cond->getOperand(1));
21400     if (!CondOp1C || !CondOp1C->isNullValue())
21401       return false;
21402
21403     Cond = Cond->getOperand(0);
21404   }
21405
21406   isAnd = false;
21407
21408   SDValue SetCC0, SetCC1;
21409   switch (Cond->getOpcode()) {
21410   default: return false;
21411   case ISD::AND:
21412   case X86ISD::AND:
21413     isAnd = true;
21414     // fallthru
21415   case ISD::OR:
21416   case X86ISD::OR:
21417     SetCC0 = Cond->getOperand(0);
21418     SetCC1 = Cond->getOperand(1);
21419     break;
21420   };
21421
21422   // Make sure we have SETCC nodes, using the same flags value.
21423   if (SetCC0.getOpcode() != X86ISD::SETCC ||
21424       SetCC1.getOpcode() != X86ISD::SETCC ||
21425       SetCC0->getOperand(1) != SetCC1->getOperand(1))
21426     return false;
21427
21428   CC0 = (X86::CondCode)SetCC0->getConstantOperandVal(0);
21429   CC1 = (X86::CondCode)SetCC1->getConstantOperandVal(0);
21430   Flags = SetCC0->getOperand(1);
21431   return true;
21432 }
21433
21434 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
21435 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
21436                                   TargetLowering::DAGCombinerInfo &DCI,
21437                                   const X86Subtarget *Subtarget) {
21438   SDLoc DL(N);
21439
21440   // If the flag operand isn't dead, don't touch this CMOV.
21441   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
21442     return SDValue();
21443
21444   SDValue FalseOp = N->getOperand(0);
21445   SDValue TrueOp = N->getOperand(1);
21446   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
21447   SDValue Cond = N->getOperand(3);
21448
21449   if (CC == X86::COND_E || CC == X86::COND_NE) {
21450     switch (Cond.getOpcode()) {
21451     default: break;
21452     case X86ISD::BSR:
21453     case X86ISD::BSF:
21454       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
21455       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
21456         return (CC == X86::COND_E) ? FalseOp : TrueOp;
21457     }
21458   }
21459
21460   SDValue Flags;
21461
21462   Flags = checkBoolTestSetCCCombine(Cond, CC);
21463   if (Flags.getNode() &&
21464       // Extra check as FCMOV only supports a subset of X86 cond.
21465       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
21466     SDValue Ops[] = { FalseOp, TrueOp,
21467                       DAG.getConstant(CC, MVT::i8), Flags };
21468     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
21469   }
21470
21471   // If this is a select between two integer constants, try to do some
21472   // optimizations.  Note that the operands are ordered the opposite of SELECT
21473   // operands.
21474   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
21475     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
21476       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
21477       // larger than FalseC (the false value).
21478       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
21479         CC = X86::GetOppositeBranchCondition(CC);
21480         std::swap(TrueC, FalseC);
21481         std::swap(TrueOp, FalseOp);
21482       }
21483
21484       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
21485       // This is efficient for any integer data type (including i8/i16) and
21486       // shift amount.
21487       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
21488         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
21489                            DAG.getConstant(CC, MVT::i8), Cond);
21490
21491         // Zero extend the condition if needed.
21492         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
21493
21494         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
21495         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
21496                            DAG.getConstant(ShAmt, MVT::i8));
21497         if (N->getNumValues() == 2)  // Dead flag value?
21498           return DCI.CombineTo(N, Cond, SDValue());
21499         return Cond;
21500       }
21501
21502       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
21503       // for any integer data type, including i8/i16.
21504       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
21505         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
21506                            DAG.getConstant(CC, MVT::i8), Cond);
21507
21508         // Zero extend the condition if needed.
21509         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
21510                            FalseC->getValueType(0), Cond);
21511         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
21512                            SDValue(FalseC, 0));
21513
21514         if (N->getNumValues() == 2)  // Dead flag value?
21515           return DCI.CombineTo(N, Cond, SDValue());
21516         return Cond;
21517       }
21518
21519       // Optimize cases that will turn into an LEA instruction.  This requires
21520       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
21521       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
21522         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
21523         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
21524
21525         bool isFastMultiplier = false;
21526         if (Diff < 10) {
21527           switch ((unsigned char)Diff) {
21528           default: break;
21529           case 1:  // result = add base, cond
21530           case 2:  // result = lea base(    , cond*2)
21531           case 3:  // result = lea base(cond, cond*2)
21532           case 4:  // result = lea base(    , cond*4)
21533           case 5:  // result = lea base(cond, cond*4)
21534           case 8:  // result = lea base(    , cond*8)
21535           case 9:  // result = lea base(cond, cond*8)
21536             isFastMultiplier = true;
21537             break;
21538           }
21539         }
21540
21541         if (isFastMultiplier) {
21542           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
21543           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
21544                              DAG.getConstant(CC, MVT::i8), Cond);
21545           // Zero extend the condition if needed.
21546           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
21547                              Cond);
21548           // Scale the condition by the difference.
21549           if (Diff != 1)
21550             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
21551                                DAG.getConstant(Diff, Cond.getValueType()));
21552
21553           // Add the base if non-zero.
21554           if (FalseC->getAPIntValue() != 0)
21555             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
21556                                SDValue(FalseC, 0));
21557           if (N->getNumValues() == 2)  // Dead flag value?
21558             return DCI.CombineTo(N, Cond, SDValue());
21559           return Cond;
21560         }
21561       }
21562     }
21563   }
21564
21565   // Handle these cases:
21566   //   (select (x != c), e, c) -> select (x != c), e, x),
21567   //   (select (x == c), c, e) -> select (x == c), x, e)
21568   // where the c is an integer constant, and the "select" is the combination
21569   // of CMOV and CMP.
21570   //
21571   // The rationale for this change is that the conditional-move from a constant
21572   // needs two instructions, however, conditional-move from a register needs
21573   // only one instruction.
21574   //
21575   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
21576   //  some instruction-combining opportunities. This opt needs to be
21577   //  postponed as late as possible.
21578   //
21579   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
21580     // the DCI.xxxx conditions are provided to postpone the optimization as
21581     // late as possible.
21582
21583     ConstantSDNode *CmpAgainst = nullptr;
21584     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
21585         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
21586         !isa<ConstantSDNode>(Cond.getOperand(0))) {
21587
21588       if (CC == X86::COND_NE &&
21589           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
21590         CC = X86::GetOppositeBranchCondition(CC);
21591         std::swap(TrueOp, FalseOp);
21592       }
21593
21594       if (CC == X86::COND_E &&
21595           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
21596         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
21597                           DAG.getConstant(CC, MVT::i8), Cond };
21598         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
21599       }
21600     }
21601   }
21602
21603   // Fold and/or of setcc's to double CMOV:
21604   //   (CMOV F, T, ((cc1 | cc2) != 0)) -> (CMOV (CMOV F, T, cc1), T, cc2)
21605   //   (CMOV F, T, ((cc1 & cc2) != 0)) -> (CMOV (CMOV T, F, !cc1), F, !cc2)
21606   //
21607   // This combine lets us generate:
21608   //   cmovcc1 (jcc1 if we don't have CMOV)
21609   //   cmovcc2 (same)
21610   // instead of:
21611   //   setcc1
21612   //   setcc2
21613   //   and/or
21614   //   cmovne (jne if we don't have CMOV)
21615   // When we can't use the CMOV instruction, it might increase branch
21616   // mispredicts.
21617   // When we can use CMOV, or when there is no mispredict, this improves
21618   // throughput and reduces register pressure.
21619   //
21620   if (CC == X86::COND_NE) {
21621     SDValue Flags;
21622     X86::CondCode CC0, CC1;
21623     bool isAndSetCC;
21624     if (checkBoolTestAndOrSetCCCombine(Cond, CC0, CC1, Flags, isAndSetCC)) {
21625       if (isAndSetCC) {
21626         std::swap(FalseOp, TrueOp);
21627         CC0 = X86::GetOppositeBranchCondition(CC0);
21628         CC1 = X86::GetOppositeBranchCondition(CC1);
21629       }
21630
21631       SDValue LOps[] = {FalseOp, TrueOp, DAG.getConstant(CC0, MVT::i8),
21632         Flags};
21633       SDValue LCMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), LOps);
21634       SDValue Ops[] = {LCMOV, TrueOp, DAG.getConstant(CC1, MVT::i8), Flags};
21635       SDValue CMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
21636       DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SDValue(CMOV.getNode(), 1));
21637       return CMOV;
21638     }
21639   }
21640
21641   return SDValue();
21642 }
21643
21644 static SDValue PerformINTRINSIC_WO_CHAINCombine(SDNode *N, SelectionDAG &DAG,
21645                                                 const X86Subtarget *Subtarget) {
21646   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
21647   switch (IntNo) {
21648   default: return SDValue();
21649   // SSE/AVX/AVX2 blend intrinsics.
21650   case Intrinsic::x86_avx2_pblendvb:
21651     // Don't try to simplify this intrinsic if we don't have AVX2.
21652     if (!Subtarget->hasAVX2())
21653       return SDValue();
21654     // FALL-THROUGH
21655   case Intrinsic::x86_avx_blendv_pd_256:
21656   case Intrinsic::x86_avx_blendv_ps_256:
21657     // Don't try to simplify this intrinsic if we don't have AVX.
21658     if (!Subtarget->hasAVX())
21659       return SDValue();
21660     // FALL-THROUGH
21661   case Intrinsic::x86_sse41_blendvps:
21662   case Intrinsic::x86_sse41_blendvpd:
21663   case Intrinsic::x86_sse41_pblendvb: {
21664     SDValue Op0 = N->getOperand(1);
21665     SDValue Op1 = N->getOperand(2);
21666     SDValue Mask = N->getOperand(3);
21667
21668     // Don't try to simplify this intrinsic if we don't have SSE4.1.
21669     if (!Subtarget->hasSSE41())
21670       return SDValue();
21671
21672     // fold (blend A, A, Mask) -> A
21673     if (Op0 == Op1)
21674       return Op0;
21675     // fold (blend A, B, allZeros) -> A
21676     if (ISD::isBuildVectorAllZeros(Mask.getNode()))
21677       return Op0;
21678     // fold (blend A, B, allOnes) -> B
21679     if (ISD::isBuildVectorAllOnes(Mask.getNode()))
21680       return Op1;
21681
21682     // Simplify the case where the mask is a constant i32 value.
21683     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Mask)) {
21684       if (C->isNullValue())
21685         return Op0;
21686       if (C->isAllOnesValue())
21687         return Op1;
21688     }
21689
21690     return SDValue();
21691   }
21692
21693   // Packed SSE2/AVX2 arithmetic shift immediate intrinsics.
21694   case Intrinsic::x86_sse2_psrai_w:
21695   case Intrinsic::x86_sse2_psrai_d:
21696   case Intrinsic::x86_avx2_psrai_w:
21697   case Intrinsic::x86_avx2_psrai_d:
21698   case Intrinsic::x86_sse2_psra_w:
21699   case Intrinsic::x86_sse2_psra_d:
21700   case Intrinsic::x86_avx2_psra_w:
21701   case Intrinsic::x86_avx2_psra_d: {
21702     SDValue Op0 = N->getOperand(1);
21703     SDValue Op1 = N->getOperand(2);
21704     EVT VT = Op0.getValueType();
21705     assert(VT.isVector() && "Expected a vector type!");
21706
21707     if (isa<BuildVectorSDNode>(Op1))
21708       Op1 = Op1.getOperand(0);
21709
21710     if (!isa<ConstantSDNode>(Op1))
21711       return SDValue();
21712
21713     EVT SVT = VT.getVectorElementType();
21714     unsigned SVTBits = SVT.getSizeInBits();
21715
21716     ConstantSDNode *CND = cast<ConstantSDNode>(Op1);
21717     const APInt &C = APInt(SVTBits, CND->getAPIntValue().getZExtValue());
21718     uint64_t ShAmt = C.getZExtValue();
21719
21720     // Don't try to convert this shift into a ISD::SRA if the shift
21721     // count is bigger than or equal to the element size.
21722     if (ShAmt >= SVTBits)
21723       return SDValue();
21724
21725     // Trivial case: if the shift count is zero, then fold this
21726     // into the first operand.
21727     if (ShAmt == 0)
21728       return Op0;
21729
21730     // Replace this packed shift intrinsic with a target independent
21731     // shift dag node.
21732     SDValue Splat = DAG.getConstant(C, VT);
21733     return DAG.getNode(ISD::SRA, SDLoc(N), VT, Op0, Splat);
21734   }
21735   }
21736 }
21737
21738 /// PerformMulCombine - Optimize a single multiply with constant into two
21739 /// in order to implement it with two cheaper instructions, e.g.
21740 /// LEA + SHL, LEA + LEA.
21741 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
21742                                  TargetLowering::DAGCombinerInfo &DCI) {
21743   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
21744     return SDValue();
21745
21746   EVT VT = N->getValueType(0);
21747   if (VT != MVT::i64 && VT != MVT::i32)
21748     return SDValue();
21749
21750   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
21751   if (!C)
21752     return SDValue();
21753   uint64_t MulAmt = C->getZExtValue();
21754   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
21755     return SDValue();
21756
21757   uint64_t MulAmt1 = 0;
21758   uint64_t MulAmt2 = 0;
21759   if ((MulAmt % 9) == 0) {
21760     MulAmt1 = 9;
21761     MulAmt2 = MulAmt / 9;
21762   } else if ((MulAmt % 5) == 0) {
21763     MulAmt1 = 5;
21764     MulAmt2 = MulAmt / 5;
21765   } else if ((MulAmt % 3) == 0) {
21766     MulAmt1 = 3;
21767     MulAmt2 = MulAmt / 3;
21768   }
21769   if (MulAmt2 &&
21770       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
21771     SDLoc DL(N);
21772
21773     if (isPowerOf2_64(MulAmt2) &&
21774         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
21775       // If second multiplifer is pow2, issue it first. We want the multiply by
21776       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
21777       // is an add.
21778       std::swap(MulAmt1, MulAmt2);
21779
21780     SDValue NewMul;
21781     if (isPowerOf2_64(MulAmt1))
21782       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
21783                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
21784     else
21785       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
21786                            DAG.getConstant(MulAmt1, VT));
21787
21788     if (isPowerOf2_64(MulAmt2))
21789       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
21790                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
21791     else
21792       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
21793                            DAG.getConstant(MulAmt2, VT));
21794
21795     // Do not add new nodes to DAG combiner worklist.
21796     DCI.CombineTo(N, NewMul, false);
21797   }
21798   return SDValue();
21799 }
21800
21801 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
21802   SDValue N0 = N->getOperand(0);
21803   SDValue N1 = N->getOperand(1);
21804   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
21805   EVT VT = N0.getValueType();
21806
21807   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
21808   // since the result of setcc_c is all zero's or all ones.
21809   if (VT.isInteger() && !VT.isVector() &&
21810       N1C && N0.getOpcode() == ISD::AND &&
21811       N0.getOperand(1).getOpcode() == ISD::Constant) {
21812     SDValue N00 = N0.getOperand(0);
21813     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
21814         ((N00.getOpcode() == ISD::ANY_EXTEND ||
21815           N00.getOpcode() == ISD::ZERO_EXTEND) &&
21816          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
21817       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
21818       APInt ShAmt = N1C->getAPIntValue();
21819       Mask = Mask.shl(ShAmt);
21820       if (Mask != 0)
21821         return DAG.getNode(ISD::AND, SDLoc(N), VT,
21822                            N00, DAG.getConstant(Mask, VT));
21823     }
21824   }
21825
21826   // Hardware support for vector shifts is sparse which makes us scalarize the
21827   // vector operations in many cases. Also, on sandybridge ADD is faster than
21828   // shl.
21829   // (shl V, 1) -> add V,V
21830   if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
21831     if (auto *N1SplatC = N1BV->getConstantSplatNode()) {
21832       assert(N0.getValueType().isVector() && "Invalid vector shift type");
21833       // We shift all of the values by one. In many cases we do not have
21834       // hardware support for this operation. This is better expressed as an ADD
21835       // of two values.
21836       if (N1SplatC->getZExtValue() == 1)
21837         return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
21838     }
21839
21840   return SDValue();
21841 }
21842
21843 /// \brief Returns a vector of 0s if the node in input is a vector logical
21844 /// shift by a constant amount which is known to be bigger than or equal
21845 /// to the vector element size in bits.
21846 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
21847                                       const X86Subtarget *Subtarget) {
21848   EVT VT = N->getValueType(0);
21849
21850   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
21851       (!Subtarget->hasInt256() ||
21852        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
21853     return SDValue();
21854
21855   SDValue Amt = N->getOperand(1);
21856   SDLoc DL(N);
21857   if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Amt))
21858     if (auto *AmtSplat = AmtBV->getConstantSplatNode()) {
21859       APInt ShiftAmt = AmtSplat->getAPIntValue();
21860       unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
21861
21862       // SSE2/AVX2 logical shifts always return a vector of 0s
21863       // if the shift amount is bigger than or equal to
21864       // the element size. The constant shift amount will be
21865       // encoded as a 8-bit immediate.
21866       if (ShiftAmt.trunc(8).uge(MaxAmount))
21867         return getZeroVector(VT, Subtarget, DAG, DL);
21868     }
21869
21870   return SDValue();
21871 }
21872
21873 /// PerformShiftCombine - Combine shifts.
21874 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
21875                                    TargetLowering::DAGCombinerInfo &DCI,
21876                                    const X86Subtarget *Subtarget) {
21877   if (N->getOpcode() == ISD::SHL) {
21878     SDValue V = PerformSHLCombine(N, DAG);
21879     if (V.getNode()) return V;
21880   }
21881
21882   if (N->getOpcode() != ISD::SRA) {
21883     // Try to fold this logical shift into a zero vector.
21884     SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
21885     if (V.getNode()) return V;
21886   }
21887
21888   return SDValue();
21889 }
21890
21891 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
21892 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
21893 // and friends.  Likewise for OR -> CMPNEQSS.
21894 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
21895                             TargetLowering::DAGCombinerInfo &DCI,
21896                             const X86Subtarget *Subtarget) {
21897   unsigned opcode;
21898
21899   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
21900   // we're requiring SSE2 for both.
21901   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
21902     SDValue N0 = N->getOperand(0);
21903     SDValue N1 = N->getOperand(1);
21904     SDValue CMP0 = N0->getOperand(1);
21905     SDValue CMP1 = N1->getOperand(1);
21906     SDLoc DL(N);
21907
21908     // The SETCCs should both refer to the same CMP.
21909     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
21910       return SDValue();
21911
21912     SDValue CMP00 = CMP0->getOperand(0);
21913     SDValue CMP01 = CMP0->getOperand(1);
21914     EVT     VT    = CMP00.getValueType();
21915
21916     if (VT == MVT::f32 || VT == MVT::f64) {
21917       bool ExpectingFlags = false;
21918       // Check for any users that want flags:
21919       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
21920            !ExpectingFlags && UI != UE; ++UI)
21921         switch (UI->getOpcode()) {
21922         default:
21923         case ISD::BR_CC:
21924         case ISD::BRCOND:
21925         case ISD::SELECT:
21926           ExpectingFlags = true;
21927           break;
21928         case ISD::CopyToReg:
21929         case ISD::SIGN_EXTEND:
21930         case ISD::ZERO_EXTEND:
21931         case ISD::ANY_EXTEND:
21932           break;
21933         }
21934
21935       if (!ExpectingFlags) {
21936         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
21937         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
21938
21939         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
21940           X86::CondCode tmp = cc0;
21941           cc0 = cc1;
21942           cc1 = tmp;
21943         }
21944
21945         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
21946             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
21947           // FIXME: need symbolic constants for these magic numbers.
21948           // See X86ATTInstPrinter.cpp:printSSECC().
21949           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
21950           if (Subtarget->hasAVX512()) {
21951             SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
21952                                          CMP01, DAG.getConstant(x86cc, MVT::i8));
21953             if (N->getValueType(0) != MVT::i1)
21954               return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
21955                                  FSetCC);
21956             return FSetCC;
21957           }
21958           SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
21959                                               CMP00.getValueType(), CMP00, CMP01,
21960                                               DAG.getConstant(x86cc, MVT::i8));
21961
21962           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
21963           MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
21964
21965           if (is64BitFP && !Subtarget->is64Bit()) {
21966             // On a 32-bit target, we cannot bitcast the 64-bit float to a
21967             // 64-bit integer, since that's not a legal type. Since
21968             // OnesOrZeroesF is all ones of all zeroes, we don't need all the
21969             // bits, but can do this little dance to extract the lowest 32 bits
21970             // and work with those going forward.
21971             SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
21972                                            OnesOrZeroesF);
21973             SDValue Vector32 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f32,
21974                                            Vector64);
21975             OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
21976                                         Vector32, DAG.getIntPtrConstant(0));
21977             IntVT = MVT::i32;
21978           }
21979
21980           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, IntVT, OnesOrZeroesF);
21981           SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
21982                                       DAG.getConstant(1, IntVT));
21983           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
21984           return OneBitOfTruth;
21985         }
21986       }
21987     }
21988   }
21989   return SDValue();
21990 }
21991
21992 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
21993 /// so it can be folded inside ANDNP.
21994 static bool CanFoldXORWithAllOnes(const SDNode *N) {
21995   EVT VT = N->getValueType(0);
21996
21997   // Match direct AllOnes for 128 and 256-bit vectors
21998   if (ISD::isBuildVectorAllOnes(N))
21999     return true;
22000
22001   // Look through a bit convert.
22002   if (N->getOpcode() == ISD::BITCAST)
22003     N = N->getOperand(0).getNode();
22004
22005   // Sometimes the operand may come from a insert_subvector building a 256-bit
22006   // allones vector
22007   if (VT.is256BitVector() &&
22008       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
22009     SDValue V1 = N->getOperand(0);
22010     SDValue V2 = N->getOperand(1);
22011
22012     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
22013         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
22014         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
22015         ISD::isBuildVectorAllOnes(V2.getNode()))
22016       return true;
22017   }
22018
22019   return false;
22020 }
22021
22022 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
22023 // register. In most cases we actually compare or select YMM-sized registers
22024 // and mixing the two types creates horrible code. This method optimizes
22025 // some of the transition sequences.
22026 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
22027                                  TargetLowering::DAGCombinerInfo &DCI,
22028                                  const X86Subtarget *Subtarget) {
22029   EVT VT = N->getValueType(0);
22030   if (!VT.is256BitVector())
22031     return SDValue();
22032
22033   assert((N->getOpcode() == ISD::ANY_EXTEND ||
22034           N->getOpcode() == ISD::ZERO_EXTEND ||
22035           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
22036
22037   SDValue Narrow = N->getOperand(0);
22038   EVT NarrowVT = Narrow->getValueType(0);
22039   if (!NarrowVT.is128BitVector())
22040     return SDValue();
22041
22042   if (Narrow->getOpcode() != ISD::XOR &&
22043       Narrow->getOpcode() != ISD::AND &&
22044       Narrow->getOpcode() != ISD::OR)
22045     return SDValue();
22046
22047   SDValue N0  = Narrow->getOperand(0);
22048   SDValue N1  = Narrow->getOperand(1);
22049   SDLoc DL(Narrow);
22050
22051   // The Left side has to be a trunc.
22052   if (N0.getOpcode() != ISD::TRUNCATE)
22053     return SDValue();
22054
22055   // The type of the truncated inputs.
22056   EVT WideVT = N0->getOperand(0)->getValueType(0);
22057   if (WideVT != VT)
22058     return SDValue();
22059
22060   // The right side has to be a 'trunc' or a constant vector.
22061   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
22062   ConstantSDNode *RHSConstSplat = nullptr;
22063   if (auto *RHSBV = dyn_cast<BuildVectorSDNode>(N1))
22064     RHSConstSplat = RHSBV->getConstantSplatNode();
22065   if (!RHSTrunc && !RHSConstSplat)
22066     return SDValue();
22067
22068   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22069
22070   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
22071     return SDValue();
22072
22073   // Set N0 and N1 to hold the inputs to the new wide operation.
22074   N0 = N0->getOperand(0);
22075   if (RHSConstSplat) {
22076     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
22077                      SDValue(RHSConstSplat, 0));
22078     SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
22079     N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
22080   } else if (RHSTrunc) {
22081     N1 = N1->getOperand(0);
22082   }
22083
22084   // Generate the wide operation.
22085   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
22086   unsigned Opcode = N->getOpcode();
22087   switch (Opcode) {
22088   case ISD::ANY_EXTEND:
22089     return Op;
22090   case ISD::ZERO_EXTEND: {
22091     unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
22092     APInt Mask = APInt::getAllOnesValue(InBits);
22093     Mask = Mask.zext(VT.getScalarType().getSizeInBits());
22094     return DAG.getNode(ISD::AND, DL, VT,
22095                        Op, DAG.getConstant(Mask, VT));
22096   }
22097   case ISD::SIGN_EXTEND:
22098     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
22099                        Op, DAG.getValueType(NarrowVT));
22100   default:
22101     llvm_unreachable("Unexpected opcode");
22102   }
22103 }
22104
22105 static SDValue VectorZextCombine(SDNode *N, SelectionDAG &DAG,
22106                                  TargetLowering::DAGCombinerInfo &DCI,
22107                                  const X86Subtarget *Subtarget) {
22108   SDValue N0 = N->getOperand(0);
22109   SDValue N1 = N->getOperand(1);
22110   SDLoc DL(N);
22111
22112   // A vector zext_in_reg may be represented as a shuffle,
22113   // feeding into a bitcast (this represents anyext) feeding into
22114   // an and with a mask.
22115   // We'd like to try to combine that into a shuffle with zero
22116   // plus a bitcast, removing the and.
22117   if (N0.getOpcode() != ISD::BITCAST ||
22118       N0.getOperand(0).getOpcode() != ISD::VECTOR_SHUFFLE)
22119     return SDValue();
22120
22121   // The other side of the AND should be a splat of 2^C, where C
22122   // is the number of bits in the source type.
22123   if (N1.getOpcode() == ISD::BITCAST)
22124     N1 = N1.getOperand(0);
22125   if (N1.getOpcode() != ISD::BUILD_VECTOR)
22126     return SDValue();
22127   BuildVectorSDNode *Vector = cast<BuildVectorSDNode>(N1);
22128
22129   ShuffleVectorSDNode *Shuffle = cast<ShuffleVectorSDNode>(N0.getOperand(0));
22130   EVT SrcType = Shuffle->getValueType(0);
22131
22132   // We expect a single-source shuffle
22133   if (Shuffle->getOperand(1)->getOpcode() != ISD::UNDEF)
22134     return SDValue();
22135
22136   unsigned SrcSize = SrcType.getScalarSizeInBits();
22137
22138   APInt SplatValue, SplatUndef;
22139   unsigned SplatBitSize;
22140   bool HasAnyUndefs;
22141   if (!Vector->isConstantSplat(SplatValue, SplatUndef,
22142                                 SplatBitSize, HasAnyUndefs))
22143     return SDValue();
22144
22145   unsigned ResSize = N1.getValueType().getScalarSizeInBits();
22146   // Make sure the splat matches the mask we expect
22147   if (SplatBitSize > ResSize ||
22148       (SplatValue + 1).exactLogBase2() != (int)SrcSize)
22149     return SDValue();
22150
22151   // Make sure the input and output size make sense
22152   if (SrcSize >= ResSize || ResSize % SrcSize)
22153     return SDValue();
22154
22155   // We expect a shuffle of the form <0, u, u, u, 1, u, u, u...>
22156   // The number of u's between each two values depends on the ratio between
22157   // the source and dest type.
22158   unsigned ZextRatio = ResSize / SrcSize;
22159   bool IsZext = true;
22160   for (unsigned i = 0; i < SrcType.getVectorNumElements(); ++i) {
22161     if (i % ZextRatio) {
22162       if (Shuffle->getMaskElt(i) > 0) {
22163         // Expected undef
22164         IsZext = false;
22165         break;
22166       }
22167     } else {
22168       if (Shuffle->getMaskElt(i) != (int)(i / ZextRatio)) {
22169         // Expected element number
22170         IsZext = false;
22171         break;
22172       }
22173     }
22174   }
22175
22176   if (!IsZext)
22177     return SDValue();
22178
22179   // Ok, perform the transformation - replace the shuffle with
22180   // a shuffle of the form <0, k, k, k, 1, k, k, k> with zero
22181   // (instead of undef) where the k elements come from the zero vector.
22182   SmallVector<int, 8> Mask;
22183   unsigned NumElems = SrcType.getVectorNumElements();
22184   for (unsigned i = 0; i < NumElems; ++i)
22185     if (i % ZextRatio)
22186       Mask.push_back(NumElems);
22187     else
22188       Mask.push_back(i / ZextRatio);
22189
22190   SDValue NewShuffle = DAG.getVectorShuffle(Shuffle->getValueType(0), DL,
22191     Shuffle->getOperand(0), DAG.getConstant(0, SrcType), Mask);
22192   return DAG.getNode(ISD::BITCAST, DL,  N0.getValueType(), NewShuffle);
22193 }
22194
22195 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
22196                                  TargetLowering::DAGCombinerInfo &DCI,
22197                                  const X86Subtarget *Subtarget) {
22198   if (DCI.isBeforeLegalizeOps())
22199     return SDValue();
22200
22201   if (SDValue Zext = VectorZextCombine(N, DAG, DCI, Subtarget))
22202     return Zext;
22203
22204   if (SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget))
22205     return R;
22206
22207   EVT VT = N->getValueType(0);
22208   SDValue N0 = N->getOperand(0);
22209   SDValue N1 = N->getOperand(1);
22210   SDLoc DL(N);
22211
22212   // Create BEXTR instructions
22213   // BEXTR is ((X >> imm) & (2**size-1))
22214   if (VT == MVT::i32 || VT == MVT::i64) {
22215     // Check for BEXTR.
22216     if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
22217         (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
22218       ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
22219       ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
22220       if (MaskNode && ShiftNode) {
22221         uint64_t Mask = MaskNode->getZExtValue();
22222         uint64_t Shift = ShiftNode->getZExtValue();
22223         if (isMask_64(Mask)) {
22224           uint64_t MaskSize = countPopulation(Mask);
22225           if (Shift + MaskSize <= VT.getSizeInBits())
22226             return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
22227                                DAG.getConstant(Shift | (MaskSize << 8), VT));
22228         }
22229       }
22230     } // BEXTR
22231
22232     return SDValue();
22233   }
22234
22235   // Want to form ANDNP nodes:
22236   // 1) In the hopes of then easily combining them with OR and AND nodes
22237   //    to form PBLEND/PSIGN.
22238   // 2) To match ANDN packed intrinsics
22239   if (VT != MVT::v2i64 && VT != MVT::v4i64)
22240     return SDValue();
22241
22242   // Check LHS for vnot
22243   if (N0.getOpcode() == ISD::XOR &&
22244       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
22245       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
22246     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
22247
22248   // Check RHS for vnot
22249   if (N1.getOpcode() == ISD::XOR &&
22250       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
22251       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
22252     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
22253
22254   return SDValue();
22255 }
22256
22257 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
22258                                 TargetLowering::DAGCombinerInfo &DCI,
22259                                 const X86Subtarget *Subtarget) {
22260   if (DCI.isBeforeLegalizeOps())
22261     return SDValue();
22262
22263   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
22264   if (R.getNode())
22265     return R;
22266
22267   SDValue N0 = N->getOperand(0);
22268   SDValue N1 = N->getOperand(1);
22269   EVT VT = N->getValueType(0);
22270
22271   // look for psign/blend
22272   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
22273     if (!Subtarget->hasSSSE3() ||
22274         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
22275       return SDValue();
22276
22277     // Canonicalize pandn to RHS
22278     if (N0.getOpcode() == X86ISD::ANDNP)
22279       std::swap(N0, N1);
22280     // or (and (m, y), (pandn m, x))
22281     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
22282       SDValue Mask = N1.getOperand(0);
22283       SDValue X    = N1.getOperand(1);
22284       SDValue Y;
22285       if (N0.getOperand(0) == Mask)
22286         Y = N0.getOperand(1);
22287       if (N0.getOperand(1) == Mask)
22288         Y = N0.getOperand(0);
22289
22290       // Check to see if the mask appeared in both the AND and ANDNP and
22291       if (!Y.getNode())
22292         return SDValue();
22293
22294       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
22295       // Look through mask bitcast.
22296       if (Mask.getOpcode() == ISD::BITCAST)
22297         Mask = Mask.getOperand(0);
22298       if (X.getOpcode() == ISD::BITCAST)
22299         X = X.getOperand(0);
22300       if (Y.getOpcode() == ISD::BITCAST)
22301         Y = Y.getOperand(0);
22302
22303       EVT MaskVT = Mask.getValueType();
22304
22305       // Validate that the Mask operand is a vector sra node.
22306       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
22307       // there is no psrai.b
22308       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
22309       unsigned SraAmt = ~0;
22310       if (Mask.getOpcode() == ISD::SRA) {
22311         if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Mask.getOperand(1)))
22312           if (auto *AmtConst = AmtBV->getConstantSplatNode())
22313             SraAmt = AmtConst->getZExtValue();
22314       } else if (Mask.getOpcode() == X86ISD::VSRAI) {
22315         SDValue SraC = Mask.getOperand(1);
22316         SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
22317       }
22318       if ((SraAmt + 1) != EltBits)
22319         return SDValue();
22320
22321       SDLoc DL(N);
22322
22323       // Now we know we at least have a plendvb with the mask val.  See if
22324       // we can form a psignb/w/d.
22325       // psign = x.type == y.type == mask.type && y = sub(0, x);
22326       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
22327           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
22328           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
22329         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
22330                "Unsupported VT for PSIGN");
22331         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
22332         return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
22333       }
22334       // PBLENDVB only available on SSE 4.1
22335       if (!Subtarget->hasSSE41())
22336         return SDValue();
22337
22338       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
22339
22340       X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
22341       Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
22342       Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
22343       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
22344       return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
22345     }
22346   }
22347
22348   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
22349     return SDValue();
22350
22351   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
22352   MachineFunction &MF = DAG.getMachineFunction();
22353   bool OptForSize =
22354       MF.getFunction()->hasFnAttribute(Attribute::OptimizeForSize);
22355
22356   // SHLD/SHRD instructions have lower register pressure, but on some
22357   // platforms they have higher latency than the equivalent
22358   // series of shifts/or that would otherwise be generated.
22359   // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
22360   // have higher latencies and we are not optimizing for size.
22361   if (!OptForSize && Subtarget->isSHLDSlow())
22362     return SDValue();
22363
22364   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
22365     std::swap(N0, N1);
22366   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
22367     return SDValue();
22368   if (!N0.hasOneUse() || !N1.hasOneUse())
22369     return SDValue();
22370
22371   SDValue ShAmt0 = N0.getOperand(1);
22372   if (ShAmt0.getValueType() != MVT::i8)
22373     return SDValue();
22374   SDValue ShAmt1 = N1.getOperand(1);
22375   if (ShAmt1.getValueType() != MVT::i8)
22376     return SDValue();
22377   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
22378     ShAmt0 = ShAmt0.getOperand(0);
22379   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
22380     ShAmt1 = ShAmt1.getOperand(0);
22381
22382   SDLoc DL(N);
22383   unsigned Opc = X86ISD::SHLD;
22384   SDValue Op0 = N0.getOperand(0);
22385   SDValue Op1 = N1.getOperand(0);
22386   if (ShAmt0.getOpcode() == ISD::SUB) {
22387     Opc = X86ISD::SHRD;
22388     std::swap(Op0, Op1);
22389     std::swap(ShAmt0, ShAmt1);
22390   }
22391
22392   unsigned Bits = VT.getSizeInBits();
22393   if (ShAmt1.getOpcode() == ISD::SUB) {
22394     SDValue Sum = ShAmt1.getOperand(0);
22395     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
22396       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
22397       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
22398         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
22399       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
22400         return DAG.getNode(Opc, DL, VT,
22401                            Op0, Op1,
22402                            DAG.getNode(ISD::TRUNCATE, DL,
22403                                        MVT::i8, ShAmt0));
22404     }
22405   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
22406     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
22407     if (ShAmt0C &&
22408         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
22409       return DAG.getNode(Opc, DL, VT,
22410                          N0.getOperand(0), N1.getOperand(0),
22411                          DAG.getNode(ISD::TRUNCATE, DL,
22412                                        MVT::i8, ShAmt0));
22413   }
22414
22415   return SDValue();
22416 }
22417
22418 // Generate NEG and CMOV for integer abs.
22419 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
22420   EVT VT = N->getValueType(0);
22421
22422   // Since X86 does not have CMOV for 8-bit integer, we don't convert
22423   // 8-bit integer abs to NEG and CMOV.
22424   if (VT.isInteger() && VT.getSizeInBits() == 8)
22425     return SDValue();
22426
22427   SDValue N0 = N->getOperand(0);
22428   SDValue N1 = N->getOperand(1);
22429   SDLoc DL(N);
22430
22431   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
22432   // and change it to SUB and CMOV.
22433   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
22434       N0.getOpcode() == ISD::ADD &&
22435       N0.getOperand(1) == N1 &&
22436       N1.getOpcode() == ISD::SRA &&
22437       N1.getOperand(0) == N0.getOperand(0))
22438     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
22439       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
22440         // Generate SUB & CMOV.
22441         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
22442                                   DAG.getConstant(0, VT), N0.getOperand(0));
22443
22444         SDValue Ops[] = { N0.getOperand(0), Neg,
22445                           DAG.getConstant(X86::COND_GE, MVT::i8),
22446                           SDValue(Neg.getNode(), 1) };
22447         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
22448       }
22449   return SDValue();
22450 }
22451
22452 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
22453 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
22454                                  TargetLowering::DAGCombinerInfo &DCI,
22455                                  const X86Subtarget *Subtarget) {
22456   if (DCI.isBeforeLegalizeOps())
22457     return SDValue();
22458
22459   if (Subtarget->hasCMov()) {
22460     SDValue RV = performIntegerAbsCombine(N, DAG);
22461     if (RV.getNode())
22462       return RV;
22463   }
22464
22465   return SDValue();
22466 }
22467
22468 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
22469 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
22470                                   TargetLowering::DAGCombinerInfo &DCI,
22471                                   const X86Subtarget *Subtarget) {
22472   LoadSDNode *Ld = cast<LoadSDNode>(N);
22473   EVT RegVT = Ld->getValueType(0);
22474   EVT MemVT = Ld->getMemoryVT();
22475   SDLoc dl(Ld);
22476   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22477
22478   // For chips with slow 32-byte unaligned loads, break the 32-byte operation
22479   // into two 16-byte operations.
22480   ISD::LoadExtType Ext = Ld->getExtensionType();
22481   unsigned Alignment = Ld->getAlignment();
22482   bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
22483   if (RegVT.is256BitVector() && Subtarget->isUnalignedMem32Slow() &&
22484       !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
22485     unsigned NumElems = RegVT.getVectorNumElements();
22486     if (NumElems < 2)
22487       return SDValue();
22488
22489     SDValue Ptr = Ld->getBasePtr();
22490     SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
22491
22492     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
22493                                   NumElems/2);
22494     SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
22495                                 Ld->getPointerInfo(), Ld->isVolatile(),
22496                                 Ld->isNonTemporal(), Ld->isInvariant(),
22497                                 Alignment);
22498     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
22499     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
22500                                 Ld->getPointerInfo(), Ld->isVolatile(),
22501                                 Ld->isNonTemporal(), Ld->isInvariant(),
22502                                 std::min(16U, Alignment));
22503     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
22504                              Load1.getValue(1),
22505                              Load2.getValue(1));
22506
22507     SDValue NewVec = DAG.getUNDEF(RegVT);
22508     NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
22509     NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
22510     return DCI.CombineTo(N, NewVec, TF, true);
22511   }
22512
22513   return SDValue();
22514 }
22515
22516 /// PerformMLOADCombine - Resolve extending loads
22517 static SDValue PerformMLOADCombine(SDNode *N, SelectionDAG &DAG,
22518                                    TargetLowering::DAGCombinerInfo &DCI,
22519                                    const X86Subtarget *Subtarget) {
22520   MaskedLoadSDNode *Mld = cast<MaskedLoadSDNode>(N);
22521   if (Mld->getExtensionType() != ISD::SEXTLOAD)
22522     return SDValue();
22523
22524   EVT VT = Mld->getValueType(0);
22525   unsigned NumElems = VT.getVectorNumElements();
22526   EVT LdVT = Mld->getMemoryVT();
22527   SDLoc dl(Mld);
22528
22529   assert(LdVT != VT && "Cannot extend to the same type");
22530   unsigned ToSz = VT.getVectorElementType().getSizeInBits();
22531   unsigned FromSz = LdVT.getVectorElementType().getSizeInBits();
22532   // From, To sizes and ElemCount must be pow of two
22533   assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
22534     "Unexpected size for extending masked load");
22535
22536   unsigned SizeRatio  = ToSz / FromSz;
22537   assert(SizeRatio * NumElems * FromSz == VT.getSizeInBits());
22538
22539   // Create a type on which we perform the shuffle
22540   EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
22541           LdVT.getScalarType(), NumElems*SizeRatio);
22542   assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
22543
22544   // Convert Src0 value
22545   SDValue WideSrc0 = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Mld->getSrc0());
22546   if (Mld->getSrc0().getOpcode() != ISD::UNDEF) {
22547     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
22548     for (unsigned i = 0; i != NumElems; ++i)
22549       ShuffleVec[i] = i * SizeRatio;
22550
22551     // Can't shuffle using an illegal type.
22552     assert (DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT)
22553             && "WideVecVT should be legal");
22554     WideSrc0 = DAG.getVectorShuffle(WideVecVT, dl, WideSrc0,
22555                                     DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
22556   }
22557   // Prepare the new mask
22558   SDValue NewMask;
22559   SDValue Mask = Mld->getMask();
22560   if (Mask.getValueType() == VT) {
22561     // Mask and original value have the same type
22562     NewMask = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Mask);
22563     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
22564     for (unsigned i = 0; i != NumElems; ++i)
22565       ShuffleVec[i] = i * SizeRatio;
22566     for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
22567       ShuffleVec[i] = NumElems*SizeRatio;
22568     NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
22569                                    DAG.getConstant(0, WideVecVT),
22570                                    &ShuffleVec[0]);
22571   }
22572   else {
22573     assert(Mask.getValueType().getVectorElementType() == MVT::i1);
22574     unsigned WidenNumElts = NumElems*SizeRatio;
22575     unsigned MaskNumElts = VT.getVectorNumElements();
22576     EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(),  MVT::i1,
22577                                      WidenNumElts);
22578
22579     unsigned NumConcat = WidenNumElts / MaskNumElts;
22580     SmallVector<SDValue, 16> Ops(NumConcat);
22581     SDValue ZeroVal = DAG.getConstant(0, Mask.getValueType());
22582     Ops[0] = Mask;
22583     for (unsigned i = 1; i != NumConcat; ++i)
22584       Ops[i] = ZeroVal;
22585
22586     NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
22587   }
22588
22589   SDValue WideLd = DAG.getMaskedLoad(WideVecVT, dl, Mld->getChain(),
22590                                      Mld->getBasePtr(), NewMask, WideSrc0,
22591                                      Mld->getMemoryVT(), Mld->getMemOperand(),
22592                                      ISD::NON_EXTLOAD);
22593   SDValue NewVec = DAG.getNode(X86ISD::VSEXT, dl, VT, WideLd);
22594   return DCI.CombineTo(N, NewVec, WideLd.getValue(1), true);
22595
22596 }
22597 /// PerformMSTORECombine - Resolve truncating stores
22598 static SDValue PerformMSTORECombine(SDNode *N, SelectionDAG &DAG,
22599                                     const X86Subtarget *Subtarget) {
22600   MaskedStoreSDNode *Mst = cast<MaskedStoreSDNode>(N);
22601   if (!Mst->isTruncatingStore())
22602     return SDValue();
22603
22604   EVT VT = Mst->getValue().getValueType();
22605   unsigned NumElems = VT.getVectorNumElements();
22606   EVT StVT = Mst->getMemoryVT();
22607   SDLoc dl(Mst);
22608
22609   assert(StVT != VT && "Cannot truncate to the same type");
22610   unsigned FromSz = VT.getVectorElementType().getSizeInBits();
22611   unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
22612
22613   // From, To sizes and ElemCount must be pow of two
22614   assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
22615     "Unexpected size for truncating masked store");
22616   // We are going to use the original vector elt for storing.
22617   // Accumulated smaller vector elements must be a multiple of the store size.
22618   assert (((NumElems * FromSz) % ToSz) == 0 &&
22619           "Unexpected ratio for truncating masked store");
22620
22621   unsigned SizeRatio  = FromSz / ToSz;
22622   assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
22623
22624   // Create a type on which we perform the shuffle
22625   EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
22626           StVT.getScalarType(), NumElems*SizeRatio);
22627
22628   assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
22629
22630   SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Mst->getValue());
22631   SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
22632   for (unsigned i = 0; i != NumElems; ++i)
22633     ShuffleVec[i] = i * SizeRatio;
22634
22635   // Can't shuffle using an illegal type.
22636   assert (DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT)
22637           && "WideVecVT should be legal");
22638
22639   SDValue TruncatedVal = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
22640                                         DAG.getUNDEF(WideVecVT),
22641                                         &ShuffleVec[0]);
22642
22643   SDValue NewMask;
22644   SDValue Mask = Mst->getMask();
22645   if (Mask.getValueType() == VT) {
22646     // Mask and original value have the same type
22647     NewMask = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Mask);
22648     for (unsigned i = 0; i != NumElems; ++i)
22649       ShuffleVec[i] = i * SizeRatio;
22650     for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
22651       ShuffleVec[i] = NumElems*SizeRatio;
22652     NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
22653                                    DAG.getConstant(0, WideVecVT),
22654                                    &ShuffleVec[0]);
22655   }
22656   else {
22657     assert(Mask.getValueType().getVectorElementType() == MVT::i1);
22658     unsigned WidenNumElts = NumElems*SizeRatio;
22659     unsigned MaskNumElts = VT.getVectorNumElements();
22660     EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(),  MVT::i1,
22661                                      WidenNumElts);
22662
22663     unsigned NumConcat = WidenNumElts / MaskNumElts;
22664     SmallVector<SDValue, 16> Ops(NumConcat);
22665     SDValue ZeroVal = DAG.getConstant(0, Mask.getValueType());
22666     Ops[0] = Mask;
22667     for (unsigned i = 1; i != NumConcat; ++i)
22668       Ops[i] = ZeroVal;
22669
22670     NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
22671   }
22672
22673   return DAG.getMaskedStore(Mst->getChain(), dl, TruncatedVal, Mst->getBasePtr(),
22674                             NewMask, StVT, Mst->getMemOperand(), false);
22675 }
22676 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
22677 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
22678                                    const X86Subtarget *Subtarget) {
22679   StoreSDNode *St = cast<StoreSDNode>(N);
22680   EVT VT = St->getValue().getValueType();
22681   EVT StVT = St->getMemoryVT();
22682   SDLoc dl(St);
22683   SDValue StoredVal = St->getOperand(1);
22684   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22685
22686   // If we are saving a concatenation of two XMM registers and 32-byte stores
22687   // are slow, such as on Sandy Bridge, perform two 16-byte stores.
22688   unsigned Alignment = St->getAlignment();
22689   bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
22690   if (VT.is256BitVector() && Subtarget->isUnalignedMem32Slow() &&
22691       StVT == VT && !IsAligned) {
22692     unsigned NumElems = VT.getVectorNumElements();
22693     if (NumElems < 2)
22694       return SDValue();
22695
22696     SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
22697     SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
22698
22699     SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
22700     SDValue Ptr0 = St->getBasePtr();
22701     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
22702
22703     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
22704                                 St->getPointerInfo(), St->isVolatile(),
22705                                 St->isNonTemporal(), Alignment);
22706     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
22707                                 St->getPointerInfo(), St->isVolatile(),
22708                                 St->isNonTemporal(),
22709                                 std::min(16U, Alignment));
22710     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
22711   }
22712
22713   // Optimize trunc store (of multiple scalars) to shuffle and store.
22714   // First, pack all of the elements in one place. Next, store to memory
22715   // in fewer chunks.
22716   if (St->isTruncatingStore() && VT.isVector()) {
22717     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22718     unsigned NumElems = VT.getVectorNumElements();
22719     assert(StVT != VT && "Cannot truncate to the same type");
22720     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
22721     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
22722
22723     // From, To sizes and ElemCount must be pow of two
22724     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
22725     // We are going to use the original vector elt for storing.
22726     // Accumulated smaller vector elements must be a multiple of the store size.
22727     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
22728
22729     unsigned SizeRatio  = FromSz / ToSz;
22730
22731     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
22732
22733     // Create a type on which we perform the shuffle
22734     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
22735             StVT.getScalarType(), NumElems*SizeRatio);
22736
22737     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
22738
22739     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
22740     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
22741     for (unsigned i = 0; i != NumElems; ++i)
22742       ShuffleVec[i] = i * SizeRatio;
22743
22744     // Can't shuffle using an illegal type.
22745     if (!TLI.isTypeLegal(WideVecVT))
22746       return SDValue();
22747
22748     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
22749                                          DAG.getUNDEF(WideVecVT),
22750                                          &ShuffleVec[0]);
22751     // At this point all of the data is stored at the bottom of the
22752     // register. We now need to save it to mem.
22753
22754     // Find the largest store unit
22755     MVT StoreType = MVT::i8;
22756     for (MVT Tp : MVT::integer_valuetypes()) {
22757       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
22758         StoreType = Tp;
22759     }
22760
22761     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
22762     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
22763         (64 <= NumElems * ToSz))
22764       StoreType = MVT::f64;
22765
22766     // Bitcast the original vector into a vector of store-size units
22767     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
22768             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
22769     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
22770     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
22771     SmallVector<SDValue, 8> Chains;
22772     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
22773                                         TLI.getPointerTy());
22774     SDValue Ptr = St->getBasePtr();
22775
22776     // Perform one or more big stores into memory.
22777     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
22778       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
22779                                    StoreType, ShuffWide,
22780                                    DAG.getIntPtrConstant(i));
22781       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
22782                                 St->getPointerInfo(), St->isVolatile(),
22783                                 St->isNonTemporal(), St->getAlignment());
22784       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
22785       Chains.push_back(Ch);
22786     }
22787
22788     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
22789   }
22790
22791   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
22792   // the FP state in cases where an emms may be missing.
22793   // A preferable solution to the general problem is to figure out the right
22794   // places to insert EMMS.  This qualifies as a quick hack.
22795
22796   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
22797   if (VT.getSizeInBits() != 64)
22798     return SDValue();
22799
22800   const Function *F = DAG.getMachineFunction().getFunction();
22801   bool NoImplicitFloatOps = F->hasFnAttribute(Attribute::NoImplicitFloat);
22802   bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
22803                      && Subtarget->hasSSE2();
22804   if ((VT.isVector() ||
22805        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
22806       isa<LoadSDNode>(St->getValue()) &&
22807       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
22808       St->getChain().hasOneUse() && !St->isVolatile()) {
22809     SDNode* LdVal = St->getValue().getNode();
22810     LoadSDNode *Ld = nullptr;
22811     int TokenFactorIndex = -1;
22812     SmallVector<SDValue, 8> Ops;
22813     SDNode* ChainVal = St->getChain().getNode();
22814     // Must be a store of a load.  We currently handle two cases:  the load
22815     // is a direct child, and it's under an intervening TokenFactor.  It is
22816     // possible to dig deeper under nested TokenFactors.
22817     if (ChainVal == LdVal)
22818       Ld = cast<LoadSDNode>(St->getChain());
22819     else if (St->getValue().hasOneUse() &&
22820              ChainVal->getOpcode() == ISD::TokenFactor) {
22821       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
22822         if (ChainVal->getOperand(i).getNode() == LdVal) {
22823           TokenFactorIndex = i;
22824           Ld = cast<LoadSDNode>(St->getValue());
22825         } else
22826           Ops.push_back(ChainVal->getOperand(i));
22827       }
22828     }
22829
22830     if (!Ld || !ISD::isNormalLoad(Ld))
22831       return SDValue();
22832
22833     // If this is not the MMX case, i.e. we are just turning i64 load/store
22834     // into f64 load/store, avoid the transformation if there are multiple
22835     // uses of the loaded value.
22836     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
22837       return SDValue();
22838
22839     SDLoc LdDL(Ld);
22840     SDLoc StDL(N);
22841     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
22842     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
22843     // pair instead.
22844     if (Subtarget->is64Bit() || F64IsLegal) {
22845       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
22846       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
22847                                   Ld->getPointerInfo(), Ld->isVolatile(),
22848                                   Ld->isNonTemporal(), Ld->isInvariant(),
22849                                   Ld->getAlignment());
22850       SDValue NewChain = NewLd.getValue(1);
22851       if (TokenFactorIndex != -1) {
22852         Ops.push_back(NewChain);
22853         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
22854       }
22855       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
22856                           St->getPointerInfo(),
22857                           St->isVolatile(), St->isNonTemporal(),
22858                           St->getAlignment());
22859     }
22860
22861     // Otherwise, lower to two pairs of 32-bit loads / stores.
22862     SDValue LoAddr = Ld->getBasePtr();
22863     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
22864                                  DAG.getConstant(4, MVT::i32));
22865
22866     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
22867                                Ld->getPointerInfo(),
22868                                Ld->isVolatile(), Ld->isNonTemporal(),
22869                                Ld->isInvariant(), Ld->getAlignment());
22870     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
22871                                Ld->getPointerInfo().getWithOffset(4),
22872                                Ld->isVolatile(), Ld->isNonTemporal(),
22873                                Ld->isInvariant(),
22874                                MinAlign(Ld->getAlignment(), 4));
22875
22876     SDValue NewChain = LoLd.getValue(1);
22877     if (TokenFactorIndex != -1) {
22878       Ops.push_back(LoLd);
22879       Ops.push_back(HiLd);
22880       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
22881     }
22882
22883     LoAddr = St->getBasePtr();
22884     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
22885                          DAG.getConstant(4, MVT::i32));
22886
22887     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
22888                                 St->getPointerInfo(),
22889                                 St->isVolatile(), St->isNonTemporal(),
22890                                 St->getAlignment());
22891     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
22892                                 St->getPointerInfo().getWithOffset(4),
22893                                 St->isVolatile(),
22894                                 St->isNonTemporal(),
22895                                 MinAlign(St->getAlignment(), 4));
22896     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
22897   }
22898   return SDValue();
22899 }
22900
22901 /// Return 'true' if this vector operation is "horizontal"
22902 /// and return the operands for the horizontal operation in LHS and RHS.  A
22903 /// horizontal operation performs the binary operation on successive elements
22904 /// of its first operand, then on successive elements of its second operand,
22905 /// returning the resulting values in a vector.  For example, if
22906 ///   A = < float a0, float a1, float a2, float a3 >
22907 /// and
22908 ///   B = < float b0, float b1, float b2, float b3 >
22909 /// then the result of doing a horizontal operation on A and B is
22910 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
22911 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
22912 /// A horizontal-op B, for some already available A and B, and if so then LHS is
22913 /// set to A, RHS to B, and the routine returns 'true'.
22914 /// Note that the binary operation should have the property that if one of the
22915 /// operands is UNDEF then the result is UNDEF.
22916 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
22917   // Look for the following pattern: if
22918   //   A = < float a0, float a1, float a2, float a3 >
22919   //   B = < float b0, float b1, float b2, float b3 >
22920   // and
22921   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
22922   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
22923   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
22924   // which is A horizontal-op B.
22925
22926   // At least one of the operands should be a vector shuffle.
22927   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
22928       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
22929     return false;
22930
22931   MVT VT = LHS.getSimpleValueType();
22932
22933   assert((VT.is128BitVector() || VT.is256BitVector()) &&
22934          "Unsupported vector type for horizontal add/sub");
22935
22936   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
22937   // operate independently on 128-bit lanes.
22938   unsigned NumElts = VT.getVectorNumElements();
22939   unsigned NumLanes = VT.getSizeInBits()/128;
22940   unsigned NumLaneElts = NumElts / NumLanes;
22941   assert((NumLaneElts % 2 == 0) &&
22942          "Vector type should have an even number of elements in each lane");
22943   unsigned HalfLaneElts = NumLaneElts/2;
22944
22945   // View LHS in the form
22946   //   LHS = VECTOR_SHUFFLE A, B, LMask
22947   // If LHS is not a shuffle then pretend it is the shuffle
22948   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
22949   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
22950   // type VT.
22951   SDValue A, B;
22952   SmallVector<int, 16> LMask(NumElts);
22953   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
22954     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
22955       A = LHS.getOperand(0);
22956     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
22957       B = LHS.getOperand(1);
22958     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
22959     std::copy(Mask.begin(), Mask.end(), LMask.begin());
22960   } else {
22961     if (LHS.getOpcode() != ISD::UNDEF)
22962       A = LHS;
22963     for (unsigned i = 0; i != NumElts; ++i)
22964       LMask[i] = i;
22965   }
22966
22967   // Likewise, view RHS in the form
22968   //   RHS = VECTOR_SHUFFLE C, D, RMask
22969   SDValue C, D;
22970   SmallVector<int, 16> RMask(NumElts);
22971   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
22972     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
22973       C = RHS.getOperand(0);
22974     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
22975       D = RHS.getOperand(1);
22976     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
22977     std::copy(Mask.begin(), Mask.end(), RMask.begin());
22978   } else {
22979     if (RHS.getOpcode() != ISD::UNDEF)
22980       C = RHS;
22981     for (unsigned i = 0; i != NumElts; ++i)
22982       RMask[i] = i;
22983   }
22984
22985   // Check that the shuffles are both shuffling the same vectors.
22986   if (!(A == C && B == D) && !(A == D && B == C))
22987     return false;
22988
22989   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
22990   if (!A.getNode() && !B.getNode())
22991     return false;
22992
22993   // If A and B occur in reverse order in RHS, then "swap" them (which means
22994   // rewriting the mask).
22995   if (A != C)
22996     ShuffleVectorSDNode::commuteMask(RMask);
22997
22998   // At this point LHS and RHS are equivalent to
22999   //   LHS = VECTOR_SHUFFLE A, B, LMask
23000   //   RHS = VECTOR_SHUFFLE A, B, RMask
23001   // Check that the masks correspond to performing a horizontal operation.
23002   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
23003     for (unsigned i = 0; i != NumLaneElts; ++i) {
23004       int LIdx = LMask[i+l], RIdx = RMask[i+l];
23005
23006       // Ignore any UNDEF components.
23007       if (LIdx < 0 || RIdx < 0 ||
23008           (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
23009           (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
23010         continue;
23011
23012       // Check that successive elements are being operated on.  If not, this is
23013       // not a horizontal operation.
23014       unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
23015       int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
23016       if (!(LIdx == Index && RIdx == Index + 1) &&
23017           !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
23018         return false;
23019     }
23020   }
23021
23022   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
23023   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
23024   return true;
23025 }
23026
23027 /// Do target-specific dag combines on floating point adds.
23028 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
23029                                   const X86Subtarget *Subtarget) {
23030   EVT VT = N->getValueType(0);
23031   SDValue LHS = N->getOperand(0);
23032   SDValue RHS = N->getOperand(1);
23033
23034   // Try to synthesize horizontal adds from adds of shuffles.
23035   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
23036        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
23037       isHorizontalBinOp(LHS, RHS, true))
23038     return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
23039   return SDValue();
23040 }
23041
23042 /// Do target-specific dag combines on floating point subs.
23043 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
23044                                   const X86Subtarget *Subtarget) {
23045   EVT VT = N->getValueType(0);
23046   SDValue LHS = N->getOperand(0);
23047   SDValue RHS = N->getOperand(1);
23048
23049   // Try to synthesize horizontal subs from subs of shuffles.
23050   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
23051        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
23052       isHorizontalBinOp(LHS, RHS, false))
23053     return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
23054   return SDValue();
23055 }
23056
23057 /// Do target-specific dag combines on X86ISD::FOR and X86ISD::FXOR nodes.
23058 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
23059   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
23060
23061   // F[X]OR(0.0, x) -> x
23062   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
23063     if (C->getValueAPF().isPosZero())
23064       return N->getOperand(1);
23065
23066   // F[X]OR(x, 0.0) -> x
23067   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
23068     if (C->getValueAPF().isPosZero())
23069       return N->getOperand(0);
23070   return SDValue();
23071 }
23072
23073 /// Do target-specific dag combines on X86ISD::FMIN and X86ISD::FMAX nodes.
23074 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
23075   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
23076
23077   // Only perform optimizations if UnsafeMath is used.
23078   if (!DAG.getTarget().Options.UnsafeFPMath)
23079     return SDValue();
23080
23081   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
23082   // into FMINC and FMAXC, which are Commutative operations.
23083   unsigned NewOp = 0;
23084   switch (N->getOpcode()) {
23085     default: llvm_unreachable("unknown opcode");
23086     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
23087     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
23088   }
23089
23090   return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
23091                      N->getOperand(0), N->getOperand(1));
23092 }
23093
23094 /// Do target-specific dag combines on X86ISD::FAND nodes.
23095 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
23096   // FAND(0.0, x) -> 0.0
23097   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
23098     if (C->getValueAPF().isPosZero())
23099       return N->getOperand(0);
23100
23101   // FAND(x, 0.0) -> 0.0
23102   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
23103     if (C->getValueAPF().isPosZero())
23104       return N->getOperand(1);
23105
23106   return SDValue();
23107 }
23108
23109 /// Do target-specific dag combines on X86ISD::FANDN nodes
23110 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
23111   // FANDN(0.0, x) -> x
23112   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
23113     if (C->getValueAPF().isPosZero())
23114       return N->getOperand(1);
23115
23116   // FANDN(x, 0.0) -> 0.0
23117   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
23118     if (C->getValueAPF().isPosZero())
23119       return N->getOperand(1);
23120
23121   return SDValue();
23122 }
23123
23124 static SDValue PerformBTCombine(SDNode *N,
23125                                 SelectionDAG &DAG,
23126                                 TargetLowering::DAGCombinerInfo &DCI) {
23127   // BT ignores high bits in the bit index operand.
23128   SDValue Op1 = N->getOperand(1);
23129   if (Op1.hasOneUse()) {
23130     unsigned BitWidth = Op1.getValueSizeInBits();
23131     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
23132     APInt KnownZero, KnownOne;
23133     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
23134                                           !DCI.isBeforeLegalizeOps());
23135     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23136     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
23137         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
23138       DCI.CommitTargetLoweringOpt(TLO);
23139   }
23140   return SDValue();
23141 }
23142
23143 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
23144   SDValue Op = N->getOperand(0);
23145   if (Op.getOpcode() == ISD::BITCAST)
23146     Op = Op.getOperand(0);
23147   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
23148   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
23149       VT.getVectorElementType().getSizeInBits() ==
23150       OpVT.getVectorElementType().getSizeInBits()) {
23151     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
23152   }
23153   return SDValue();
23154 }
23155
23156 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
23157                                                const X86Subtarget *Subtarget) {
23158   EVT VT = N->getValueType(0);
23159   if (!VT.isVector())
23160     return SDValue();
23161
23162   SDValue N0 = N->getOperand(0);
23163   SDValue N1 = N->getOperand(1);
23164   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
23165   SDLoc dl(N);
23166
23167   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
23168   // both SSE and AVX2 since there is no sign-extended shift right
23169   // operation on a vector with 64-bit elements.
23170   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
23171   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
23172   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
23173       N0.getOpcode() == ISD::SIGN_EXTEND)) {
23174     SDValue N00 = N0.getOperand(0);
23175
23176     // EXTLOAD has a better solution on AVX2,
23177     // it may be replaced with X86ISD::VSEXT node.
23178     if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
23179       if (!ISD::isNormalLoad(N00.getNode()))
23180         return SDValue();
23181
23182     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
23183         SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
23184                                   N00, N1);
23185       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
23186     }
23187   }
23188   return SDValue();
23189 }
23190
23191 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
23192                                   TargetLowering::DAGCombinerInfo &DCI,
23193                                   const X86Subtarget *Subtarget) {
23194   SDValue N0 = N->getOperand(0);
23195   EVT VT = N->getValueType(0);
23196
23197   // (i8,i32 sext (sdivrem (i8 x, i8 y)) ->
23198   // (i8,i32 (sdivrem_sext_hreg (i8 x, i8 y)
23199   // This exposes the sext to the sdivrem lowering, so that it directly extends
23200   // from AH (which we otherwise need to do contortions to access).
23201   if (N0.getOpcode() == ISD::SDIVREM && N0.getResNo() == 1 &&
23202       N0.getValueType() == MVT::i8 && VT == MVT::i32) {
23203     SDLoc dl(N);
23204     SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
23205     SDValue R = DAG.getNode(X86ISD::SDIVREM8_SEXT_HREG, dl, NodeTys,
23206                             N0.getOperand(0), N0.getOperand(1));
23207     DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
23208     return R.getValue(1);
23209   }
23210
23211   if (!DCI.isBeforeLegalizeOps())
23212     return SDValue();
23213
23214   if (!Subtarget->hasFp256())
23215     return SDValue();
23216
23217   if (VT.isVector() && VT.getSizeInBits() == 256) {
23218     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
23219     if (R.getNode())
23220       return R;
23221   }
23222
23223   return SDValue();
23224 }
23225
23226 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
23227                                  const X86Subtarget* Subtarget) {
23228   SDLoc dl(N);
23229   EVT VT = N->getValueType(0);
23230
23231   // Let legalize expand this if it isn't a legal type yet.
23232   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
23233     return SDValue();
23234
23235   EVT ScalarVT = VT.getScalarType();
23236   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
23237       (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
23238     return SDValue();
23239
23240   SDValue A = N->getOperand(0);
23241   SDValue B = N->getOperand(1);
23242   SDValue C = N->getOperand(2);
23243
23244   bool NegA = (A.getOpcode() == ISD::FNEG);
23245   bool NegB = (B.getOpcode() == ISD::FNEG);
23246   bool NegC = (C.getOpcode() == ISD::FNEG);
23247
23248   // Negative multiplication when NegA xor NegB
23249   bool NegMul = (NegA != NegB);
23250   if (NegA)
23251     A = A.getOperand(0);
23252   if (NegB)
23253     B = B.getOperand(0);
23254   if (NegC)
23255     C = C.getOperand(0);
23256
23257   unsigned Opcode;
23258   if (!NegMul)
23259     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
23260   else
23261     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
23262
23263   return DAG.getNode(Opcode, dl, VT, A, B, C);
23264 }
23265
23266 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
23267                                   TargetLowering::DAGCombinerInfo &DCI,
23268                                   const X86Subtarget *Subtarget) {
23269   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
23270   //           (and (i32 x86isd::setcc_carry), 1)
23271   // This eliminates the zext. This transformation is necessary because
23272   // ISD::SETCC is always legalized to i8.
23273   SDLoc dl(N);
23274   SDValue N0 = N->getOperand(0);
23275   EVT VT = N->getValueType(0);
23276
23277   if (N0.getOpcode() == ISD::AND &&
23278       N0.hasOneUse() &&
23279       N0.getOperand(0).hasOneUse()) {
23280     SDValue N00 = N0.getOperand(0);
23281     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
23282       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
23283       if (!C || C->getZExtValue() != 1)
23284         return SDValue();
23285       return DAG.getNode(ISD::AND, dl, VT,
23286                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
23287                                      N00.getOperand(0), N00.getOperand(1)),
23288                          DAG.getConstant(1, VT));
23289     }
23290   }
23291
23292   if (N0.getOpcode() == ISD::TRUNCATE &&
23293       N0.hasOneUse() &&
23294       N0.getOperand(0).hasOneUse()) {
23295     SDValue N00 = N0.getOperand(0);
23296     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
23297       return DAG.getNode(ISD::AND, dl, VT,
23298                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
23299                                      N00.getOperand(0), N00.getOperand(1)),
23300                          DAG.getConstant(1, VT));
23301     }
23302   }
23303   if (VT.is256BitVector()) {
23304     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
23305     if (R.getNode())
23306       return R;
23307   }
23308
23309   // (i8,i32 zext (udivrem (i8 x, i8 y)) ->
23310   // (i8,i32 (udivrem_zext_hreg (i8 x, i8 y)
23311   // This exposes the zext to the udivrem lowering, so that it directly extends
23312   // from AH (which we otherwise need to do contortions to access).
23313   if (N0.getOpcode() == ISD::UDIVREM &&
23314       N0.getResNo() == 1 && N0.getValueType() == MVT::i8 &&
23315       (VT == MVT::i32 || VT == MVT::i64)) {
23316     SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
23317     SDValue R = DAG.getNode(X86ISD::UDIVREM8_ZEXT_HREG, dl, NodeTys,
23318                             N0.getOperand(0), N0.getOperand(1));
23319     DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
23320     return R.getValue(1);
23321   }
23322
23323   return SDValue();
23324 }
23325
23326 // Optimize x == -y --> x+y == 0
23327 //          x != -y --> x+y != 0
23328 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
23329                                       const X86Subtarget* Subtarget) {
23330   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
23331   SDValue LHS = N->getOperand(0);
23332   SDValue RHS = N->getOperand(1);
23333   EVT VT = N->getValueType(0);
23334   SDLoc DL(N);
23335
23336   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
23337     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
23338       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
23339         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N), LHS.getValueType(), RHS,
23340                                    LHS.getOperand(1));
23341         return DAG.getSetCC(SDLoc(N), N->getValueType(0), addV,
23342                             DAG.getConstant(0, addV.getValueType()), CC);
23343       }
23344   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
23345     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
23346       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
23347         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N), RHS.getValueType(), LHS,
23348                                    RHS.getOperand(1));
23349         return DAG.getSetCC(SDLoc(N), N->getValueType(0), addV,
23350                             DAG.getConstant(0, addV.getValueType()), CC);
23351       }
23352
23353   if (VT.getScalarType() == MVT::i1 &&
23354       (CC == ISD::SETNE || CC == ISD::SETEQ || ISD::isSignedIntSetCC(CC))) {
23355     bool IsSEXT0 =
23356         (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
23357         (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
23358     bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
23359
23360     if (!IsSEXT0 || !IsVZero1) {
23361       // Swap the operands and update the condition code.
23362       std::swap(LHS, RHS);
23363       CC = ISD::getSetCCSwappedOperands(CC);
23364
23365       IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
23366                 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
23367       IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
23368     }
23369
23370     if (IsSEXT0 && IsVZero1) {
23371       assert(VT == LHS.getOperand(0).getValueType() &&
23372              "Uexpected operand type");
23373       if (CC == ISD::SETGT)
23374         return DAG.getConstant(0, VT);
23375       if (CC == ISD::SETLE)
23376         return DAG.getConstant(1, VT);
23377       if (CC == ISD::SETEQ || CC == ISD::SETGE)
23378         return DAG.getNOT(DL, LHS.getOperand(0), VT);
23379
23380       assert((CC == ISD::SETNE || CC == ISD::SETLT) &&
23381              "Unexpected condition code!");
23382       return LHS.getOperand(0);
23383     }
23384   }
23385
23386   return SDValue();
23387 }
23388
23389 static SDValue NarrowVectorLoadToElement(LoadSDNode *Load, unsigned Index,
23390                                          SelectionDAG &DAG) {
23391   SDLoc dl(Load);
23392   MVT VT = Load->getSimpleValueType(0);
23393   MVT EVT = VT.getVectorElementType();
23394   SDValue Addr = Load->getOperand(1);
23395   SDValue NewAddr = DAG.getNode(
23396       ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
23397       DAG.getConstant(Index * EVT.getStoreSize(), Addr.getSimpleValueType()));
23398
23399   SDValue NewLoad =
23400       DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
23401                   DAG.getMachineFunction().getMachineMemOperand(
23402                       Load->getMemOperand(), 0, EVT.getStoreSize()));
23403   return NewLoad;
23404 }
23405
23406 static SDValue PerformINSERTPSCombine(SDNode *N, SelectionDAG &DAG,
23407                                       const X86Subtarget *Subtarget) {
23408   SDLoc dl(N);
23409   MVT VT = N->getOperand(1)->getSimpleValueType(0);
23410   assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
23411          "X86insertps is only defined for v4x32");
23412
23413   SDValue Ld = N->getOperand(1);
23414   if (MayFoldLoad(Ld)) {
23415     // Extract the countS bits from the immediate so we can get the proper
23416     // address when narrowing the vector load to a specific element.
23417     // When the second source op is a memory address, insertps doesn't use
23418     // countS and just gets an f32 from that address.
23419     unsigned DestIndex =
23420         cast<ConstantSDNode>(N->getOperand(2))->getZExtValue() >> 6;
23421
23422     Ld = NarrowVectorLoadToElement(cast<LoadSDNode>(Ld), DestIndex, DAG);
23423
23424     // Create this as a scalar to vector to match the instruction pattern.
23425     SDValue LoadScalarToVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Ld);
23426     // countS bits are ignored when loading from memory on insertps, which
23427     // means we don't need to explicitly set them to 0.
23428     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N->getOperand(0),
23429                        LoadScalarToVector, N->getOperand(2));
23430   }
23431   return SDValue();
23432 }
23433
23434 static SDValue PerformBLENDICombine(SDNode *N, SelectionDAG &DAG) {
23435   SDValue V0 = N->getOperand(0);
23436   SDValue V1 = N->getOperand(1);
23437   SDLoc DL(N);
23438   EVT VT = N->getValueType(0);
23439
23440   // Canonicalize a v2f64 blend with a mask of 2 by swapping the vector
23441   // operands and changing the mask to 1. This saves us a bunch of
23442   // pattern-matching possibilities related to scalar math ops in SSE/AVX.
23443   // x86InstrInfo knows how to commute this back after instruction selection
23444   // if it would help register allocation.
23445
23446   // TODO: If optimizing for size or a processor that doesn't suffer from
23447   // partial register update stalls, this should be transformed into a MOVSD
23448   // instruction because a MOVSD is 1-2 bytes smaller than a BLENDPD.
23449
23450   if (VT == MVT::v2f64)
23451     if (auto *Mask = dyn_cast<ConstantSDNode>(N->getOperand(2)))
23452       if (Mask->getZExtValue() == 2 && !isShuffleFoldableLoad(V0)) {
23453         SDValue NewMask = DAG.getConstant(1, MVT::i8);
23454         return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V0, NewMask);
23455       }
23456
23457   return SDValue();
23458 }
23459
23460 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
23461 // as "sbb reg,reg", since it can be extended without zext and produces
23462 // an all-ones bit which is more useful than 0/1 in some cases.
23463 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
23464                                MVT VT) {
23465   if (VT == MVT::i8)
23466     return DAG.getNode(ISD::AND, DL, VT,
23467                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
23468                                    DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
23469                        DAG.getConstant(1, VT));
23470   assert (VT == MVT::i1 && "Unexpected type for SECCC node");
23471   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
23472                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
23473                                  DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS));
23474 }
23475
23476 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
23477 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
23478                                    TargetLowering::DAGCombinerInfo &DCI,
23479                                    const X86Subtarget *Subtarget) {
23480   SDLoc DL(N);
23481   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
23482   SDValue EFLAGS = N->getOperand(1);
23483
23484   if (CC == X86::COND_A) {
23485     // Try to convert COND_A into COND_B in an attempt to facilitate
23486     // materializing "setb reg".
23487     //
23488     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
23489     // cannot take an immediate as its first operand.
23490     //
23491     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
23492         EFLAGS.getValueType().isInteger() &&
23493         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
23494       SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
23495                                    EFLAGS.getNode()->getVTList(),
23496                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
23497       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
23498       return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
23499     }
23500   }
23501
23502   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
23503   // a zext and produces an all-ones bit which is more useful than 0/1 in some
23504   // cases.
23505   if (CC == X86::COND_B)
23506     return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
23507
23508   SDValue Flags;
23509
23510   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
23511   if (Flags.getNode()) {
23512     SDValue Cond = DAG.getConstant(CC, MVT::i8);
23513     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
23514   }
23515
23516   return SDValue();
23517 }
23518
23519 // Optimize branch condition evaluation.
23520 //
23521 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
23522                                     TargetLowering::DAGCombinerInfo &DCI,
23523                                     const X86Subtarget *Subtarget) {
23524   SDLoc DL(N);
23525   SDValue Chain = N->getOperand(0);
23526   SDValue Dest = N->getOperand(1);
23527   SDValue EFLAGS = N->getOperand(3);
23528   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
23529
23530   SDValue Flags;
23531
23532   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
23533   if (Flags.getNode()) {
23534     SDValue Cond = DAG.getConstant(CC, MVT::i8);
23535     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
23536                        Flags);
23537   }
23538
23539   return SDValue();
23540 }
23541
23542 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
23543                                                          SelectionDAG &DAG) {
23544   // Take advantage of vector comparisons producing 0 or -1 in each lane to
23545   // optimize away operation when it's from a constant.
23546   //
23547   // The general transformation is:
23548   //    UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
23549   //       AND(VECTOR_CMP(x,y), constant2)
23550   //    constant2 = UNARYOP(constant)
23551
23552   // Early exit if this isn't a vector operation, the operand of the
23553   // unary operation isn't a bitwise AND, or if the sizes of the operations
23554   // aren't the same.
23555   EVT VT = N->getValueType(0);
23556   if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
23557       N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
23558       VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
23559     return SDValue();
23560
23561   // Now check that the other operand of the AND is a constant. We could
23562   // make the transformation for non-constant splats as well, but it's unclear
23563   // that would be a benefit as it would not eliminate any operations, just
23564   // perform one more step in scalar code before moving to the vector unit.
23565   if (BuildVectorSDNode *BV =
23566           dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
23567     // Bail out if the vector isn't a constant.
23568     if (!BV->isConstant())
23569       return SDValue();
23570
23571     // Everything checks out. Build up the new and improved node.
23572     SDLoc DL(N);
23573     EVT IntVT = BV->getValueType(0);
23574     // Create a new constant of the appropriate type for the transformed
23575     // DAG.
23576     SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
23577     // The AND node needs bitcasts to/from an integer vector type around it.
23578     SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
23579     SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
23580                                  N->getOperand(0)->getOperand(0), MaskConst);
23581     SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
23582     return Res;
23583   }
23584
23585   return SDValue();
23586 }
23587
23588 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
23589                                         const X86Subtarget *Subtarget) {
23590   // First try to optimize away the conversion entirely when it's
23591   // conditionally from a constant. Vectors only.
23592   SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG);
23593   if (Res != SDValue())
23594     return Res;
23595
23596   // Now move on to more general possibilities.
23597   SDValue Op0 = N->getOperand(0);
23598   EVT InVT = Op0->getValueType(0);
23599
23600   // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
23601   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
23602     SDLoc dl(N);
23603     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
23604     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
23605     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
23606   }
23607
23608   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
23609   // a 32-bit target where SSE doesn't support i64->FP operations.
23610   if (Op0.getOpcode() == ISD::LOAD) {
23611     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
23612     EVT VT = Ld->getValueType(0);
23613     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
23614         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
23615         !Subtarget->is64Bit() && VT == MVT::i64) {
23616       SDValue FILDChain = Subtarget->getTargetLowering()->BuildFILD(
23617           SDValue(N, 0), Ld->getValueType(0), Ld->getChain(), Op0, DAG);
23618       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
23619       return FILDChain;
23620     }
23621   }
23622   return SDValue();
23623 }
23624
23625 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
23626 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
23627                                  X86TargetLowering::DAGCombinerInfo &DCI) {
23628   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
23629   // the result is either zero or one (depending on the input carry bit).
23630   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
23631   if (X86::isZeroNode(N->getOperand(0)) &&
23632       X86::isZeroNode(N->getOperand(1)) &&
23633       // We don't have a good way to replace an EFLAGS use, so only do this when
23634       // dead right now.
23635       SDValue(N, 1).use_empty()) {
23636     SDLoc DL(N);
23637     EVT VT = N->getValueType(0);
23638     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
23639     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
23640                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
23641                                            DAG.getConstant(X86::COND_B,MVT::i8),
23642                                            N->getOperand(2)),
23643                                DAG.getConstant(1, VT));
23644     return DCI.CombineTo(N, Res1, CarryOut);
23645   }
23646
23647   return SDValue();
23648 }
23649
23650 // fold (add Y, (sete  X, 0)) -> adc  0, Y
23651 //      (add Y, (setne X, 0)) -> sbb -1, Y
23652 //      (sub (sete  X, 0), Y) -> sbb  0, Y
23653 //      (sub (setne X, 0), Y) -> adc -1, Y
23654 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
23655   SDLoc DL(N);
23656
23657   // Look through ZExts.
23658   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
23659   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
23660     return SDValue();
23661
23662   SDValue SetCC = Ext.getOperand(0);
23663   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
23664     return SDValue();
23665
23666   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
23667   if (CC != X86::COND_E && CC != X86::COND_NE)
23668     return SDValue();
23669
23670   SDValue Cmp = SetCC.getOperand(1);
23671   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
23672       !X86::isZeroNode(Cmp.getOperand(1)) ||
23673       !Cmp.getOperand(0).getValueType().isInteger())
23674     return SDValue();
23675
23676   SDValue CmpOp0 = Cmp.getOperand(0);
23677   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
23678                                DAG.getConstant(1, CmpOp0.getValueType()));
23679
23680   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
23681   if (CC == X86::COND_NE)
23682     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
23683                        DL, OtherVal.getValueType(), OtherVal,
23684                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
23685   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
23686                      DL, OtherVal.getValueType(), OtherVal,
23687                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
23688 }
23689
23690 /// PerformADDCombine - Do target-specific dag combines on integer adds.
23691 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
23692                                  const X86Subtarget *Subtarget) {
23693   EVT VT = N->getValueType(0);
23694   SDValue Op0 = N->getOperand(0);
23695   SDValue Op1 = N->getOperand(1);
23696
23697   // Try to synthesize horizontal adds from adds of shuffles.
23698   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
23699        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
23700       isHorizontalBinOp(Op0, Op1, true))
23701     return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
23702
23703   return OptimizeConditionalInDecrement(N, DAG);
23704 }
23705
23706 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
23707                                  const X86Subtarget *Subtarget) {
23708   SDValue Op0 = N->getOperand(0);
23709   SDValue Op1 = N->getOperand(1);
23710
23711   // X86 can't encode an immediate LHS of a sub. See if we can push the
23712   // negation into a preceding instruction.
23713   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
23714     // If the RHS of the sub is a XOR with one use and a constant, invert the
23715     // immediate. Then add one to the LHS of the sub so we can turn
23716     // X-Y -> X+~Y+1, saving one register.
23717     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
23718         isa<ConstantSDNode>(Op1.getOperand(1))) {
23719       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
23720       EVT VT = Op0.getValueType();
23721       SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
23722                                    Op1.getOperand(0),
23723                                    DAG.getConstant(~XorC, VT));
23724       return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
23725                          DAG.getConstant(C->getAPIntValue()+1, VT));
23726     }
23727   }
23728
23729   // Try to synthesize horizontal adds from adds of shuffles.
23730   EVT VT = N->getValueType(0);
23731   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
23732        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
23733       isHorizontalBinOp(Op0, Op1, true))
23734     return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
23735
23736   return OptimizeConditionalInDecrement(N, DAG);
23737 }
23738
23739 /// performVZEXTCombine - Performs build vector combines
23740 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
23741                                    TargetLowering::DAGCombinerInfo &DCI,
23742                                    const X86Subtarget *Subtarget) {
23743   SDLoc DL(N);
23744   MVT VT = N->getSimpleValueType(0);
23745   SDValue Op = N->getOperand(0);
23746   MVT OpVT = Op.getSimpleValueType();
23747   MVT OpEltVT = OpVT.getVectorElementType();
23748   unsigned InputBits = OpEltVT.getSizeInBits() * VT.getVectorNumElements();
23749
23750   // (vzext (bitcast (vzext (x)) -> (vzext x)
23751   SDValue V = Op;
23752   while (V.getOpcode() == ISD::BITCAST)
23753     V = V.getOperand(0);
23754
23755   if (V != Op && V.getOpcode() == X86ISD::VZEXT) {
23756     MVT InnerVT = V.getSimpleValueType();
23757     MVT InnerEltVT = InnerVT.getVectorElementType();
23758
23759     // If the element sizes match exactly, we can just do one larger vzext. This
23760     // is always an exact type match as vzext operates on integer types.
23761     if (OpEltVT == InnerEltVT) {
23762       assert(OpVT == InnerVT && "Types must match for vzext!");
23763       return DAG.getNode(X86ISD::VZEXT, DL, VT, V.getOperand(0));
23764     }
23765
23766     // The only other way we can combine them is if only a single element of the
23767     // inner vzext is used in the input to the outer vzext.
23768     if (InnerEltVT.getSizeInBits() < InputBits)
23769       return SDValue();
23770
23771     // In this case, the inner vzext is completely dead because we're going to
23772     // only look at bits inside of the low element. Just do the outer vzext on
23773     // a bitcast of the input to the inner.
23774     return DAG.getNode(X86ISD::VZEXT, DL, VT,
23775                        DAG.getNode(ISD::BITCAST, DL, OpVT, V));
23776   }
23777
23778   // Check if we can bypass extracting and re-inserting an element of an input
23779   // vector. Essentialy:
23780   // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
23781   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR &&
23782       V.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
23783       V.getOperand(0).getSimpleValueType().getSizeInBits() == InputBits) {
23784     SDValue ExtractedV = V.getOperand(0);
23785     SDValue OrigV = ExtractedV.getOperand(0);
23786     if (auto *ExtractIdx = dyn_cast<ConstantSDNode>(ExtractedV.getOperand(1)))
23787       if (ExtractIdx->getZExtValue() == 0) {
23788         MVT OrigVT = OrigV.getSimpleValueType();
23789         // Extract a subvector if necessary...
23790         if (OrigVT.getSizeInBits() > OpVT.getSizeInBits()) {
23791           int Ratio = OrigVT.getSizeInBits() / OpVT.getSizeInBits();
23792           OrigVT = MVT::getVectorVT(OrigVT.getVectorElementType(),
23793                                     OrigVT.getVectorNumElements() / Ratio);
23794           OrigV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigVT, OrigV,
23795                               DAG.getIntPtrConstant(0));
23796         }
23797         Op = DAG.getNode(ISD::BITCAST, DL, OpVT, OrigV);
23798         return DAG.getNode(X86ISD::VZEXT, DL, VT, Op);
23799       }
23800   }
23801
23802   return SDValue();
23803 }
23804
23805 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
23806                                              DAGCombinerInfo &DCI) const {
23807   SelectionDAG &DAG = DCI.DAG;
23808   switch (N->getOpcode()) {
23809   default: break;
23810   case ISD::EXTRACT_VECTOR_ELT:
23811     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
23812   case ISD::VSELECT:
23813   case ISD::SELECT:
23814   case X86ISD::SHRUNKBLEND:
23815     return PerformSELECTCombine(N, DAG, DCI, Subtarget);
23816   case ISD::BITCAST:        return PerformBITCASTCombine(N, DAG);
23817   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
23818   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
23819   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
23820   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
23821   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
23822   case ISD::SHL:
23823   case ISD::SRA:
23824   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
23825   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
23826   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
23827   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
23828   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
23829   case ISD::MLOAD:          return PerformMLOADCombine(N, DAG, DCI, Subtarget);
23830   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
23831   case ISD::MSTORE:         return PerformMSTORECombine(N, DAG, Subtarget);
23832   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, Subtarget);
23833   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
23834   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
23835   case X86ISD::FXOR:
23836   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
23837   case X86ISD::FMIN:
23838   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
23839   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
23840   case X86ISD::FANDN:       return PerformFANDNCombine(N, DAG);
23841   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
23842   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
23843   case ISD::ANY_EXTEND:
23844   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
23845   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
23846   case ISD::SIGN_EXTEND_INREG:
23847     return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
23848   case ISD::TRUNCATE:       return PerformTruncateCombine(N, DAG,DCI,Subtarget);
23849   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG, Subtarget);
23850   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
23851   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
23852   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
23853   case X86ISD::SHUFP:       // Handle all target specific shuffles
23854   case X86ISD::PALIGNR:
23855   case X86ISD::UNPCKH:
23856   case X86ISD::UNPCKL:
23857   case X86ISD::MOVHLPS:
23858   case X86ISD::MOVLHPS:
23859   case X86ISD::PSHUFB:
23860   case X86ISD::PSHUFD:
23861   case X86ISD::PSHUFHW:
23862   case X86ISD::PSHUFLW:
23863   case X86ISD::MOVSS:
23864   case X86ISD::MOVSD:
23865   case X86ISD::VPERMILPI:
23866   case X86ISD::VPERM2X128:
23867   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
23868   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
23869   case ISD::INTRINSIC_WO_CHAIN:
23870     return PerformINTRINSIC_WO_CHAINCombine(N, DAG, Subtarget);
23871   case X86ISD::INSERTPS: {
23872     if (getTargetMachine().getOptLevel() > CodeGenOpt::None)
23873       return PerformINSERTPSCombine(N, DAG, Subtarget);
23874     break;
23875   }
23876   case X86ISD::BLENDI:    return PerformBLENDICombine(N, DAG);
23877   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DAG, Subtarget);
23878   }
23879
23880   return SDValue();
23881 }
23882
23883 /// isTypeDesirableForOp - Return true if the target has native support for
23884 /// the specified value type and it is 'desirable' to use the type for the
23885 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
23886 /// instruction encodings are longer and some i16 instructions are slow.
23887 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
23888   if (!isTypeLegal(VT))
23889     return false;
23890   if (VT != MVT::i16)
23891     return true;
23892
23893   switch (Opc) {
23894   default:
23895     return true;
23896   case ISD::LOAD:
23897   case ISD::SIGN_EXTEND:
23898   case ISD::ZERO_EXTEND:
23899   case ISD::ANY_EXTEND:
23900   case ISD::SHL:
23901   case ISD::SRL:
23902   case ISD::SUB:
23903   case ISD::ADD:
23904   case ISD::MUL:
23905   case ISD::AND:
23906   case ISD::OR:
23907   case ISD::XOR:
23908     return false;
23909   }
23910 }
23911
23912 /// IsDesirableToPromoteOp - This method query the target whether it is
23913 /// beneficial for dag combiner to promote the specified node. If true, it
23914 /// should return the desired promotion type by reference.
23915 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
23916   EVT VT = Op.getValueType();
23917   if (VT != MVT::i16)
23918     return false;
23919
23920   bool Promote = false;
23921   bool Commute = false;
23922   switch (Op.getOpcode()) {
23923   default: break;
23924   case ISD::LOAD: {
23925     LoadSDNode *LD = cast<LoadSDNode>(Op);
23926     // If the non-extending load has a single use and it's not live out, then it
23927     // might be folded.
23928     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
23929                                                      Op.hasOneUse()*/) {
23930       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
23931              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
23932         // The only case where we'd want to promote LOAD (rather then it being
23933         // promoted as an operand is when it's only use is liveout.
23934         if (UI->getOpcode() != ISD::CopyToReg)
23935           return false;
23936       }
23937     }
23938     Promote = true;
23939     break;
23940   }
23941   case ISD::SIGN_EXTEND:
23942   case ISD::ZERO_EXTEND:
23943   case ISD::ANY_EXTEND:
23944     Promote = true;
23945     break;
23946   case ISD::SHL:
23947   case ISD::SRL: {
23948     SDValue N0 = Op.getOperand(0);
23949     // Look out for (store (shl (load), x)).
23950     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
23951       return false;
23952     Promote = true;
23953     break;
23954   }
23955   case ISD::ADD:
23956   case ISD::MUL:
23957   case ISD::AND:
23958   case ISD::OR:
23959   case ISD::XOR:
23960     Commute = true;
23961     // fallthrough
23962   case ISD::SUB: {
23963     SDValue N0 = Op.getOperand(0);
23964     SDValue N1 = Op.getOperand(1);
23965     if (!Commute && MayFoldLoad(N1))
23966       return false;
23967     // Avoid disabling potential load folding opportunities.
23968     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
23969       return false;
23970     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
23971       return false;
23972     Promote = true;
23973   }
23974   }
23975
23976   PVT = MVT::i32;
23977   return Promote;
23978 }
23979
23980 //===----------------------------------------------------------------------===//
23981 //                           X86 Inline Assembly Support
23982 //===----------------------------------------------------------------------===//
23983
23984 // Helper to match a string separated by whitespace.
23985 static bool matchAsm(StringRef S, ArrayRef<const char *> Pieces) {
23986   S = S.substr(S.find_first_not_of(" \t")); // Skip leading whitespace.
23987
23988   for (StringRef Piece : Pieces) {
23989     if (!S.startswith(Piece)) // Check if the piece matches.
23990       return false;
23991
23992     S = S.substr(Piece.size());
23993     StringRef::size_type Pos = S.find_first_not_of(" \t");
23994     if (Pos == 0) // We matched a prefix.
23995       return false;
23996
23997     S = S.substr(Pos);
23998   }
23999
24000   return S.empty();
24001 }
24002
24003 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
24004
24005   if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
24006     if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
24007         std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
24008         std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
24009
24010       if (AsmPieces.size() == 3)
24011         return true;
24012       else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
24013         return true;
24014     }
24015   }
24016   return false;
24017 }
24018
24019 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
24020   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
24021
24022   std::string AsmStr = IA->getAsmString();
24023
24024   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
24025   if (!Ty || Ty->getBitWidth() % 16 != 0)
24026     return false;
24027
24028   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
24029   SmallVector<StringRef, 4> AsmPieces;
24030   SplitString(AsmStr, AsmPieces, ";\n");
24031
24032   switch (AsmPieces.size()) {
24033   default: return false;
24034   case 1:
24035     // FIXME: this should verify that we are targeting a 486 or better.  If not,
24036     // we will turn this bswap into something that will be lowered to logical
24037     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
24038     // lower so don't worry about this.
24039     // bswap $0
24040     if (matchAsm(AsmPieces[0], {"bswap", "$0"}) ||
24041         matchAsm(AsmPieces[0], {"bswapl", "$0"}) ||
24042         matchAsm(AsmPieces[0], {"bswapq", "$0"}) ||
24043         matchAsm(AsmPieces[0], {"bswap", "${0:q}"}) ||
24044         matchAsm(AsmPieces[0], {"bswapl", "${0:q}"}) ||
24045         matchAsm(AsmPieces[0], {"bswapq", "${0:q}"})) {
24046       // No need to check constraints, nothing other than the equivalent of
24047       // "=r,0" would be valid here.
24048       return IntrinsicLowering::LowerToByteSwap(CI);
24049     }
24050
24051     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
24052     if (CI->getType()->isIntegerTy(16) &&
24053         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
24054         (matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) ||
24055          matchAsm(AsmPieces[0], {"rolw", "$$8,", "${0:w}"}))) {
24056       AsmPieces.clear();
24057       const std::string &ConstraintsStr = IA->getConstraintString();
24058       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
24059       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
24060       if (clobbersFlagRegisters(AsmPieces))
24061         return IntrinsicLowering::LowerToByteSwap(CI);
24062     }
24063     break;
24064   case 3:
24065     if (CI->getType()->isIntegerTy(32) &&
24066         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
24067         matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) &&
24068         matchAsm(AsmPieces[1], {"rorl", "$$16,", "$0"}) &&
24069         matchAsm(AsmPieces[2], {"rorw", "$$8,", "${0:w}"})) {
24070       AsmPieces.clear();
24071       const std::string &ConstraintsStr = IA->getConstraintString();
24072       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
24073       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
24074       if (clobbersFlagRegisters(AsmPieces))
24075         return IntrinsicLowering::LowerToByteSwap(CI);
24076     }
24077
24078     if (CI->getType()->isIntegerTy(64)) {
24079       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
24080       if (Constraints.size() >= 2 &&
24081           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
24082           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
24083         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
24084         if (matchAsm(AsmPieces[0], {"bswap", "%eax"}) &&
24085             matchAsm(AsmPieces[1], {"bswap", "%edx"}) &&
24086             matchAsm(AsmPieces[2], {"xchgl", "%eax,", "%edx"}))
24087           return IntrinsicLowering::LowerToByteSwap(CI);
24088       }
24089     }
24090     break;
24091   }
24092   return false;
24093 }
24094
24095 /// getConstraintType - Given a constraint letter, return the type of
24096 /// constraint it is for this target.
24097 X86TargetLowering::ConstraintType
24098 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
24099   if (Constraint.size() == 1) {
24100     switch (Constraint[0]) {
24101     case 'R':
24102     case 'q':
24103     case 'Q':
24104     case 'f':
24105     case 't':
24106     case 'u':
24107     case 'y':
24108     case 'x':
24109     case 'Y':
24110     case 'l':
24111       return C_RegisterClass;
24112     case 'a':
24113     case 'b':
24114     case 'c':
24115     case 'd':
24116     case 'S':
24117     case 'D':
24118     case 'A':
24119       return C_Register;
24120     case 'I':
24121     case 'J':
24122     case 'K':
24123     case 'L':
24124     case 'M':
24125     case 'N':
24126     case 'G':
24127     case 'C':
24128     case 'e':
24129     case 'Z':
24130       return C_Other;
24131     default:
24132       break;
24133     }
24134   }
24135   return TargetLowering::getConstraintType(Constraint);
24136 }
24137
24138 /// Examine constraint type and operand type and determine a weight value.
24139 /// This object must already have been set up with the operand type
24140 /// and the current alternative constraint selected.
24141 TargetLowering::ConstraintWeight
24142   X86TargetLowering::getSingleConstraintMatchWeight(
24143     AsmOperandInfo &info, const char *constraint) const {
24144   ConstraintWeight weight = CW_Invalid;
24145   Value *CallOperandVal = info.CallOperandVal;
24146     // If we don't have a value, we can't do a match,
24147     // but allow it at the lowest weight.
24148   if (!CallOperandVal)
24149     return CW_Default;
24150   Type *type = CallOperandVal->getType();
24151   // Look at the constraint type.
24152   switch (*constraint) {
24153   default:
24154     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
24155   case 'R':
24156   case 'q':
24157   case 'Q':
24158   case 'a':
24159   case 'b':
24160   case 'c':
24161   case 'd':
24162   case 'S':
24163   case 'D':
24164   case 'A':
24165     if (CallOperandVal->getType()->isIntegerTy())
24166       weight = CW_SpecificReg;
24167     break;
24168   case 'f':
24169   case 't':
24170   case 'u':
24171     if (type->isFloatingPointTy())
24172       weight = CW_SpecificReg;
24173     break;
24174   case 'y':
24175     if (type->isX86_MMXTy() && Subtarget->hasMMX())
24176       weight = CW_SpecificReg;
24177     break;
24178   case 'x':
24179   case 'Y':
24180     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
24181         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
24182       weight = CW_Register;
24183     break;
24184   case 'I':
24185     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
24186       if (C->getZExtValue() <= 31)
24187         weight = CW_Constant;
24188     }
24189     break;
24190   case 'J':
24191     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24192       if (C->getZExtValue() <= 63)
24193         weight = CW_Constant;
24194     }
24195     break;
24196   case 'K':
24197     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24198       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
24199         weight = CW_Constant;
24200     }
24201     break;
24202   case 'L':
24203     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24204       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
24205         weight = CW_Constant;
24206     }
24207     break;
24208   case 'M':
24209     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24210       if (C->getZExtValue() <= 3)
24211         weight = CW_Constant;
24212     }
24213     break;
24214   case 'N':
24215     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24216       if (C->getZExtValue() <= 0xff)
24217         weight = CW_Constant;
24218     }
24219     break;
24220   case 'G':
24221   case 'C':
24222     if (dyn_cast<ConstantFP>(CallOperandVal)) {
24223       weight = CW_Constant;
24224     }
24225     break;
24226   case 'e':
24227     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24228       if ((C->getSExtValue() >= -0x80000000LL) &&
24229           (C->getSExtValue() <= 0x7fffffffLL))
24230         weight = CW_Constant;
24231     }
24232     break;
24233   case 'Z':
24234     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24235       if (C->getZExtValue() <= 0xffffffff)
24236         weight = CW_Constant;
24237     }
24238     break;
24239   }
24240   return weight;
24241 }
24242
24243 /// LowerXConstraint - try to replace an X constraint, which matches anything,
24244 /// with another that has more specific requirements based on the type of the
24245 /// corresponding operand.
24246 const char *X86TargetLowering::
24247 LowerXConstraint(EVT ConstraintVT) const {
24248   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
24249   // 'f' like normal targets.
24250   if (ConstraintVT.isFloatingPoint()) {
24251     if (Subtarget->hasSSE2())
24252       return "Y";
24253     if (Subtarget->hasSSE1())
24254       return "x";
24255   }
24256
24257   return TargetLowering::LowerXConstraint(ConstraintVT);
24258 }
24259
24260 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
24261 /// vector.  If it is invalid, don't add anything to Ops.
24262 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
24263                                                      std::string &Constraint,
24264                                                      std::vector<SDValue>&Ops,
24265                                                      SelectionDAG &DAG) const {
24266   SDValue Result;
24267
24268   // Only support length 1 constraints for now.
24269   if (Constraint.length() > 1) return;
24270
24271   char ConstraintLetter = Constraint[0];
24272   switch (ConstraintLetter) {
24273   default: break;
24274   case 'I':
24275     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24276       if (C->getZExtValue() <= 31) {
24277         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
24278         break;
24279       }
24280     }
24281     return;
24282   case 'J':
24283     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24284       if (C->getZExtValue() <= 63) {
24285         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
24286         break;
24287       }
24288     }
24289     return;
24290   case 'K':
24291     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24292       if (isInt<8>(C->getSExtValue())) {
24293         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
24294         break;
24295       }
24296     }
24297     return;
24298   case 'L':
24299     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24300       if (C->getZExtValue() == 0xff || C->getZExtValue() == 0xffff ||
24301           (Subtarget->is64Bit() && C->getZExtValue() == 0xffffffff)) {
24302         Result = DAG.getTargetConstant(C->getSExtValue(), Op.getValueType());
24303         break;
24304       }
24305     }
24306     return;
24307   case 'M':
24308     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24309       if (C->getZExtValue() <= 3) {
24310         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
24311         break;
24312       }
24313     }
24314     return;
24315   case 'N':
24316     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24317       if (C->getZExtValue() <= 255) {
24318         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
24319         break;
24320       }
24321     }
24322     return;
24323   case 'O':
24324     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24325       if (C->getZExtValue() <= 127) {
24326         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
24327         break;
24328       }
24329     }
24330     return;
24331   case 'e': {
24332     // 32-bit signed value
24333     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24334       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
24335                                            C->getSExtValue())) {
24336         // Widen to 64 bits here to get it sign extended.
24337         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
24338         break;
24339       }
24340     // FIXME gcc accepts some relocatable values here too, but only in certain
24341     // memory models; it's complicated.
24342     }
24343     return;
24344   }
24345   case 'Z': {
24346     // 32-bit unsigned value
24347     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24348       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
24349                                            C->getZExtValue())) {
24350         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
24351         break;
24352       }
24353     }
24354     // FIXME gcc accepts some relocatable values here too, but only in certain
24355     // memory models; it's complicated.
24356     return;
24357   }
24358   case 'i': {
24359     // Literal immediates are always ok.
24360     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
24361       // Widen to 64 bits here to get it sign extended.
24362       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
24363       break;
24364     }
24365
24366     // In any sort of PIC mode addresses need to be computed at runtime by
24367     // adding in a register or some sort of table lookup.  These can't
24368     // be used as immediates.
24369     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
24370       return;
24371
24372     // If we are in non-pic codegen mode, we allow the address of a global (with
24373     // an optional displacement) to be used with 'i'.
24374     GlobalAddressSDNode *GA = nullptr;
24375     int64_t Offset = 0;
24376
24377     // Match either (GA), (GA+C), (GA+C1+C2), etc.
24378     while (1) {
24379       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
24380         Offset += GA->getOffset();
24381         break;
24382       } else if (Op.getOpcode() == ISD::ADD) {
24383         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
24384           Offset += C->getZExtValue();
24385           Op = Op.getOperand(0);
24386           continue;
24387         }
24388       } else if (Op.getOpcode() == ISD::SUB) {
24389         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
24390           Offset += -C->getZExtValue();
24391           Op = Op.getOperand(0);
24392           continue;
24393         }
24394       }
24395
24396       // Otherwise, this isn't something we can handle, reject it.
24397       return;
24398     }
24399
24400     const GlobalValue *GV = GA->getGlobal();
24401     // If we require an extra load to get this address, as in PIC mode, we
24402     // can't accept it.
24403     if (isGlobalStubReference(
24404             Subtarget->ClassifyGlobalReference(GV, DAG.getTarget())))
24405       return;
24406
24407     Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
24408                                         GA->getValueType(0), Offset);
24409     break;
24410   }
24411   }
24412
24413   if (Result.getNode()) {
24414     Ops.push_back(Result);
24415     return;
24416   }
24417   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
24418 }
24419
24420 std::pair<unsigned, const TargetRegisterClass *>
24421 X86TargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
24422                                                 const std::string &Constraint,
24423                                                 MVT VT) const {
24424   // First, see if this is a constraint that directly corresponds to an LLVM
24425   // register class.
24426   if (Constraint.size() == 1) {
24427     // GCC Constraint Letters
24428     switch (Constraint[0]) {
24429     default: break;
24430       // TODO: Slight differences here in allocation order and leaving
24431       // RIP in the class. Do they matter any more here than they do
24432       // in the normal allocation?
24433     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
24434       if (Subtarget->is64Bit()) {
24435         if (VT == MVT::i32 || VT == MVT::f32)
24436           return std::make_pair(0U, &X86::GR32RegClass);
24437         if (VT == MVT::i16)
24438           return std::make_pair(0U, &X86::GR16RegClass);
24439         if (VT == MVT::i8 || VT == MVT::i1)
24440           return std::make_pair(0U, &X86::GR8RegClass);
24441         if (VT == MVT::i64 || VT == MVT::f64)
24442           return std::make_pair(0U, &X86::GR64RegClass);
24443         break;
24444       }
24445       // 32-bit fallthrough
24446     case 'Q':   // Q_REGS
24447       if (VT == MVT::i32 || VT == MVT::f32)
24448         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
24449       if (VT == MVT::i16)
24450         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
24451       if (VT == MVT::i8 || VT == MVT::i1)
24452         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
24453       if (VT == MVT::i64)
24454         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
24455       break;
24456     case 'r':   // GENERAL_REGS
24457     case 'l':   // INDEX_REGS
24458       if (VT == MVT::i8 || VT == MVT::i1)
24459         return std::make_pair(0U, &X86::GR8RegClass);
24460       if (VT == MVT::i16)
24461         return std::make_pair(0U, &X86::GR16RegClass);
24462       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
24463         return std::make_pair(0U, &X86::GR32RegClass);
24464       return std::make_pair(0U, &X86::GR64RegClass);
24465     case 'R':   // LEGACY_REGS
24466       if (VT == MVT::i8 || VT == MVT::i1)
24467         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
24468       if (VT == MVT::i16)
24469         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
24470       if (VT == MVT::i32 || !Subtarget->is64Bit())
24471         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
24472       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
24473     case 'f':  // FP Stack registers.
24474       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
24475       // value to the correct fpstack register class.
24476       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
24477         return std::make_pair(0U, &X86::RFP32RegClass);
24478       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
24479         return std::make_pair(0U, &X86::RFP64RegClass);
24480       return std::make_pair(0U, &X86::RFP80RegClass);
24481     case 'y':   // MMX_REGS if MMX allowed.
24482       if (!Subtarget->hasMMX()) break;
24483       return std::make_pair(0U, &X86::VR64RegClass);
24484     case 'Y':   // SSE_REGS if SSE2 allowed
24485       if (!Subtarget->hasSSE2()) break;
24486       // FALL THROUGH.
24487     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
24488       if (!Subtarget->hasSSE1()) break;
24489
24490       switch (VT.SimpleTy) {
24491       default: break;
24492       // Scalar SSE types.
24493       case MVT::f32:
24494       case MVT::i32:
24495         return std::make_pair(0U, &X86::FR32RegClass);
24496       case MVT::f64:
24497       case MVT::i64:
24498         return std::make_pair(0U, &X86::FR64RegClass);
24499       // Vector types.
24500       case MVT::v16i8:
24501       case MVT::v8i16:
24502       case MVT::v4i32:
24503       case MVT::v2i64:
24504       case MVT::v4f32:
24505       case MVT::v2f64:
24506         return std::make_pair(0U, &X86::VR128RegClass);
24507       // AVX types.
24508       case MVT::v32i8:
24509       case MVT::v16i16:
24510       case MVT::v8i32:
24511       case MVT::v4i64:
24512       case MVT::v8f32:
24513       case MVT::v4f64:
24514         return std::make_pair(0U, &X86::VR256RegClass);
24515       case MVT::v8f64:
24516       case MVT::v16f32:
24517       case MVT::v16i32:
24518       case MVT::v8i64:
24519         return std::make_pair(0U, &X86::VR512RegClass);
24520       }
24521       break;
24522     }
24523   }
24524
24525   // Use the default implementation in TargetLowering to convert the register
24526   // constraint into a member of a register class.
24527   std::pair<unsigned, const TargetRegisterClass*> Res;
24528   Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
24529
24530   // Not found as a standard register?
24531   if (!Res.second) {
24532     // Map st(0) -> st(7) -> ST0
24533     if (Constraint.size() == 7 && Constraint[0] == '{' &&
24534         tolower(Constraint[1]) == 's' &&
24535         tolower(Constraint[2]) == 't' &&
24536         Constraint[3] == '(' &&
24537         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
24538         Constraint[5] == ')' &&
24539         Constraint[6] == '}') {
24540
24541       Res.first = X86::FP0+Constraint[4]-'0';
24542       Res.second = &X86::RFP80RegClass;
24543       return Res;
24544     }
24545
24546     // GCC allows "st(0)" to be called just plain "st".
24547     if (StringRef("{st}").equals_lower(Constraint)) {
24548       Res.first = X86::FP0;
24549       Res.second = &X86::RFP80RegClass;
24550       return Res;
24551     }
24552
24553     // flags -> EFLAGS
24554     if (StringRef("{flags}").equals_lower(Constraint)) {
24555       Res.first = X86::EFLAGS;
24556       Res.second = &X86::CCRRegClass;
24557       return Res;
24558     }
24559
24560     // 'A' means EAX + EDX.
24561     if (Constraint == "A") {
24562       Res.first = X86::EAX;
24563       Res.second = &X86::GR32_ADRegClass;
24564       return Res;
24565     }
24566     return Res;
24567   }
24568
24569   // Otherwise, check to see if this is a register class of the wrong value
24570   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
24571   // turn into {ax},{dx}.
24572   if (Res.second->hasType(VT))
24573     return Res;   // Correct type already, nothing to do.
24574
24575   // All of the single-register GCC register classes map their values onto
24576   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
24577   // really want an 8-bit or 32-bit register, map to the appropriate register
24578   // class and return the appropriate register.
24579   if (Res.second == &X86::GR16RegClass) {
24580     if (VT == MVT::i8 || VT == MVT::i1) {
24581       unsigned DestReg = 0;
24582       switch (Res.first) {
24583       default: break;
24584       case X86::AX: DestReg = X86::AL; break;
24585       case X86::DX: DestReg = X86::DL; break;
24586       case X86::CX: DestReg = X86::CL; break;
24587       case X86::BX: DestReg = X86::BL; break;
24588       }
24589       if (DestReg) {
24590         Res.first = DestReg;
24591         Res.second = &X86::GR8RegClass;
24592       }
24593     } else if (VT == MVT::i32 || VT == MVT::f32) {
24594       unsigned DestReg = 0;
24595       switch (Res.first) {
24596       default: break;
24597       case X86::AX: DestReg = X86::EAX; break;
24598       case X86::DX: DestReg = X86::EDX; break;
24599       case X86::CX: DestReg = X86::ECX; break;
24600       case X86::BX: DestReg = X86::EBX; break;
24601       case X86::SI: DestReg = X86::ESI; break;
24602       case X86::DI: DestReg = X86::EDI; break;
24603       case X86::BP: DestReg = X86::EBP; break;
24604       case X86::SP: DestReg = X86::ESP; break;
24605       }
24606       if (DestReg) {
24607         Res.first = DestReg;
24608         Res.second = &X86::GR32RegClass;
24609       }
24610     } else if (VT == MVT::i64 || VT == MVT::f64) {
24611       unsigned DestReg = 0;
24612       switch (Res.first) {
24613       default: break;
24614       case X86::AX: DestReg = X86::RAX; break;
24615       case X86::DX: DestReg = X86::RDX; break;
24616       case X86::CX: DestReg = X86::RCX; break;
24617       case X86::BX: DestReg = X86::RBX; break;
24618       case X86::SI: DestReg = X86::RSI; break;
24619       case X86::DI: DestReg = X86::RDI; break;
24620       case X86::BP: DestReg = X86::RBP; break;
24621       case X86::SP: DestReg = X86::RSP; break;
24622       }
24623       if (DestReg) {
24624         Res.first = DestReg;
24625         Res.second = &X86::GR64RegClass;
24626       }
24627     }
24628   } else if (Res.second == &X86::FR32RegClass ||
24629              Res.second == &X86::FR64RegClass ||
24630              Res.second == &X86::VR128RegClass ||
24631              Res.second == &X86::VR256RegClass ||
24632              Res.second == &X86::FR32XRegClass ||
24633              Res.second == &X86::FR64XRegClass ||
24634              Res.second == &X86::VR128XRegClass ||
24635              Res.second == &X86::VR256XRegClass ||
24636              Res.second == &X86::VR512RegClass) {
24637     // Handle references to XMM physical registers that got mapped into the
24638     // wrong class.  This can happen with constraints like {xmm0} where the
24639     // target independent register mapper will just pick the first match it can
24640     // find, ignoring the required type.
24641
24642     if (VT == MVT::f32 || VT == MVT::i32)
24643       Res.second = &X86::FR32RegClass;
24644     else if (VT == MVT::f64 || VT == MVT::i64)
24645       Res.second = &X86::FR64RegClass;
24646     else if (X86::VR128RegClass.hasType(VT))
24647       Res.second = &X86::VR128RegClass;
24648     else if (X86::VR256RegClass.hasType(VT))
24649       Res.second = &X86::VR256RegClass;
24650     else if (X86::VR512RegClass.hasType(VT))
24651       Res.second = &X86::VR512RegClass;
24652   }
24653
24654   return Res;
24655 }
24656
24657 int X86TargetLowering::getScalingFactorCost(const AddrMode &AM,
24658                                             Type *Ty) const {
24659   // Scaling factors are not free at all.
24660   // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
24661   // will take 2 allocations in the out of order engine instead of 1
24662   // for plain addressing mode, i.e. inst (reg1).
24663   // E.g.,
24664   // vaddps (%rsi,%drx), %ymm0, %ymm1
24665   // Requires two allocations (one for the load, one for the computation)
24666   // whereas:
24667   // vaddps (%rsi), %ymm0, %ymm1
24668   // Requires just 1 allocation, i.e., freeing allocations for other operations
24669   // and having less micro operations to execute.
24670   //
24671   // For some X86 architectures, this is even worse because for instance for
24672   // stores, the complex addressing mode forces the instruction to use the
24673   // "load" ports instead of the dedicated "store" port.
24674   // E.g., on Haswell:
24675   // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
24676   // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.
24677   if (isLegalAddressingMode(AM, Ty))
24678     // Scale represents reg2 * scale, thus account for 1
24679     // as soon as we use a second register.
24680     return AM.Scale != 0;
24681   return -1;
24682 }
24683
24684 bool X86TargetLowering::isTargetFTOL() const {
24685   return Subtarget->isTargetKnownWindowsMSVC() && !Subtarget->is64Bit();
24686 }